o
    ߗi                     @   s  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mZm	Z	m
Z
mZmZmZmZ d dlmZ d dlZddlmZmZ ddlmZ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" dd
l#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* ddl+m,Z,m-Z-m.Z. ddl/m0Z0 zd dl1m2Z2 W n e3y   dZ2Y nw erd dl4m5Z5 d dl6m7Z7m8Z8 ededZ9dCdDddZ:dDddZ;de	e<e.f fddZ=dd Z>G dd de.Z?G d d! d!e?Z@G d"d# d#e@ZAG d$d% d%eAZBG d&d' d'e@ZCdDd(d)ZDG d*d+ d+e?ZEG d,d- d-e.ZFG d.d/ d/e.ZGd0d1 ZHdDd2d3ZIG d4d5 d5e@ZJG d6d7 d7e.ZKG d8d9 d9e.ZLd d:l6mMZMmNZN G d;d< d<eNZOeO ZPG d=d> d>e.ZQG d?d@ d@e.ZRG dAdB dBe.ZSdS )E    N)AnyCallableDictListOptionalTupleTYPE_CHECKINGTypeVar)Never   )	polyfills	variables)create_call_functioncreate_rot_n)unimplementedUnsupported)GuardBuilderinstall_guard)
AttrSourceConstantSourceDefaultsSourceGetItemSource)check_constant_argscheck_unspec_or_constant_argsidentityis_functionis_wrapper_or_member_descriptoristype	make_cell   )typestrValueMutationNewVariableTrackerConstantVariable)_fsdp_param_group)InstructionTranslator)TritonGridTypeTritonKernelType_F)boundtxr&   c                 C   s,   t |tr|S |st| |S tj||S N)
isinstancer"   buildr   LazyVariableTrackercreate)r+   valsource r3   _/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/torch/_dynamo/variables/functions.pywrap_bound_arg1   s
   
r5   c                 C   s6   t | D ]\}}t|ttfrt| |||< qd S r,   )listitemsr-   tupledictr5   )r+   resultkvr3   r3   r4   wrap_args_kwargs=   s
   r=   r:   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_cellpop)parentr:   coder?   namenew_cellr3   r3   r4   init_cellvarsD   s   

rH   c           
      C   sd   ddl m} || ||||}||_t|tr"ddlm}	 t|	|}|d u s-t|ts-J ||_|S )Nr   )FunctionTypepairwise)	typesrI   __kwdefaults__r-   r8   	itertoolsrK   r9   __annotations__)
rE   	f_globalsrF   defaultsclosure
kwdefaultsannotationsrI   funcrK   r3   r3   r4   _create_nested_fnU   s   
rV   c                   @   s\   e Zd Zdd Zdd Z							
		dddZdddedefddZdd Z	dd Z
dS )BaseUserFunctionVariablec                 C   
   |   jS r,   )get_codeco_filenameselfr3   r3   r4   get_filenamej      
z%BaseUserFunctionVariable.get_filenamec                 C   rX   r,   )rY   co_namer[   r3   r3   r4   get_namem   r^   z!BaseUserFunctionVariable.get_namer+   r&   argsList[VariableTracker]kwargsDict[str, VariableTracker]returnr"   c                 C   s   | | g |  ||S r,   )inline_user_function_return	self_argsr\   r+   ra   rc   r3   r3   r4   call_functionp   s   z&BaseUserFunctionVariable.call_functionrF   c                 C   sL   d}z	t |  |}W n ty   |dkrt| trd}Y nw tj|S )NF__name__T)hasattrget_functionNotImplementedErrorr-   NestedUserFunctionVariabler   r$   r0   r\   r+   rF   r:   r3   r3   r4   call_hasattrx   s   z%BaseUserFunctionVariable.call_hasattrc                 C   s   t t|  jS r,   )r6   inspect	signaturerl   
parametersr[   r3   r3   r4   inspect_parameter_names   s   z0BaseUserFunctionVariable.inspect_parameter_namesc                 C      i S r,   r3   )r\   r+   r3   r3   r4   closure_vars      z%BaseUserFunctionVariable.closure_varsNr+   r&   ra   rb   rc   rd   re   r"   )rj   
__module____qualname__r]   r`   ri   strr"   rp   rt   rv   r3   r3   r3   r4   rW   i   s    

rW   c                       s   e Zd ZdZddhejZedd Zd)d* fd	d
Z fddZ	dd Z
dd Zdd Zdd Zdd Zdd Zdeeef fddZdddefddZdddedefd d!Z			"	#	$	%		&d+ fd'd(Z  ZS ),UserFunctionVariablez-Some unsupported user-defined global functionfnis_constantc                 C      t |tj | ||dS Nr2   )r   
make_guardr   CLOSURE_MATCHclsvaluer2   r3   r3   r4   create_with_source   s   z'UserFunctionVariable.create_with_sourceFre   Nc                    sp   t  jdi | t|ddrd| _nd| _t|tjtjj	fs,J dt
| d| t|d|}|| _d S )N_dynamo_marked_constantFTzexpected FunctionType found  _torchdynamo_inliner3   )super__init__getattrr~   r-   rL   rI   torchjitScriptFunctionr    rq   getattr_staticr}   )r\   r}   r~   rc   	__class__r3   r4   r      s   
zUserFunctionVariable.__init__c                    s   t | tr| jS t  S r,   )r   r|   r}   r   as_python_constantr[   r   r3   r4   r      s   

z'UserFunctionVariable.as_python_constantc                 C      g S r,   r3   r[   r3   r3   r4   rg      rw   zUserFunctionVariable.self_argsc                 C      | j S r,   r}   r[   r3   r3   r4   rl         z!UserFunctionVariable.get_functionc                 C      | j jS r,   )r}   __code__r[   r3   r3   r4   rY         zUserFunctionVariable.get_codec                 C      t jS r,   )rL   rI   r[   r3   r3   r4   python_type   r   z UserFunctionVariable.python_typec                 C   s   t | jdd d uS )N__self__)r   r}   r[   r3   r3   r4   has_self      zUserFunctionVariable.has_selfc                 C   r   r,   )r}   __globals__r[   r3   r3   r4   get_globals   r   z UserFunctionVariable.get_globalsc              
      s  j rJ |jj}tjt|dj}|jpg }fddt|D }t	
|j|j|jtfddt||D |j}|jrWfdd|jD   fdd|j D |_t|j|i |}	|	  t|	j }
t||
 t||
|j jjp~d}t|tjjjksJ tt jjj|D ]e\}}}|jj}||v r|| }nOj rt!t"j d	|}t"|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||}||
|< q|
S )z
        Assume `args` and `kwargs` are VariableTracker arguments for a call to
        this function, create new bindings for initial locals.
        )r+   c                    s*   g | ]\}} j d u rd nt j |qS r,   r2   r   ).0idx_r[   r3   r4   
<listcomp>   s    z2UserFunctionVariable.bind_args.<locals>.<listcomp>c                    s   g | ]
\}} ||d qS )r1   r2   r3   )r   argr2   )wrapr3   r4   r      s    
c                    s,   i | ]}| j d u rd nt j |ddqS )NT)is_kwr   )r   r;   r[   r3   r4   
<dictcomp>   s    
z2UserFunctionVariable.bind_args.<locals>.<dictcomp>c                    s"   i | ]\}}|| | d qS r   r3   r   r;   r<   )kwdefaults_sourcesr   r3   r4   r      s    r3   __closure__cell_contentsN)*r~   r>   root_tx	functoolspartialr5   r}   __defaults__	enumeraterL   rI   r   r   rj   r8   zipr   rM   r7   rq   rr   bindapply_defaultsr9   	argumentsr=   rH   lenco_freevarsrN   countr?   r2   r   r   r"   r.   r   
ValueErrorr   DeletedVariabletrack_cell_existing)r\   rD   ra   rc   r   r}   rQ   defaults_sources	fake_funcr*   r:   rR   r   rF   cellr?   cell_varclosure_cellclosure_cell_contentscontents_varr3   )r   r\   r   r4   	bind_args   s|   








zUserFunctionVariable.bind_argsr+   r&   rF   c                 C   sf   | j ot| j |}z	t| j|}W n ty#   tj| ||d Y S w |r-tj	||S t
||S r   )r2   r   rq   r   r}   AttributeErrorr   GetAttrVariabler/   r0   r"   r.   )r\   r+   rF   r2   subobjr3   r3   r4   var_getattr  s   z UserFunctionVariable.var_getattrc                 C   s   t | j|}tj|S r,   )rk   r}   r   r$   r0   ro   r3   r3   r4   rp   !  s   z!UserFunctionVariable.call_hasattrra   rb   rc   rd   r"   c                    s   | j rt|| j|  ||S |jjjrX|jjjsXzddlm	} W n t
y+   d }Y nw |d urX| j|j|jfv rXtjj| t |||W  d    S 1 sSw   Y  t |||S )Nr   )	FSDPState)r~   invoke_and_store_as_constantr}   r`   r>   current_tracerunder_activation_checkpoint#allow_side_effects_under_checkpoint/torch.distributed.fsdp._fully_shard._fsdp_stater   	Exception_pre_forward_post_forwardr   _dynamor?   r   ri   )r\   r+   ra   rc   r   r   r3   r4   ri   %  s*    z"UserFunctionVariable.call_function)Fre   Nrx   )rj   ry   rz   __doc__rW   _nonvar_fieldsclassmethodr   r   r   rg   rl   rY   r   r   r   r   r{   r"   r   r   rp   ri   __classcell__r3   r3   r   r4   r|      s:    
W
r|   c                       sj   e Zd ZdZd fddZdefddZdd	 Zd
d Z								d fddZ	 fddZ
  ZS )UserMethodVariablez$Some unsupported user-defined methodre   Nc                    s    t  jdd|i| || _d S )Nr}   r3   )r   r   obj)r\   r}   r   rc   r   r3   r4   r   C  s   
zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )N(z, ))r   rj   r}   r   r[   r3   r3   r4   __repr__G  s   zUserMethodVariable.__repr__c                 C   s   | j gS r,   )r   r[   r3   r3   r4   rg   J  r   zUserMethodVariable.self_argsc                 C   r   r,   )rL   
MethodTyper[   r3   r3   r4   r   M  r   zUserMethodVariable.python_typer+   r&   ra   rb   rc   rd   r"   c                    s   |j  r2t| jtjr2t| jdd}|d ur |dr |dks#| j	r1| jj
|| jj||| j	dS ntd urM| jtjju rMt| j|| jg|R |S | j	rct| jj| jj}t|||  ||S t |||S )Nry    z	torch.nn.ztorch.nn.utils.parametrize)constant)r>   is_root_tracerr-   r   r   NNModuleVariabler   r}   
startswithr~   call_methodrj   r%   FSDPParamGroupuse_training_stateTorchCtxManagerClassVariableri   r   r   r`   r   )r\   r+   ra   rc   module_attrr}   r   r3   r4   ri   P  s.   z UserMethodVariable.call_functionc                    s   t   dd  S )Nr   )r   rt   r[   r   r3   r4   rt   |  r   z*UserMethodVariable.inspect_parameter_namesr   rx   )rj   ry   rz   r   r   r{   r   rg   r   ri   rt   r   r3   r3   r   r4   r   @  s     ,r   c                       <   e Zd Zd fddZ							
		d fddZ  ZS )WrappedUserMethodVariablere   Nc                    sB   | dd  | dd  t j|j|jfi | || _|| _d S Nr}   r   )rC   r   r   r}   r   wrappedcontextr\   r   r   rc   r   r3   r4   r     s
   
z"WrappedUserMethodVariable.__init__r+   r&   ra   rb   rc   rd   r"   c                    ,   | j | t |||}| j | |S r,   r   enterr   ri   exitr\   r+   ra   rc   r:   r   r3   r4   ri        z'WrappedUserMethodVariable.call_functionr   rx   rj   ry   rz   r   ri   r   r3   r3   r   r4   r         r   c                       r   )WrappedUserFunctionVariablere   Nc                    s>   | dd  | dd  t j|jfi | || _|| _d S r   )rC   r   r   r}   r   r   r   r   r3   r4   r     s
   
z$WrappedUserFunctionVariable.__init__r+   r&   ra   rb   rc   rd   r"   c                    r   r,   r   r   r   r3   r4   ri     r   z)WrappedUserFunctionVariable.call_functionr   rx   r   r3   r3   r   r4   r     r   r   c                    sT   dd   fdd|D } fdd|  D }||i |}| jj||t|dS )Nc                 S   s   t | tjr
|  S |  S r,   )r-   r   TensorVariableget_real_valuer   )xr3   r3   r4   convert  s   z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS r3   r3   r   r   r   r3   r4   r         z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]	\}}| |qS r3   r3   r   r   r3   r4   r         z0invoke_and_store_as_constant.<locals>.<dictcomp>r   )r7   r>   register_attr_or_moduler   )r+   r}   rF   ra   rc   resr3   r   r4   r     s   r   c                       sp   e Zd ZdhejZ	d	d fddZdd Zdd	 Zd
d Zdd Z	dd Z
dd Zdd Zdd Z  ZS )rn   rP   Nre   c	           
         sz   t  jdi |	 t| tsJ t| tjsJ t|ts#J || _|| _	|| _
|| _|| _|| _|| _|| _d S Nr3   )r   r   r-   r   r{   rL   CodeTyper9   fn_namerE   rP   rQ   rS   rT   rR   
wrapped_fn)
r\   r  rE   rP   rQ   rS   rT   rR   r  rc   r   r3   r4   r     s   
z#NestedUserFunctionVariable.__init__c                 C   r   r,   r3   r[   r3   r3   r4   rg     rw   z$NestedUserFunctionVariable.self_argsc                 C   s
   | j  S r,   )rE   r   r[   r3   r3   r4   rY     r^   z#NestedUserFunctionVariable.get_codec                 C   s   | j rtt| j | j| j }| jr| j |_	| j
r%| j
 |_| jrH| j }t|tr>ddlm} t||}t|tsEJ ||_|S )Nr   rJ   )rR   rm   rL   rI   rE   r   rP   r  rQ   r   rS   rM   rT   r-   r8   rN   rK   r9   rO   )r\   rU   rT   rK   r3   r3   r4   rl     s&   

z'NestedUserFunctionVariable.get_functionc                 C   s
   | j d uS r,   )rR   r[   r3   r3   r4   has_closure  r^   z&NestedUserFunctionVariable.has_closurec                 C   s   dS )NFr3   r[   r3   r3   r4   r     rw   z#NestedUserFunctionVariable.has_selfc                 C   r   r,   )rP   r[   r3   r3   r4   r     r   z&NestedUserFunctionVariable.get_globalsc                 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,   )r   )r   r   r3   r3   r4   	<genexpr>      z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>)rY   rL   rI   rP   r  r   rQ   r8   r7   ranger   r   rS   keys_as_python_constantrM   rq   rr   r   r   r9   r   r=   r>   r   rH   r   rR   )r\   rD   ra   rc   rE   rU   r*   r:   r   rF   r   r3   r3   r4   r      s(   
z$NestedUserFunctionVariable.bind_argsc                    sn     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 d S d S )	Nc                      s     tdS )NrV   )load_import_fromrj   r3   codegenr3   r4   <lambda>      z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>   Fc                           ddS )Nr   wrapsr  r3   r  r3   r4   r  >  r  r   r   T)add_push_nullrE   extend_outputcreate_load_const_uncheckedrP   r$   r0   r   r_   rQ   create_load_constrR   rS   rT   r   rm   r   r  r   )r\   r  rT   r3   r  r4   reconstruct  sF   





z&NestedUserFunctionVariable.reconstructr,   r   )rj   ry   rz   rW   r   r   rg   rY   rl   r  r   r   r   r  r   r3   r3   r   r4   rn     s"    rn   c                       sr   e Zd ZddhejZdd fddZdd Zed	d
 Ze	e
ddd Z								dddZ  ZS )SkipFunctionVariabler   reasonNre   c                    "   t  jdi | || _|| _d S r  )r   r   r   r  )r\   r   r  rc   r   r3   r4   r   M     
zSkipFunctionVariable.__init__c                 C   r   r,   r   r[   r3   r3   r4   r   R  r   z'SkipFunctionVariable.as_python_constantc                 C   s$   t |st|tj | ||dS r   )r   r   r   r   FUNCTION_MATCHr   r3   r3   r4   r   U  s   z'SkipFunctionVariable.create_with_sourcec                   C   s   t jtjiS r,   )collections
namedtupler   UserDefinedClassVariabler3   r3   r3   r4    fold_through_function_to_wrapper^  s   z5SkipFunctionVariable.fold_through_function_to_wrapperr+   r&   ra   rb   rc   rd   r"   c           	         s  t | jddrtd| j  d S | j|   v rAt |rA| jdd  D i dd | D }|  | j|t	 dS | jt
ju rZ|sZt d	krZ fd
d}t|S zt | j}d| jj d| d}W nW ty   ddh}| jj|v rd| jj d| jj d}n6| jjd ur| jjdrd| jj d| jj d}tjj| nd| jj d| jj d}tjj| Y nw | jjdkrd}|| jrd| j dnd7 }t| d S )N_torchdynamo_disableFz.call torch._dynamo.disable() wrapped function c                 S      g | ]}|  qS r3   r   r   r3   r3   r4   r   t  r   z6SkipFunctionVariable.call_function.<locals>.<listcomp>c                 S      i | ]	\}}||  qS r3   r'  r   r3   r3   r4   r   u  r  z6SkipFunctionVariable.call_function.<locals>.<dictcomp>)mutation_typer   c                    s0   t | tjr| j d dS td|  d d S )Nr   )r  zfunctools.wraps(r   )r-   r   rn   cloner   r   ra   r3   r4   r  |  s   z1SkipFunctionVariable.call_function.<locals>.wrapsz'skip function z	 in file '_abc	_warningsz.Graph break due to unsupported Python builtin .zM. Please file an issue on GitHub so the PyTorch team can add support for it. optreez)Graph break for an optree C/C++ function zj. Consider using torch.utils._pytree - https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.pyz'Graph break due to unsupported builtin a  . This function is either a Python builtin (e.g. _warnings.warn) or a third-party C/C++ Python extension (perhaps created with pybind). If 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. 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', r   )rq   r   r   r   r$  keysr   r7   getr!   r   r  r   r   LambdaVariablegetfilerz   	TypeErrorry   r   r   r   utils	warn_oncer  )	r\   r+   ra   rc   r   r  pathmsgknown_python_builtin_modulesr3   r+  r4   ri   e  sP   
"z"SkipFunctionVariable.call_functionr,   r   rx   )rj   ry   rz   r"   r   r   r   r   r   staticmethodr   	lru_cacher$  ri   r   r3   r3   r   r4   r  F  s,    
r  c                       sJ   e Zd ZdZd fddZd fdd	Z			
					d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".
    re   Nc                    r  r  )r   r   wrapper_objattr_to_trace)r\   r?  r@  rc   r   r3   r4   r     r  z$WrapperUserFunctionVariable.__init__r+   r&   c                    sF   || j krt| j| j }| jot| j|}t|||S t ||S r,   )	r@  r   r?  r2   r   r"   r.   r   r   )r\   r+   rF   r1   r2   r   r3   r4   r     s
   
z'WrapperUserFunctionVariable.var_getattrra   rb   rc   rd   r"   c                 C   s&   t tj|| t | jg||S r,   )r   r|   r   getattr_and_traceri   r$   r@  rh   r3   r3   r4   ri     s   z)WrapperUserFunctionVariable.call_functionr   r+   r&   rx   )rj   ry   rz   r   r   r   ri   r   r3   r3   r   r4   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_collectivesrD  rC  r3   r3   r4   _traceable_collective_remaps  s   
rH  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   rE  rF  rH  valuesrj   import_sourcer   )r+   r}   
inner_namepath_sourcer3   r3   r4   _traceable_collectives_source  s
   

rM  c                       sd   e Zd ZdZd fddZeddd	Zed
d ZedddZ								d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.
    re   Nc                   s,   t  j|fi | t|tsJ || _d S r,   )r   r   r-   r|   replacement_var)r\   r}   rO  rc   r   r3   r4   r     s   
z*CollectiveFunctionRewriteVariable.__init__r+   r&   c                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr2   )rO  r2   )rN  rewriter|   )r+   old_fnr2   optionsnew_fn
new_sourcer3   r3   r4   r0     s   z(CollectiveFunctionRewriteVariable.createc                 C   s   t | o	| t v S r,   )rq   
isfunctionrH  )variabler3   r3   r4   can_rewrite  s   z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS r,   )rH  rM  )r+   r}   rS  r3   r3   r4   rP    s   
z)CollectiveFunctionRewriteVariable.rewritera   rb   rc   rd   r"   c           	      C   s   dd l m} ddlm} t| j}t|j|i |j	}d}d|v r1|d 
 r1td| j  | j|j|j|jfv rc|d}|d urH|jn|jd j}||vrYtd| tj|| |d< | j|||S )Nr   )REDUCE_OP_TO_STRr3   async_opzBCollectiveFunctionRewriteVariable can't support async_op=True for opzUnsupported all_reduce op: )torch.distributedrE  rG  rX  rq   rr   r}   r9   r   r   r   r   
all_reducereduce_scatter_tensor_reduce_scatter_baser3  r   rs   defaultr   r   r$   r0   rO  ri   )	r\   r+   ra   rc   distrX  rr   reduce_op_var	reduce_opr3   r3   r4   ri     s2   	


z/CollectiveFunctionRewriteVariable.call_functionr   rB  rx   )rj   ry   rz   r   r   r<  r0   rW  rP  ri   r   r3   r3   r   r4   rN    s$    
	
rN  c                       sv   e Zd Zdeddf fddZdd Zdd	 Z	
							dddZd
ddedefddZ	dd Z
dd Z  ZS )FunctoolsPartialVariablerU   re   Nc                    sD   t  jdi | || _t|tsJ || _t|tsJ || _d S r  )r   r   rU   r-   r6   ra   r9   keywords)r\   rU   ra   rd  rc   r   r3   r4   r   8  s   
z!FunctoolsPartialVariable.__init__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  r3   r  r3   r4   r  A  r  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>r   F)r  rU   ra   foreachrd  r  r   r   rI  r8   r2  create_call_function_kw)r\   r  r2  r3   r  r4   r  @  s   
z$FunctoolsPartialVariable.reconstructc                 C      |   S r,   r'  r[   r3   r3   r4   rl   O  r   z%FunctoolsPartialVariable.get_functionr+   r&   ra   rb   rc   rd   r"   c                 C   s(   | j | }i | j|}| j|||S r,   )ra   rd  rU   ri   )r\   r+   ra   rc   merged_argsmerged_kwargsr3   r3   r4   ri   R  s   
z&FunctoolsPartialVariable.call_functionrF   c                 C   s   t jttt|S r,   )r   r$   r0   rk   r   r   r   )r\   r+   rF   r3   r3   r4   rp   \  s   z%FunctoolsPartialVariable.call_hasattrc                 C   :   t j| j gdd | jD R i dd | j D S )Nc                 S   r&  r3   r'  )r   r   r3   r3   r4   r   e  r   z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   r(  r3   r'  r   r3   r3   r4   r   f  r  z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)r   r   rU   r   ra   rd  r7   r[   r3   r3   r4   r   b  s   z+FunctoolsPartialVariable.as_python_constantc                 C   rj  )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   r&  r3   guard_as_python_constant)r   r<   r3   r3   r4   r   m  r   zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   r(  r3   rk  r   r3   r3   r4   r   n  r  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>)r   r   rU   rl  ra   rd  r7   r[   r3   r3   r4   rl  i  s   z1FunctoolsPartialVariable.guard_as_python_constantrx   )rj   ry   rz   r"   r   r  rl   ri   r{   rp   r   rl  r   r3   r3   r   r4   rc  7  s     

rc  c                       s   e Zd ZdddhejZeeddee	de
f ejf fddZed	d
 Zdeddf fddZedefddZdd Zdd Z								d ddZ						d!ddZdd Z  ZS )"PolyfilledFunctionVariabler}   r  traceable_fnNre   .c                 C   ru   r,   r3   )r   r3   r3   r4   _get_polyfill_handlersz  s   z1PolyfilledFunctionVariable._get_polyfill_handlersc                 C   r   r   )r   r   r   r   r   r3   r3   r4   r     s   z-PolyfilledFunctionVariable.create_with_sourcec                    s   t  jdi | || _|  ||}t|s"J d| d| dD ]}t||d }|r8t|s4J |} 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 functionr3   )
r   r   r}   ro  r3  callabler   RuntimeErrorr  rn  )r\   r}   rc   handlercandidate_attr	candidatern  r   r3   r4   r     s    

z#PolyfilledFunctionVariable.__init__c                 C   r   r,   )rn  r[   r3   r3   r4   polyfill_fn  s   z&PolyfilledFunctionVariable.polyfill_fnc                 C   s   t | jddS )N*__torch_dynamo_can_constant_fold_through__F)r   r  r[   r3   r3   r4   can_constant_fold_through     z4PolyfilledFunctionVariable.can_constant_fold_throughc                 C   rg  r,   r'  r[   r3   r3   r4   rl     r   z'PolyfilledFunctionVariable.get_functionr+   r&   ra   rb   rc   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&  r3   r'  r   r3   r3   r4   r     r   z<PolyfilledFunctionVariable.call_function.<locals>.<listcomp>c                 S   r(  r3   r'  r   r3   r3   r4   r     r  z<PolyfilledFunctionVariable.call_function.<locals>.<dictcomp>r   r   c                 s   s@    | ]}t |tjrt |jtpt |tjo| tu V  qd S r,   )r-   r   r$   r   intSymNodeVariabler   r   r3   r3   r4   r	    s    
z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>ri   c                 s   s    | ]}|  V  qd S r,   as_proxy)r   ar3   r3   r4   r	    r
  c                 S   s$   g | ]}t |tjr|jn|jqS r3   )r-   r   r$   r   sym_numr   r3   r3   r4   r     s    
)r  )ry  r   r}   r7   r"   r.   builtinssumr   r-   r   ListVariableTupleVariableallr|  r0   r>   create_proxyr   sym_sumr8   rn  ri   )r\   r+   ra   rc   r:   traceable_function_variabler3   r3   r4   ri     sH   
	z(PolyfilledFunctionVariable.call_functionc                 C   s   |dkr|  |||S t| j|d }|d us!J d| d| j t|s0J d| d| j i }| jr=t| j||d< t|fi |}| |||S )N__call__zMember z not found in z is not callable in r2   )ri   r   r}   r   r2   r   rm  )r\   r+   rF   ra   rc   methodrR  polyfilled_method_variabler3   r3   r4   r     s   z&PolyfilledFunctionVariable.call_methodc                 C   r   r,   r   r[   r3   r3   r4   r     r   z-PolyfilledFunctionVariable.as_python_constantrx   ra   rb   rc   rd   re   r"   )rj   ry   rz   r"   r   r   r   r=  r   r   r   rL   rI   ro  r   r)   r   propertyrw  ry  rl   ri   r   r   r   r3   r3   r   r4   rm  r  sD    $

4
rm  )TMADescriptorMetadataTritonHOPifierc                   @   st   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e
ejjjdf fddZdd ZdefddZdS )DynamoTritonHOPifierr:  re   c                 C   s   t |r,   )r   )r\   r:  r3   r3   r4   raise_unsupported  r   z&DynamoTritonHOPifier.raise_unsupportedmaybe_callablec                 C   s   t |ttfS r,   )r-   rn   r|   )r\   r  r3   r3   r4   is_callable  rz  z DynamoTritonHOPifier.is_callabler1   c                 C   s   |j S r,   r  )r\   r1   r3   r3   r4   	get_value  r   zDynamoTritonHOPifier.get_value.c                 C   s4   ddl m} t||r| S tdt|  d S )Nr   )BaseListVariablezgrid for the triton kernel is )listsr  r-   r~  r   type)r\   gridr  r3   r3   r4   
check_grid  s   
zDynamoTritonHOPifier.check_gridc                 C   s&   dd |  D }|||gi }|S )Nc                 S      i | ]\}}t j||qS r3   r   r$   r0   r   r3   r3   r4   r     s    z2DynamoTritonHOPifier.call_grid.<locals>.<dictcomp>)r7   ri   )r\   r  metar+   r3   r3   r4   	call_grid  s   zDynamoTritonHOPifier.call_gridc                    s&  ddl m  ddlm} i }t| D ]}|| }t|tr+| ||< |j	j
||< qdd | D }	ddlm}
m}  fdd| D } fd	d|	 D }| D ]}| }t|tjtjfsq| d
t| d qW|
|}||t}|jd|d|j|||| d td S )Nr   r#   )ConstDictVariablec                 S   r  r3   r  r   r3   r3   r4   r   "  s    z1DynamoTritonHOPifier.call_HOP.<locals>.<dictcomp>r   )kernel_side_tabletriton_kernel_wrapper_mutationc                    s$   i | ]\}}t | r|| qS r3   )r-   r   r   r#   r3   r4   r   /  s    c                    s    i | ]\}}t | s||qS r3   )r-   r   r#   r3   r4   r   4  s    z.Unexpected argument type for a Triton kernel: r/  ri   r3   )
kernel_idxconstant_args_idxr  tma_descriptor_metadatarc   )r   r$   dictsr  r6   r2  r-   TMADescriptorVariableto_metadatadata_ptrfrom_tensorr7   *torch._higher_order_ops.triton_kernel_wrapr  r  rI  realizer   r   r|  r  repradd_constant_argsr9   r>   r  r  r~  )r\   rV  gridscombined_args_rawr+   r  r  r;   r<   combined_argsr  r  constant_argsnon_constant_argsr  r  r3   r#   r4   call_HOP  sT   




zDynamoTritonHOPifier.call_HOPN)rj   ry   rz   r{   r
   r  r   boolr  r  r   r   fxproxyProxyr  r  r$   r  r3   r3   r3   r4   r    s    r  c                       s   e Zd ZU ded< ded< ee ed< d fdd	Z	
							dddZ						d fddZde	de	fddZ
  ZS )TritonKernelVariabler'   r  r(   kernelr  re   Nc                    s&   t  jdi | t| ||| d S r  )r   r    dynamo_triton_hopifier_singletoninit_variable)r\   r  r  r  rc   r   r3   r4   r   ]  s   zTritonKernelVariable.__init__r+   r&   ra   rb   rc   rd   r"   c                 C   s   t | |||S r,   )r  call_triton_kernelrh   r3   r3   r4   ri   a  s   z"TritonKernelVariable.call_functionc                    s>   |dkr
t | |S |dkrt | |||S t ||||S )N__getitem__run)r  call_getitemcall_runr   r   )r\   r+   rF   ra   rc   r   r3   r4   r   k  s
   z TritonKernelVariable.call_methodr   c                 C   s4   ddl m} ddlm} t||r|| S |S )Nr   r#   )r|  )r   r$   tensorr|  r-   r0   evaluate_expr)r\   r   r$   r|  r3   r3   r4   specialize_symbolicz  s
   
z(TritonKernelVariable.specialize_symbolicr   rx   r  )rj   ry   rz   rO   r   r{  r   ri   r   r   r  r   r3   r3   r   r4   r  X  s,   
 

r  c                       s>   e Zd Z								d fdd	Zd
d Zdd Z  ZS )r  r  variables.DataPtrVariabledimsList[ConstantVariable]
block_dimselement_sizer$   c                    s>   t |tjsJ t jdi | || _|| _|| _|| _d S r  )	r-   r   DataPtrVariabler   r   r  r  r  r  )r\   r  r  r  r  rc   r   r3   r4   r     s   
zTMADescriptorVariable.__init__c                 C   s(   dd | j D dd | jD | j fS )Nc                 S   r&  r3   r}  r   dimr3   r3   r4   r     r   z5TMADescriptorVariable.to_metadata.<locals>.<listcomp>c                 S   r&  r3   r}  r  r3   r3   r4   r     r   )r  r  r  r~  r[   r3   r3   r4   r    s   z!TMADescriptorVariable.to_metadatac                    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)r  r   r  r3   r  r\   r3   r4   r    s    z3TMADescriptorVariable.reconstruct.<locals>.<lambda>r   F)	r  r  r  r  r  r  re  ri   r   )r\   r  ra   r3   r  r4   r    s   
z!TMADescriptorVariable.reconstruct)r  r  r  r  r  r  r  r$   )rj   ry   rz   r   r  r  r   r3   r3   r   r4   r    s    r  c                       s@   e Zd Zdeddf fddZ						
			dddZ  ZS )CreateTMADescriptorVariablerankre   Nc                    s(   |dv sJ t  jdi | || _d S )N)r   r   r3   )r   r   r  )r\   r  rc   r   r3   r4   r     s   
z$CreateTMADescriptorVariable.__init__r+   r&   ra   rb   rc   rd   r"   c                 C   s.  d|v r|d n|d }t |tjstd| j d| jdkrGt|t| dks,J d|v r4|d n|d g}d|v rA|d n|d	 g}n<t|t| d
ksSJ d|v r[|d n|d d|v rf|d n|d	 g}d|v rs|d n|d d|v r~|d n|d g}d|v r|d n|d }t||||dS )Nptrr   z8Please ensure there were no graph breaks between create_z3d_tma_descriptor and the upstream .data_ptr() call.r      r  	block_dimr      dim1dim0
block_dim1   
block_dim0r  )r  r  r  r  )r-   r   r  r   r  r   r  )r\   r+   ra   rc   r  r  r  r  r3   r3   r4   ri     s6   
z)CreateTMADescriptorVariable.call_functionrx   )rj   ry   rz   r{  r   ri   r   r3   r3   r   r4   r    s    	r  r,   rB  )Tr  r!  r   rq   rN   rL   typingr   r   r   r   r   r   r   r	   typing_extensionsr
   r   r   r   r   bytecode_transformationr   r   excr   r   guardsr   r   r2   r   r   r   r   r7  r   r   r   r   r   r   r   baser    r!   r"   r   r$   #torch.distributed.fsdp._fully_shardr%   ModuleNotFoundErrortorch._dynamo.symbolic_convertr&   r  r'   r(   r)   r5   r=   r{   rH   rV   rW   r|   r   r   r   r   rn   r  r>  rH  rM  rN  rc  rm  r  r  r  r  r  r  r  r3   r3   r3   r4   <module>   sj   ($	
  8@
 l"
	O; \,$