o
    ei                    @   s  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 zddlWmXZX W n eYy   dZXY nw 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 dZkd Zld!Zmenh d"Zoend#hZpd$Zqe Zreeef esd%< G d&d' d'etZuejvd(e<fd)d*ZwG d+d, d,Zxd-ed(exfd.d/Zyd-ed0d1d2e dB d3ee d4eze{ef d(eze{eSf fd5d6Z|	dd0d1d7ed8e dB d(eSfd9d:Z}d0d1d;eze{ef d(dfd<d=Z~d>d1d;eze{eSf d?e	jd(dfd@dAZd?e	jdBeze{ef dCe{dDeedf dB dEee dB dFeze{ef dB dGeze{ef dB d(e	jfdHdIZh dJZd0d1dKed8e dB dCe{d(eSf
dLdMZG dNdO dOeSZG dPdQ dQeZG dRdS dSeZG dTdU dUeZG dVdW dWeZG dXdY dYeSZG dZd[ d[eZG d\d] d]eZG d^d_ d_eZG d`da daeZG dbdc dceZG ddde deeZd0d1dKedef dCe{d3eeS d4eze{eSf d(eSfdfdgZG dhdi dieZG djdk dkeZG dldm dmeSZG dndo doeZG dpdq dqeSZG drds dseZd(ezeef fdtduZd0d1dKedef d(e<fdvdwZG dxdy dyeZG dzd{ d{eZG d|d} d}eZG d~d deSZG dd deSZG dd deSZddlcmZmZmZmZ G dd deZe ZG dd deSZG dd deSZG dd deSZG dd deSZG dd deSZG dd deZG dd deZG dd deZG dd deZdS )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_leafrP   zihttps://github.com/pytorch/pytorch/issues/new?&labels=oncall%3A+pt2&projects=&template=pt2-bug-report.yml_spec_cachec                   @   s   e Zd ZdS )ClosureConversionErrorN)__name__
__module____qualname__ rX   rX   k/var/www/addictedbytheproject.nl/epg/venv/lib/python3.10/site-packages/torch/_dynamo/variables/functions.pyrT      s    rT   returnc                   C   s   t t t tddddS )Ntorchutils_pytreeSUPPORTED_NODES)r'   r-   rX   rX   rX   rY   !get_pytree_SUPPORTED_NODES_source   s   r_   c                   @   s0   e Zd ZdeddfddZdeddfddZdS )FunctionSpecfuncrZ   Nc                 C   s   |j }|j}|j| _|j| _|j| _|d | j | _|| j| j | _	| j| j	 | _
|| j| j| j  | _| j| j }|jt@ rE|| nd | _|| jrNdnd7 }|jt@ r]|| | _d S d | _d S Nr8   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)selfra   codevnoffrX   rX   rY   __init__   s   "zFunctionSpec.__init__c                 C   sH   |j pd| _|jp
i | _tt| jt| j d  tt| j| _	d S NrX   )
__defaults__defaults__kwdefaults__
kwdefaultsdictziprm   lenrangepos_default_map)rt   ra   rX   rX   rY   update_defaults   s
   $
zFunctionSpec.update_defaults)rU   rV   rW   r   rx   r   rX   rX   rX   rY   r`      s    r`   ra   c                 C   s&   t | }|d u rt| }|t | < |S N)rS   getr`   )ra   specrX   rX   rY   	_get_spec   s
   
r   txrD   	fn_sourceargskwargsc                    s  t | }t |jkr&| js&|s&|js&|js&|js& fddt|jD S |	|  i }t
|}|j D ]#\}}	d }
|rNt|j|	 rItjsNt||	}
t|j|	 |
||< q6t|jD ]3\}}|t k rst | ||< q_||v r||jvrt||||< q_||vrtd| q_ t|jd  }|jrtt|||j< n|rtdt  dt|j |jD ]3}||v rt||||< q||jv rd }|rt||dd}t|j| |||< qtd| |jrt|||j< |S |rtd	t| |S )
Nc                    s    i | ]\}}|t  | qS rX   )wrap_bound_arg).0inamer   r   rX   rY   
<dictcomp>   s    z$bind_args_cached.<locals>.<dictcomp>z&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   rh   rz   rq   rs   rn   	enumeraterm   r   r~   r   itemsr?   
is_literalr{   r   %skip_guards_on_constant_func_defaultsr+   r   rk   pop	TypeErrortupler}   list)ra   r   r   r   r   r   barem_kwr   idxdefault_sourcer   extrakwdefault_sourcerX   r   rY   bind_args_cached   st   




r   valsourcec                 C   s,   t |tr|S |st| |S tj||S r   )
isinstancer=   buildr   LazyVariableTrackercreate)r   r   r   rX   rX   rY   r     s
   
r   resultc                 C   s6   t | D ]\}}t|ttfrt| |||< qd S r   )r   r   r   r   r~   r   )r   r   kvrX   rX   rY   wrap_args_kwargs  s
   r   parentru   c                 C   sB   | j j}|jD ]}| }||v r|||| |||< qdS )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   ru   r   r   new_cellrX   rX   rY   init_cellvars!  s   


r   	f_globalsr   r{   closurer}   annotationsc           
      C   sd   ddl m} || ||||}||_t|tr"ddlm}	 t|	|}|d u s-t|ts-J ||_|S )Nr   r   pairwise)	typesr   r|   r   r   	itertoolsr   r~   __annotations__)
ru   r   r   r{   r   r}   r   r   ra   r   rX   rX   rY   _create_nested_fn6  s   	
r   >   __doc__rc   __closure____globals__rz   r|   r   fnc                 C   s   |ot ||}|r|dkrt|}d }zt||}W n ty)   tt|  Y nw |tv r3t||}|r<tj	
||S t| |S )Nr   )r'   r.   inspectgetattr_staticAttributeErrorr!   fn_known_dunder_attrsgetattrr   r   r   r=   r   )r   r   r   r   subobjrX   rX   rY   fn_var_getattr[  s   
r   c                   @   s   e Zd ZdefddZdefddZdeeef fddZde	j
fdd	Zdefd
dZdddee deeef defddZdddedefddZdddeeef fddZdefddZdS )BaseUserFunctionVariablerZ   c                 C   
   |   jS r   get_codeco_filenamert   rX   rX   rY   get_filenamew     
z%BaseUserFunctionVariable.get_filenamec                 C   r   r   r   co_namer   rX   rX   rY   get_namez  r   z!BaseUserFunctionVariable.get_namec                 C      t r   NotImplementedErrorr   rX   rX   rY   get_globals}     z$BaseUserFunctionVariable.get_globalsc                 C   r   r   r   r   rX   rX   rY   r     r   z!BaseUserFunctionVariable.get_codec                 C   r   r   r   r   rX   rX   rY   has_self  r   z!BaseUserFunctionVariable.has_selfr   rD   r   r   c                 C   s8   |   dkr|  drtS || g |  ||S )Npatch_track_step_calledztorch/optim/lr_scheduler.py)r   r   endswithr>   inline_user_function_return	self_argsrt   r   r   r   rX   rX   rY   call_function  s
   	z&BaseUserFunctionVariable.call_functionr   c                 C   sL   d}z	t |  |}W n ty   |dkrt| trd}Y nw tj|S )NFrU   T)hasattrget_functionr   r   NestedUserFunctionVariabler   r?   r   rt   r   r   r   rX   rX   rY   call_obj_hasattr  s   z)BaseUserFunctionVariable.call_obj_hasattrc                 C      i S r   rX   rt   r   rX   rX   rY   closure_vars  r   z%BaseUserFunctionVariable.closure_varsc                 C      dS NTrX   r   rX   rX   rY    should_allow_nested_graph_breaks  r   z9BaseUserFunctionVariable.should_allow_nested_graph_breaksN)rU   rV   rW   strr   r   r~   r   r   r   CodeTyper   boolr   r   r=   r   r?   r   r   r   rX   rX   rX   rY   r   v  s0    


r   c                       s  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d	Z
	
dDdejejjB dede	ddf fddZde	f fddZdee fddZdejfddZdejfddZdefddZdefddZdeee	f fddZdefddZ dd d!e!e deeef deeef fd"d#Z"d$d d%edefd&d'Z#d$d d%ede$fd(d)Z%d$d d!e!e deeef def fd*d+Z&d$d d!e!e deeef dedB fd,d-Z'defd.d/Z(defd0d1Z)d$d d!e!e deeef de*d e!e eeef f dB fd2d3Z+dejdB fd4d5Z,d6ede*ed7f dB fd8d9Z-de	dee dB fd:d;Z.de/d< fd=d>Z0de1fd?d@Z2dAe3defdBdCZ4  Z5S )EUserFunctionVariablez-Some unsupported user-defined global functionr   is_constant>   
optree.opstorch.utils._pytreetorch.utils._cxx_pytreeoptreevaluer   rZ   c                 C      t |tj | ||dS Nr   r&   
make_guardr%   CLOSURE_MATCHclsr   r   rX   rX   rY   create_with_source  s   z'UserFunctionVariable.create_with_sourceFr   Nc                    sr   t  jd	i | t|ddrd| _nd| _t|tjtjj	fs-t
d| ddgtjd t|d|}|| _d S )
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_inlinerX   )superrx   r   r   r   r   r   r[   jitScriptFunctionr#   r   INFERENCE_MODEr   r   r   rt   r   r   r   	__class__rX   rY   rx     s    
zUserFunctionVariable.__init__c                    s   t | tr| jS t  S r   )r6   r   r   r  as_python_constantr   r
  rX   rY   r    s   

z'UserFunctionVariable.as_python_constantc                 C      g S r   rX   r   rX   rX   rY   r     r   zUserFunctionVariable.self_argsc                 C      | j S r   r   r   rX   rX   rY   r        z!UserFunctionVariable.get_functionc                 C      | j jS r   )r   rc   r   rX   rX   rY   r        zUserFunctionVariable.get_codec                 C      t jS r   r   r   r   rX   rX   rY   python_type  r  z UserFunctionVariable.python_typec                 C   s   t | jdd d uS )N__self__)r   r   r   rX   rX   rY   r     s   zUserFunctionVariable.has_selfc                 C   r  r   )r   r   r   rX   rX   rY   r     r  z UserFunctionVariable.get_globalsc                 C   s    | j }|rt| tjr| j}|S r   )r   r   r   UserMethodVariable	source_fn)rt   r   rX   rX   rY   
get_source  s   zUserFunctionVariable.get_sourcer   rD   r   c              	   C   sZ  | j rJ | j}t|tstd|jj}|  }t|||||}t	|||j
 | jjp-d}t|t| jj
jks;J tt | jj
j|D ]d\}	}
}|jj}||v rX|| }nN|rtt||	}t|d|
d}z
t||j|}W n ty   t }Y nw ||||}nz	t||j}W n ty   t }Y nw |d||}|||
< qF|S )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.rX   cell_contents)freevar_nameN)r   r   r   r   r   r   root_txr  r   r   rc   r   r   co_freevarsr   r   countr   r,   r)   r(   r=   r   r  
ValueErrorr   DeletedVariabletrack_cell_existing)rt   r   r   r   r   r  r   r   r   r   r   cellr   cell_varclosure_cellclosure_cell_contentscontents_varrX   rX   rY   	bind_args   sN   




zUserFunctionVariable.bind_argsr   r   c                 C   s,   |t v r
t| |S |  }t|| j||S r   )r2   r   GetAttrVariabler  r   r   )rt   r   r   r   rX   rX   rY   var_getattr>  s   z UserFunctionVariable.var_getattrc                 C   s   t | j|}tj|S r   )r   r   r   r?   r   r   rX   rX   rY   r   D  s   z%UserFunctionVariable.call_obj_hasattrc              
      s  | j tjju r?z dd |D }dd | D }tjj|i |j}t|W S  ty> } zt	d| d| |d }~ww | j tjj
u r~z t| j j|i |}|jd  }	t|	tsaJ t|	W S  ty} } zt	d| d| |d }~ww | j tjju rt| j j|i |}|jd	 }
t|
ts|
 }d
|j d}tdd| j d| d| d|g tjd t|
ts|
 }d| d}td|  |d| ddgd |
j }tj|tjj j!dS | j"rt#|| j |  ||S |j$j%j&s$| j tjj'j(u r$tjj)*| t+ ,|||W  d    S 1 sw   Y  t-|j$j%dd dkry|j$j%j.syzd	dl/m0} W n tyI   d }Y nw |d ury| j |j1|j2fv rytjj).| t+ ,|||W  d    S 1 stw   Y  | 3|||}|d ur|S t+ ,|||S )Nc                 S      g | ]}|  qS rX   r  r   argrX   rX   rY   
<listcomp>S      z6UserFunctionVariable.call_function.<locals>.<listcomp>c                 S      i | ]	\}}||  qS rX   r+  )r   keyr   rX   rX   rY   r   T  s    z6UserFunctionVariable.call_function.<locals>.<dictcomp>zCannot 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   changesr   DynamoConfigPatchVariabler9   RuntimeErrorr2  r   	signaturebind	argumentsr  r   r   ErrorOnGraphBreakVariable	Exceptionnonstrict_tracer   r   r  rU   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_stater9  _pre_forward_post_forward_maybe_call_tree_map_fastpath)rt   r   r   r   
args_constkwargs_constr<  erM   r2  fn_vartypmsgfn_namer   r9  tree_map_resultr
  rX   rY   r   J  s   


	


""
z"UserFunctionVariable.call_functionc                 C   s   |  |||}|d ur|\}}}n| }|}|}t|tr,| r,h |t s,t|dks.d S |d }|d }	|dd  }
|	||||
|S )Nr   r   r8   )_rewrite_tree_map_only_callr   r   _is_tree_map_function_SUPPORTED_TREE_MAP_KWARGSr   call_tree_map)rt   r   r   r   rewritetree_map_fntree_map_argstree_map_kwargsmap_fn
first_treerestrX   rX   rY   rR    s0   
z2UserFunctionVariable._maybe_call_tree_map_fastpathc                 C   &   t | jdd dkot | jdd | jv S )NrU   tree_maprV   r   r   _TREE_MAP_MODULESr   rX   rX   rY   r\       z*UserFunctionVariable._is_tree_map_functionc                 C   rf  )NrU   tree_map_onlyrV   rh  r   rX   rX   rY   _is_tree_map_only_function  rj  z/UserFunctionVariable._is_tree_map_only_functionc                 C   s   |   sd S t|dkrd S h |t rd S |\}}}| |}|d u r&d S |  }|d u r0d S t||t|dd d}	t|}
|
|	|gt	|fS )N   r   r   )
rl  r   _TREE_MAP_ONLY_SUPPORTED_KWARGS_extract_tree_map_only_types_lookup_tree_map_functionTreeMapOnlyFunctionVariabler   r   r   r~   )rt   r   r   r   type_selectorrc  tree_argallowed_typestree_map_callablewrapped_map_fntree_map_variablerX   rX   rY   r[    s(   



z0UserFunctionVariable._rewrite_tree_map_only_callc                 C   sN   t | jdd }|sd S tj|}|d u rd S t |dd }t|tjr%|S d S )NrV   rg  )r   r   sysmodulesr   r   r   r   )rt   module_namemodulerg  rX   rX   rY   rp    s   z.UserFunctionVariable._lookup_tree_map_functionselector.c                 C   sd   |  sd S z| }W n
 ty   Y d S w | |}|s d S tdd |D s+d S tt|S )Nc                 s   s    | ]}t |tV  qd S r   )r   type)r   rW  rX   rX   rY   	<genexpr>!      zDUserFunctionVariable._extract_tree_map_only_types.<locals>.<genexpr>)is_python_constantr  r   _flatten_type_specallr   r~   fromkeys)rt   r|  	raw_value	flattenedrX   rX   rY   ro    s   
z1UserFunctionVariable._extract_tree_map_only_typesc                 C   s   t |tr|gS t |tr'g }|D ]}| |}|d u r d S || q|S ttdd }|d urQt ||rQg }|jD ]}| |}|d u rI d S || q;|S d S )N	UnionType)r   r}  r   r  extendr   r   __args__)rt   r   	collectedentryflat
union_typerX   rX   rY   r  %  s(   




z'UserFunctionVariable._flatten_type_specTc                 C   r   r   rX   r   rX   rX   rY   is_python_hashable;  r   z'UserFunctionVariable.is_python_hashablec                 C   
   t | jS r   )hashr   r   rX   rX   rY   get_python_hash>  r   z$UserFunctionVariable.get_python_hashotherc                 C   s   t |tjo| j|ju S r   )r   r   r   r   rt   r  rX   rX   rY   is_python_equalA     z$UserFunctionVariable.is_python_equalF)6rU   rV   rW   r   r   _nonvar_fields	frozensetri  classmethodr   r   r   r   r[   r  r  r   rx   r  r   r=   r   r   r   r   r}  r  r   r~   r   r   r   r  r   r'  r)  r?   r   r   rR  r\  rl  r   r[  rp  ro  r  r	   r  intr  objectr  __classcell__rX   rX   r
  rY   r     s    	


>

k

!


&
r   c                       >   e Zd ZdZdddee deeef def fddZ  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   rD   r   r   rZ   c                    s   t |dkr9|s9|d }d }t|ttfr| }|d ur9||jjv r)|jj| S t |||}||jj|< |S t |||S rb   )	r   r   r   r  r   r   signature_cacher  r   )rt   r   r   r   
target_arg	cache_keyr   r
  rX   rY   r   P  s   z&InspectSignatureVariable.call_function
rU   rV   rW   r   r   r=   r~   r   r   r  rX   rX   r
  rY   r  E  s    

r  c                       s   e Zd ZdhejZdeedf dededdf fddZ	defd	d
Z
dedefddZdddee deeef defddZ  ZS )rq  rt  .rc  r   rZ   Nc                    "   t  jdi | || _|| _d S ry   )r  rx   rt  rc  )rt   rt  rc  r   r
  rX   rY   rx   o  s   
z$TreeMapOnlyFunctionVariable.__init__c                 C   s   t S r   r   r   rX   rX   rY   r  y  r   z'TreeMapOnlyFunctionVariable.python_typenodec                    s:   z|   W n
 ty   Y dS w t fdd| jD S )NFc                 3   s    | ]}t  |V  qd S r   )
issubclass)r   allowed	node_typerX   rY   r~    r  zDTreeMapOnlyFunctionVariable._matches_allowed_type.<locals>.<genexpr>)r  r   anyrt  )rt   r  rX   r  rY   _matches_allowed_type|  s   z1TreeMapOnlyFunctionVariable._matches_allowed_typer   rD   r   c                 C   sZ   |s
| j |||S |d }| |r| j |||S t|dks#|r+| j |||S |S )Nr   r8   )rc  r   r  r   )rt   r   r   r   leafrX   rX   rY   r     s   
z)TreeMapOnlyFunctionVariable.call_function)rU   rV   rW   r   r  r   r}  r=   r   rx   r  r   r  r   r~   r   r   r  rX   rX   r
  rY   rq  i  s2    


rq  c                	       sp   e Zd Z	ddejdededdf fddZed	edefd
dZ	ddde
e deeef defddZ  ZS )BuiltinMethodVariableFr   r   r   rZ   Nc                    s,   t  jdi | t|tjsJ || _d S ry   )r  rx   r   r   BuiltinMethodTyper   r	  r
  rX   rY   rx     s   
zBuiltinMethodVariable.__init__objc                 C   s0   | j }| j}|tu r|dkpt|tu o|dkS )N__new____contains__)r  rU   r   r}  r  )r  method_selfmethod_namerX   rX   rY   is_supported_builtin_method  s
   z1BuiltinMethodVariable.is_supported_builtin_methodr   rD   r   c                 C   sD   | j j}| j j}| jot| jd}tj|||dd}|||||S )Nr  T)realize)r   r  rU   r   r'   r=   r   call_method)rt   r   r   r   r  r   
obj_sourceobj_vtrX   rX   rY   r     s
   z#BuiltinMethodVariable.call_functionr  )rU   rV   rW   r   r  r   r   rx   staticmethodr  r   r=   r~   r   r   r  rX   rX   r
  rY   r    s,    

r  c                
       s  e Zd Zdejdeeef dddeddf
 fdd	Zdejfd
dZ	defddZ
defddZdefddZdefddZdefddZ defddZeZd>ddZdeeef fddZdefddZd d!defd"d#Zd d$d%edefd&d'Zd d$defd(d)Zd d$defd*d+Zd d!dee fd,d-Zd d!d.eegef ddfd/d0Zde d1 fd2d3Z!d d$d4eddfd5d6Z"defd7d8Z#defd9d:Z$d d$d%ed;ee deeef def
 fd<d=Z%  Z&S )?LocalGeneratorObjectVariableru   r   inline_tracerrB   r   rZ   Nc                    s(   t  jdi | || _|| _|| _d S ry   )r  rx   ru   r   r  )rt   ru   r   r  r   r
  rX   rY   rx     s   
z%LocalGeneratorObjectVariable.__init__c                 C   r  r   )ru   r   rX   rX   rY   r     r  z%LocalGeneratorObjectVariable.get_codec                 C   r   r   r   r   rX   rX   rY   r     r   z)LocalGeneratorObjectVariable.get_filenamec                 C   r   r   r   r   rX   rX   rY   r     r   z%LocalGeneratorObjectVariable.get_namec                 C   s   t d)Nr   r   r   rX   rX   rY   r     r  z)LocalGeneratorObjectVariable.get_functionc                 C   r   NFrX   r   rX   rX   rY   r     r   z%LocalGeneratorObjectVariable.has_selfc                 C      |   S r   )r   r   rX   rX   rY   rU     r  z%LocalGeneratorObjectVariable.__name__c                 C   s   | j j d|   dS )N(r5  )r  rU   r   r   rX   rX   rY   __str__  r  z$LocalGeneratorObjectVariable.__str__codegenrA   c           
   
   C   s   ddl m} ddlm}m} |j}||}||}||}|J |/ | | j}	|	js2| || _	t
| j	| W d    n1 sEw   Y  W d    n1 sTw   Y  W d    d S W d    d S 1 slw   Y  d S )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)
rt   r  r  r  r  r   savedisallowtemptracerrX   rX   rY   r    s   P z(LocalGeneratorObjectVariable.reconstructc                 C   r  r   r   r   rX   rX   rY   r     r  z(LocalGeneratorObjectVariable.get_globalsc                 C   r  r   )r   GeneratorTyper   rX   rX   rY   r    r  z(LocalGeneratorObjectVariable.python_typer   rE   c              
   C   s   | j }|  rtt| z| W S  ty" } zd|_|d }~w ty;   tddddt	 dgt
jd Y d S  ty` } ztjj|   d|_|js[|js[| jd7  _ d }~w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   rE  r$   r[   r:  
eval_frame	skip_coder   
skip_frame	one_graphr2  rX  )rt   r   r  rU  rX   rX   rY   next_variable  s6   



z*LocalGeneratorObjectVariable.next_variablerD   r   c                 C   s"   ||   jv rtdS tdS NTF)r  __dict__r?   r   rt   r   r   rX   rX   rY   r     s   

z-LocalGeneratorObjectVariable.call_obj_hasattrc                 C   r   r  rX   r   rX   rX   rY   has_unpack_var_sequence  r   z4LocalGeneratorObjectVariable.has_unpack_var_sequencec                 C   r   r   rX   r   rX   rX   rY   has_force_unpack_var_sequence  r   z:LocalGeneratorObjectVariable.has_force_unpack_var_sequencec                 C   s   g }|  ||j |S r   )force_apply_to_var_sequenceappend)rt   r   r   rX   rX   rY   r    s   z6LocalGeneratorObjectVariable.force_unpack_var_sequencer   c                 C   s4   	 z	||  | W n ty   t| Y d S w qr   )r  r    r   )rt   r   r   rX   rX   rY   r  &  s   z8LocalGeneratorObjectVariable.force_apply_to_var_sequenceFc                 C   r   r  rX   r   rX   rX   rY   r   1  r   z=LocalGeneratorObjectVariable.should_allow_nested_graph_breaksexcc              
   C   sH   | j }z|| W d S  ty# } z|| W Y d }~d S d }~ww r   )r  _raise_exception_variabler   exception_handler)rt   r   r  r  rU  rX   rX   rY   _setup_exception4  s   z-LocalGeneratorObjectVariable._setup_exceptionc                 C   s   | j d u p
| j jdkS )Nr   )r  instruction_pointerr   rX   rX   rY   _is_generator_just_started?  s   z7LocalGeneratorObjectVariable._is_generator_just_startedc                 C      t | jddS )Nr  F)r   r  r   rX   rX   rY   r  B  s   z4LocalGeneratorObjectVariable._is_generator_exhaustedr   c              	      s
  |dkr	|  |S |dkr| S |dkr6|  r)t|r)tdd |D s)tt| | j}|| |  |S |dkr| j}|  sE|  rKd|_	t
jS z| |t
td tjd	krh|jjd
krhd|_	t
jW S W n tyx   d|_	t
j Y S w z|  |rtt| W nv ty   d|_	t
j Y S  ty   |jd usJ |j Y S w |dkr| j}z| |t|dkr|d n|d  W n ty    w |  |}tdtfi }z| |t
|d |  | W n t|y   Y |S w tt| |S t ||||S )N__next____iter__sendc                 s       | ]}|  V  qd S r   )is_constant_noner,  rX   rX   rY   r~  X      z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>closeTrX   )rm     CALL_INTRINSIC_1throwrm  r8   r   __InternalThrowException)r  r  r   r  r!   r   r  	push_manyr  r  r   r>   r  ExceptionVariableGeneratorExitrx  version_infonext_instructionopnamer   r>  r    symbolic_resultr   r}  rC  r   r  r  )rt   r   r   r   r   r  retvalexc_typer
  rX   rY   r  E  sv   









(
>
z(LocalGeneratorObjectVariable.call_methodr  rA   rZ   N)'rU   rV   rW   r   r   r~   r   r   rx   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  rX   rX   r
  rY   r    s    

!




r  c                   @   s   e Zd ZdZdS )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)rU   rV   rW   r   rX   rX   rX   rY   r    s    r  c                	       s   e Zd ZdZeddedededdf fdd	Zd
e	defddZ
dejfddZdee	ef fddZdefddZdddee dee	ef ddfddZdddee dee	ef defddZ  ZS )LocalGeneratorFunctionVariablezxfunctions that behaves like iterators

    .. note::

        This is a wrapper around (Nested)UserFunctionVariable
    )generator_clsvtr   r   rZ   Nc                   r  ry   )r  rx   r  r   )rt   r  r   r   r
  rX   rY   rx     s   
z'LocalGeneratorFunctionVariable.__init__r   c                 C   s"   || j jv rt| |S t| j|S r   )r  r  r   r  )rt   r   rX   rX   rY   __getattr__  s   
z*LocalGeneratorFunctionVariable.__getattr__c                 C   
   | j  S r   )r  r   r   rX   rX   rY   r   %  r   z'LocalGeneratorFunctionVariable.get_codec                 C   r  r   )r  r   r   rX   rX   rY   r   (  r   z*LocalGeneratorFunctionVariable.get_globalsc                 C   r  r   )r  r   r   rX   rX   rY   r   +  r   z'LocalGeneratorFunctionVariable.has_selfr   rE   r   rC   c                 C   s   ddl m} ||| ||S )Nr   )rC   )r  rC   build_inline_tracer)rt   r   r   r   rC   rX   rX   rY   _build_inline_tracer.  s   z3LocalGeneratorFunctionVariable._build_inline_tracerrD   c                 C   sf   t | j stdt| j dddgd | |t||}| j }| j }| j|||| j	d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   r  r   r#   r   r  r   r   r   r   )rt   r   r   r   r  ru   r   rX   rX   rY   r   =  s$   

z,LocalGeneratorFunctionVariable.call_function)rU   rV   rW   r   r  r   r}  r   rx   r   r  r   r   r   r~   r   r   r   r   r=   r  r   r   r  rX   rX   r
  rY   r    sD    


r  c                       sX   e Zd ZdZdededdf fddZdd	d
ee de	e
ef ddf fddZ  ZS )3FunctionDecoratedByContextlibContextManagerVariablezm
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager
    r  r   rZ   Nc                    s   t  j|fdti| d S )Nr   )r  rx   r  )rt   r  r   r
  rX   rY   rx   e  s   
z<FunctionDecoratedByContextlibContextManagerVariable.__init__r   rE   r   rB   c                    s.   t  |||}t|tjjjsJ d|_|S r   )r  r  r   r[   r:  symbolic_convertrB   is_generator_from_ctx_manager)rt   r   r   r   r  r
  rX   rY   r  l  s   
zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracer)rU   rV   rW   r   r   r   rx   r   r=   r~   r   r  r  rX   rX   r
  rY   r  \  s    
r  c                       s   e Zd ZdZ	ddedef dededB deddf
 fd	d
Zde	fddZ
dee fddZdeej fddZdddee dee	ef def fddZddde	def fddZ  ZS )r  z$Some unsupported user-defined methodNr   .r  r  r   rZ   c                    sV   t  jdd|i| || _|| _|d u r'|dd ur)t|dd| _d S d S d S )Nr   r   __func__rX   )r  rx   r  r  r   r'   )rt   r   r  r  r   r
  rX   rY   rx     s   zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )Nr  r4  r5  )r  rU   r   r  r   rX   rX   rY   r    s   zUserMethodVariable.__repr__c                 C      | j gS r   r  r   rX   rX   rY   r     r  zUserMethodVariable.self_argsc                 C   r  r   )r   
MethodTyper   rX   rX   rY   r    r  zUserMethodVariable.python_typer   rD   r   c           
         sf  ddl m}m} || jr'g |  |}tj| jtjjj	d}|
|||S || jrFg |  |}tj| jtjjjd}|
|||S |j rzt| jtjrzt| jdd}|d urf|drf|dksi| jry| jj|| jjt||| jdS ntd ur| jtjju rt| j
|| jg|R |S | jrt| jj| jj}	t||	|  ||S t 
|||S )	Nr   )is_leaf_functionis_nonstrict_trace_callabler6  rV   r  z	torch.nn.ztorch.nn.utils.parametrize)constant)trace_rulesr  r  r   r   r   rF  r[   rG  rH  r   LEAF_FUNCTIONr   is_root_tracerr   r  NNModuleVariabler   
startswithr   r  rU   r   r@   FSDPParamGroupuse_training_stateTorchCtxManagerClassVariabler   rI  r   r  )
rt   r   r   r   r  r  	call_argsvarmodule_attrr   r
  rX   rY   r     sH   

z UserMethodVariable.call_functionr   c                    s6   |dkr| j S |dkrt|| j| jS t ||S )Nr  r	  )r  r=   r   r   r  r  r)  r  r
  rX   rY   r)    s
   zUserMethodVariable.var_getattrr   )rU   rV   rW   r   r   r   r=   r   rx   r   r  r   r   r}  r   r  r  r   r~   r   r)  r  rX   rX   r
  rY   r    s6    

"Dr  c                       b   e Zd Zdedddeddf fddZd	d
dee dee	ef def fddZ
dddZ  ZS )WrappedUserMethodVariablewrappedr  rF   r   rZ   Nc                    sB   | dd  | dd  t j|j|jfi | || _|| _d S )Nr   r  )r   r  rx   r   r  r  r  rt   r  r  r   r
  rX   rY   rx     s
   
z"WrappedUserMethodVariable.__init__r   rD   r   c                    ,   | j | t |||}| j | |S r   r  enterr  r   exitrt   r   r   r   r   r
  rX   rY   r         z'WrappedUserMethodVariable.call_functionr  rA   c                    2      fdd  j  tdd d S )Nc                      
    j S r   r  rX   r  rt   rX   rY   <lambda>     
 z7WrappedUserMethodVariable.reconstruct.<locals>.<lambda>r8   Fadd_push_nullr  extend_outputr   rt   r  rX   r(  rY   r       
z%WrappedUserMethodVariable.reconstructr  )rU   rV   rW   r  r   rx   r   r=   r~   r   r   r  r  rX   rX   r
  rY   r    (    
r  c                       r  )WrappedUserFunctionVariabler  r  rF   r   rZ   Nc                    s2   | dd  t j|jfi | || _|| _d S )Nr   )r   r  rx   r   r  r  r  r
  rX   rY   rx     s   
z$WrappedUserFunctionVariable.__init__r   rD   r   c                    r  r   r   r#  r
  rX   rY   r     r$  z)WrappedUserFunctionVariable.call_functionr  rA   c                    r%  )Nc                      r&  r   r'  rX   r(  rX   rY   r)  )  r*  z9WrappedUserFunctionVariable.reconstruct.<locals>.<lambda>r8   Fr+  r.  rX   r(  rY   r  (  r/  z'WrappedUserFunctionVariable.reconstructr  )rU   rV   rW   r   r   rx   r   r=   r~   r   r   r  r  rX   rX   r
  rY   r1    s(    
r1  c                    s^   dt dtfdd  fdd|D } fdd| D }||i |}| jj||t|d	S )
NxrZ   c                 S   s   |   rtd|  S |  S )NrK   )	is_tensorr   get_real_valuer  )r2  rX   rX   rY   convert5  s   z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS rX   rX   r   r2  r5  rX   rY   r.  :  r/  z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]	\}}| |qS rX   rX   r   r   r   r7  rX   rY   r   ;      z0invoke_and_store_as_constant.<locals>.<dictcomp>r   )r=   r   r   r   register_attr_or_moduler*   )r   r   r   r   r   resrX   r7  rY   rI  .  s   rI  c                       s  e Zd ZdhejZ	d8dededeeef dedB dedB dedB dedB d	edB d
eddf fddZ	de
e fddZdejfddZdejfddZdeej fddZd8dee dB dejfddZdefddZdee dejfddZddded edefd!d"Zddd#ed$ee d
eeef def
 fd%d&Zdefd'd(Zddd#edef fd)d*Zddd#edef fd+d,Zdefd-d.Z deeef fd/d0Z!d1dd$ee d
eeef deeef fd2d3Z"d9d6d7Z#  Z$S ):r   r   NrY  ru   r{   r}   r   r   
wrapped_fnr   rZ   c	           
         s   |	 dd u r|	jt d t jdi |	 t| ts J t| tj	s*J t|t
s1J || _|| _|| _|| _|| _|| _|| _|| _d S )Nmutation_typer=  rX   )r   updater:   r  rx   r   r  r   r   r   r~   rY  ru   r   r{   r}   r   r   r<  )
rt   rY  ru   r   r{   r}   r   r   r<  r   r
  rX   rY   rx   J  s   
z#NestedUserFunctionVariable.__init__c                 C   r  r   rX   r   rX   rX   rY   r   g  r   z$NestedUserFunctionVariable.self_argsc                 C   r  r   )r   r   rX   rX   rY   r  j  r  z-NestedUserFunctionVariable.as_python_constantc                 C   r  r   )ru   r  r   rX   rX   rY   r   m  r   z#NestedUserFunctionVariable.get_codec                 C   r  r   r  r   rX   rX   rY   r  p  r  z&NestedUserFunctionVariable.python_type_convertingc              
   C   s   ddl m} t| }|d u rt }||v rtd|| zz| |W W || S  |y< } ztd|d }~ww || w )Nr8   )r9   z-cycle detected in mutually recursive closuresz1failed to convert closure cell to Python constant)baser9   idsetrT   add_get_function_impldiscard)rt   r@  r9   self_idrU  rX   rX   rY   r   s  s*   
z'NestedUserFunctionVariable.get_functionc              	   C   s(   z|    W dS  ttfy   Y dS w r  )r  r   r$   r   rX   rX   rY   r    s   z-NestedUserFunctionVariable.is_python_constantc                 C   s  d }| j rAddlm} | }g }| j jD ]'}|jj|}|| u r&tdt	|t
r1||}n| }|t| qt|}tj| j | j| j d |d}	| jr[| j |	_| jrd| j |	_| jr| j }
t	|
tr}ddlm} t||
}
t	|
tsJ |
|	_|	S )Nr   )rD   z self-referential nested function)argdefsr   r   )r   r  rD   
current_txr   r   r   	load_cellrT   r   r   r   r  r  r7   r   r   r   ru   r   rY  r{   rz   r}   r|   r   r   r   r~   r   )rt   r@  closure_cellsrD   r   cellsr#  r  r   ra   r   r   rX   rX   rY   rE    sB   



z-NestedUserFunctionVariable._get_function_implr   rD   name_varr   c                 C   s   |j j| |j| tS r   )r   r   
store_attrr   r>   )rt   r   rM  r   rX   rX   rY   call_setattr  s   z'NestedUserFunctionVariable.call_setattrr   r   c                    s0   |dkr| j |g|R  S t ||t||S )N__setattr__)rO  r  r  r   rt   r   r   r   r   r
  rX   rY   r    s   z&NestedUserFunctionVariable.call_methodc                 C   s
   | j d uS r   )r   r   rX   rX   rY   has_closure  r   z&NestedUserFunctionVariable.has_closurec                    sR   |dkr|   S |dkr|  S |dkr"t| dd }|r | S d S t ||S )NrU   rc   rz   r{   )r   r   r   r  r  const_getattr)rt   r   r   dr
  rX   rY   rS    s   z(NestedUserFunctionVariable.const_getattrc                    sB   |dkrt jt| dS |dkrt jt| dS t ||S )Nrc   ru   rz   r{   )r   r?   r   r   r  r   r  r
  rX   rY   r     s
   z+NestedUserFunctionVariable.call_obj_hasattrc                 C   r   r  rX   r   rX   rX   rY   r     r   z#NestedUserFunctionVariable.has_selfc                 C   r  r   r  r   rX   rX   rY   r     r  z&NestedUserFunctionVariable.get_globalsr   c                 C   s   |   }t|| j| j | jrt| jjnd tdd t	t
|   jD }| jr1| j |_t|j|i |}|  t|j }t|jj| t||| t|jD ]\}}	|	|vscJ | jj| }
|
||	< qY|S )Nc                 s   s    | ]}t d V  qd S r   )r7   )r   _rX   rX   rY   r~    r  z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>)r   r   r   r   rY  r  r{   r   r   r   r   r  r}   keys_as_python_constantr|   r   r?  r@  apply_defaultsr~   rA  r   r   r  r   r   r   )rt   r   r   r   ru   ra   rM   r   r   r   r"  rX   rX   rY   r'    s(   
z$NestedUserFunctionVariable.bind_argsr  rA   c                    s     fdd  | j   | jg  t| jjj | j	r+ | j	 n	  
d g | jr= | j n	  
d g | jrO | j n	  
d g | jrzz| j }  |g W n tyy    | j Y n
w   
d g  tdd | jr   fdd  | j  tdd  td  tdd  j}|jj| r|jjj|   D ]\}}    |  td  | qd S d S )	Nc                      s     tdS )Nr   )load_import_fromrU   rX   r  rX   rY   r)        z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>   Fc                           ddS )N	functoolswrapsrX  rX   rY  rX   rY   r)  ;  rZ  r8   r   T)r,  ru   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_toprN  )rt   r  r   r   r   r   rX   rY  rY   r    s^   






z&NestedUserFunctionVariable.reconstructr   r  )%rU   rV   rW   r   r  r=   r~   r   r   rx   r   r   r   r   r  r   r   r}  r  rC  r  r   r   r  rE  rO  r   r  rR  rS  r?   r   r   r   r'  r  r  rX   rX   r
  rY   r   D  s    
8
	

	


r   c                       r  )!WrappedNestedUserFunctionVariabler  r  rF   r   rZ   Nc              
      s   | dd  | dd  | dd  | dd  | dd  | dd  | dd  | dd  t |j|j|j|j|j|j|j	|j
 || _|| _d S )	NrY  ru   r   r{   r}   r   r   r<  )r   r  rx   rY  ru   r   r{   r}   r   r   r<  r  r  r  r
  rX   rY   rx   O  s(   

z*WrappedNestedUserFunctionVariable.__init__r   rD   r   c                    r  r   r   r#  r
  rX   rY   r   j  r$  z/WrappedNestedUserFunctionVariable.call_functionr  rA   c                    r%  )Nc                      r&  r   r'  rX   r(  rX   rY   r)  v  r*  z?WrappedNestedUserFunctionVariable.reconstruct.<locals>.<lambda>r8   Fr+  r.  rX   r(  rY   r  u  r/  z-WrappedNestedUserFunctionVariable.reconstructr  )rU   rV   rW   r   r   rx   r   r=   r~   r   r   r  r  rX   rX   r
  rY   re  N  s(    
re  c                	       s   e Zd ZddhejZddededB deddf fddZdefdd	Ze	ded
e
dd fddZdddee deeef defddZdddedefddZdddedefddZdefddZdefddZdedefddZ  ZS )SkipFunctionVariabler   reasonNr   rZ   c                    r  ry   )r  rx   r   rg  )rt   r   rg  r   r
  rX   rY   rx        
zSkipFunctionVariable.__init__c                 C   r  r   r   r   rX   rX   rY   r    r  z'SkipFunctionVariable.as_python_constantr   c                 C   s   t |ddr&|}|}t|ddr|j}t|d}t|dds|tj nt |r4t	|tj
 nt|s@t	|tj | ||dS )N_torchdynamo_disableF_torchdynamo_orig_callabler   )r   r   r   rk  r'   r   r%   r   	isbuiltinr&   BUILTIN_MATCHr5   )r   r   r   guard_on_sourceguard_on_valuerX   rX   rY   r     s   
z'SkipFunctionVariable.create_with_sourcer   rD   r   c              
   C   s  t | jddr&t | jdd }tdt| jd| j d| ddgd	 d S | jtjju rM|d
}|r8|	 }tdd| d| dd| dgd	 d S | jtjj
u r~|d
}|r`|	 }nd}tdd| d| dt|j dd| dgdd d S | jtjju rztddddgd	 W d S  ty } zt|jd d }~ww tjrddlm} ||| j}	t|	ts|	|||S t| jdd }
t| jd!d }|d u rd"nt|}z&t | j}d#|
 d$| d%}d&|
 d'g}d(|vr|d)|
 d*d+g7 }W nb ty`   d,d-h}||v rd.| d|
 d'}d/d0g}nA|d urC|d1rCd2| d|
 d}d3g}tjj|d4 d4|  nd5| d|
 d6}d7d8g}tjj|d4 d4|  Y nw |
d9krjd:}g }| j rq| j nd;}td<d=| d>|
 d?| ||d	 d S )@Nrj  F_torchdynamo_disable_msgz1Skip calling `torch.compiler.disable()`d functionzSkip calling function `z>` since it was wrapped with `torch.compiler.disable` (reason: r5  z(Remove the `torch.compiler.disable` callr   rX  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.r8   SourcelessBuilderrW   z<unknown qualname>rV   z<unknown module>z?Dynamo developers have intentionally marked that the function `z` in file `z` should not be traced.zAvoid calling the function `z`.r:  z: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[   r:  graph_breakr   r  r  r   f_codestep_unsupportedr$   r"   rX  r   dont_skip_tracingbuilderrs  r   r   rf  r   r   getfiler   r  r\   	warn_oncejoinrg  )rt   r   r   r   rX  graph_break_msgskip_frame_msgrU  rs  
rebuilt_fnqualname	module_orrz  pathr  r  known_python_builtin_modulesrg  rX   rX   rY   r     s   

	











&
z"SkipFunctionVariable.call_functionr   c                 C   s   t jt| j|S r   )r   r?   r   r   r   r  rX   rX   rY   r   3  s   z%SkipFunctionVariable.call_obj_hasattrc                 C   s&   |t v r
t| |S t|| j| j|S r   )r2   r   r(  r   r   r   r  rX   rX   rY   r)  8  s   z SkipFunctionVariable.var_getattrc                 C   r   r   rX   r   rX   rX   rY   r  >  r   z'SkipFunctionVariable.is_python_hashablec                 C   r  r   )r  r   r   rX   rX   rY   r  A  r   z$SkipFunctionVariable.get_python_hashr  c                 C   s   t |to|  | kS r   )r   r=   r  r  rX   rX   rY   r  D  s   
z$SkipFunctionVariable.is_python_equalr   )rU   rV   rW   r=   r  r   r   rx   r  r  r   r   r   r~   r   r?   r   r)  r   r  r  r  r  r  r  rX   rX   r
  rY   rf  {  s>    $

 
rf  c                       r  )WrappedSkipFunctionVariabler  r  rF   r   rZ   Nc                    sD   | dd  | dd  t j|jfd|ji| || _|| _d S )Nr   rg  )r   r  rx   r   rg  r  r  r  r
  rX   rY   rx   L  s
   
z$WrappedSkipFunctionVariable.__init__r   rD   r   c                    r  r   r   r#  r
  rX   rY   r   X  r$  z)WrappedSkipFunctionVariable.call_functionr  rA   c                    r%  )Nc                      r&  r   r'  rX   r(  rX   rY   r)  d  r*  z9WrappedSkipFunctionVariable.reconstruct.<locals>.<lambda>r8   Fr+  r.  rX   r(  rY   r  c  r/  z'WrappedSkipFunctionVariable.reconstructr  )rU   rV   rW   rf  r   rx   r   r=   r~   r   r   r  r  rX   rX   r
  rY   r  K  r0  r  c                       s   e Zd ZdZdedededdf fddZd	d
dedef fddZde	e fddZ
d	d
dee deeef defddZ  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   rZ   Nc                    r  ry   )r  rx   r  r  )rt   r  r  r   r
  rX   rY   rx   q  rh  z$WrapperUserFunctionVariable.__init__r   rD   r   c                    sF   || j krt| j| j }| jot| j|}t|||S t ||S r   )	r  r   r  r   r'   r=   r   r  r)  )rt   r   r   r   r   r
  rX   rY   r)  v  s
   
z'WrapperUserFunctionVariable.var_getattrc                 C   r  r   rX   r   rX   rX   rY   r   ~  r   z%WrapperUserFunctionVariable.self_argsr   c              
   C   sL  t | jdrt| j| jd }t|ddpd}|jdddd dkr| }tj|j	}|j
}d	| d
| ddt|g }	tjj|	 tjjjd}
|
tjrtjj }t | }|d j	|d j
f}dt|}d|d  d
|d  d}|t|7 }|
| |  t| }tt j!"|| t#| jg||S )N
cache_inforV   r  r  r8   )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: rv  )$r   r  r   r  splitframe_summaryosr  basenamefilenamelinenor  	tracebackformat_listr[   r:  r\   r~  logging	getLoggerisEnabledForDEBUG_guardsTracingContextextract_stackr   r   debugr   r   r   r   r   getattr_and_tracer   r?   )rt   r   r   r   	target_fnrz  r  r  r  rX  dynamo_logger
user_stack	frame_locuser_stack_formatteduser_stack_traceall_argsrX   rX   rY   r     sF   

z)WrapperUserFunctionVariable.call_function)rU   rV   rW   r   r   r   rx   r=   r)  r   r   r   r~   r   r  rX   rX   r
  rY   r  i  s    
r  c                
       sH   e Zd ZdZdededededdf
 fdd	Zdee fd
dZ	  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   rZ   Nc                    s    t  j||fi | || _d S r   )r  rx   r  )rt   r  r  r  r   r
  rX   rY   rx     s   
z"WrapperUserMethodVariable.__init__c                 C   r
  r   r  r   rX   rX   rY   r     r  z#WrapperUserMethodVariable.self_args)rU   rV   rW   r   r   r   r=   rx   r   r   r  rX   rX   r
  rY   r    s    
r  c                  C   s   t j rddlm}  | S i S )Nr   traceable_collective_remaps)r[   distributedis_available)torch.distributed._functional_collectivesr  r  rX   rX   rY   _traceable_collective_remaps  s   
r  c                 C   s>   t j s	J d|t  v sJ |j}| d}t||S )NzIllegal invocation.z)torch.distributed._functional_collectives)r[   r  r  r  valuesrU   import_sourcer'   )r   r   
inner_namepath_sourcerX   rX   rY   _traceable_collectives_source  s
   

r  c                       s   e Zd ZdZdedef dededdf fdd	Zed
ddedef de	dedd f
ddZ
ededefddZed
ddedef deeef fddZd
ddee deeef defddZ  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   rZ   Nc                   s,   t  j|fi | t|tsJ || _d S r   )r  rx   r   r   r  )rt   r   r  r   r
  rX   rY   rx     s   
z*CollectiveFunctionRewriteVariable.__init__r   rD   old_fnr   optionsc                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr   )r  r   )r  r_  r   )r   r  r   r  new_fn
new_sourcerX   rX   rY   r     s   z(CollectiveFunctionRewriteVariable.createvariablec                 C   s   t | o	| t v S r   )r   
isfunctionr  )r  rX   rX   rY   can_rewrite 	  s   z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS r   )r  r  )r   r   r  rX   rX   rY   r_  	  s   
z)CollectiveFunctionRewriteVariable.rewriter   c           	      C   s   dd l m} ddlm} t| j}t|j|i |j	}d}d|v rA|d 
 rAtd| j d|d|d| j g tjd	 | j|j|j|jfv rs|d
}|d urX|jn|jd
 j}||vritd| tj|| |d
< | j|||S )Nr   )REDUCE_OP_TO_STRrX   async_opz)async_op=True for distributed collectivesz, args=	, kwargs=z3`torch.compile` doesn't support `async_op=True for r   opzUnsupported all_reduce op: )torch.distributedr  r  r  r   r?  r   r~   r@  rA  r  r#   r   SUPPORTABLE
all_reducereduce_scatter_tensor_reduce_scatter_baser   r   
parametersdefaultr  r   r?   r   r  r   )	rt   r   r   r   distr  r?  reduce_op_var	reduce_oprX   rX   rY   r   	  s<   	
	

z/CollectiveFunctionRewriteVariable.call_function)rU   rV   rW   r   r   r   r   rx   r  r   r   r   r  r   r'   r_  r   r=   r~   r   r   r  rX   rX   r
  rY   r    sT    





r  c                       s:   e Zd Zdddee deeef def fddZ  ZS )FunctoolsWrapsVariabler   rD   r   r   rZ   c                    s@   |st  dkrdtdtf fdd}t|S t | |S )Nr8   r   rZ   c                    s8   t | tjr| j d dS td|  dg tjd d S )Nr   )r<  zfunctools.wrapsz]`torch.compile` can't trace `functools.wraps` on functions defined outside the compile regionr   )r   r   r   cloner#   r   r  r  r   rX   rY   r^  F	  s   
z3FunctoolsWrapsVariable.call_function.<locals>.wraps)r   r   r=   r   LambdaVariabler  r   )rt   r   r   r   r^  r
  r  rY   r   >	  s   
z$FunctoolsWrapsVariable.call_function)	rU   rV   rW   r   r=   r~   r   r   r  rX   rX   r
  rY   r  =	  s    
r  c                   @   s@   e Zd ZdefddZdddee deeef defdd	Z	d
S )CollectionsNamedTupleFunctionrZ   c                 C   r  r   r  r   rX   rX   rY   r  X	  r  z0CollectionsNamedTupleFunction.as_python_constantr   rD   r   r   c              
   C   s   t ||}|rHz| jdd |D i dd | D }W n" ty? } ztt||tttj	|j
d W Y d }~nd }~ww tj|t dS tdd|d	|d
g tjd d S )Nc                 S   r*  rX   r+  r6  rX   rX   rY   r.  e	  r/  z?CollectionsNamedTupleFunction.call_function.<locals>.<listcomp>c                 S   r0  rX   r+  r8  rX   rX   rY   r   f	  r9  z?CollectionsNamedTupleFunction.call_function.<locals>.<dictcomp>r  r>  znamedtuple constructionzargs=r  z?`torch.compile` only support certain input types for namedtupler   )r0   r   r   r   r!   r}  r   mapr?   r   r   r   UserDefinedClassVariabler<   r#   r   r  )rt   r   r   r   constant_argsr   r  rX   rX   rY   r   [	  s8   


z+CollectionsNamedTupleFunction.call_functionN)
rU   rV   rW   r   r  r   r=   r~   r   r   rX   rX   rX   rY   r  W	  s    
r  c                       s  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d	Z	de
fd
dZd'ddZdefddZdddee deeef defddZdddedefddZdddedefddZdefddZdefddZdefdd Zdefd!d"Zd#edefd$d%Z  ZS )(FunctoolsPartialVariableoriginal_cache_hashNra   r   keywordsr   rZ   c                    sV   t  jdi | || _t|tsJ || _t|tsJ || _t	t
| _|| _d S ry   )r  rx   ra   r   r   r   r~   r  r]  partialr3   
fake_valuer  )rt   ra   r   r  r  r   r
  rX   rY   rx   	  s   
z!FunctoolsPartialVariable.__init__c                 C   r  r   )r]  r  r   rX   rX   rY   r  	  r  z$FunctoolsPartialVariable.python_typer  rA   c                    s      fdd  | j | jr | j | js) tt| jd d d S  | j  t	| j
 }  t|t| j d |d d S )Nc                      r\  )Nr]  r  r_  rX   rY  rX   rY   r)  	  rZ  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>r8   F)r,  ra   r   foreachr  r-  r   r   r  r   keyscreate_call_function_kw)rt   r  r  rX   rY  rY   r  	  s   
z$FunctoolsPartialVariable.reconstructc                 C   r  r   r+  r   rX   rX   rY   r   	  r  z%FunctoolsPartialVariable.get_functionr   rD   c                 C   s,   | j t| }i | j|}| j|||S r   )r   r   r  ra   r   )rt   r   r   r   merged_argsmerged_kwargsrX   rX   rY   r   	  s   z&FunctoolsPartialVariable.call_functionr   c                 C   s   t jttt|S r   )r   r?   r   r   r]  r  r3   r  rX   rX   rY   r   	  s   z)FunctoolsPartialVariable.call_obj_hasattrc                 C   s   | j ot| j |}|dkr| jS |dkrtj| j|dS |dkr1dd | j D }tj||dS |t	v r;t
| |S tt| d S )Nra   r   r   r  c                 S   s   i | ]
\}}t ||qS rX   )r?   r   r8  rX   rX   rY   r   	  s    z8FunctoolsPartialVariable.var_getattr.<locals>.<dictcomp>)r   r'   ra   r   rJ   r   r  r   ConstDictVariabler2   r(  r!   r   )rt   r   r   r   r   rX   rX   rY   r)  	  s   z$FunctoolsPartialVariable.var_getattrc                 C   s:   t j| j gdd | jD R i dd | j D S )Nc                 S   r*  rX   r+  r,  rX   rX   rY   r.  	  r/  z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   r0  rX   r+  r8  rX   rX   rY   r   	  r9  z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)r]  r  ra   r  r   r  r   r   rX   rX   rY   r  	  s   z+FunctoolsPartialVariable.as_python_constantc                 C   sP   t j| j gdd | jD R i dd | j D }| jdur&| j|_|S )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   r*  rX   guard_as_python_constant)r   r   rX   rX   rY   r.  	  r/  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   r0  rX   r  r8  rX   rX   rY   r   	  r9  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>N)	r]  r  ra   r  r   r  r   r  
cache_hashrt   r   rX   rX   rY   r  	  s   
z1FunctoolsPartialVariable.guard_as_python_constantc                 C   s6   | j  otdd | jD otdd | j D S )Nc                 s   r  r   r  r,  rX   rX   rY   r~  	  r  z>FunctoolsPartialVariable.is_python_hashable.<locals>.<genexpr>c                 s   r  r   r  r   r   rX   rX   rY   r~  	  r  )ra   r  r  r   r  r  r   rX   rX   rY   r  	  s
   
z+FunctoolsPartialVariable.is_python_hashablec                 C   sB   | j  }dd | jD }dd | j D }t|g||R S )Nc                 s   r  r   r  r,  rX   rX   rY   r~  	  r  z;FunctoolsPartialVariable.get_python_hash.<locals>.<genexpr>c                 s   r  r   r  r  rX   rX   rY   r~  	  r  )ra   r  r   r  r  r  )rt   	func_hash	args_hashvalues_hashrX   rX   rY   r  	  s   
z(FunctoolsPartialVariable.get_python_hashr  c                 C   sX   t |to+| j|jo+tdd t| j|jD o+tdd t| j |j D S )Nc                 s       | ]
\}}| |V  qd S r   r  )r   arg_aarg_brX   rX   rY   r~  	  
    
z;FunctoolsPartialVariable.is_python_equal.<locals>.<genexpr>c                 s   r  r   r  )r   value_avalue_brX   rX   rY   r~  	  r  )	r   r  ra   r  r  r   r   r  r  r  rX   rX   rY   r  	  s   
z(FunctoolsPartialVariable.is_python_equalr   r  )rU   rV   rW   r=   r  r   r~   r   r   rx   r}  r  r  r   r   r?   r   r)  r  r  r   r  r  r  r  r  r  rX   rX   r
  rY   r  }	  sX    






r  c                
       s  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dZede
d	edd fd
dZdede
ddf fddZede	de
f fddZdefddZde
fddZdddee deeef defddZdddedee deeef def
ddZde
fddZ  ZS ) PolyfilledFunctionVariabler   r<  traceable_fnrZ   .c                 C   r   r   rX   )r   rX   rX   rY   _get_polyfill_handlers
  s   z1PolyfilledFunctionVariable._get_polyfill_handlersr   r   c                 C   r   r   r   r   rX   rX   rY   r   

  s   z-PolyfilledFunctionVariable.create_with_sourcer   Nc                    s   t  jdi | || _|  ||}d }t|s$J d| d| dD ]}t||d }|r:t|s6J |} n	q&td| d|| _|| _	d S )NzPolyfill handler z is not callable for )__torch_dynamo_polyfill____python_implementation__z# does not have a traceable functionrX   )
r  rx   r   r  r   callabler   r>  r<  r  )rt   r   r   handlerr  candidate_attr	candidater
  rX   rY   rx   
  s"   

z#PolyfilledFunctionVariable.__init__c                 C   r  r   )r  r   rX   rX   rY   polyfill_fn,
  s   z&PolyfilledFunctionVariable.polyfill_fnc                 C   r  )N*__torch_dynamo_can_constant_fold_through__F)r   r<  r   rX   rX   rY   can_constant_fold_through0
     z4PolyfilledFunctionVariable.can_constant_fold_throughc                 C   r  r   r+  r   rX   rX   rY   r   5
  r  z'PolyfilledFunctionVariable.get_functionr   rD   r   c              
   C   s   |   r#t||r#| jdd |D i dd | D }t||S | jtju rot|dkro|sot	|d t
jt
jfrotdd |d jD rot
jj||jd	tjtd
d |d jD fi tdd |d jD dS t|| j}||||S )Nc                 S   r*  rX   r+  r6  rX   rX   rY   r.  C
  r/  z<PolyfilledFunctionVariable.call_function.<locals>.<listcomp>c                 S   r0  rX   r+  r8  rX   rX   rY   r   D
  r9  z<PolyfilledFunctionVariable.call_function.<locals>.<dictcomp>r8   r   c                 s   s>    | ]}|  rt| tpt|tjo| tu V  qd S r   )r  r   r  r  r   SymNodeVariabler  r6  rX   rX   rY   r~  O
  s    
z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>r   c                 s   r  r   as_proxy)r   arX   rX   rY   r~  Z
  r  c                 S   s"   g | ]}|  r| n|jqS rX   )r  r  sym_numr6  rX   rX   rY   r.  ^
  s    
)r   )r  r1   r   r   r=   r   builtinssumr   r   r   rJ   TupleVariabler  r  r   r   create_proxyr[   sym_sumr   r  r   )rt   r   r   r   r   traceable_function_variablerX   rX   rY   r   8
  sH   
	z(PolyfilledFunctionVariable.call_functionr   c                 C   s   |dkr|  |||S t| j|d }|s$t|s$t|d| d| j  i }| jr1t| j||d< t|fi |}| |||S )N__call__zCannot find callable z in r   )r   r   r   r4   r;   r   r'   r  )rt   r   r   r   r   methodr  polyfilled_method_variablerX   rX   rY   r  l
  s   z&PolyfilledFunctionVariable.call_methodc                 C   r  r   r  r   rX   rX   rY   r  
  r  z-PolyfilledFunctionVariable.as_python_constant)rU   rV   rW   r=   r  r  r]  cacher~   r   r   r   r   r  r   r   rL   rx   propertyr  r   r  r   r   r   r   r   r  r  r  rX   rX   r
  rY   r  	  sX    $

4

r  c                       sl   e Zd Zdededdf fddZdd
dZdddefddZdddee de	e
ef defddZ  ZS )SysFunctionVariabler   r   rZ   Nc                    s   t  jdi | || _d S ry   )r  rx   r   )rt   r   r   r
  rX   rY   rx   
  s   
zSysFunctionVariable.__init__r   rD   variables.TupleVariablec                 C   sT   t |jr|jd }|j}||d}t||||g}ntjtjtjg}t|S )Nr  __traceback__)	r   exn_vt_stackr  r)  r=   r   r   r>   r  )rt   r   exnrW  tbr   rX   rX   rY   exc_info
  s   


zSysFunctionVariable.exc_infoc                 C   s   |  |jd S )Nr8   )r  r   r   rX   rX   rY   	exception
  s   zSysFunctionVariable.exceptionr   c                 C   s0   | j tju r| |S | j tju sJ | |S r   )r   rx  r  r  r   rX   rX   rY   r   
  s   

z!SysFunctionVariable.call_function)r   rD   rZ   r  )rU   rV   rW   r   rx   r  r=   r  r   r~   r   r   r  rX   rX   r
  rY   r  
  s    

r  ) create_tma_experimental_metadatacreate_tma_stable_metadataTMADescriptorMetadataTritonHOPifierc                   @   sP  e Zd ZdedefddZdedefddZdede	fd	d
Z
dddeejjjdf fddZde	deee	f ddde	fddZdede	f dee deeef ded de	defddZde	ded de	dedef
ddZde	ded dee	 fd d!Zd"ede	fd#d$Zdd%dee	 dd%fd&d'Zdd%d(e	d)eee	f dddd*f
d+d,Zd-S ).DynamoTritonHOPifierrX  rZ   c                 C   s   t ddd| g d d S )Nz!triton kernel unsupported featurer  z/Encountered triton kernel unsupported feature: r   r#   )rt   rX  rX   rX   rY   raise_unsupported
  s   
z&DynamoTritonHOPifier.raise_unsupportedmaybe_callablec                 C   s   t |ttfS r   )r   r   r   )rt   r  rX   rX   rY   is_callable
  r  z DynamoTritonHOPifier.is_callabler   c                 C   s   |j S r   ri  )rt   r   rX   rX   rY   	get_value
  r  zDynamoTritonHOPifier.get_valuegridrI   .c                 C   sB   ddl m} t||r| S tddt| dg tjd d S )Nr8   )rI   z/unsupported grid type for triton hop check_gridzgrid type = z;`torch.compile` only supports list-like grid for check_gridr   )listsrI   r   r  r#   r}  r   r  )rt   r  rI   rX   rX   rY   
check_grid
  s   

zDynamoTritonHOPifier.check_gridmetar   rD   c                 C   s&   dd |  D }|||gi }|S )Nc                 S      i | ]\}}t j||qS rX   r   r?   r   r8  rX   rX   rY   r   
  s    z2DynamoTritonHOPifier.call_grid.<locals>.<dictcomp>)r   r   )rt   r  r!  r   meta_varrX   rX   rY   	call_grid
  s   zDynamoTritonHOPifier.call_griduser_fnr   r   r  c           	      C   s*   ddl m} |||}||||}|S )Nr8   rr  )r|  rs  r   r   )	rt   r&  r   r   r   r  rs  wrapped_user_functionr   rX   rX   rY   call_user_defined_fn
  s   z)DynamoTritonHOPifier.call_user_defined_fnuser_objr   c                 C   s6   ddl m} |d usJ ||t|j| |}|S )Nr8   )VariableBuilder)r|  r*  r'   kernel_source_wrap)rt   r)  r   r  r   r*  wrapped_user_objrX   rX   rY   wrap_user_defined_obj
  s   z*DynamoTritonHOPifier.wrap_user_defined_objconfigsc                 C   s   | |}dd |D }|S )Nc                 S   r*  rX   r  )r   r   rX   rX   rY   r.  
  r/  z=DynamoTritonHOPifier.maybe_unpack_configs.<locals>.<listcomp>)unpack_var_sequence)rt   r/  r   rX   rX   rY   maybe_unpack_configs
  s   
z)DynamoTritonHOPifier.maybe_unpack_configsr   c                 C   s   |  s	| d | S )Nz`@triton.heuristics must return constant values because configs can only contain constant values.)r  r  r  r  rX   rX   rY   maybe_unpack_heuristic_result
  s
   z2DynamoTritonHOPifier.maybe_unpack_heuristic_resultTritonKernelVariablec                 C   s>   |j d ust|dkr| d t||j|j|d |jdS )Nr8   z7Triton kernels should be called with only a single gridr   )kernel
kernel_idxr  r+  )r  r   r  r}  r4  r5  r   )rt   r  r   rX   rX   rY   call_getitem	  s   z!DynamoTritonHOPifier.call_getitemgridscombined_argszvariables.ConstantVariablec                 C   s  ddl m} i }t| D ]}|| }t|ttfr'| ||< | ||< qdd |	 D }	ddl
m}
m} dd |	 D }dd |		 D }| D ]}| }| sh| sh| d	t| d
 qO|
|}||t}|jd|d|j|||| d td S )Nr8   )r  c                 S   r"  rX   r#  r8  rX   rX   rY   r   3  s    z1DynamoTritonHOPifier.call_HOP.<locals>.<dictcomp>r   )kernel_side_tabletriton_kernel_wrapper_mutationc                 S   s,   i | ]\}}t |tr| r|| qS rX   )r   r=   r  r  r8  rX   rX   rY   r   ?  s    c                 S   s(   i | ]\}}t |tr| s||qS rX   )r   r=   r  r8  rX   rX   rY   r   D  s    z.Unexpected argument type for a Triton kernel: r  r   rX   )r5  constant_args_idxr  tma_descriptor_metadatar   )dictsr  r   r  r   !TMADescriptorExperimentalVariableTMADescriptorStableVariableto_metadata
get_tensorr   *torch._higher_order_ops.triton_kernel_wrapr9  r:  r  r  r3  is_symnode_liker  repradd_constant_argsr~   r   r  r5  r  r   r?   )rt   r  r7  r8  r   r  r<  r   r   combined_args_vtr9  r:  r  non_constant_argsr;  r!  rX   rX   rY   call_HOP  sV   

zDynamoTritonHOPifier.call_HOPN)rU   rV   rW   r   r   r  r=   r   r  r   r  r   r[   fxproxyProxyr   r~   r%  r   r   r
   r(  r.  r   r1  r2  r6  rH  rX   rX   rX   rY   r  
  s     









r  c                
       s   e Zd ZU ded< ded< edB ed< ded< dededB ded	ed
df
 fddZdddee d	e	e
ef d
efddZddde
dee d	e	e
ef d
ef
 fddZded
efddZ  ZS )r3  rG   r  rH   r4  Nr5  r'   r+  r   rZ   c                    s4   | dd | _t jdi | t| ||| d S )Nr+  rX   )r   r+  r  rx    dynamo_triton_hopifier_singletoninit_variable)rt   r4  r5  r  r   r
  rX   rY   rx   n  s   zTritonKernelVariable.__init__r   rD   r   c                 C   s   t | |||S r   )rL  call_triton_kernelr   rX   rX   rY   r   u  s   z"TritonKernelVariable.call_functionr   c                    s>   |dkr
t | |S |dkrt | |||S t ||||S )N__getitem__run)rL  r6  call_runr  r  rQ  r
  rX   rY   r    s
   z TritonKernelVariable.call_methodr-  c                 C   s4   ddl m} ddlm} t||r|| S |S )Nr8   )r?   )r  )r  r?   tensorr  r   r   evaluate_expr)rt   r-  r?   r  rX   rX   rY   specialize_symbolic  s
   
z(TritonKernelVariable.specialize_symbolic)rU   rV   rW   r   r  r   rx   r   r=   r~   r   r   r   r  rT  r  rX   rX   r
  rY   r3  h  sJ   
 



r3  c                       sd   e Zd Zdddee dee dededdf fd	d
ZdefddZdddZdefddZ	  Z
S )r>  data_ptrzvariables.DataPtrVariabledims
block_dimselement_sizer   rZ   Nc                    s>   t |tjsJ t jdi | || _|| _|| _|| _d S ry   )	r   r   DataPtrVariabler  rx   rU  rV  rW  rX  )rt   rU  rV  rW  rX  r   r
  rX   rY   rx     s   
z*TMADescriptorExperimentalVariable.__init__c                 C   s*   t dd | jD dd | jD | j S )Nc                 S   r*  rX   r  r   dimrX   rX   rY   r.    r/  zATMADescriptorExperimentalVariable.to_metadata.<locals>.<listcomp>c                 S   r*  rX   r  rZ  rX   rX   rY   r.    r/  )r  rV  rW  rX  r  r   rX   rX   rY   r@    s
   z-TMADescriptorExperimentalVariable.to_metadatar  rA   c                    sX      fdd j  g jjj} |  t|d d d S )Nc                      s     ddtj dS )Nz$triton.tools.experimental_descriptorcreate_d_tma_descriptor)rX  r   rV  rX   r(  rX   rY   r)    s    z?TMADescriptorExperimentalVariable.reconstruct.<locals>.<lambda>r8   F)	r,  rU  r  rV  rW  rX  r  r   r   )rt   r  r   rX   r(  rY   r    s   
z-TMADescriptorExperimentalVariable.reconstructc                 C   r  r   )rU  from_tensorr   rX   rX   rY   rA    r  z,TMADescriptorExperimentalVariable.get_tensorr  )rU   rV   rW   r   r=   r   rx   r@  r  rA  r  rX   rX   r
  rY   r>    s"    
r>  c                       sT   e Zd Zdddddeddf fdd	Zdefd
dZdddZdefddZ  ZS )r?  rR  rK   block_shaperJ   r   rZ   Nc                    s.   |  sJ t jdi | || _|| _d S ry   )r3  r  rx   rR  r_  )rt   rR  r_  r   r
  rX   rY   rx     s   
z$TMADescriptorStableVariable.__init__c                 C   s   t | j S r   )r  r_  r  r   rX   rX   rY   r@    r  z'TMADescriptorStableVariable.to_metadatar  rA   c                    s@      fdd  d | j   | j  d d S )Nc                      r\  )Nztriton.tools.tensor_descriptorTensorDescriptorr_  rX   rY  rX   rY   r)    s    z9TMADescriptorStableVariable.reconstruct.<locals>.<lambda>r^  r   )r,  load_methodrR  r  r_  r  r.  rX   rY  rY   r    s   


z'TMADescriptorStableVariable.reconstructc                 C   r  r   )rR  r   rX   rX   rY   rA    r  z&TMADescriptorStableVariable.get_tensorr  )	rU   rV   rW   r   rx   r@  r  rA  r  rX   rX   r
  rY   r?    s    
r?  c                       sP   e Zd Zdededdf fddZddd	ee dee	ef defd
dZ
  ZS )'CreateTMADescriptorExperimentalVariablerankr   rZ   Nc                    s(   |dv sJ t  jdi | || _d S )N)r8   r   rX   )r  rx   rc  )rt   rc  r   r
  rX   rY   rx     s   
z0CreateTMADescriptorExperimentalVariable.__init__r   rD   r   c                 C   s  d|v r|d n|d }t |tjs+tdd| d| d| j dd| j d	gd
 | jdkrct|t| dkrHt|dt|t|   d|v rP|d n|d g}d|v r]|d n|d g}nHt|t| dkr{t|dt|t|   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sJ t||||d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   r8   rN   z6TMA metadata rank=1 requires exactly 4 arguments, got r[  	block_dimr      z6TMA metadata rank=2 requires exactly 6 arguments, got dim1dim0
block_dim1rm  
block_dim0rX  r  )rU  rV  rW  rX  )r   r   rY  r#   rc  r   r;   r>  )rt   r   r   r   rd  rV  rW  rX  rX   rX   rY   r     sP   
z5CreateTMADescriptorExperimentalVariable.call_function)rU   rV   rW   r  r   rx   r   r=   r~   r   r   r  rX   rX   r
  rY   rb    s"    	
rb  c                   @   s2   e Zd Zdddee deeef defddZdS )	!CreateTMADescriptorStableVariabler   rD   r   r   rZ   c                 C   s<   d|v r|d n|d }d|v r|d n|d }t ||dS )NrR  r   r_  r8   )rR  r_  )r?  )rt   r   r   r   rR  r_  rX   rX   rY   r   (  s   z/CreateTMADescriptorStableVariable.call_functionN)rU   rV   rW   r   r=   r~   r   r   rX   rX   rX   rY   rk  '  s    
rk  c                   @   s6   e Zd ZdZdddee deeef defddZd	S )
!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   rD   r   r   rZ   c                 C   s   t |dkrt|dt |  d }|d jr)t|d jtj t|d j}|d  }t	|rAt
tdd}t|t|S tj|||dS )Nr8   z6pytree_get_node_type requires exactly 1 argument, got r   collectionsr   r   )r   r;   r   r&   r   r%   
TYPE_MATCHr/   r  r   r'   r-   r=   r   r   )rt   r   r   r   type_sourcer  rX   rX   rY   r   F  s   
z/PyTreeGetNodeTypeFunctionVariable.call_functionN)	rU   rV   rW   r   r   r=   r~   r   r   rX   rX   rX   rY   rl  7  s    
rl  c                       r  )	 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   rD   r   r   rZ   c           	         s   t |dk st |dkrt|dt |  |dt}t |dkr&|d }| s2t |||S |d }ttj	j
j||gi }tj|tj	j
jt d}||d|gi }t|j S )Nr8   r   z,tree_is_leaf requires 1 or 2 arguments, got rP   r   r   r  )r   r;   r   r>   r  r  r   rl  r[   r\   r]   _get_node_typer=   r   r^   r_   r  r?   r   r   )	rt   r   r   r   rP   treenode_type_varsupported_nodes_varoutr
  rX   rY   r   l  s.   z.PyTreeTreeIsLeafFunctionVariable.call_functionr  rX   rX   r
  rY   rp  \  s    
rp  c                       T   e Zd ZdZdededdf fddZdd	d
ee dee	ef defddZ
  ZS ) SparseTensorCreationSkipVariablezk
    Skip variable for sparse tensor factory functions with clear messaging regarding lack of support.
    r   r   rZ   Nc                        d}t  j|fd|i| d S )Nz8sparse tensor creation is not supported in torch.compilerg  r  rx   rt   r   r   rg  r
  rX   rY   rx        z)SparseTensorCreationSkipVariable.__init__r   rD   r   c                 C   sH   ddl m} t| jdt| j}tdd| d| dg |jd d S )	Nr   )r   rU   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)rt   r   r   r   r   rY  rX   rX   rY   r     s   

z.SparseTensorCreationSkipVariable.call_functionrU   rV   rW   r   r   rx   r   r=   r~   r   r   r  rX   rX   r
  rY   rw        
rw  c                       rv  )TritonSetAllocatorSkipVariablezm
    Skip variable for triton.set_allocator with a clear message to move it outside the compiled region.
    r   r   rZ   Nc                    rx  )Nz:triton.set_allocator is not supported inside torch.compilerg  ry  rz  r
  rX   rY   rx     r{  z'TritonSetAllocatorSkipVariable.__init__r   rD   r   c                 C   s   t ddddgd d S )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   rX   rX   rY   r     s   
z,TritonSetAllocatorSkipVariable.call_functionr}  rX   rX   r
  rY   r    r~  r  r   )r   r  r]  r   r   r  r  rx  r  r   rm  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.   r/   r\   r0   r1   r2   r3   r4   r5   r6   r7   rA  r9   r:   r;   r<   r=   r  r>   r?   #torch.distributed.fsdp._fully_shardr@   ModuleNotFoundErrortorch._dynamo.codegenrA   r  rB   rC   rD   rE   #torch._dynamo.variables.ctx_managerrF   rB  rG   rH   r  rI   rJ   rR  rK   rL   rp   rr   r  r]  rn  r  rS   r   r   rT   	lru_cacher_   r`   r   r~   r   r   r   r   r   r   r   r  r   r   r   r   r   r  rq  r  r  r  r  r  r  r  r1  rI  r   re  rf  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  rL  r3  r>  r?  rb  rk  rl  rp  rw  r  rX   rX   rX   rY   <module>   st    4,(




Y






5   $,   
L
P#t


  - QG

b&  # 70'!G%7