
    i                    (   U 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ZddlZddl	Z	ddl
mZ ddlmZmZ ddl	mZmZ ddlmZ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 dd
lm Z  ddl!m"Z" ddl#m$Z$m%Z%m&Z&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z: ddl;m<Z<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZD ddlEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZM ddlNmOZOmPZPmQZQmRZRmSZS ddlTmUZUmVZV 	 ddlWmXZX er.ddlZm[Z[ ddl\m]Z]m^Z^m_Z_m`Z` ddlambZb ddlcmdZdmeZe ddlfmgZgmhZh ddlimjZj  ededef         Zkd Zld!Zm enh d"      Zo end#h      Zpd$Zq e       Zreeef   esd%<    G d& d'et      Zuej                  d(e<fd)       Zw G d* d+      Zxd,ed(exfd-Zyd,ed.d/d0e dz  d1ee   d2eze{ef   d(eze{eSf   fd3Z|	 dd.d/d4ed5e dz  d(eSfd6Z}d.d/d7eze{ef   d(dfd8Z~d9d/d7eze{eSf   d:e	j                  d(dfd;Zd:e	j                  d<eze{ef   d=e{d>eedf   dz  d?ee   dz  d@eze{ef   dz  dAeze{ef   dz  d(e	j                   fdBZh dCZd.d/dDed5e dz  d=e{d(eSf
dEZ G dF dGeS      Z G dH dIe      Z G dJ dKe      Z G dL dMe      Z G dN dOe      Z G dP dQeS      Z G dR dSe      Z G dT dUe      Z G dV dWe      Z G dX dYe      Z G dZ d[e      Z G d\ d]e      Zd.d/dDedef   d=e{d1eeS   d2eze{eSf   d(eSfd^Z G d_ d`e      Z G da dbe      Z G dc ddeS      Z G de dfe      Z G dg dheS      Z G di dje      Zd(ezeef   fdkZd.d/dDedef   d(e<fdlZ G dm dne      Z G do dpe      Z G dq dre      Z G ds dteS      Z G du dveS      Z G dw dxeS      ZddylcmZmZmZmZ  G dz d{e      Z e       Z G d| d}eS      Z G d~ deS      Z G d deS      Z G d deS      Z G d deS      Z G d de      Z G d de      Z G d de      Z G d de      Zy# eY$ r dZXY !w xY w)a  
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)
namedtuple)CallableSequence)CellTypeFunctionType)AnycastLiteralOptionalTYPE_CHECKINGTypeVar)Never)WeakKeyDictionary)get_stack_above_dynamo)Source)is_namedtuple_class   )configgraph_break_hints	polyfills	variables)create_call_functioncreate_rot_nis_generator)format_frame_infoget_dynamo_observed_exceptionhandle_observed_exceptionInfiniteGeneratorErrorObservedExceptionObservedGeneratorExitObservedUserStopIterationraise_observed_exceptionStepUnsupportedunimplementedUnsupported)GuardBuilderinstall_guard)	
AttrSourceCellContentsSourceClosureSourceConstantSourceDefaultsSourceGetItemSourceImportSourceSkipGuardSource
TypeSource)check_constant_argscheck_unspec_or_constant_argscmp_name_to_op_mappingidentityis_functionis_wrapper_or_member_descriptoristype	make_cell   )#AsPythonConstantNotImplementedErrorAttributeMutationNewraise_type_error_excValueMutationNewVariableTracker)CONSTANT_VARIABLE_NONEConstantVariable)_fsdp_param_group)	PyCodegen)&InliningGeneratorInstructionTranslatorInliningInstructionTranslatorInstructionTranslatorInstructionTranslatorBase)ContextWrappingVariable)TritonGridTypeTritonKernelType)BaseListVariableListVariable)TensorVariable_F.)bound      >   is_leaf	namespacenone_is_leafrQ   zihttps://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.yml_spec_cachec                       e Zd Zy)ClosureConversionErrorN)__name__
__module____qualname__     r/var/www/vps2.regionflexible.com/Desarrollo/venv/lib/python3.12/site-packages/torch/_dynamo/variables/functions.pyrV   rV      s    r[   rV   returnc            	      T    t        t        t        t        d      d      d      d      S )Ntorchutils_pytreeSUPPORTED_NODES)r(   r.   rZ   r[   r\   !get_pytree_SUPPORTED_NODES_sourcerc      s(    :l73W=yI r[   c                   ,    e Zd ZdeddfdZdeddfdZy)FunctionSpecfuncr]   Nc                 p   |j                   }|j                  }|j                  | _        |j                  | _        |j                  | _        |d | j                   | _        || j                  | j
                   | _	        | j                  | j                  z   | _
        || j
                  | j
                  | j                  z    | _        | j
                  | j                  z   }|j                  t        z  r||   nd | _        || j                  rdndz  }|j                  t        z  r||   | _        y d | _        y Nr9   r   )__code__co_varnamesco_posonlyargcountposonly_countco_argcount	arg_countco_kwonlyargcountkwonly_countposonly_namespos_or_kw_namesall_pos_nameskwonly_namesco_flags
CO_VARARGSvarargs_nameCO_VARKEYWORDS
varkw_name)selfrf   codevnoffs        r\   __init__zFunctionSpec.__init__   s   }}!44)) 22 4$"4"45!$"4"4t~~F!//$2F2FFt~~ARAR0RSnnt000'+}}z'ABsGtD%%q1,%)]]^%C"S'r[   c           
         |j                   xs d| _        |j                  xs i | _        t	        t        | j                  t        | j                         d  t        t        | j                                          | _	        y NrZ   )
__defaults__defaults__kwdefaults__
kwdefaultsdictziprs   lenrangepos_default_map)rz   rf   s     r\   update_defaultszFunctionSpec.update_defaults   si     ))/R--3  $""C$6#6#895T]]AS;TU 
r[   )rW   rX   rY   r   r~   r   rZ   r[   r\   re   re      s+    N\ Nd N$	
L 	
T 	
r[   re   rf   c                 \    t         j                  |       }|t        |       }|t         | <   |S N)rT   getre   )rf   specs     r\   	_get_specr      s.    ??4 D|D! DKr[   txrE   	fn_sourceargskwargsc           
         t        |       }t        |      |j                  k(  rh| j                  s\|sZ|j                  sN|j
                  sB|j                  s6t        |j                        D ci c]  \  }}|t        |||          c}}S |j                  |        i }t        |      }	|j                  j                         D ]d  \  }}
d }|r>t        j                  |j                   |
         rt"        j$                  st'        ||
      }t        ||j                   |
   |      ||<   f t        |j                        D ]i  \  }}|t        |      k  rt        |||         ||<   '||	v r-||j(                  vrt        ||	j+                  |            ||<   X||vs]t-        d|        |t        |j                        d  }|j                  r#t        |t/        |            ||j                  <   n/|r-t-        dt        |       dt        |j                               |j                  D ]p  }||	v rt        ||	j+                  |            ||<   &||j0                  v r0d }|rt'        ||d      }t        ||j0                  |   |      ||<   dt-        d|        |j
                  rt        ||	      ||j
                  <   |S |	rt-        dt3        |	             |S c c}}w )Nz&missing required positional argument: z#Too many positional arguments: got z, expected T)is_kwz(Missing required keyword-only argument: zUnexpected keyword arguments: )r   r   rn   r   rw   ry   rt   	enumeraters   wrap_bound_argr   r   r   itemsr@   
is_literalr   r   %skip_guards_on_constant_func_defaultsr,   rq   pop	TypeErrortupler   list)rf   r   r   r   r   r   inamebarem_kwidxdefault_sourceextrakwdefault_sources                 r\   bind_args_cachedr      s    T?D
 	D	T^^#!!!!!! %T%7%78
4 .T!W--
 	
 		B&\F ))//1 J	c''c(:;<<+Is;N!"dmmC&8.I4J T//0 M4s4y=%b$q'2BtHV^ *** &b&**T*:;BtH^DTFKLL!M& T''(*+E .r5< @4	1#d)KDL^L^H_G`a
 	

 !! 	O6>%b&**T*:;BtHT__$##1)T#N %b$//$*?AQRBtHFtfMNN	O ,R84?? I 
8fGHHIE
s   .K#valsourcec                     t        |t              r|S |st        j                  | |      S t        j                  j                  ||      S r   )
isinstancer>   buildr   LazyVariableTrackercreate)r   r   r   s      r\   r   r     sD     #'
$$R-- ,,33C@@r[   resultc                     t        |j                               D ]+  \  }}t        |t        t        f      st        | |      ||<   - y r   )r   r   r   r   r   r   )r   r   kvs       r\   wrap_args_kwargsr     s>    V\\^$ .1a%'&r1-F1I.r[   parentr{   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_cellr   )r   r   r{   r   r   new_cells         r\   init_cellvarsr   !  sa     ==--L    ..06> ##Hfjj.>?t r[   	f_globalsr   r   closurer   annotationsc                     ddl m}  || ||||      }||_        t        |t              rddlm}	 t         |	|            }|t        |t              sJ ||_        |S )Nr   r   pairwise)	typesr   r   r   r   	itertoolsr   r   __annotations__)
r{   r   r   r   r   r   r   r   rf   r   s
             r\   _create_nested_fnr   6  sa     #ixAD$D+u%&8K01 *[$"???&DKr[   >   __doc__ri   __closure____globals__r   r   r   fnc                 N   |xr t        ||      }|r|dk(  rt        |      }d }	 t        j                  ||      }|t        v rt        ||      }|r t        j                  j                  ||      S t        j                  | |      S # t        $ r t        t        |        Y gw xY w)Nr   )r(   r/   inspectgetattr_staticAttributeErrorr"   fn_known_dunder_attrsgetattrr   r   r   r>   r   )r   r   r   r   subobjs        r\   fn_var_getattrr   [  s     0
640F$++ !(F5''D1 $$T",,33FFCC  V,,  5 	!45s   B B$#B$c                       e Zd ZdefdZdefdZdeeef   fdZde	j                  fdZdefdZddd	ee   d
eeef   defdZdddedefdZdddeeef   fdZdefdZy)BaseUserFunctionVariabler]   c                 6    | j                         j                  S r   get_codeco_filenamerz   s    r\   get_filenamez%BaseUserFunctionVariable.get_filenamew      }}***r[   c                 6    | j                         j                  S r   r   co_namer   s    r\   get_namez!BaseUserFunctionVariable.get_namez      }}&&&r[   c                     t         r   NotImplementedErrorr   s    r\   get_globalsz$BaseUserFunctionVariable.get_globals}      !!r[   c                     t         r   r   r   s    r\   r   z!BaseUserFunctionVariable.get_code  r   r[   c                     t         r   r   r   s    r\   has_selfz!BaseUserFunctionVariable.has_self  r   r[   r   rE   r   r   c                     | j                         dk(  r%| j                         j                  d      rt        S |j	                  | g | j                         ||      S )Npatch_track_step_calledztorch/optim/lr_scheduler.py)r   r   endswithr?   inline_user_function_return	self_argsrz   r   r   r   s       r\   call_functionz&BaseUserFunctionVariable.call_function  sY     MMO88!!#,,-JK))--d4Ndnn6F4N4NPVWWr[   r   c                     d}	 t        | j                         |      }t
        j                  j                  |      S # t        $ r |dk(  rt        | t              rd}Y Aw xY w)NFrW   T)hasattrget_functionr   r   NestedUserFunctionVariabler   r@   r   rz   r   r   r   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                     i S r   rZ   rz   r   s     r\   closure_varsz%BaseUserFunctionVariable.closure_vars      	r[   c                      yNTrZ   r   s    r\    should_allow_nested_graph_breaksz9BaseUserFunctionVariable.should_allow_nested_graph_breaks      r[   N)rW   rX   rY   strr   r   r   r   r   r   CodeTyper   boolr   r   r>   r   r@   r   r   r   rZ   r[   r\   r   r   v  s    +c +'# '"T#s(^ ""%.. ""$ "X#X 'X S/)*	X
 
X
9)
914
9	
96 4_@T;U $ r[   r   c                       e Zd ZdZddhej
                  Z eh d      Zede	de	dd fd       Z
	 d+dej                  ej                  j                  z  ded	e	dd
f fdZde	f fdZdee   fdZdej                  fdZdej.                  fdZdefdZdefdZdeee	f   fdZdefdZ ddde!e   d	eeef   deeef   fdZ"dddedefdZ#dddede$fdZ%ddde!e   d	eeef   def fdZ&ddde!e   d	eeef   ded
z  fdZ'defdZ(defdZ)ddde!e   d	eeef   de*d e!e   eeef   f   d
z  fd Z+dej                  d
z  fd!Z,d"ede*ed#f   d
z  fd$Z-de	dee   d
z  fd%Z.de/d&   fd'Z0de1fd(Z2d)e3defd*Z4 xZ5S ),UserFunctionVariablez-Some unsupported user-defined global functionr   is_constant>   
optree.opstorch.utils._pytreetorch.utils._cxx_pytreeoptreevaluer   r]   c                 f    t        |j                  t        j                                | ||      S Nr   r'   
make_guardr&   CLOSURE_MATCHclsr	  r   s      r\   create_with_sourcez'UserFunctionVariable.create_with_source  s(    f''(B(BCD5((r[   r   Nc                 B   t        |   d	i | t        |dd      rd| _        nd| _        t	        |t
        j                  t        j                  j                  f      s!t        d| ddgt        j                         t        j                  |d|      }|| _        y )
N_dynamo_marked_constantFTz1can't handle functions not implemented in python z2Dynamo can only handle functions defined in pythonz9Move usage of this function out of `torch.compile` regiongb_typecontextexplanationhints_torchdynamo_inlinerZ   )superr~   r   r  r   r   r   r_   jitScriptFunctionr$   r   INFERENCE_MODEr   r   r   rz   r   r  r   	__class__s       r\   r~   zUserFunctionVariable.__init__  s     	"6"20%8#D$D "u115993K3KLMK$PO&55	 ##B(=rBr[   c                 X    t        | t              r| j                  S t        |          S r   )r7   r  r   r  as_python_constant)rz   r   s    r\   r"  z'UserFunctionVariable.as_python_constant  s%    $,-77Nw)++r[   c                     g S r   rZ   r   s    r\   r   zUserFunctionVariable.self_args  r   r[   c                     | j                   S r   r   r   s    r\   r   z!UserFunctionVariable.get_function      wwr[   c                 .    | j                   j                  S r   )r   ri   r   s    r\   r   zUserFunctionVariable.get_code  s    wwr[   c                 "    t         j                  S r   r   r   r   s    r\   python_typez UserFunctionVariable.python_type      !!!r[   c                 4    t        | j                  dd       d uS )N__self__)r   r   r   s    r\   r   zUserFunctionVariable.has_self  s    tww
D1==r[   c                 .    | j                   j                  S r   )r   r   r   s    r\   r   z UserFunctionVariable.get_globals  s    ww"""r[   c                 n    | j                   }|r&t        | t        j                        r| j                  }|S r   )r   r   r   UserMethodVariable	source_fn)rz   r   s     r\   
get_sourcezUserFunctionVariable.get_source  s+    jy'C'CD^^Fr[   r   rE   r   c                 *   | j                   rJ | j                  }t        |t              st	        d      |j
                  j                  }| j                         }t        |||||      }t        |||j                         | j                  j                  xs d}t        |      t        | j                  j                  j                        k(  sJ t        t        j                          | j                  j                  j                  |      D ]  \  }	}
}|j
                  j"                  }||v r||   }n|rYt%        t'        |      |	      }t)        |d|
      }	 t+        j,                  ||j.                  |      }|j7                  |||      }n4	 t+        j,                  ||j.                        }|j7                  d||      }|||
<    |S # t0        $ r t3        j4                         }Y pw xY w# t0        $ r t3        j4                         }Y ^w xY w)z
        Assume `args` and `kwargs` are VariableTracker arguments for a call to
        this function, create new bindings for initial locals.
        z'Only supports regular Python functions.rZ   cell_contents)freevar_nameN)r  r   r   r   r   r   root_txr2  r   r   ri   r   r   co_freevarsr   r   countr   r-   r*   r)   r>   r   r4  
ValueErrorr   DeletedVariabletrack_cell_existing)rz   r   r   r   r   r6  r   r   r   r   r   cellr   cell_varclosure_cellclosure_cell_contentscontents_vars                    r\   	bind_argszUserFunctionVariable.bind_args   s    ####!%"l+EFF--''"!"gvtVDffbkk2''%%+7|s477#3#3#?#?@@@@"OOtww//;;W 
 "	$OCt "==55L|#'-,]6-BCH(: /)%?#2#8#8 2 24I$L (;; $?#2#8#8ASAS#TL (;;D$U#F4LE"	$H ' " ?#,#<#<#>L? " ?#,#<#<#>L?s$   !G G2G/.G/2HHr   r   c                     |t         v rt        j                  | |      S | j                         }t	        || j
                  ||      S r   )r3   r   GetAttrVariabler2  r   r   )rz   r   r   r   s       r\   var_getattrz UserFunctionVariable.var_getattr>  s?    )),,T488"b$''6488r[   c                 l    t        | j                  |      }t        j                  j	                  |      S r   )r   r   r   r@   r   r   s       r\   r   z%UserFunctionVariable.call_obj_hasattrD  s+     $'))0088r[   c           
      n	   | j                   t        j                  j                  u r	 |D cg c]  }|j	                          }}|j                         D ci c]  \  }}||j	                          }}}t        j                  j                  |i |j                  }	t        j                  |	      S | j                   t        j                  j                  u rt	  t        j                  | j                         j                  |i |}|j                  d   j	                         }t!        |t"              sJ t        j$                  |      S | j                   t        j                  j(                  u r" t        j                  | j                         j                  |i |}|j*                  d   }t!        |t,              sS|j/                         }d|j0                   d}t3        dd	| j4                   d
| d
| d|g t6        j8                         t!        |t:              s,|j=                         }d| d}t3        d|  |d| ddg       |j                   }t        j>                  |t        j                  j@                  jB                        S | jD                  r'tG        || j                   | j=                         ||      S |jH                  jJ                  jL                  st| j                   t        j                  jN                  jP                  u rDt        j                  jR                  jU                  |      5  tV        |   |||      cd d d        S t[        |jH                  jJ                  dd       dk(  r|jH                  jJ                  j\                  sq	 ddl/m0} |h| j                   |jb                  |jd                  fv rDt        j                  jR                  j]                  |      5  tV        |   |||      cd d d        S | jg                  |||      }||S tV        |   |||      S c c}w c c}}w # t        $ r}
t        d| d|       |
d }
~
ww xY w# t&        $ r}
t        d| d|       |
d }
~
ww xY w# 1 sw Y   8xY w# t&        $ r d }Y w xY w# 1 sw Y   xY w)NzCannot convert patch_dynamo_config args/kwargs to constants. Please fix your call to patch_dynamo_config by using simpler inputs. args: z
, kwargs: error_on_graph_breakz\Improper error_on_graph_break() call. Please fix your call to error_on_graph_break(). args: r   z=`nonstrict_trace` expects a callable, but got value of type <>zTypeError from user codezcall_function(, )r  z(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` regionkinddescriptionz!torch.utils.checkpoint.checkpoint)	FSDPState)4r   r_   _dynamopatch_dynamo_configr"  r   changesr   DynamoConfigPatchVariabler:   RuntimeErrorrG  r   	signaturebind	argumentsr   r  ErrorOnGraphBreakVariable	Exceptionnonstrict_tracer   r   r*  rW   r$   r	  r   
USER_ERRORr  r   TorchInGraphFunctionVariableAllowInGraphKindNONSTRICT_TRACEr  invoke_and_store_as_constantr   current_tracer,unsafe_allow_externally_visible_side_effectsr`   8_disable_side_effect_safety_checks_for_current_subtracerr   2allow_externally_visible_side_effects_in_subtracerr  r   r   allow_side_effects_in_hop/torch.distributed.fsdp._fully_shard._fsdp_staterN  _pre_forward_post_forward_maybe_call_tree_map_fastpath)rz   r   r   r   arg
args_constkeyr   kwargs_constrQ  erN   rG  fn_vartypmsgfn_namer   rN  tree_map_resultr   s                       r\   r   z"UserFunctionVariable.call_functionJ  s    77emm777BFG3c446G
GBH,,. 6>c3C//11     --;;#/'  !::7CC WW:::7))$''277HH',*($$& % ""6=== ::;OPP WW555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99II  /DGGT]]_dF 
 		((UU}}""[[\ ++^^ ? w,Rv>? ? BII,,mTB23II,,FF!U $&&''5 * ]]//II"M C 70T6BC C <<RvN&""w$Rv66A H  7 "!F*VH6 	  "!F*VH6 b? ?  ! 	!C Csx   Q P<Q Q4A Q A2Q* R$R 9R+<Q 	Q'Q""Q'*	R
3RR
RR('R(+R4c                    | j                  |||      }||\  }}}n| }|}|}t        |t              r)|j                         rh |t        z
  st        |      dk\  sy |d   }|d   }	|dd  }
|	j                  ||||
|      S )Nr   r   r9   )_rewrite_tree_map_only_callr   r  _is_tree_map_function_SUPPORTED_TREE_MAP_KWARGSr   call_tree_map)rz   r   r   r   rewritetree_map_fntree_map_argstree_map_kwargsmap_fn
first_treerests              r\   rg  z2UserFunctionVariable._maybe_call_tree_map_fastpath  s     222tVD:A7KK M$O {$89113''*DDM"a'q!"1%
QR ''
 	
r[   c                     t        | j                  dd       dk(  xr# t        | j                  dd       | j                  v S )NrW   tree_maprX   r   r   _TREE_MAP_MODULESr   s    r\   rt  z*UserFunctionVariable._is_tree_map_function  s=    DGGZ.*< Ot48N8NN	
r[   c                     t        | j                  dd       dk(  xr# t        | j                  dd       | j                  v S )NrW   tree_map_onlyrX   r  r   s    r\   _is_tree_map_only_functionz/UserFunctionVariable._is_tree_map_only_function  s=    DGGZ./A Ot48N8NN	
r[   c           	      0   | j                         sy t        |      dk7  ry h |t        z
  ry |\  }}}| j                  |      }|y | j	                         }|y t        ||t        |dd             }	t        j                  |      }
|
|	|gt        |      fS )N   r   r  )
r  r   _TREE_MAP_ONLY_SUPPORTED_KWARGS_extract_tree_map_only_types_lookup_tree_map_functionTreeMapOnlyFunctionVariabler   r   r  r   )rz   r   r   r   type_selectorr{  tree_argallowed_typestree_map_callablewrapped_map_fntree_map_variables              r\   rs  z0UserFunctionVariable._rewrite_tree_map_only_call  s     ..0t9>V966*.'vx99-H  ::<$468T2

 &::;LM >8"<d6lJJr[   c                     t        | j                  dd       }|sy t        j                  j	                  |      }|y t        |dd       }t        |t        j                        r|S y )NrX   r  )r   r   sysmodulesr   r   r   r   )rz   module_namemoduler  s       r\   r  z.UserFunctionVariable._lookup_tree_map_function  sZ    dgg|T:->6:t4h 2 23Or[   selector.c                     |j                         sy 	 |j                         }| j                  |      }|sy t	        d |D              sy t        t        j                  |            S # t        $ r Y y w xY w)Nc              3   <   K   | ]  }t        |t                y wr   )r   type).0rn  s     r\   	<genexpr>zDUserFunctionVariable._extract_tree_map_only_types.<locals>.<genexpr>!  s     >S:c4(>   )is_python_constantr"  r   _flatten_type_specallr   r   fromkeys)rz   r  	raw_value	flatteneds       r\   r  z1UserFunctionVariable._extract_tree_map_only_types  sw     **,	 335I ++I6	>I>>T]]9-.. # 		s   A( (	A43A4c                 `   t        |t              r|gS t        |t              r1g }|D ](  }| j                  |      }| y |j	                  |       * |S t        t        dd       }|Gt        ||      r;g }|j                  D ](  }| j                  |      }| y |j	                  |       * |S y )N	UnionType)r   r  r   r  extendr   r   __args__)rz   r	  	collectedentryflat
union_types         r\   r  z'UserFunctionVariable._flatten_type_spec%  s    eT"7NeU#$&I '..u5<  &	'
 UK6
!j
&CI '..u5<  &	'
 r[   Tc                      yr   rZ   r   s    r\   is_python_hashablez'UserFunctionVariable.is_python_hashable;  r   r[   c                 ,    t        | j                        S r   )hashr   r   s    r\   get_python_hashz$UserFunctionVariable.get_python_hash>  s    DGG}r[   otherc                 j    t        |t        j                        xr | j                  |j                  u S r   )r   r   r  r   rz   r  s     r\   is_python_equalz$UserFunctionVariable.is_python_equalA  s*    %!?!?@XTWWPUPXPXEXXr[   F)6rW   rX   rY   r   r   _nonvar_fields	frozensetr  classmethodr   r  r   r   r_   r  r  r  r~   r"  r   r>   r   r   r   r   r  r*  r   r   r   r   r   r2  r   rA  rD  r@   r   r   rg  rt  r  r   rs  r  r  r  r
   r  intr  objectr  __classcell__r   s   @r\   r  r    s&   7 	 
"	0	0N "	
 )s )C )<R ) ) "!9!99  	
 
>,C ,40 e00  %..  "T ">$ >#T#s(^ #F <'< '< S/)*	<
 
c?"	#<|95 9S 9_ 99)9149	9i7#i7 'i7 S/)*	i7
 
i7V
#
 '
 S/)*	

 
4	
B
t 

D 
$K#$K '$K S/)*	$K 	"_%o%&(	

 	$KL
5+=+=+D 
/'/	tSy	D	 /" T
T0A ,GDM  YV Y Yr[   r  c                   D     e Zd ZdZdddee   deeef   def fdZ xZ	S )InspectSignatureVariablea  
    Variable tracker for inspect.signature with caching support.

    inspect.Signature is expensive to trace. When inspect.signature is called
    repeatedly on the same function during tracing, we cache the result to avoid
    retracing the signature construction each time. Although this is different
    from CPython behavior, it is safe to do so because inspect.signature does
    not change across different calls to the same function.
    r   rE   r   r   r]   c                 ^   t        |      dk(  r|s|d   }d }t        |t        t        f      r|j	                         }|]||j
                  j                  v r|j
                  j                  |   S t        | !  |||      }||j
                  j                  |<   |S t        | !  |||      S rh   )	r   r   r  r0  r   r   signature_cacher  r   )rz   r   r   r   
target_arg	cache_keyr   r   s          r\   r   z&InspectSignatureVariable.call_functionP  s     t9>&aJI*';=O&PQ&335	$		 9 999944Y??.r4@7=		)))4w$Rv66r[   
rW   rX   rY   r   r   r>   r   r   r   r  r  s   @r\   r  r  E  sG    7#7 '7 S/)*	7
 
7 7r[   r  c                        e Zd Zdhej                  Zdeedf   dededdf fdZ	defdZ
d	edefd
Zdddee   deeef   defdZ xZS )r  r  .r{  r   r]   Nc                 @    t        |   di | || _        || _        y r   )r  r~   r  r{  )rz   r  r{  r   r   s       r\   r~   z$TreeMapOnlyFunctionVariable.__init__o  s$     	"6"*r[   c                     t         S r   r   r   s    r\   r*  z'TreeMapOnlyFunctionVariable.python_typey  s    r[   nodec                     	 |j                         t        fd| j                  D              S # t        $ r Y yw xY w)NFc              3   6   K   | ]  }t        |        y wr   )
issubclass)r  allowed	node_types     r\   r  zDTreeMapOnlyFunctionVariable._matches_allowed_type.<locals>.<genexpr>  s     Tg:i1Ts   )r*  r   anyr  )rz   r  r  s     @r\   _matches_allowed_typez1TreeMapOnlyFunctionVariable._matches_allowed_type|  sC    	((*I TASASTTT # 		s   1 	==r   rE   r   c                    |s| j                   j                  |||      S |d   }| j                  |      r| j                   j                  |||      S t        |      dk7  s|r| j                   j                  |||      S |S )Nr   r9   )r{  r   r  r   )rz   r   r   r   leafs        r\   r   z)TreeMapOnlyFunctionVariable.call_function  s}     ;;,,Rv>>Aw%%d+;;,,Rv>>t9>V ;;,,Rv>>r[   )rW   rX   rY   r   r  r   r  r>   r   r~   r*  r  r  r   r   r   r   r  r  s   @r\   r  r  i  s    	!	0	0N
T3Y'   	
 
T U/ Ud U# ' S/)*	
 
r[   r  c            	            e Zd Z	 ddej                  dededdf fdZededefd       Z	d	d
de
e   deeef   defdZ xZS )BuiltinMethodVariabler   r  r   r]   Nc                 j    t        |   di | t        |t        j                        sJ || _        y r   )r  r~   r   r   BuiltinMethodTyper   r  s       r\   r~   zBuiltinMethodVariable.__init__  s2     	"6""e55666r[   objc                     | j                   }| j                  }|t        u xr |dk(  xs t        |      t        u xr |dk(  S )N__new____contains__)r-  rW   r   r  r  )r  method_selfmethod_names      r\   is_supported_builtin_methodz1BuiltinMethodVariable.is_supported_builtin_method  sI    llll u$A	)A 
*L{n/L	
r[   r   rE   r   c                     | j                   j                  }| j                   j                  }| j                  xr t	        | j                  d      }t        j                  |||d      }|j                  ||||      S )Nr-  T)realize)r   r-  rW   r   r(   r>   r   call_method)rz   r   r   r   r  r   
obj_sourceobj_vts           r\   r   z#BuiltinMethodVariable.call_function  sh     gg&&ww[[HZZ%H
 &&r;
DQ!!"dD&99r[   r  )rW   rX   rY   r   r  r  r   r~   staticmethodr  r   r>   r   r   r   r  r  s   @r\   r  r    s    ?D))8<PS	 
 
 
 

:#
: '
: S/)*	
:
 

:r[   r  c            
           e Zd Zdej                  deeef   dddeddf
 fdZdej                  fd	Z	defd
Z
defdZdefdZdefdZdefdZ defdZeZd&dZdeeef   fdZdefdZdddefdZdddedefdZdddefdZdddefdZdddee   fdZdddeegef   ddfdZde d   fdZ!ddd eddfd!Z"defd"Z#defd#Z$ddded$ee   deeef   def
 fd%Z% xZ&S )'LocalGeneratorObjectVariabler{   r   inline_tracerrC   r   r]   Nc                 N    t        |   di | || _        || _        || _        y r   )r  r~   r{   r   r  )rz   r{   r   r  r   r   s        r\   r~   z%LocalGeneratorObjectVariable.__init__  s+     	"6"	"*r[   c                     | j                   S r   )r{   r   s    r\   r   z%LocalGeneratorObjectVariable.get_code  s    yyr[   c                 6    | j                         j                  S r   r   r   s    r\   r   z)LocalGeneratorObjectVariable.get_filename  r   r[   c                 6    | j                         j                  S r   r   r   s    r\   r   z%LocalGeneratorObjectVariable.get_name  r   r[   c                     t        d      )Nr   r   r   s    r\   r   z)LocalGeneratorObjectVariable.get_function  s    !.11r[   c                      yNFrZ   r   s    r\   r   z%LocalGeneratorObjectVariable.has_self      r[   c                 "    | j                         S r   )r   r   s    r\   rW   z%LocalGeneratorObjectVariable.__name__  s    }}r[   c                 V    | j                   j                   d| j                          dS )N(rJ  )r   rW   r   r   s    r\   __str__z$LocalGeneratorObjectVariable.__str__  s'    ..))*!DMMO+<A>>r[   c                    ddl m} ddl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) save_and_restart_speculation_log(temporarely_allow_writes_to_output_graph)torch._dynamo.side_effectsr  torch._dynamo.symbolic_convertr  r  r   r  generator_exhaustedforce_unpack_var_sequenceremaining_itemsr   ListIteratorVariablereconstruct)
rz   codegenr  r  r  r   savedisallowtemptracers
             r\   r  z(LocalGeneratorObjectVariable.reconstruct  s    Q	

 ZZ/35b97; 	V8 	VT 	V''F--'+'E'Eb'I$**4+?+?@LLWU		V 	V 	V 	V 	V 	V 	V 	V 	Vs:   C	B=AB1B= C	1B:6B==C	C		Cc                     | j                   S r   r   r   s    r\   r   z(LocalGeneratorObjectVariable.get_globals      ~~r[   c                 "    t         j                  S r   )r   GeneratorTyper   s    r\   r*  z(LocalGeneratorObjectVariable.python_type  s    """r[   r   rF   c           	         | j                   }| j                         rt        t        |       	 |j	                         S # t
        $ r}d|_        |d }~wt        $ r+ t        ddddt         dgt        j                         Y y t        $ rq}t        j                  j                  j!                  | j#                                d|_        |j&                  s!|j(                  s|xj*                  dz  c_         d }~ww xY w)	NTzinfinite generator detected z}Dynamo traced the YIELD_VALUE bytecode too many times. This could mean that we have attempted to trace an infinite generator.zLIf you are sure that your generator is not infinite, please report a bug at .r  zA

Skipping frame due to graph break in a generator's next() call.)r  _is_generator_exhaustedr"   StopIterationinline_call_r   r  r   r$   PT2_ISSUE_TRACKER_URLr   rZ  r%   r_   rO  
eval_frame	skip_coder   
skip_frame	one_graphrG  ro  )rz   r   r  rl  s       r\   next_variablez*LocalGeneratorObjectVariable.next_variable  s    ##'')$]B7	 &&((  	)-F&G% 	5I ccxbyyz{&11	  	MM$$..t}}?AL<<(?(?^^	s(   > 	C?	A4C?C?A,C::C?rE   r   c                     || j                         j                  v rt        j                  d      S t        j                  d      S NTF)r*  __dict__r@   r   rz   r   r   s      r\   r   z-LocalGeneratorObjectVariable.call_obj_hasattr  s=     4##%...#**400&&u--r[   c                      yr  rZ   r   s     r\   has_unpack_var_sequencez4LocalGeneratorObjectVariable.has_unpack_var_sequence  r  r[   c                      yr   rZ   r   s     r\   has_force_unpack_var_sequencez:LocalGeneratorObjectVariable.has_force_unpack_var_sequence  r   r[   c                 B    g }| j                  ||j                         |S r   )force_apply_to_var_sequenceappend)rz   r   r   s      r\   r  z6LocalGeneratorObjectVariable.force_unpack_var_sequence  s"     )+((V]];r[   r   c                 j    	 	  || j                  |             # t        $ r t        |       Y y w xY wr   )r  r!   r   )rz   r   r   s      r\   r  z8LocalGeneratorObjectVariable.force_apply_to_var_sequence&  s@     4%%b)*  - )"-s    22Fc                      yr  rZ   r   s    r\   r   z=LocalGeneratorObjectVariable.should_allow_nested_graph_breaks1  r  r[   excc                     | j                   }	 |j                  |       y # t        $ r}|j                  |       Y d }~y d }~ww xY wr   )r  _raise_exception_variabler   exception_handler)rz   r   r  r  rl  s        r\   _setup_exceptionz-LocalGeneratorObjectVariable._setup_exception4  sE     ##	(,,S1  	( $$Q''	(s     	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_started?  s*    !!T)XT-?-?-S-SWX-XXr[   c                 0    t        | j                  dd      S )Nr  F)r   r  r   s    r\   r  z4LocalGeneratorObjectVariable._is_generator_exhaustedB  s    t))+@%HHr[   r   c                 h   |dk(  r| j                  |      S |dk(  r| S |dk(  rk| 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                  S 	 | j                  |t        j                  t        d             t        j                   dk\  r0|j"                  j$                  d	k(  rd|_	        t        j                  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  ||||      S # t&        $ r d|_	        t        j                  cY S w xY w# t&        $ r d|_	        t        j                  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   | ]  }|j                           y wr   )is_constant_noner  rh  s     r\   r  z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>X  s     Bc3//1Br  closeTrZ   )r     CALL_INTRINSIC_1throwr  r9   r   __InternalThrowException)r  r%  r   r  r"   r   r  	push_manyr  r  r   r?   r"  ExceptionVariableGeneratorExitr  version_infonext_instructionopnamer    rS  r!   symbolic_resultr   r  rX  r   r  r  )	rz   r   r   r   r   r  retvalexc_typer   s	           r\   r  z(LocalGeneratorObjectVariable.call_methodE  s    :%%b))ZKV^ ..0SY BTBB,Y;''FT"%%b))W_ ''F..0D4P4P4R-1* 7778%%	33M2F( $$///66:LL15F.$;;;.%%b),\2> W_ ''F
 %%bSY!^$q'aQ
 ''+F| 6bIH?%%b)*E*EhPR*ST""2&
 )v>Mw"2tT6::a ) 8-1* 7778 ) 8-1* 777, .
 --999---., % N 1:  MsI   A,H! !I :(J 7J ! II J)"JJJJ10J1r  rB   r]   N)'rW   rX   rY   r   r   r   r   r   r~   r   r   r   r   r   r  r   r  __repr__r  r   r  r*  r>   r  r@   r   r  r  r   r  r   r  r
   r   r"  r%  r  r  r  r  s   @r\   r  r    s   
+nn
+ S>
+ @	
+
 
+ 

+%.. +c +'# '2e 2$ # ? ? HV$T#s(^ #T # ;  B.).14.	.*A d 0G D -	o	-3;_<Ms<R3S	'%. 	()	(0?	(		(YD YI Iw;#w; w; ?#	w;
 S/)*w; 
w; w;r[   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)rW   rX   rY   r   rZ   r[   r\   r?  r?    s    r[   r?  c            	            e Zd ZdZeddedededdf fdZd	e	defd
Z
dej                  fdZdee	ef   fdZdefdZdddee   dee	ef   ddfdZdddee   dee	ef   defdZ xZS )LocalGeneratorFunctionVariablezxfunctions that behaves like iterators

    .. note::

        This is a wrapper around (Nested)UserFunctionVariable
    )generator_clsvtrB  r   r]   Nc                @    t        |   di | || _        || _        y r   )r  r~   rC  rB  )rz   rC  rB  r   r   s       r\   r~   z'LocalGeneratorFunctionVariable.__init__  s$     	"6"*r[   r   c                 v    || j                   j                  v rt        | |      S t        | j                  |      S r   )r   r  r   rC  )rz   r   s     r\   __getattr__z*LocalGeneratorFunctionVariable.__getattr__  s2    4>>***4&&tww%%r[   c                 6    | j                   j                         S r   )rC  r   r   s    r\   r   z'LocalGeneratorFunctionVariable.get_code%      ww!!r[   c                 6    | j                   j                         S r   )rC  r   r   s    r\   r   z*LocalGeneratorFunctionVariable.get_globals(  s    ww""$$r[   c                 6    | j                   j                         S r   )rC  r   r   s    r\   r   z'LocalGeneratorFunctionVariable.has_self+  rH  r[   r   rF   r   rD   c                 8    ddl m}  |j                  || ||      S )Nr   )rD   )r  rD   build_inline_tracer)rz   r   r   r   rD   s        r\   _build_inline_tracerz3LocalGeneratorFunctionVariable._build_inline_tracer.  s*     	Q@,@@	
 	
r[   rE   c                    t        | j                  j                               s2t        dt	        | j                  j                               dddg       | j                  |t        |      |      }| j                  j                         }| j                  j                         }| j                  |||| j                        S )Nz'non-generator contextlib.contextmanagerzvCannot compile function decorated with `@contextlib.contextmanager` that is not a generator, i.e. does not use `yield`z5Use `yield` in the function body instead of `return`.z2Remove the `@contextlib.contextmanager` decorator.r  r  )
r   rC  r   r$   r   rM  r   r   rB  r   )rz   r   r   r   r  r{   r   s          r\   r   z,LocalGeneratorFunctionVariable.call_function=  s     DGG,,./ADGG,,./. LH	 11"d4j&Iww!GG'')	 !!;;	 " 
 	
r[   )rW   rX   rY   r   r  r   r  r   r~   r   rF  r   r   r   r   r   r  r   r   r>   rM  r   r   r  r  s   @r\   rA  rA    s     ;		+$	+ 		+
 	+ 
	+& & &"%.. "%T#s(^ %"$ "
'
 ?#
 S/)*	

 
)

#
 '
 S/)*	

 

r[   rA  c                   \     e Zd ZdZdededdf fdZddd	ee   de	e
ef   dd
f fdZ xZS )3FunctionDecoratedByContextlibContextManagerVariablezm
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager
    rC  r   r]   Nc                 2    t        |   |fdt        i| y )NrB  )r  r~   r?  )rz   rC  r   r   s      r\   r~   z<FunctionDecoratedByContextlibContextManagerVariable.__init__e  s%    	
N	
 	
r[   r   rF   r   rC   c                     t         |   |||      }t        |t        j                  j
                  j                        sJ d|_        |S r   )r  rM  r   r_   rO  symbolic_convertrC   is_generator_from_ctx_manager)rz   r   r   r   r  r   s        r\   rM  zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracerl  sO     -b$?MM**QQ
 	
 
 04,r[   )rW   rX   rY   r   r   r   r~   r   r>   r   r   rM  r  r  s   @r\   rP  rP  \  sb    
3 
s 
t 
' ?# S/)*	
 
2 r[   rP  c                        e Zd ZdZ	 ddedef   dededz  deddf
 fd	Zde	fd
Z
dee   fdZdeej                     fdZdddee   dee	ef   def fdZddde	def fdZ xZS )r0  z$Some unsupported user-defined methodNr   .r  r1  r   r]   c                     t        |   dd|i| || _        || _        |3|j	                  d      !t        |j	                  d      d      | _        y y y )Nr   r   __func__rZ   )r  r~   r  r1  r   r(   )rz   r   r  r1  r   r   s        r\   r~   zUserMethodVariable.__init__  s^     	)B)&)" H!5!A'

8(<jIDN "Br[   c                 h    | j                   j                   d| j                   d| j                   dS )Nr  rI  rJ  )r   rW   r   r  r   s    r\   r=  zUserMethodVariable.__repr__  s.    ..))*!DGG9BtxxjBBr[   c                     | j                   gS r   r  r   s    r\   r   zUserMethodVariable.self_args      zr[   c                 "    t         j                  S r   )r   
MethodTyper   s    r\   r*  zUserMethodVariable.python_type  s    r[   r   rE   r   c                 4   ddl m}m}  || j                        rjg | j	                         |}t        j                  | j                  t
        j                  j                  j                        }|j                  |||      S  || j                        rjg | j	                         |}t        j                  | j                  t
        j                  j                  j                        }|j                  |||      S |j                  j                         rt        | j                  t
        j                         rt#        | j                  dd      }||j%                  d      r|dk7  s| j&                  r| j                  j)                  || j                  j*                  t-        |      || j&                        S t.        d| j                  t.        j0                  j2                  u r>t        j4                  | j                        j                  || j                  g||      S | j&                  rQt#        | j                  j6                  | j                  j*                        }	t9        ||	| j;                         ||      S t<        
| )  |||      S )	Nr   )is_leaf_functionis_nonstrict_trace_callablerK  rX   r  z	torch.nn.ztorch.nn.utils.parametrize)constant)trace_rulesr_  r`  r   r   r   r[  r_   r\  r]  r   LEAF_FUNCTIONr   is_root_tracerr   r  NNModuleVariabler   
startswithr  r  rW   r   rA   FSDPParamGroupuse_training_stateTorchCtxManagerClassVariabler	  r^  r   r  )rz   r   r   r   r_  r`  	call_argsvarmodule_attrr   r   s             r\   r   z UserMethodVariable.call_function  s    	P&tww/2$..*2T2I88ioo>>NNC $$RF;;DGG$2$..*2T2I88ioo>>LLC $$RF;; 99##%*HHi00+
 "$''<<K '**;7#??##xx++(($t*ftGWGW ,   ),;;NNN99$''BPPTXX%%v  )9)9:B/BvVVw$Rv66r[   r   c                     |dk(  r| j                   S |dk(  r+t        j                  || j                  | j                        S t
        |   ||      S )Nr-  rW  )r  r>   r   r   r1  r  rD  rz   r   r   r   s      r\   rD  zUserMethodVariable.var_getattr  sM    :88O: #((TWWdnnEEw"2t,,r[   r   )rW   rX   rY   r   r   r   r>   r   r~   r   r=  r   r   r  r   r]  r*  r   r   r   rD  r  r  s   @r\   r0  r0    s    . $(	JS#XJ J D=	J
 J 
J2C# C40  T%"2"23  B7#B7 'B7 S/)*	B7
 
B7H-5 -S -_ - -r[   r0  c                   d     e Zd Zdedddeddf fdZdd	d
ee   dee	ef   def fdZ
ddZ xZS )WrappedUserMethodVariablewrappedr  rG   r   r]   Nc                     |j                  dd        |j                  dd        t        |   |j                  |j                  fi | || _        || _        y )Nr   r  )r   r  r~   r   r  rq  r  rz   rq  r  r   r   s       r\   r~   z"WrappedUserMethodVariable.__init__  sK     	

4

5$W[[;F;r[   r   rE   r   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r   r  enterr  r   exitrz   r   r   r   r   r   s        r\   r   z'WrappedUserMethodVariable.call_function   A     	2&r48"r[   c                      j                   fd         j                         j                  t        dd             y )Nc                  (      j                         S r   r  r  rz   s   r\   <lambda>z7WrappedUserMethodVariable.reconstruct.<locals>.<lambda>      gdll&; r[   r9   Fadd_push_nullrq  extend_outputr   rz   r  s   ``r\   r  z%WrappedUserMethodVariable.reconstruct  4    ;<21e<=r[   r<  )rW   rX   rY   r0  r   r~   r   r>   r   r   r   r  r  r  s   @r\   rp  rp    sm    
#
 +
 	

 

	#	 '	 S/)*		
 
	>r[   rp  c                   d     e Zd Zdedddeddf fdZdd	d
ee   dee	ef   def fdZ
ddZ xZS )WrappedUserFunctionVariablerq  r  rG   r   r]   Nc                 z    |j                  dd        t        |   |j                  fi | || _        || _        y )Nr   )r   r  r~   r   rq  r  rs  s       r\   r~   z$WrappedUserFunctionVariable.__init__  s7     	

4.v.r[   r   rE   r   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r   ru  rx  s        r\   r   z)WrappedUserFunctionVariable.call_function  ry  r[   c                      j                   fd         j                         j                  t        dd             y )Nc                  (      j                         S r   r|  r}  s   r\   r~  z9WrappedUserFunctionVariable.reconstruct.<locals>.<lambda>)  r  r[   r9   Fr  r  s   ``r\   r  z'WrappedUserFunctionVariable.reconstruct(  r  r[   r<  )rW   rX   rY   r  r   r~   r   r>   r   r   r   r  r  r  s   @r\   r  r    sm    	%	 +	 		
 
		#	 '	 S/)*		
 
	>r[   r  c                    dt         dt        fd}|D cg c]
  } ||       }}|j                         D ci c]  \  }}| ||       }}} ||i |}	| j                  j	                  |	|t        |            S c c}w c c}}w )Nxr]   c                 v    | j                         rt        d|       j                         S | j                         S )NrL   )	is_tensorr	   get_real_valuer"  )r  s    r\   convertz-invoke_and_store_as_constant.<locals>.convert5  s1    ;;=(!,;;==##%%r[   r  )r>   r   r   r   register_attr_or_moduler+   )
r   r   r   r   r   r  r  r   r   ress
             r\   r^  r^  .  s    &? &s &
 !%%1GAJ%D%(.71am7F7
d
f
C99,,d# -   &7s
   A>Bc                   R    e Zd Zdhej                  Z	 d%dededeeef   dedz  dedz  dedz  dedz  d	edz  d
eddf fdZ	de
e   fdZdej                  fdZdej                  fdZdeej                     fdZd%dee   dz  dej                  fdZdefdZdee   dej                  fdZdddededefdZdddedee   d
eeef   def
 fdZdefdZdddedef fdZdddedef fdZdefd Z deeef   fd!Z!d"ddee   d
eeef   deeef   fd#Z"d&d$Z# xZ$S )'r   r   Nrp  r{   r   r   r   r   
wrapped_fnr   r]   c	                    |	j                  d      |	j                  t                      t        
|   di |	 t        |j                         t              sJ t        |j                         t        j                        sJ t        |t              sJ || _        || _        || _        || _        || _        || _        || _        || _        y )Nmutation_typer  rZ   )r   updater;   r  r~   r   r"  r   r   r   r   rp  r{   r   r   r   r   r   r  )rz   rp  r{   r   r   r   r   r   r  r   r   s             r\   r~   z#NestedUserFunctionVariable.__init__J  s     ::o&.MM(<(>M?"6"'446<<<$113U^^DDD)T***	" $&2<r[   c                     g S r   rZ   r   s    r\   r   z$NestedUserFunctionVariable.self_argsg  r   r[   c                 "    | j                         S r   )r   r   s    r\   r"  z-NestedUserFunctionVariable.as_python_constantj  s      ""r[   c                 6    | j                   j                         S r   )r{   r"  r   s    r\   r   z#NestedUserFunctionVariable.get_codem  s    yy++--r[   c                 "    t         j                  S r   r)  r   s    r\   r*  z&NestedUserFunctionVariable.python_typep  r+  r[   _convertingc                     ddl m} t        |       }|
t               }||v rt	        d      |j                  |       	 | j                  |      |j                  |       S # |$ r}t	        d      |d }~ww xY w# |j                  |       w xY w)Nr9   )r:   z-cycle detected in mutually recursive closuresz1failed to convert closure cell to Python constant)baser:   idsetrV   add_get_function_impldiscard)rz   r  r:   self_idrl  s        r\   r   z'NestedUserFunctionVariable.get_functions  s     	>T(%Kk!(?  	 	)**;7 ( 3 	(C	
 (s#   A! !A7&A22A77A: :Bc                 P    	 | j                          y# t        t        f$ r Y yw xY wr  )r"  r   r%   r   s    r\   r  z-NestedUserFunctionVariable.is_python_constant  s-    	##%#[1 		s    %%c                    d }| j                   rddlm}  |j                         }g }| j                   j                  D ]  }|j
                  j                  j                  |      }|| u rt        d      t        |t              r|j                  |      }n|j                         }|j                  t        |              t        |      }t!        j"                  | j$                  j                         | j&                  | j(                  j                         d |      }	| j*                  r| j*                  j                         |	_        | j.                  r| j.                  j                         |	_        | j2                  rZ| j2                  j                         }
t        |
t              rddlm} t9         ||
            }
t        |
t8              sJ |
|	_        |	S )Nr   )rE   z self-referential nested function)argdefsr   r   )r   r  rE   
current_txr   r   r   	load_cellrV   r   r   r   r"  r  r8   r   r   r   r{   r   rp  r   r   r   r   r   r   r   r   r   )rz   r  closure_cellsrE   r   cellsr=  r4  r	  rf   r   r   s               r\   r  z-NestedUserFunctionVariable._get_function_impl  s   <<L1&113BE LL.. / !#		 6 6 @ @ J !D(01STT m-GH)66{CE)<<>EYu-.-/. "%LM!!II((*NNLL++-!
 == $ @ @ BD??"&//"D"D"FD**==?K+u-."8K#89 k4000#.D r[   r   rE   name_varr   c                 p    |j                   j                  j                  | |j                  |       t        S r   )r   r   
store_attrr	  r?   )rz   r   r  r   s       r\   call_setattrz'NestedUserFunctionVariable.call_setattr  s*     			))$D%%r[   r   r   c                 j    |dk(  r | j                   |g| S t        | 	  ||t        |      |      S )N__setattr__)r  r  r  r   rz   r   r   r   r   r   s        r\   r  z&NestedUserFunctionVariable.call_method  s?     = $4$$R/$//w"2tT$Z@@r[   c                     | j                   d uS r   )r   r   s    r\   has_closurez&NestedUserFunctionVariable.has_closure  s    ||4''r[   c                     |dk(  r| j                         S |dk(  r| j                         S |dk(  r!t        | dd       }|r|j                         S d S t        |   ||      S )NrW   ri   r   r   )r   r   r   r"  r  const_getattr)rz   r   r   dr   s       r\   r  z(NestedUserFunctionVariable.const_getattr  si    :==?":==?">!j$/A-.1'')8D8w$R..r[   c                     |dk(  r)t         j                  j                  t        | d            S |dk(  r)t         j                  j                  t        | d            S t        |   ||      S )Nri   r{   r   r   )r   r@   r   r   r  r   rn  s      r\   r   z+NestedUserFunctionVariable.call_obj_hasattr  sc     :--44WT65JKK>!--44WT:5NOOw'D11r[   c                      yr  rZ   r   s    r\   r   z#NestedUserFunctionVariable.has_self  r  r[   c                     | j                   S r   r  r   s    r\   r   z&NestedUserFunctionVariable.get_globals  r  r[   r   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r   )r8   )r  _s     r\   r  z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>  s     Sa)D/Ss   )r   r   r   r   rp  r"  r   r   r   r   r   r7  r   keys_as_python_constantr   r   rT  rU  apply_defaultsr   rV  r   r   r6  r   r   r   )rz   r   r   r   r{   rf   rN   r   r   r   r<  s              r\   rA  z$NestedUserFunctionVariable.bind_args  sJ    }}!!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	 
 r[   c                 H   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"                  rvj                  fd        | j"                         j                  t!        dd             j                  t%        d             j                  t!        dd             j&                  }|j(                  j*                  j-                  |       r}|j(                  j*                  j.                  |    j1                         D ]H  \  }}j3                           |       j                  t%        d             j5                  |       J y y # t        $ r  | j                         Y jw xY w)Nc                  0     j                  t        d      S )Nr   )load_import_fromrW   r  s   r\   r~  z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>  s    G,,X7JK r[      Fc                  (     j                  dd      S )N	functoolswrapsr  r  s   r\   r~  z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>;  s    00gF r[   r9   r   T)r  r{   r  create_load_const_uncheckedr   r@   r   r	  r   r   create_load_constr   r   r   r"  r   r   r  r   r   r   r   has_pending_mutationstore_attr_mutationsr   dup_topr  )rz   r  r   r   r   r	  s    `    r\   r  z&NestedUserFunctionVariable.reconstruct  sv   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$"?@ ZZ99!!66t<!yy55JJ eg)e !%%l1o6""4() =% ' *(()*s   ;L L! L!r   r<  )%rW   rX   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@   r   r   r   rA  r  r  r  s   @r\   r   r   D  s_   	!	0	0N  .2= = = S>	=
 "D(= $d*= %t+= !4'= $d*= = 
=:40 #E$6$6 #.%.. ."T%"4"45 ")C4 )5CUCU ),D 6c#h 65;M;M 6p&#& "& 	&
 
&	A#	A 	A '		A
 S/)*	A 
	A(T (/ 7 /s /s /2)2142	2$ T#s(^ ' ' S/)*	
 
c?"	#:6)r[   r   c                   d     e Zd Zdedddeddf fdZdd	d
ee   dee	ef   def fdZ
ddZ xZS )!WrappedNestedUserFunctionVariablerq  r  rG   r   r]   Nc           
         |j                  dd        |j                  dd        |j                  dd        |j                  dd        |j                  dd        |j                  dd        |j                  dd        |j                  dd        t        | 	  |j                  |j                  |j
                  |j                  |j                  |j                  |j                  |j                         || _        || _        y )	Nrp  r{   r   r   r   r   r   r  )r   r  r~   rp  r{   r   r   r   r   r   r  rq  r  rs  s       r\   r~   z*WrappedNestedUserFunctionVariable.__init__O  s     	

9d#

64 

;%

:t$

<&

=$'

9d#

<&OOLLOO		
 r[   r   rE   r   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r   ru  rx  s        r\   r   z/WrappedNestedUserFunctionVariable.call_functionj  ry  r[   c                      j                   fd         j                         j                  t        dd             y )Nc                  (      j                         S r   r|  r}  s   r\   r~  z?WrappedNestedUserFunctionVariable.reconstruct.<locals>.<lambda>v  r  r[   r9   Fr  r  s   ``r\   r  z-WrappedNestedUserFunctionVariable.reconstructu  r  r[   r<  )rW   rX   rY   r   r   r~   r   r>   r   r   r   r  r  r  s   @r\   r  r  N  sm    + + 	
 
6	#	 '	 S/)*		
 
	>r[   r  c            	            e Zd Zddhej                  Zddededz  deddf fdZdefdZe	dede
dd fd	       Zd
ddee   deeef   defdZd
ddedefdZd
ddedefdZdefdZdefdZdedefdZ xZS )SkipFunctionVariabler	  reasonNr   r]   c                 @    t        |   di | || _        || _        y r   )r  r~   r	  r  )rz   r	  r  r   r   s       r\   r~   zSkipFunctionVariable.__init__  s!    "6"
r[   c                     | j                   S r   r	  r   s    r\   r"  z'SkipFunctionVariable.as_python_constant  s    zzr[   r   c                    t        j                  |dd      rW|}|}t        |dd      r&|j                  }t	        |d      }t        |dd      r&|j                  t        j                         nqt        j                  |      r)t        |j                  t        j                               n3t        |      s(t        |j                  t        j                                | ||      S )N_torchdynamo_disableF_torchdynamo_orig_callabler  )r   r   r   r  r(   r  r&   r  	isbuiltinr'   BUILTIN_MATCHr6   )r  r	  r   guard_on_sourceguard_on_values        r\   r  z'SkipFunctionVariable.create_with_source  s     !!%)?G %O"N.*FN!/!J!J",#%A# .*FN &&|'A'ABu%&++L,F,FGH07 &++L,F,FGH5((r[   r   rE   r   c                 *   t        j                  | j                  dd      rVt        j                  | j                  dd       }t        dt	        | j                        d| j                   d| ddg	       y | j                  t
        j                  j                  u r>|j                  d
      }|r|j                         }t        dd| d| dd| dg	       y | j                  t
        j                  j                  u rX|j                  d
      }|r|j                         }nd}t        dd| d| dt        |j                         dd| dgd       y | j                  t
        j                  j                  u r	 t        ddddg	       y t"        j$                  rEddlm} |j+                  || j                        }	t-        |	t.              s|	j1                  |||      S t3        | j                  dd       }
t3        | j                  d!d       }|d"n
t	        |      }	 t        j4                  | j                        }d#|
 d$| d%}d&|
 d'g}d(|vr|d)|
 d*d+gz  }|
d9k(  rd:}g }| j@                  r| j@                  nd;}t        d<d=| d>|
 d?| ||	       y # t        $ r}t        |j                         d d }~ww xY w# t6        $ r d,d-h}||v rd.| d|
 d'}d/d0g}n|\|j9                  d1      rKd2| d|
 d}d3g}t
        j                  j:                  j=                  |d4z   d4j?                  |      z          nKd5| d|
 d6}d7d8g}t
        j                  j:                  j=                  |d4z   d4j?                  |      z          Y .w xY w)@Nr  F_torchdynamo_disable_msgz1Skip calling `torch.compiler.disable()`d functionzSkip calling function `z>` since it was wrapped with `torch.compiler.disable` (reason: rJ  z(Remove the `torch.compiler.disable` callr  ro  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$Call to `torch._dynamo.skip_frame()`z/Called `torch._dynamo.skip_frame()` with args `z`. Skipping frame r  z#User-inserted skip frame. Message: z-Remove the `torch._dynamo.skip_frame()` call.T)r  r  r  r  r  z*Call to `torch._dynamo.step_unsupported()`zUser-inserted step_unsupported.z3Remove the `torch._dynamo.step_unsupported()` call.r9   SourcelessBuilderrY   z<unknown qualname>rX   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`.rO  z:Apply `@torch._dynamo.dont_skip_tracing` to the function `zw` to force tracing into the function. 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. r  z*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: )!r   r   r	  r$   r   r_   rO  graph_breakr   r"  r  r   f_codestep_unsupportedr%   r#   ro  r   dont_skip_tracingbuilderr  r   r   r  r   r   getfiler   rf  r`   	warn_oncejoinr  )rz   r   r   r   ro  graph_break_msgskip_frame_msgrl  r  
rebuilt_fnqualname	module_orr  pathr  r  known_python_builtin_modulesr  s                     r\   r   z"SkipFunctionVariable.call_function  s>    !!$**.DeL((5OQUVCKDJJ5djj\ B::=aA ? ZZ5==444$jj/O"1"D"D"F?J4&P[\b[ccdeB?BSTD	 ZZ5==333#ZZ.N!/!B!B!D!#>I${[aZb c""3BII">!?qBA.AQRC  	 ZZ5==999
7H AM	 ''6 /55b$**E
!*.BC%33BfEEtzz>;OPH

L$?I090A,s9~K8Ytzz2UV^U_ `  $v%<> 
 38*B? D(TU]T^ _l l ;	 EX ++?  $(KKT[[5GFF";-|H:_U[T\]'	a  7%aee,$67B  %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+   J %>K 	K(J>>KCNNr   c                 h    t         j                  j                  t        | j                  |            S r   )r   r@   r   r   r	  r  s      r\   r   z%SkipFunctionVariable.call_obj_hasattr3  s&     ))00T1JKKr[   c                     |t         v rt        j                  | |      S t        || j                  | j
                  |      S r   )r3   r   rC  r   r	  r   r  s      r\   rD  z SkipFunctionVariable.var_getattr8  s7    )),,T488b$**dkk4@@r[   c                      yr   rZ   r   s    r\   r  z'SkipFunctionVariable.is_python_hashable>  r   r[   c                 ,    t        | j                        S r   )r  r	  r   s    r\   r  z$SkipFunctionVariable.get_python_hashA  s    DJJr[   r  c                 h    t        |t              xr! | j                         |j                         k(  S r   )r   r>   r"  r  s     r\   r  z$SkipFunctionVariable.is_python_equalD  s1    uo. H'')U-E-E-GG	
r[   r   )rW   rX   rY   r>   r  r   r   r~   r"  r  r   r  r   r   r   r@   r   rD  r  r  r  r  r  r  r  r  s   @r\   r  r  {  s'    
	'	'Nc 3:  PT 
C  )s )F )?U ) )4L#L 'L S/)*	L
 
L\L)L14L	L
A5 AS A_ AD    
V 
 
r[   r  c                   d     e Zd Zdedddeddf fdZdd	d
ee   dee	ef   def fdZ
ddZ xZS )WrappedSkipFunctionVariablerq  r  rG   r   r]   Nc                     |j                  dd        |j                  dd        t        |   |j                  fd|j                  i| || _        || _        y )Nr	  r  )r   r  r~   r	  r  rq  r  rs  s       r\   r~   z$WrappedSkipFunctionVariable.__init__L  sN     	

7D!

8T"Hw~~HHr[   r   rE   r   c                     | j                   j                  |       t        |   |||      }| j                   j	                  |       |S r   ru  rx  s        r\   r   z)WrappedSkipFunctionVariable.call_functionX  ry  r[   c                      j                   fd         j                         j                  t        dd             y )Nc                  (      j                         S r   r|  r}  s   r\   r~  z9WrappedSkipFunctionVariable.reconstruct.<locals>.<lambda>d  r  r[   r9   Fr  r  s   ``r\   r  z'WrappedSkipFunctionVariable.reconstructc  r  r[   r<  )rW   rX   rY   r  r   r~   r   r>   r   r   r   r  r  r  s   @r\   r   r   K  sm    
%
 +
 	

 

	#	 '	 S/)*		
 
	>r[   r   c                        e Zd ZdZdedededdf fdZdd	d
edef fdZde	e   fdZ
dd	dee   deeef   def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".
    wrapper_objattr_to_tracer   r]   Nc                 @    t        |   di | || _        || _        y r   )r  r~   r  r  )rz   r  r  r   r   s       r\   r~   z$WrapperUserFunctionVariable.__init__q  s#    "6"&*r[   r   rE   r   c                     || j                   k(  r[t        | j                  | j                         }| j                  xr t	        | j                  |      }t        j                  |||      S t        | !  ||      S r   )	r  r   r  r   r(   r>   r   r  rD  )rz   r   r   r   r   r   s        r\   rD  z'WrapperUserFunctionVariable.var_getattrv  si    4%%%$**D,>,>?C[[BZT%BF"((S&99w"2t,,r[   c                     g S r   rZ   r   s    r\   r   z%WrapperUserFunctionVariable.self_args~  r   r[   r   c           
         t        | j                  d      rt        | j                  | j                  d       }t        |dd      xs d}|j	                  dd      d   dk7  r|j                         }t        j                  j                  |j                        }|j                  }d	| d
| ddj                  t        j                  |g             }	t        j                  j                   j#                  |	       t        j                  j                   j$                  j'                  d      }
|
j)                  t$        j*                        rt        j,                  j.                  j1                         }t3               |z   }|d   j                  |d   j                  f}dj                  t        j                  |            }d|d    d
|d    d}|t5        |      z  }|
j7                  |       | j9                         t;        |      z   }t=        j>                  t@        jB                        jE                  || t=        jF                  | j                        g||      S )N
cache_inforX   r  r  r9   )maxsplitr   r_   zGDynamo detected a call to a `functools.lru_cache`-wrapped function at ':z'. Dynamo ignores the cache wrapper and directly traces the wrapped function. Silent incorrectness is only a *potential* risk, not something we have observed. Enable TORCH_LOGS=+dynamo for a DEBUG stack trace.

This call originates from:
ztorch._dynamoz)call to a lru_cache wrapped function at: r  )$r   r  r   r  splitframe_summaryosr  basenamefilenamelinenor  	tracebackformat_listr_   rO  r`   r  logging	getLoggerisEnabledForDEBUG_guardsTracingContextextract_stackr   r   debugr   r   r   r  r   getattr_and_tracer   r@   )rz   r   r   r   	target_fnr  r  r  r  ro  dynamo_logger
user_stack	frame_locuser_stack_formatteduser_stack_traceall_argss                   r\   r   z)WrapperUserFunctionVariable.call_function  s    4##\2 0 0$2D2DdKI!)\2>D"K  q 1!4? " 0 0 277++M,B,BC&--$$,:Qvh 73 wwy44m_EFGI  ##--c2 % 3 3 ; ; E Eo V --gmm<!&!=!=!K!K!MJ!7!9J!FJ!+B!8!8*R.:O:O PI+-7793H3H3T+U()RS\]^S_R``abklmbnaooq'r$$,@(AA$!''(89>>#d4j0--''

-9--d.@.@AMHM
	
r[   )rW   rX   rY   r   r   r   r~   r>   rD  r   r   r   r   r   r  r  s   @r\   r  r  i  s    +C + +s +t +
-5 -S -_ -40 ,
#,
 ',
 S/)*	,

 
,
r[   r  c            
       J     e Zd ZdZdededededdf
 fdZdee   fd	Z	 xZ
S )
WrapperUserMethodVariablez
    Similar to WrapperUserFunctionVariable, but for methods. The only delta is
    saving the vt for `self` object of the method which is then used by
    WrapperUserFunctionVariable in `call_function` method.
    r  r  self_objr   r]   Nc                 6    t        |   ||fi | || _        y r   )r  r~   r  )rz   r  r  r+  r   r   s        r\   r~   z"WrapperUserMethodVariable.__init__  s      	m>v>r[   c                     | j                   gS r   rZ  r   s    r\   r   z#WrapperUserMethodVariable.self_args  r[  r[   )rW   rX   rY   r   r   r   r>   r~   r   r   r  r  s   @r\   r*  r*    sN      "	
  
40 r[   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_collectivesr0  r/  s    r\   _traceable_collective_remapsr4    s&    %%'	
 +*Ir[   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_   r1  r2  r4  valuesrW   import_sourcer(   )r   r   
inner_namepath_sources       r\   _traceable_collectives_sourcer:    sd     ))+B-BB+-/668888J""#NOKk:..r[   c                        e Zd ZdZdedef   dededdf fdZed	d
dedef   de	dedd f
d       Z
ededefd       Zed	d
dedef   deeef   fd       Zd	d
dee   deeef   def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.
    r   .replacement_varr   r]   Nc                X    t        |   |fi | t        |t              sJ || _        y r   )r  r~   r   r  r=  )rz   r   r=  r   r   s       r\   r~   z*CollectiveFunctionRewriteVariable.__init__  s0     	&v&/+?@@@.r[   r   rE   old_fnr   optionsc                 j    t         j                  | |      \  }}t        |ft        |fd|i||d|S )Nr   )r=  r   )r<  rw  r  )r   r?  r   r@  new_fn
new_sources         r\   r   z(CollectiveFunctionRewriteVariable.create  sO     ?FFr6R
0
0V
VgV
 	
 	
r[   variablec                 H    t        j                  |       xr | t               v S r   )r   
isfunctionr4  )rD  s    r\   can_rewritez-CollectiveFunctionRewriteVariable.can_rewrite 	  s%     x(WX9U9W-W	
r[   c                 8    t               |   }|t        | |      fS r   )r4  r:  )r   r   rB  s      r\   rw  z)CollectiveFunctionRewriteVariable.rewrite	  s$     ./34R@@@r[   r   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_STRrZ   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.distributedr1  r3  rJ  r   rT  r   r   rU  rV  r"  r$   r   SUPPORTABLE
all_reducereduce_scatter_tensor_reduce_scatter_baser   r	  
parametersdefaultr9  r   r@   r   r=  r   )	rz   r   r   r   distrJ  rT  reduce_op_var	reduce_ops	            r\   r   z/CollectiveFunctionRewriteVariable.call_function	  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Cr[   )rW   rX   rY   r   r   r   r  r~   r  r   r   r  rG  r   r(   rw  r   r>   r   r   r   r  r  s   @r\   r<  r<    s+   	/S#X	/ .		/
 	/ 
	/ 
#
c"
 
 	

 
-
 
 
c 
d 
 

 A#A)1#s();A	sJ	A A-D#-D '-D S/)*	-D
 
-Dr[   r<  c                   @     e Zd Zdddee   deeef   def fdZ xZS )FunctoolsWrapsVariabler   rE   r   r   r]   c                     |s5t              dk(  r'dt        dt        ffd}t        j                  |      S t
        |   ||      S )Nr9   r   r]   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  )r   r   r   cloner$   r   rO  )r   r   s    r\   r  z3FunctoolsWrapsVariable.call_function.<locals>.wrapsF	  sN    b)"F"FG88tAw877-!d *66	r[   )r   r   r>   r   LambdaVariabler  r   )rz   r   r   r   r  r   s     `  r\   r   z$FunctoolsWrapsVariable.call_function>	  sL     #d)q.
# 
/ 
 ++E22w$Rv66r[   )	rW   rX   rY   r   r>   r   r   r   r  r  s   @r\   rY  rY  =	  sB    7#7 '7 S/)*	7
 
7 7r[   rY  c                   @    e Zd ZdefdZdddee   deeef   defdZ	y)	CollectionsNamedTupleFunctionr]   c                     | j                   S r   r%  r   s    r\   r"  z0CollectionsNamedTupleFunction.as_python_constantX	  r&  r[   r   rE   r   r   c                 ,   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 # t        $ rL}	t        t        |	      |t        t        t        j                  |	j                                     Y d }	~	d }	~	ww xY w)N)r   r  znamedtuple constructionzargs=rL  z?`torch.compile` only support certain input types for namedtupler  )r1   r   r"  r   r   r"   r  r   mapr@   r   r   r   UserDefinedClassVariabler=   r$   r   rO  )
rz   r   r   r   constant_argsr  r   r   r	  r  s
             r\   r   z+CollectionsNamedTupleFunction.call_function[	  s    ,D&9
6:;a**,;=C\\^LTQq!..00L 55.0 
 	-tgZy)Y"..		
 <L (Ic"2"9"9388DE s4   B> B3B> B8(B> 3B> >	DADDN)
rW   rX   rY   r   r"  r   r>   r   r   r   rZ   r[   r\   r_  r_  W	  sH    C 
#
 '
 S/)*	

 

r[   r_  c                       e Zd Zdhej                  Z	 ddedee   deeef   dededdf fdZ	de
fd	Zdd
ZdefdZdddee   deeef   defdZdddedefdZdddedefdZdefdZdefdZdefdZdefdZdedefdZ xZS )FunctoolsPartialVariableoriginal_cache_hashNrf   r   keywordsr   r]   c                     t        |   di | || _        t        |t              sJ || _        t        |t              sJ || _        t        j                  t              | _        || _        y r   )r  r~   rf   r   r   r   r   rh  r  partialr4   
fake_valuerg  )rz   rf   r   rh  rg  r   r   s         r\   r~   z!FunctoolsPartialVariable.__init__	  sf     	"6"	$%%%	(D)))  $++H5#6 r[   c                 "    t         j                  S r   )r  rj  r   s    r\   r*  z$FunctoolsPartialVariable.python_type	  s       r[   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  rj  r  r  s   r\   r~  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>	  s    g&>&>{I&V r[   r9   F)r  rf   r   foreachrh  r  r   r   r6  r   keyscreate_call_function_kw)rz   r  rp  s    ` r\   r  z$FunctoolsPartialVariable.reconstruct	  s    VW		99OODII&}}!!"6s499~7I5"QR,,./T]]'')*++CIDII,F,JDRWX	
r[   c                 "    | j                         S r   r"  r   s    r\   r   z%FunctoolsPartialVariable.get_function	      &&((r[   r   rE   c                     | j                   t        |      z   }i | j                  |}| j                  j	                  |||      S r   )r   r   rh  rf   r   )rz   r   r   r   merged_argsmerged_kwargss         r\   r   z&FunctoolsPartialVariable.call_function	  sB     ii$t*,34==3F3yy&&r;FFr[   r   c                     t         j                  j                  t        t	        j
                  t              |            S r   )r   r@   r   r   r  rj  r4   r  s      r\   r   z)FunctoolsPartialVariable.call_obj_hasattr	  s2     ))00I%%h/6
 	
r[   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        v rt        j                  | |      S t        t        |       y c c}}w )Nrf   r   r  rh  )r   r(   rf   r   rK   r   rh  r   r@   r   ConstDictVariabler3   rC  r"   r   )rz   r   r   r   r   r   r   s          r\   rD  z$FunctoolsPartialVariable.var_getattr	  s    >DKK!>6>996>))$))FCC:?C}}?R?R?TUtq!%,,Q/2UEU..uVDD)),,T488 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 r   )r  rj  rf   r"  r   rh  r   )rz   rh  r   r   s       r\   r"  z+FunctoolsPartialVariable.as_python_constant	  s      II((*
26))<3c$$&<
 6:]]5H5H5JKTQq!&&((K
 	
<Ks   B
1Bc                 x   t        j                  | j                  j                         g| j                  D cg c]  }|j                          c}i | j
                  j                         D ci c]  \  }}||j                          c}}}| j                  | j                  |_        |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  rj  rf   guard_as_python_constantr   rh  r   rg  
cache_hash)rz   r   r   r   s       r\   r}  z1FunctoolsPartialVariable.guard_as_python_constant	  s    ""II..0
48II>qa((*>
 <@==;N;N;PQ41aq!,,..Q
 ##/ $ 8 8F ?Qs   B1
1B6c                     | j                   j                         xrH t        d | j                  D              xr* t        d | j                  j                         D              S )Nc              3   <   K   | ]  }|j                           y wr   r  r-  s     r\   r  z>FunctoolsPartialVariable.is_python_hashable.<locals>.<genexpr>	  s     BC**,Br  c              3   <   K   | ]  }|j                           y wr   r  r  r	  s     r\   r  z>FunctoolsPartialVariable.is_python_hashable.<locals>.<genexpr>	  s     S5E,,.Sr  )rf   r  r  r   rh  r6  r   s    r\   r  z+FunctoolsPartialVariable.is_python_hashable	  sP    II((* TB		BBTSDMM<P<P<RSS	
r[   c                     | j                   j                         }d | j                  D        }d | j                  j	                         D        }t        |g||      S )Nc              3   <   K   | ]  }|j                           y wr   r  r-  s     r\   r  z;FunctoolsPartialVariable.get_python_hash.<locals>.<genexpr>	  s     @sS((*@r  c              3   <   K   | ]  }|j                           y wr   r  r  s     r\   r  z;FunctoolsPartialVariable.get_python_hash.<locals>.<genexpr>	  s     S5u,,.Sr  )rf   r  r   rh  r6  r  )rz   	func_hash	args_hashvalues_hashs       r\   r  z(FunctoolsPartialVariable.get_python_hash	  sQ    II--/	@dii@	SDMM<P<P<RSY99[9::r[   r  c                 p   t        |t              xr | j                  j                  |j                        xr~ t	        d t        | j                  |j                        D              xrL t	        d t        | j                  j                         |j                  j                               D              S )Nc              3   D   K   | ]  \  }}|j                  |        y wr   r  )r  arg_aarg_bs      r\   r  z;FunctoolsPartialVariable.is_python_equal.<locals>.<genexpr>	  s'      "UE %%e,    c              3   D   K   | ]  \  }}|j                  |        y wr   r  )r  value_avalue_bs      r\   r  z;FunctoolsPartialVariable.is_python_equal.<locals>.<genexpr>	  s'      &Wg ''0r  )	r   rf  rf   r  r  r   r   rh  r6  r  s     r\   r  z(FunctoolsPartialVariable.is_python_equal	  s    u67 		))%**5 &)$))UZZ&@   *-MM((*ENN,A,A,C+ 	
r[   r   r<  )rW   rX   rY   r>   r  r   r   r   r   r~   r  r*  r  r   r   r@   r   rD  r"  r}  r  r  r  r  r  r  r  r  s   @r\   rf  rf  }	  sE   		'	'N $(77 '7 sO+,	7
 !7 7 
7(!T !
)c )G#G 'G S/)*	G
 
G
)
14
	
55 5S 5_ 5
C 

# 

D 
; ;
V 
 
r[   rf  c            
       `    e Zd Zdddhej                  Zeej                  dee	de
f   ej                  f   fd              Zede
dedd fd	       Zded
e
ddf fdZede	de
f   fd       ZdefdZde
fdZdddee   d
eeef   defdZdddedee   d
eeef   def
dZde
fdZ xZS )PolyfilledFunctionVariabler   r  traceable_fnr]   .c                     i S r   rZ   )r  s    r\   _get_polyfill_handlersz1PolyfilledFunctionVariable._get_polyfill_handlers
  s	     	r[   r	  r   c                 f    t        |j                  t        j                                | ||      S r  r  r  s      r\   r  z-PolyfilledFunctionVariable.create_with_source

  s*     	f''(B(BCD5((r[   r   Nc                 .   t        |   di | || _        | j                         j	                  ||      }d }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 functionrZ   )
r  r~   r   r  r   callabler   rS  r  r  )rz   r   r   handlerr  candidate_attr	candidater   s          r\   r~   z#PolyfilledFunctionVariable.__init__
  s    "6"--/33B; X$5gY>STVSW"XX 
 	N  >I	***(	 #G9,OP  " ,r[   c                     | j                   S r   )r  r   s    r\   polyfill_fnz&PolyfilledFunctionVariable.polyfill_fn,
  s       r[   c                 0    t        | j                  dd      S )N*__torch_dynamo_can_constant_fold_through__F)r   r  r   s    r\   can_constant_fold_throughz4PolyfilledFunctionVariable.can_constant_fold_through0
  s    OOI5
 	
r[   c                 "    | j                         S r   rs  r   s    r\   r   z'PolyfilledFunctionVariable.get_function5
  rt  r[   r   rE   r   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].  }|j-                         r|j                         n|j.                  0 c}            S t        j                  || j0                        }|j3                  |||      S c c}w c c}}w c c}w )Nr9   r   c              3      K   | ]h  }|j                         xr t        |j                         t              xs2 t        |t        j
                        xr |j                         t        u  j y wr   )r  r   r"  r  r   SymNodeVariabler*  )r  r  s     r\   r  z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>O
  se        %%'SJq7K7K7Ms,S Yq)";";<WTWAWYs   A.A0r   c              3   <   K   | ]  }|j                           y wr   )as_proxy)r  as     r\   r  z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>Z
  s     ?A1::<?r  )sym_num)r  r2   r   r"  r   r>   r   builtinssumr   r   r   rK   TupleVariabler  r  r   r   create_proxyr_   sym_sumr   r  r  r  r   )	rz   r   r   r   r  r   r   r   traceable_function_variables	            r\   r   z(PolyfilledFunctionVariable.call_function8
  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   !335 002!"+	 4  ( '6&;&;B@Q@Q&R#*88T6JJO <L4s   HH3Hr   c                 >   |dk(  r| j                  |||      S t        | j                  |d       }|s't        |      st	        |d| d| j                          i }| j
                  rt        | j
                  |      |d<   t        |fi |}|j                  |||      S )N__call__zCannot find callable z in r   )r   r   r   r5   r<   r   r(   r  )rz   r   r   r   r   methodr@  polyfilled_method_variables           r\   r  z&PolyfilledFunctionVariable.call_methodl
  s     :%%b$77$-+f- '<TF$twwi%PQ;; *4;; =GH%?%R'%R")77D&IIr[   c                     | j                   S r   r%  r   s    r\   r"  z-PolyfilledFunctionVariable.as_python_constant
  r&  r[   )rW   rX   rY   r>   r  r  r  cacher   r   r   r   r   r  r   r  rM   r~   propertyr  r  r  r   r   r   r   r   r  r"  r  r  s   @r\   r  r  	  s{    
	'	'	N __tHS#X,>@R@R,R'S    ))!')	%) )-2 - - -4 !Xc3h/ ! !
4 

)c )2K#2K '2K S/)*	2K
 
2KhJ#J J ?#	J
 S/)*J 
J(C r[   r  c                   l     e Zd Zdededdf fdZddZdddefd	Zddd
ee   de	e
ef   defdZ xZS )SysFunctionVariabler	  r   r]   Nc                 2    t        |   di | || _        y r   )r  r~   r	  )rz   r	  r   r   s      r\   r~   zSysFunctionVariable.__init__
  s    "6"
r[   r   rE   c                 B   t        |j                        rG|j                  d   }|j                  }|j                  |d      }t	        j
                  ||      ||g}n/t        j                  t        j                  t        j                  g}t        j                  |      S )Nr  __traceback__)	r   exn_vt_stackr;  rD  r>   r   r   r?   r  )rz   r   exnrn  tbr   s         r\   exc_infozSysFunctionVariable.exc_info
  s    r//"%C,,C_5B$**2s3S"=E 000000E
 &&u--r[   c                 >    | j                  |      j                  d   S )Nr9   )r  r   r   s     r\   	exceptionzSysFunctionVariable.exception
  s    }}R &&q))r[   r   c                     | j                   t        j                  u r| j                  |      S | j                   t        j                  u sJ | j                  |      S r   )r	  r  r  r  r   s       r\   r   z!SysFunctionVariable.call_function
  sH     ::%==$$zzS]]***~~b!!r[   )r   rE   r]   zvariables.TupleVariable)rW   rX   rY   r   r~   r  r>   r  r   r   r   r   r  r  s   @r\   r  r  
  sp    c S T .*3 * *
"#
" '
" S/)*	
"
 

"r[   r  ) create_tma_experimental_metadatacreate_tma_stable_metadata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d	deej                  j                  j                  d
f   fdZde	deee	f   ddde	fdZded
e	f   dee   deeef   ded   de	defdZde	ded   de	dedef
dZde	ded   dee	   fdZdede	fdZdddee	   ddfdZddde	deee	f   dddd f
d!Zy")#DynamoTritonHOPifierro  r]   c                 (    t        ddd| g        y )Nz!triton kernel unsupported featurer  z/Encountered triton kernel unsupported feature: r  r$   )rz   ro  s     r\   raise_unsupportedz&DynamoTritonHOPifier.raise_unsupported
  s    7I#O		
r[   maybe_callablec                 .    t        |t        t        f      S r   )r   r   r  )rz   r  s     r\   is_callablez DynamoTritonHOPifier.is_callable
  s    79MN
 	
r[   r   c                     |j                   S r   r  )rz   r   s     r\   	get_valuezDynamoTritonHOPifier.get_value
  s    yyr[   gridrJ   .c                     ddl m} t        ||      r|j                         S t	        ddt        |       dg t        j                         y )Nr9   )rJ   z/unsupported grid type for triton hop check_gridzgrid type = z;`torch.compile` only supports list-like grid for check_gridr  )listsrJ   r   r  r$   r  r   rO  )rz   r  rJ   s      r\   
check_gridzDynamoTritonHOPifier.check_grid
  sK    +d,-==?"I&tDzl3Y&22	r[   metar   rE   c                     |j                         D ci c]%  \  }}t        j                  j                  |      |' }}}|j	                  ||gi       }|S c c}}w r   )r   r   r@   r   r   )rz   r  r  r   r   r   meta_vars          r\   	call_gridzDynamoTritonHOPifier.call_grid
  sZ     IM

U1I..55a8!;UU!!"xj"5 Vs   *Auser_fnr   r   rD  c                 \    ddl m} |j                  ||      }|j                  |||      }|S )Nr9   r  )r  r  r   r   )	rz   r  r   r   r   rD  r  wrapped_user_functionr   s	            r\   call_user_defined_fnz)DynamoTritonHOPifier.call_user_defined_fn
  s3     	/ 1 8 8W E&44RvFr[   user_objr   c                 t    ddl m} |J  ||t        |j                  |             j	                  |      }|S )Nr9   )VariableBuilder)r  r  r(   kernel_source_wrap)rz   r  r   rD  r   r  wrapped_user_objs          r\   wrap_user_defined_objz*DynamoTritonHOPifier.wrap_user_defined_obj
  sC     	-~~*
811dV=

%/ 	  r[   configsc                 n    |j                  |      }|D cg c]  } |j                          }}|S c c}w r   )unpack_var_sequencer}  )rz   r  r   r   s       r\   maybe_unpack_configsz)DynamoTritonHOPifier.maybe_unpack_configs
  sB     --b1 DKK26224KK Ls   2r   c                 d    |j                         s| j                  d       |j                         S )Nz`@triton.heuristics must return constant values because configs can only contain constant values.)r  r  r}  )rz   r   s     r\   maybe_unpack_heuristic_resultz2DynamoTritonHOPifier.maybe_unpack_heuristic_result
  s0    ((*""r ..00r[   TritonKernelVariablec                     |j                   t        |      dk7  r| j                  d        t        |      |j                  |j
                  |d   |j                        S )Nr9   z7Triton kernels should be called with only a single gridr   )kernel
kernel_idxr  r  )r  r   r  r  r  r  r   )rz   rD  r   s      r\   call_getitemz!DynamoTritonHOPifier.call_getitem	  s\     ==$D	Q""I tH~??**a"//	
 	
r[   gridscombined_argszvariables.ConstantVariablec                 V   ddl m} i }t        |j                               D ]D  }||   }t	        |t
        t        f      s|j                         ||<   |j                         ||<   F |j                         D ci c]%  \  }}t        j                  j                  |      |' }	}}ddlm}
m} |j                         D ci c]6  \  }}t	        |t               r!|j#                         r||j%                         8 }}}|	j                         D ci c](  \  }}t	        |t               r|j#                         s||* }}}|j'                         D ]R  }|j)                         }|j+                         r$|j-                         r5| j/                  dt1        |       d       T |
j3                  |      } ||t4              }|j6                  j9                  d|d|j:                  ||||j=                         d	       t        j                  d       S c c}}w c c}}w c c}}w )
Nr9   )rz  r   )kernel_side_tabletriton_kernel_wrapper_mutationz.Unexpected argument type for a Triton kernel: r  r   rZ   )r  constant_args_idxr  tma_descriptor_metadatar   )dictsrz  r   rp  r   !TMADescriptorExperimentalVariableTMADescriptorStableVariableto_metadata
get_tensorr   r   r@   r   *torch._higher_order_ops.triton_kernel_wrapr  r  r>   r  r"  r6  r  r  is_symnode_liker  repradd_constant_argsr   r   r  r  r  )rz   rD  r  r  r   rz  r  r   r   combined_args_vtr  r  rd  non_constant_argsr  r  s                   r\   call_HOPzDynamoTritonHOPifier.call_HOP  s#    	- :<m((*+ 	2Aa A57RS ./]]_'*#$<<>a 	2 AN@S@S@U
8<1I&&--a0!3
 
	
 &++-
1!_-!2F2F2H q##%%
 
 )..0
1q/2q7K7K7M qD
 
 #))+ 	A		AKKMQ%6%6%8&&DT!WIQO	 .??N !2D9
		*&11%6+B--/		
 ))
 	
[



s   <*H;H-H%N)rW   rX   rY   r   r   r  r>   r  r  r   r  r   r_   fxproxyProxyr  r   r  r   r   r   r  r  r   r  r  r  r  rZ   r[   r\   r  r  
  s   
S 
U 

/ 
d 

_  1 eEHHNN<P<PRU<U6V #CH~3J	#s(# ' S/)*	
 ,-  
   ,-  	 
   
 		 ()@ A		c	1O 1 1
(
 sm
 
 	
$G
(G
 G
 CH~	G

 $G
 
&G
r[   r  c            
            e Zd ZU ded<   ded<   edz  ed<   ded<   dededz  ded	ed
df
 fdZdddee   d	e	e
ef   d
efdZddde
dee   d	e	e
ef   d
ef
 fdZded
efdZ xZS )r  rH   r  rI   r  Nr  r(   r  r   r]   c                     |j                  dd       | _        t        |   di | t        j                  | |||       y )Nr  rZ   )r   r  r  r~    dynamo_triton_hopifier_singletoninit_variable)rz   r  r  r  r   r   s        r\   r~   zTritonKernelVariable.__init__n  s=     $ZZ>"6"(66tVZQUVr[   r   rE   r   c                 2    t         j                  | |||      S r   )r  call_triton_kernelr   s       r\   r   z"TritonKernelVariable.call_functionu  s      0BB$
 	
r[   r   c                     |dk(  rt         j                  | |      S |dk(  rt         j                  | |||      S t        |   ||||      S )N__getitem__run)r  r  call_runr  r  r  s        r\   r  z TritonKernelVariable.call_method  sW     = 3@@tLLU]3<<T4QSTT w"2tT6::r[   rh  c                 v    ddl m} ddlm} t	        ||      r  |j
                  |j                               S |S )Nr9   )r@   )r  )ra  r@   tensorr  r   r   evaluate_expr)rz   rh  r@   r  s       r\   specialize_symbolicz(TritonKernelVariable.specialize_symbolic  s6    .+ c?+*#**3+<+<+>??
r[   )rW   rX   rY   r   r  r   r~   r   r>   r   r   r   r   r  r  r  r  s   @r\   r  r  h  s    
d
WW'*TzW9<WHKW	W
#
 '
 S/)*	

 

;#; ; ?#	;
 S/)*; 
;s s r[   r  c                   d     e Zd Zdddee   dee   dededdf fd	Zdefd
ZddZdefdZ	 xZ
S )r  data_ptrzvariables.DataPtrVariabledims
block_dimselement_sizer   r]   Nc                     t        |t        j                        sJ t        |   di | || _        || _        || _        || _        y r   )	r   r   DataPtrVariabler  r~   r  r  r  r  )rz   r  r  r  r  r   r   s         r\   r~   z*TMADescriptorExperimentalVariable.__init__  sH     (I$=$=>>>"6" 	$(r[   c                     t        | j                  D cg c]  }|j                          c}| j                  D cg c]  }|j                          c}| j                  j                               S c c}w c c}w r   )r  r  r  r  r  )rz   dims     r\   r  z-TMADescriptorExperimentalVariable.to_metadata  sW    /'+yy1S\\^1'+7S\\^7&&(
 	
17s
   A2A7
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}  s   r\   r~  z?TMADescriptorExperimentalVariable.reconstruct.<locals>.<lambda>  s+    G,,6#dii.))9: r[   r9   F)	r  r  r  r  r  r  ro  r   r   )rz   r  r   s   `` r\   r  z-TMADescriptorExperimentalVariable.reconstruct  sp    	
 	!!'*@@T__@d.?.?@c$i!mU3r[   c                 .    | j                   j                  S r   )r  from_tensorr   s    r\   r  z,TMADescriptorExperimentalVariable.get_tensor  s    }}(((r[   r<  )rW   rX   rY   r   r>   r   r~   r  r  r  r  r  s   @r\   r  r    si    )-) ?#) )	)
 &) ) 
)
S 

4)O )r[   r  c                   P     e Zd Zdddddeddf fdZdefd	Zdd
ZdefdZ xZS )r  r  rL   block_shaperK   r   r]   Nc                 d    |j                         sJ t        |   di | || _        || _        y r   )r  r  r~   r  r'  )rz   r  r'  r   r   s       r\   r~   z$TMADescriptorStableVariable.__init__  s6     !!!"6"&r[   c                 H    t        | j                  j                               S r   )r  r'  r  r   s    r\   r  z'TMADescriptorStableVariable.to_metadata  s!    )%%'
 	
r[   c                     j                  fd       j                  d       | j                  j                          | j                         j                  d       y )Nc                  (     j                  dd      S )Nztriton.tools.tensor_descriptorTensorDescriptorr  r  s   r\   r~  z9TMADescriptorStableVariable.reconstruct.<locals>.<lambda>  s    G,,0" r[   r%  r   )r  load_methodr  r  r'  r  r  s    `r\   r  z'TMADescriptorStableVariable.reconstruct  sT    	
 	M*(  !Ar[   c                     | j                   S r   )r  r   s    r\   r  z&TMADescriptorStableVariable.get_tensor  s    {{r[   r<  )	rW   rX   rY   r   r~   r  r  r  r  r  s   @r\   r  r    sK    	' 	' $	' 		'
 
	'
S 


C r[   r  c                   T     e Zd Zdededdf fdZdddee   dee	ef   defd	Z
 xZS )
'CreateTMADescriptorExperimentalVariablerankr   r]   Nc                 >    |dv sJ t        |   di | || _        y )N)r9   r   rZ   )r  r~   r1  )rz   r1  r   r   s      r\   r~   z0CreateTMADescriptorExperimentalVariable.__init__  s(    
 v~~"6"	r[   r   rE   r   c                    d|v r|d   n|d   }t        |t        j                        s2t        dd| d| d| j                   dd| j                   d	g
       | j                  dk(  r]t        |      t        |      z   dk7  r$t        |dt        |      t        |      z           d|v r|d   n|d   g}d|v r|d   n|d   g}nvt        |      t        |      z   dk7  r$t        |dt        |      t        |      z           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        |t        j                        sJ t        ||||      S )Nptrr   z.invalid ptr argument for create_tma_descriptorzargs = z, kwargs = z#Expected `ptr` argument of `create_z]d_tma_descriptor`to be from a `.data_ptr()` call, represented internally by `DataPtrVariable`z`torch.compile` may fail to internally represent result of `.data_ptr()` with `DataPtrVariable` due to a graph break between the `.data_ptr()` call and `create_zTd_tma_descriptor`. Please ensure there were no graph breaks between these two calls.r  r9   rO   z6TMA metadata rank=1 requires exactly 4 arguments, got r  	block_dimr      z6TMA metadata rank=2 requires exactly 6 arguments, got dim1dim0
block_dim1r  
block_dim0r  r  )r  r  r  r  )r   r   r  r$   r1  r   r<   r  )rz   r   r   r   r4  r  r  r  s           r\   r   z5CreateTMADescriptorExperimentalVariable.call_function  s     %fUmDG#y889H!${6(;A$)) M_ _#yyk *// 99>4y3v;&!+$LSQUYY\]cYdMdLef
 "'&ud1gD (3f'<{#$q'J 4y3v;&!+$LSQUYY\]cYdMdLef
 #)F"2vQ"(F"2vQD
 )5(>|$DG(4(>|$DGJ 2@61Ivn-tTVx #y889990!%	
 	
r[   )rW   rX   rY   r  r   r~   r   r>   r   r   r   r  r  s   @r\   r0  r0    s^      
	:
#:
 ':
 S/)*	:

 
:
r[   r0  c                   4    e Zd Zdddee   deeef   defdZy)!CreateTMADescriptorStableVariabler   rE   r   r   r]   c                 T    d|v r|d   n|d   }d|v r|d   n|d   }t        ||      S )Nr  r   r'  r9   )r  r'  )r  )rz   r   r   r   r  r'  s         r\   r   z/CreateTMADescriptorStableVariable.call_function(  sF     &.%7!T!W/</Ff]+DQRG*#
 	
r[   N)rW   rX   rY   r   r>   r   r   r   rZ   r[   r\   r<  r<  '  s<    
#
 '
 S/)*	

 

r[   r<  c                   8    e Zd ZdZdddee   deeef   defdZy)	!PyTreeGetNodeTypeFunctionVariableaK  
    `torch.utils._pytree._get_node_type` function is very hot function. We want to special case it to reduce Dynamo tracing time.

    def _get_node_type(tree: Any) -> Any:
        node_type = type(tree)
        # All namedtuple types are implicitly registered as pytree nodes.
        # XXX: Other parts of the codebase expect namedtuple types always return
        #      `namedtuple` instead of the actual namedtuple type. Even if the type
        #      is explicitly registered.
        if is_namedtuple_class(node_type):
            return namedtuple
        return node_type
    r   rE   r   r   r]   c                    t        |      dk7  rt        |dt        |              d }|d   j                  rMt        |d   j                  j	                  t
        j                               t        |d   j                        }|d   j                         }t        |      r0t        t        d      d      }t        j                  |t        |      S t        j                  |||      S )Nr9   z6pytree_get_node_type requires exactly 1 argument, got r   collectionsr   r  )r   r<   r   r'   r  r&   
TYPE_MATCHr0   r*  r   r(   r.   r>   r   r   )rz   r   r   r   type_sourcer*  s         r\   r   z/PyTreeGetNodeTypeFunctionVariable.call_functionF  s     t9> HTT 7>>$q'..33L4K4KLM$T!W^^4K1g))+{+$\-%@,OK"((ZEE$$R[IIr[   N)	rW   rX   rY   r   r   r>   r   r   r   rZ   r[   r\   r?  r?  7  sF    J#J 'J S/)*	J
 
Jr[   r?  c                   D     e Zd ZdZdddee   deeef   def fdZ xZ	S ) PyTreeTreeIsLeafFunctionVariablea@  
    `torch.utils._pytree.tree_is_leaf` function is a hot function. We want to special case it to reduce Dynamo tracing time.

    def tree_is_leaf(
        tree: PyTree,
        is_leaf: Callable[[PyTree], bool] | None = None,
    ) -> bool:
        if is_leaf is not None and is_leaf(tree):
            return True
        return _get_node_type(tree) not in SUPPORTED_NODES

    When is_leaf is None (the common case), we can optimize by not tracing into the function.
    When is_leaf is not None, we fall back to regular tracing since it requires executing user code.
    r   rE   r   r   r]   c                 v   t        |      dk  st        |      dkD  rt        |dt        |              |j                  dt              }t        |      dk(  r|d   }|j	                         st
        	|   |||      S |d   }t        t        j                  j                  j                        j                  ||gi       }t        j                  |t        j                  j                  j                  t                     }|j!                  |d|gi       }t#        j$                  |j&                         S )Nr9   r   z,tree_is_leaf requires 1 or 2 arguments, got rQ   r   r  r  )r   r<   r   r?   r,  r  r   r?  r_   r`   ra   _get_node_typer>   r   rb   rc   r  r@   r   r	  )
rz   r   r   r   rQ   treenode_type_varsupported_nodes_varoutr   s
            r\   r   z.PyTreeTreeIsLeafFunctionVariable.call_functionl  s    t9q=CIM >s4ykJ **Y(>?t9>1gG'')7(T6:: Aw9KK..

-TFB
' 	 .33KK//46

 "--b.=/SUV&&399}55r[   r  r  s   @r\   rE  rE  \  sG    $6#$6 '$6 S/)*	$6
 
$6 $6r[   rE  c                   X     e Zd ZdZdededdf fdZddd	ee   dee	ef   defd
Z
 xZS ) SparseTensorCreationSkipVariablezk
    Skip variable for sparse tensor factory functions with clear messaging regarding lack of support.
    r	  r   r]   Nc                 .    d}t        |   |fd|i| y )Nz8sparse tensor creation is not supported in torch.compiler  r  r~   rz   r	  r   r  r   s       r\   r~   z)SparseTensorCreationSkipVariable.__init__  s    K8v88r[   r   rE   r   c                     ddl m} t        | j                  dt	        | j                              }t        dd| d| dg |j                         y )	Nr   )r   rW   z$Sparse tensor creation not supportedz
function: zEtorch.compile does not support sparse tensor creation functions like zZ. Sparse tensors require specialized handling that is not yet implemented in the compiler.r  )r  r   r   r	  r   r$   SPARSE_TENSOR)rz   r   r   r   r   rp  s         r\   r   z.SparseTensorCreationSkipVariable.call_function  s]     	)$**j#djj/B: 	*WX_W` ak k 5%334	
r[   rW   rX   rY   r   r   r~   r   r>   r   r   r   r  r  s   @r\   rM  rM    \    9c 9S 9T 9
#
 '
 S/)*	

 

r[   rM  c                   X     e Zd ZdZdededdf fdZddd	ee   dee	ef   defd
Z
 xZS )TritonSetAllocatorSkipVariablezm
    Skip variable for triton.set_allocator with a clear message to move it outside the compiled region.
    r	  r   r]   Nc                 .    d}t        |   |fd|i| y )Nz:triton.set_allocator is not supported inside torch.compiler  rO  rP  s       r\   r~   z'TritonSetAllocatorSkipVariable.__init__  s    M8v88r[   r   rE   r   c                 $    t        ddddg       y )Nz"triton.set_allocator not supportedz2triton.set_allocator called inside compiled regionz{triton.set_allocator is not supported inside torch.compile. It modifies global Triton allocator state and cannot be traced.zgMove triton.set_allocator() outside of the torch.compile region (call it before the compiled function).r  r  r   s       r\   r   z,TritonSetAllocatorSkipVariable.call_function  s"     	8HR:	
r[   rS  r  s   @r\   rV  rV    rT  r[   rV  r   )r   r  r  r   r   r  r  r  r  r   rA  r   collections.abcr   r   r   r   typingr   r	   r
   r   r   r   typing_extensionsr   weakrefr   r_   torch._dynamo.excr   torch._guardsr   torch.utils._pytreer   r  r   r   r   r   bytecode_transformationr   r   r   r  r   r   r   r   r   r    r!   r"   r#   r$   r%   guardsr&   r'   r   r(   r)   r*   r+   r,   r-   r.   r/   r0   r`   r1   r2   r3   r4   r5   r6   r7   r8   r  r:   r;   r<   r=   r>   ra  r?   r@   #torch.distributed.fsdp._fully_shardrA   ModuleNotFoundErrortorch._dynamo.codegenrB   r  rC   rD   rE   rF   #torch._dynamo.variables.ctx_managerrG   r  rH   rI   r  rJ   rK   r  rL   rM   rv   rx   r  ru  r  r  rT   r   r   rV   	lru_cacherc   re   r   r   r   r   r   r   r   r   r   r  r   r   r   r   r  r  r  r  r  r?  rA  rP  r0  rp  r  r^  r   r  r  r   r  r*  r4  r:  r<  rY  r_  rf  r  r  r  r  r  r  r  r  r  r  r  r0  r<  r?  rE  rM  rV  rZ   r[   r\   <module>rg     s  .      	 
   " . ( G G # %  4   3 > > V V    1
 
 
	 	 	  ?E
 /  L
 6& T#s(+,
&'OP "+YK"8  D  ,=+>sCx( >	0 	 :  
 
>L \ U
UU }U 3-	U
 cNU 
#
Ur DHAA&)A39D=AA.0 .$sCx. .T . # o%&  ..  
	 *
..CH~  FCK 4'	
 8_t# S#X% c3h$& 4 --%+-5;d]-JM--62 2jWY3 WYt!73 !7H)": )X:4 :@G;? G;T

 
M
%= M
` " Fq-- q-h> 2 ><>"6 >:c  ?
#	
 o%& ,G)!9 G)T*>(B *>ZM
? M
`>"6 ><D
/ D
N ; *d38n //%-c3h%7//_D(< _DD71 74#
$8 #
L}
 }
@D DN "/  "F s
> s
l $8#9  -? -`$) $)N/ BD
o D
N
 
 "J(< "JJ46'; 46n
'; 
:
%9 
eb  s   )P PP