U
    zh                     @   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 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 ddlmZmZmZmZ dd	lmZmZm Z m!Z!m"Z" d
dl#m$Z$m%Z%m&Z& d
dl'm(Z( e
rd dl)m*Z* d0ddZ+dd Z,dd Z-dd Z.G dd de&Z/G dd de/Z0G dd de0Z1G dd de1Z2G dd de0Z3d d! Z4G d"d# d#e/Z5G d$d% d%e&Z6d&d' Z7d(d) Z8G d*d+ d+e0Z9G d,d- d-e&Z:G d.d/ d/e&Z;dS )1    N)DictListOptionalTYPE_CHECKINGUnion   )	variables)create_call_functioncreate_rot_n)unimplementedUnsupported)GuardBuilderinstall_guard)
AttrSourceConstantSourceDefaultsSourceGetItemSource)check_constant_argsget_first_attridentityistype	make_cell   )MutableLocaltypestrVariableTrackerConstantVariable)Sourcec                 C   s<   t |tr|S |s*ddlm} || |S tj||S d S )Nr   SourcelessBuilder)
isinstancer   Ztorch._dynamo.variables.builderr    creater   ZLazyVariableTracker)txvalsourcer     r&   S/var/www/html/venv/lib/python3.8/site-packages/torch/_dynamo/variables/functions.pywrap_bound_arg   s    
r(   c                 C   s6   t | D ]$\}}t|ttfrt| |||< qd S N)listitemsr!   tupledictr(   )r#   resultkvr&   r&   r'   wrap_args_kwargs(   s    r1   c                 C   sH   t  }| jj}|jD ].}| ||< ||kr||| || q|S r)   )r-   outputside_effectsco_cellvarsZtrack_cell_new
store_cellpop)parentr.   codeclosure_cellsr3   namer&   r&   r'   init_cellvars/   s    
r;   c           
      C   sd   ddl m} || ||||}||_t|trDddlm}	 t|	|}|d ksZt|tsZt||_	|S )Nr   )FunctionTypepairwise)
typesr<   __kwdefaults__r!   r,   	itertoolsr>   r-   AssertionError__annotations__)
r8   	f_globalsr:   defaultsclosure
kwdefaultsannotationsr<   funcr>   r&   r&   r'   _create_nested_fn<   s    
rJ   c                   @   sN   e Zd Zdd Zdd Zddddd	d
ZeedddZdd Z	dd Z
dS )BaseUserFunctionVariablec                 C   s
   |   jS r)   )get_codeco_filenameselfr&   r&   r'   get_filenameQ   s    z%BaseUserFunctionVariable.get_filenamec                 C   s
   |   jS r)   )rL   co_namerN   r&   r&   r'   get_nameT   s    z!BaseUserFunctionVariable.get_nameList[VariableTracker]Dict[str, VariableTracker]r   argskwargsreturnc                 C   s   | | |  ||S r)   )Zinline_user_function_return	self_argsrO   r#   rV   rW   r&   r&   r'   call_functionW   s    z&BaseUserFunctionVariable.call_functionr:   rX   c                 C   sN   d}zt |  |}W n* tk
r@   |dkr<t| tr<d}Y nX tj|S )NF__name__T)hasattrget_functionNotImplementedErrorr!   NestedUserFunctionVariabler   r   r"   rO   r#   r:   r.   r&   r&   r'   call_hasattr\   s    
z%BaseUserFunctionVariable.call_hasattrc                 C   s   t t|  jS r)   )r*   inspect	signaturer_   
parametersrN   r&   r&   r'   inspect_parameter_namesf   s    z0BaseUserFunctionVariable.inspect_parameter_namesc                 C   s   i S r)   r&   )rO   r#   r&   r&   r'   closure_varsi   s    z%BaseUserFunctionVariable.closure_varsN)r]   
__module____qualname__rP   rR   r[   strr   rc   rg   rh   r&   r&   r&   r'   rK   P   s    
rK   c                       s   e Zd ZdZddhejZedd Z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d Zdd ZeedddZddd d! fd"d#Z  ZS )%UserFunctionVariablez-Some unsupported user-defined global functionfnis_constantc                 C   s   t |tj | ||dS Nr%   )r   
make_guardr   ZCLOSURE_MATCHclsvaluer%   r&   r&   r'   create_with_sourcev   s
    z'UserFunctionVariable.create_with_sourceFc                    s   t  jf | t|ddr"d| _nd| _t|tjtjj	fsTt
dt| d| t|d|}t|ddr~t|d|}|| _d S )	NZ_dynamo_marked_constantFTzexpected FunctionType found  Z_torchdynamo_inlineZ__script_if_tracing_wrapperZ__original_fn)super__init__getattrrn   r!   r?   r<   torchZjitZScriptFunctionrB   r   rd   getattr_staticrm   )rO   rm   rn   rW   	__class__r&   r'   rx   ~   s     zUserFunctionVariable.__init__c                    s   t | tr| jS t  S r)   )r   rl   rm   rw   as_python_constantrN   r|   r&   r'   r~      s    
z'UserFunctionVariable.as_python_constantc                 C   s   g S r)   r&   rN   r&   r&   r'   rY      s    zUserFunctionVariable.self_argsc                 C   s   | j S r)   )rm   rN   r&   r&   r'   r_      s    z!UserFunctionVariable.get_functionc                 C   s   | j jS r)   )rm   __code__rN   r&   r&   r'   rL      s    zUserFunctionVariable.get_codec                 C   s   t jS r)   )r?   r<   rN   r&   r&   r'   python_type   s    z UserFunctionVariable.python_typec                 C   s   t | jdd d k	S )N__self__)ry   rm   rN   r&   r&   r'   has_self   s    zUserFunctionVariable.has_selfc                 C   s   | j jS r)   )rm   __globals__rN   r&   r&   r'   get_globals   s    z UserFunctionVariable.get_globalsc              
      sx  j r
t|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rfdd|jD   fdd|j D |_t|j||}	|	  t|	j }
t||
 t||
|j}jjpd}t|tjjjksttt jjj|D ]@\}}}|d	krpj rVt!j d	nd }t"j#|j$|d
|
|< n|%||}|d k	r||
|< n܈j rNddl&m'} |jj(}||kr|| }nt)t!j d|}t!|d}z||||j$}W n t*k
r   t"+ }Y nX |, |j-kr,||
|< q,|.||}|/|| ||
|< nddl&m0} |1||j$|
|< q,|
|fS )N)r#   c                    s*   g | ]"\}} j d krd n
t j |qS r)   r%   r   ).0idx_rN   r&   r'   
<listcomp>   s   z2UserFunctionVariable.bind_args.<locals>.<listcomp>c                    s   g | ]\}} ||d qS )r$   r%   r&   )r   argr%   )wrapr&   r'   r      s   c                    s,   i | ]$}| j d krd nt j |ddqS )NT)Zis_kwr   )r   r/   rN   r&   r'   
<dictcomp>   s
   z2UserFunctionVariable.bind_args.<locals>.<dictcomp>c                    s"   i | ]\}}|| | d qS r   r&   r   r/   r0   )kwdefaults_sourcesr   r&   r'   r      s    r&   r}   rp   r   )VariableBuilder__closure__cell_contentsr   )2rn   rB   r2   root_tx	functoolspartialr(   rm   __defaults__	enumerater?   r<   r   r   r]   r,   zipr   r@   r+   rd   re   bindapply_defaultsr-   	argumentsr1   r;   lenco_freevarsrA   countr%   r   r   UserDefinedClassVariabler   Zmatch_nested_cellbuilderr   r3   r   
ValueErrorZDeletedVariabler:   Zmutated_closure_cell_contentsZtrack_cell_existingr5   r    r"   )rO   r7   rV   rW   r#   rm   rE   Zdefaults_sourcesZ	fake_funcboundr.   r9   rF   r   r:   cellr%   varr   r3   outZclosure_cellZclosure_cell_contentsZcontents_varr    r&   )r   rO   r   r'   	bind_args   s    





  





   
zUserFunctionVariable.bind_argsc                 C   s   d S r)   r&   )rO   r7   childr&   r&   r'   export_freevars  s    z$UserFunctionVariable.export_freevarsr\   c                 C   s   t | j|}tj|S r)   )r^   rm   r   r   r"   rb   r&   r&   r'   rc     s    z!UserFunctionVariable.call_hasattrrS   rT   r   rU   c                    s,   | j rt|| j|  ||S t |||S r)   )rn   invoke_and_store_as_constantrm   rR   rw   r[   rZ   r|   r&   r'   r[     s        z"UserFunctionVariable.call_function)F)r]   ri   rj   __doc__rK   _nonvar_fieldsclassmethodru   rx   r~   rY   r_   rL   r   r   r   r   r   rk   r   rc   r[   __classcell__r&   r&   r|   r'   rl   m   s.   
n rl   c                       sZ   e Zd ZdZ fddZdd Zdd Zdd	 Zd
ddd fddZ fddZ	  Z
S )UserMethodVariablez$Some unsupported user-defined methodc                    s    t  jf d|i| || _d S )Nrm   )rw   rx   obj)rO   rm   r   rW   r|   r&   r'   rx   +  s    zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )N(z, ))r}   r]   rm   r   rN   r&   r&   r'   __str__/  s    zUserMethodVariable.__str__c                 C   s   | j gS r)   )r   rN   r&   r&   r'   rY   2  s    zUserMethodVariable.self_argsc                 C   s   t jS r)   )r?   
MethodTyperN   r&   r&   r'   r   5  s    zUserMethodVariable.python_typerS   rT   r   rU   c                    s   |j  rbt| jtjrbt| jdd}|d k	r@|dr@|dksF| j	rb| jj
|| jj||| j	dS | j	rt| jj| jj}t|||  ||S t |||S )Nri    z	torch.nn.ztorch.nn.utils.parametrize)constant)r2   Zis_root_tracerr!   r   r   ZNNModuleVariablery   rm   
startswithrn   call_methodr]   rt   r   rR   rw   r[   )rO   r#   rV   rW   Zmodule_attrrm   r|   r&   r'   r[   8  s0         z UserMethodVariable.call_functionc                    s   t   dd  S )Nr   )rw   rg   rN   r|   r&   r'   rg   Z  s    z*UserMethodVariable.inspect_parameter_names)r]   ri   rj   r   rx   r   rY   r   r[   rg   r   r&   r&   r|   r'   r   (  s    "r   c                       s2   e Zd Z fddZdddd fddZ  ZS )	WrappedUserMethodVariablec                    s>   | dd  | dd  t j|j|jf| || _|| _d S Nrm   r   )r6   rw   rx   rm   r   wrappedcontextrO   r   r   rW   r|   r&   r'   rx   _  s
    z"WrappedUserMethodVariable.__init__rS   rT   r   rU   c                    s,   | j | t |||}| j | |S r)   r   Zenterrw   r[   exitrO   r#   rV   rW   r.   r|   r&   r'   r[   f  s    z'WrappedUserMethodVariable.call_functionr]   ri   rj   rx   r[   r   r&   r&   r|   r'   r   ^  s
    r   c                       s2   e Zd Z fddZdddd fddZ  ZS )	WrappedUserFunctionVariablec                    s:   | dd  | dd  t j|jf| || _|| _d S r   )r6   rw   rx   rm   r   r   r   r|   r&   r'   rx   p  s
    z$WrappedUserFunctionVariable.__init__rS   rT   r   rU   c                    s,   | j | t |||}| j | |S r)   r   r   r|   r&   r'   r[   w  s    z)WrappedUserFunctionVariable.call_functionr   r&   r&   r|   r'   r   o  s
    r   c                    sP   dd   fdd|D } fdd|  D }|||}| jj||t|dS )Nc                 S   s   t | tjr|  S |  S r)   )r!   r   ZTensorVariableZget_real_valuer~   )xr&   r&   r'   convert  s    z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS r&   r&   r   r   r   r&   r'   r     s     z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]\}}| |qS r&   r&   r   r   r&   r'   r     s      z0invoke_and_store_as_constant.<locals>.<dictcomp>rp   )r+   r2   Zregister_attr_or_moduler   )r#   rm   r:   rV   rW   resr&   r   r'   r     s    
r   c                       st   e Zd ZddhejZ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dd Z  ZS )ra   closure_scoperD   Nc
                    s   t  jf |
 t| ts tt| tjs4tt|tsBt|| _	|| _
|| _|| _|| _|| _|| _|d krxd }|| _|	| _d S r)   )rw   rx   r!   r~   rk   rB   r?   CodeTyper-   fn_namer8   rD   rE   rG   rH   rF   r   wrapped_reconstructible)rO   r   r8   rD   rE   rG   rH   rF   r   r   rW   r|   r&   r'   rx     s     z#NestedUserFunctionVariable.__init__c                 C   s   g S r)   r&   rN   r&   r&   r'   rY     s    z$NestedUserFunctionVariable.self_argsc                 C   s
   | j  S r)   )r8   r~   rN   r&   r&   r'   rL     s    z#NestedUserFunctionVariable.get_codec                 C   s   | j r
tt| j | j| j }| jr8| j |_	| j
rJ| j
 |_| jr| j }t|tr|ddlm} t||}t|tst||_|S )Nr   r=   )rF   r`   r?   r<   r8   r~   rD   r   rE   r   rG   r@   rH   r!   r,   rA   r>   r-   rB   rC   )rO   rI   rH   r>   r&   r&   r'   r_     s&    

z'NestedUserFunctionVariable.get_functionc                 C   s
   | j d k	S r)   )rF   rN   r&   r&   r'   has_closure  s    z&NestedUserFunctionVariable.has_closurec                 C   s   dS )NFr&   rN   r&   r&   r'   r     s    z#NestedUserFunctionVariable.has_selfc                 C   s   | j S r)   )rD   rN   r&   r&   r'   r     s    z&NestedUserFunctionVariable.get_globalsc                 C   s\  ddl m} |  }t|| j| j | jr8t	| jj
nd t	dd tt|  jD }| jrn| j |_t|j||}|  t|j
 }t|jj| t|||}	t|jD ]\}
}| jj
|
 }t||||kst||kstt||rB|}|r||j kr|j!}q|d kr2t"d| d|j | ||< q| jj
|
 |	|< q||	fS )Nr   )InlinedClosureVariablec                 s   s   | ]}t d V  qd S r)   )r   )r   r   r&   r&   r'   	<genexpr>  s     z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>zCouldn't find z7 in the symbolic_locals of the inline interpreter stack)#miscr   rL   r?   r<   rD   r   r~   rE   r,   r+   ranger   r   rG   Zkeys_as_python_constantr@   rd   re   r   r   r-   r   r1   r2   r   r;   r   rF   ry   rB   r!   symbolic_localsr7   RuntimeError)rO   r7   rV   rW   r   r8   rI   r   r.   r9   r   r:   r   candr&   r&   r'   r     s>    

z$NestedUserFunctionVariable.bind_argsc                 C   s2   |   }|jD ]}||jkr|j| |j|< qd S r)   )rL   r   r   )rO   r7   r   r8   r   r&   r&   r'   r   	  s    

z*NestedUserFunctionVariable.export_freevarsc                 C   sf  | td || j ||| jg |t| jjj	 | j
rP|| j
 n||d g | jrt|| j n||d g | jr|| j n||d g | jrz | j }|||g W n tk
r   || j Y nX n||d g |tddd | jrb| dd || j |tdd |td |tdd d S )	NrJ      T)Z	push_nullr   wrapsr   r   )load_import_fromr]   r8   extend_outputZ_create_load_constrD   r   r"   rt   rQ   rE   Zcreate_load_constrF   rG   rH   r~   r`   r	   r   r
   )rO   codegenrH   r&   r&   r'   reconstruct  s6    


z&NestedUserFunctionVariable.reconstruct)N)r]   ri   rj   rK   r   rx   rY   rL   r_   r   r   r   r   r   r   r   r&   r&   r|   r'   ra     s      +ra   c                       sp   e Zd ZddhejZd fdd	Zdd Zdd	 Zed
d Z	e
eddd ZddddddZ  ZS )SkipFunctionVariablert   reasonNc                    s   t  jf | || _|| _d S r)   )rw   rx   rt   r   )rO   rt   r   rW   r|   r&   r'   rx   >  s    zSkipFunctionVariable.__init__c                 C   s
   t | jS r)   )typert   rN   r&   r&   r'   r   C  s    z SkipFunctionVariable.python_typec                 C   s   | j S r)   )rt   rN   r&   r&   r'   r~   F  s    z'SkipFunctionVariable.as_python_constantc                 C   s   t |tj | ||dS ro   )r   rq   r   ZFUNCTION_MATCHrr   r&   r&   r'   ru   I  s
    z'SkipFunctionVariable.create_with_sourcec                   C   s   t jtjiS r)   )collections
namedtupler   r   r&   r&   r&   r'    fold_through_function_to_wrapperQ  s     z5SkipFunctionVariable.fold_through_function_to_wrapperrS   rT   r   rU   c           	         s  t | jddr$td| j  nj| j|   kr~t |r~| jdd  D dd | D }|  | j|t	 dS | jt
jkr|st d	krЈ d
 jd k	s d
 |jjrЇ fdd}t|S z&t | j}d| jj d| d}W np tk
rf   ddh}| jj|kr:d| jj d| jj d}n(d| jj d| jj d}tjj| Y nX || jrd| j dnd7 }t| d S )NZ_torchdynamo_disableFz.call torch._dynamo.disable() wrapped function c                 S   s   g | ]}|  qS r&   r~   r   r&   r&   r'   r   d  s     z6SkipFunctionVariable.call_function.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS r&   r   r   r&   r&   r'   r   e  s      z6SkipFunctionVariable.call_function.<locals>.<dictcomp>)Zmutable_localr   r   c                    sJ   t | tjr6 d jr" d j}n d }| j|dS td|  d d S )Nr   )r   zfunctools.wraps(r   )r!   r   ra   r%   cloner   )rm   ZreconstructiblerV   r&   r'   r   s  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. z'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.z', r   )rd   r{   rt   r   r   keysr   r+   getr   r   r   r   r%   Zcan_reconstructr2   r   r   ZLambdaVariablegetfilerj   	TypeErrorri   rz   Z_dynamoutilsZ	warn_oncer   )	rO   r#   rV   rW   rt   r   pathmsgZknown_python_builtin_modulesr&   r   r'   r[   X  sN     

		
z"SkipFunctionVariable.call_function)N)r]   ri   rj   r   r   rx   r   r~   r   ru   staticmethodr   	lru_cacher   r[   r   r&   r&   r|   r'   r   7  s"   
 r   c                  C   s   t j rddlm}  | S i S )Nr   traceable_collective_remaps)rz   distributedis_available)torch.distributed._functional_collectivesr   r   r&   r&   r'   _traceable_collective_remaps  s    
r   c                 C   s>   t j std|t  ks$t|j}| d}t||S )NzIllegal invocation.z)torch.distributed._functional_collectives)	rz   r   r   rB   r   valuesr]   Zimport_sourcer   )r#   rm   Z
inner_nameZpath_sourcer&   r&   r'   _traceable_collectives_source  s
    
r   c                       sV   e Zd ZdZ fddZedd Zedd Zedd	 Zd
dd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.
    c                   s(   t  j|f| t|tst|| _d S r)   )rw   rx   r!   rl   rB   replacement_var)rO   rm   r   rW   r|   r&   r'   rx     s    z*CollectiveFunctionRewriteVariable.__init__c                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr%   )r   r%   )r   rewriterl   )r#   Zold_fnr%   optionsnew_fnZ
new_sourcer&   r&   r'   r"     s    z(CollectiveFunctionRewriteVariable.createc                 C   s   t | o| t kS r)   )rd   
isfunctionr   )variabler&   r&   r'   can_rewrite  s    z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS r)   )r   r   )r#   rm   r   r&   r&   r'   r     s    
z)CollectiveFunctionRewriteVariable.rewriterS   rT   r   rU   c           	      C   s   dd l m} ddlm} t| j}t|j||j	}d}d|kr^|d 
 r^td| j  | j|j|j|jfkr|d}|d k	r|jn
|jd j}||krtd| tj|| |d< | j|||S )Nr   )REDUCE_OP_TO_STRr&   Zasync_opzBCollectiveFunctionRewriteVariable can't support async_op=True for opzUnsupported all_reduce op: )Ztorch.distributedr   r   r   rd   re   rm   r-   r   r   r~   r   Z
all_reduceZreduce_scatter_tensorZ_reduce_scatter_baser   rt   rf   defaultr   r   r   r"   r   r[   )	rO   r#   rV   rW   distr   re   Zreduce_op_varZ	reduce_opr&   r&   r'   r[     s2    


z/CollectiveFunctionRewriteVariable.call_function)r]   ri   rj   r   rx   r   r"   r   r   r[   r   r&   r&   r|   r'   r     s   

	

 r   c                       sd   e Zd Zed fddZdd Zdd Zdd	d
dddZeedddZ	dd Z
dd Z  ZS )FunctoolsPartialVariable)rI   c                    s@   t  jf | || _t|ts"t|| _t|ts6t|| _d S r)   )	rw   rx   rI   r!   r*   rB   rV   r-   keywords)rO   rI   rV   r  rW   r|   r&   r'   rx     s    z!FunctoolsPartialVariable.__init__c                 C   s   | dd || j | jr(|| j | jsL|tt| jd d d S || j  t	| j
 }||t|t| j d |d d S )Nr   r   r   T)r   rI   rV   Zforeachr  r   r	   r   r   r,   r   Zcreate_call_function_kw)rO   r   r   r&   r&   r'   r     s    
z$FunctoolsPartialVariable.reconstructc                 C   s   |   S r)   r   rN   r&   r&   r'   r_     s    z%FunctoolsPartialVariable.get_functionrS   rT   r   rU   c                 C   s$   | j | }| j|}| j|||S r)   )rV   r  rI   r[   )rO   r#   rV   rW   Zmerged_argsZmerged_kwargsr&   r&   r'   r[     s    

z&FunctoolsPartialVariable.call_functionr\   c                 C   s   t jttt|S r)   )r   r   r"   r^   r   r   r   )rO   r#   r:   r&   r&   r'   rc     s    z%FunctoolsPartialVariable.call_hasattrc                 C   s4   t j| j fdd | jD dd | j D S )Nc                 S   s   g | ]}|  qS r&   r   )r   r   r&   r&   r'   r   '  s     z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS r&   r   r   r&   r&   r'   r   (  s      z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)r   r   rI   r~   rV   r  r+   rN   r&   r&   r'   r~   $  s    z+FunctoolsPartialVariable.as_python_constantc                 C   s4   t j| j fdd | jD dd | j D S )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   s   g | ]}|  qS r&   guard_as_python_constant)r   r0   r&   r&   r'   r   /  s     zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS r&   r  r   r&   r&   r'   r   0  s      zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>)r   r   rI   r  rV   r  r+   rN   r&   r&   r'   r  +  s    z1FunctoolsPartialVariable.guard_as_python_constant)r]   ri   rj   r   rx   r   r_   r[   rk   rc   r~   r  r   r&   r&   r|   r'   r    s    r  c                       sD   e Zd Z fddZddddddZdddd fd	d
Z  ZS )TritonKernelVariablec                    s   ddl m} ddlm} t jf | |d k	s2t|| _||| _	|d ksZ| j	|ksZt|| _
t||rt|jj}d|kr|d jt|ddksd|kr|d jt|ddksd|kr|d j|jkst|jdkst|jdkrtd	d S )
Nr   )	Autotuner)kernel_side_tablewarmupZnum_warmupsrepZnum_repsZprune_configs_byz7Only configs and keys are supported for triton.autotune)triton.runtime.autotunerr  *torch._higher_order_ops.triton_kernel_wrapr	  rw   rx   rB   kernelZ
add_kernel
kernel_idxgridr!   rd   re   rf   r  r   Zearly_config_pruner   Z	reset_idxZrestore_idxr   )rO   r  r  r  rW   r  r	  rE   r|   r&   r'   rx   5  sF    


zTritonKernelVariable.__init__rS   rT   r   rU   c              
      sD  ddl m}m}m} ddlm  ddlm} ddlm	} d|krHt
di }	d	D ].}
|
|krP||
}t| stt|j|	|
< qP|	rt| j|rt| jj}|D ]}|j|	 q||g d
| jj}n&|f di i|	}||gg d
| j}t|d | j}||||S | jd kr"t
dtt| jj||}dd | D }t| j|rjdd | jjD ni g}g }|D ]~}| j}t|ttfrƇ fdd| D }|||t}|||gi }t||r||   nt!dt"|  qxt#t$|D ]}t|| t%s t
dt$|| dkrJ|| d ddf||< nLt$|| dkr||| d || d df||< nt$|| dkrt
dqt$|dkstt$t&|dkr|d g}ddl'm(}m)}  fdd| D } fdd| D }|*|}||t}|j+,d|d| j-|||  d t.d S )Nr   )autotuner  Configr   r   )ConstDictVariable)BaseListVariableZnum_ctaszqPassing num_ctas directly to the Triton kernel is not supported. Please use a Config in @triton.autotune instead.)Z	num_warpsZ
num_stages)configskeyrW   z2Triton kernels should always be called with a gridc                 S   s   i | ]\}}t j||qS r&   )r   r   r"   r   r&   r&   r'   r     s   
 z6TritonKernelVariable.call_function.<locals>.<dictcomp>c                 S   s   g | ]
}|j qS r&   )rW   )r   configr&   r&   r'   r     s     z6TritonKernelVariable.call_function.<locals>.<listcomp>c                    s"   i | ]\}}  |  |qS r&   )r"   r   r   r&   r'   r     s    zgrid for the triton kernel is zOnly tuple grids are supportedr      zGrid can have at most rank 3)r	  triton_kernel_wrapper_mutationc                    s$   i | ]\}}t | r|| qS r&   )r!   r~   r   r   r&   r'   r     s   
 c                    s    i | ]\}}t | s||qS r&   )r!   r   r   r&   r'   r     s   
 r[   r&   )r  constant_args_idxr  rW   )/r  r  r  r  r   r   Zdictsr  listsr  r   r6   r!   rB   rt   r  copydeepcopyr  __dict__updaterm   r  r  r[   r-   r   	arg_namesr+   ra   rl   appendZas_proxyr   r   r   r   r,   setr  r	  r  Zadd_constant_argsr2   Zcreate_proxyr  r   )rO   r#   rV   rW   r  r  r  r  r  Zspecial_kwargsr:   r$   Znew_configsr  Z
new_kernelZ
new_configZnew_varZcombined_args_rawZcombined_argsr  ZgridsZconfig_argsr  metair	  r  Zconstant_argsZnon_constant_argsr  r&   r   r'   r[   d  s    


 




z"TritonKernelVariable.call_functionc                    s   |dkr<| j d k	st|dkr&tdt| j| j|d dS |dkrd|krTtd|d}|d	d  t| j| j|d|||S t 	||||S )
N__getitem__r   z7Triton kernels should be called with only a single gridr   )r  r  r  runr  z/Triton kernel requires to be called with a gridr
  )
r  r   r   r  r  r  r6   r[   rw   r   )rO   r#   r:   rV   rW   r  r|   r&   r'   r     s2    
    z TritonKernelVariable.call_method)r]   ri   rj   rx   r[   r   r   r&   r&   r|   r'   r  4  s   0  	r  )N)<r   r  r   rd   rA   r?   typingr   r   r   r   r   rz   r   r   Zbytecode_transformationr	   r
   excr   r   Zguardsr   r   r%   r   r   r   r   r   r   r   r   r   r   baser   r   r   r   r   Ztorch._guardsr   r(   r1   r;   rJ   rK   rl   r   r   r   r   ra   r   r   r   r   r  r  r&   r&   r&   r'   <module>   sH   
 <6 (e	L8