o
    Zh"                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZ ddlmZ ddlmZ ddlZddlmZmZ dd	lmZmZmZ dd
lmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& ddl'm(Z(m)Z) ddl*m+Z+m,Z,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z:m;Z;m<Z< ddl=m>Z> zddl?m@Z@ W n eAy   dZ@Y nw erddlBmCZC ddlDmEZEmFZF ededZGd[d\ddZHd\ddZIdeJeKe<f fddZLdd  ZMh d!ZNd"d# ZOG d$d% d%e<ZPG d&d' d'ePZQG d(d) d)ePZRG d*d+ d+e<ZSG d,d- d-eSZTG d.d/ d/ePZUG d0d1 d1eUZVG d2d3 d3eQZWG d4d5 d5eWZXG d6d7 d7eQZYd\d8d9ZZG d:d; d;ePZ[G d<d= d=e<Z\G d>d? d?e<Z]d@dA Z^d\dBdCZ_G dDdE dEeQZ`G dFdG dGeQZaG dHdI dIeQZbG dJdK dKe<ZcG dLdM dMe<ZdG dNdO dOe<ZeG dPdQ dQe<ZfddRlDmgZgmhZh G dSdT dTehZiei ZjG dUdV dVe<ZkG dWdX dXe<ZlG dYdZ dZe<Zmd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)Sequence)AnyCallableOptionalTYPE_CHECKINGTypeVar)Never)patch   )	polyfills	variables)create_call_functioncreate_rot_nis_generator)get_dynamo_observed_exceptionhandle_observed_exceptionInfiniteGeneratorErrorObservedExceptionObservedGeneratorExitObservedUserStopIterationraise_observed_exception	SkipFrameunimplementedunimplemented_v2Unsupported)GuardBuilderinstall_guard)
AttrSourceConstantSourceDefaultsSourceGetItemSource)	check_constant_argscheck_unspec_or_constant_argscmp_name_to_op_mappingcountersidentityis_functionis_wrapper_or_member_descriptoristype	make_cell   )typestrValueMutationNewVariableTrackerConstantVariable)_fsdp_param_group)InstructionTranslator)TritonGridTypeTritonKernelType_F)boundtxr1   c                 C   s,   t |tr|S |st| |S tj||S N)
isinstancer-   buildr   LazyVariableTrackercreate)r6   valsource r>   P/var/www/auris/lib/python3.10/site-packages/torch/_dynamo/variables/functions.pywrap_bound_argX   s
   
r@   c                 C   s6   t | D ]\}}t|ttfrt| |||< qd S r7   )listitemsr8   tupledictr@   )r6   resultkvr>   r>   r?   wrap_args_kwargsd   s
   rH   rE   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_cellvarsZtrack_cell_newZ
store_cellpop)parentrE   coderJ   nameZnew_cellr>   r>   r?   init_cellvarsk   s   

rP   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)	typesrQ   __kwdefaults__r8   rC   	itertoolsrS   rD   __annotations__)
rN   	f_globalsrO   defaultsclosure
kwdefaultsannotationsrQ   funcrS   r>   r>   r?   _create_nested_fn|   s   
r^   >   __code____globals____closure____doc__rW   __defaults__rU   c                 C   sl   |ot ||}zt||}W n ty   tt|  Y nw |tv r't||}|r0tj	||S t
| |S r7   )r   inspectgetattr_staticAttributeErrorr   fn_known_dunder_attrsgetattrr   r:   r;   r-   r9   )r6   fnr=   rO   Zsubobjr>   r>   r?   fn_var_getattr   s   
rj   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 r7   get_codeco_filenameselfr>   r>   r?   get_filename      
z%BaseUserFunctionVariable.get_filenamec                 C   rl   r7   rn   co_namerp   r>   r>   r?   get_name   rs   z!BaseUserFunctionVariable.get_namer6   r1   argslist[VariableTracker]kwargsdict[str, VariableTracker]returnr-   c                 C   s   | | g |  ||S r7   )Zinline_user_function_return	self_argsrq   r6   rw   ry   r>   r>   r?   call_function   s   z&BaseUserFunctionVariable.call_functionrO   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NotImplementedErrorr8   NestedUserFunctionVariabler   r/   r;   rq   r6   rO   rE   r>   r>   r?   call_obj_hasattr   s   z)BaseUserFunctionVariable.call_obj_hasattrc                 C   s   t t|  jS r7   )rA   rd   	signaturer   
parametersrp   r>   r>   r?   inspect_parameter_names      z0BaseUserFunctionVariable.inspect_parameter_namesc                 C      i S r7   r>   rq   r6   r>   r>   r?   closure_vars      z%BaseUserFunctionVariable.closure_varsNr6   r1   rw   rx   ry   rz   r{   r-   )r   
__module____qualname__rr   rv   r~   strr-   r   r   r   r>   r>   r>   r?   rk      s*    

rk   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 functionri   is_constantc                 C      t |tj | ||dS Nr=   )r   
make_guardr   ZCLOSURE_MATCHclsvaluer=   r>   r>   r?   create_with_source   s   z'UserFunctionVariable.create_with_sourceFr{   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 )NZ_dynamo_marked_constantFTzexpected FunctionType found  Z_torchdynamo_inliner>   )super__init__rh   r   r8   rT   rQ   torchZjitZScriptFunctionr+   rd   re   ri   rq   ri   r   ry   	__class__r>   r?   r      s   
zUserFunctionVariable.__init__c                    s   t | tr| jS t  S r7   )r(   r   ri   r   as_python_constantrp   r   r>   r?   r      s   

z'UserFunctionVariable.as_python_constantc                 C      g S r7   r>   rp   r>   r>   r?   r|      r   zUserFunctionVariable.self_argsc                 C      | j S r7   ri   rp   r>   r>   r?   r         z!UserFunctionVariable.get_functionc                 C      | j jS r7   )ri   r_   rp   r>   r>   r?   rn         zUserFunctionVariable.get_codec                 C      t jS r7   rT   rQ   rp   r>   r>   r?   python_type   r   z UserFunctionVariable.python_typec                 C   s   t | jdd d uS N__self__)rh   ri   rp   r>   r>   r?   has_self      zUserFunctionVariable.has_selfc                 C   r   r7   )ri   r`   rp   r>   r>   r?   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.
        )r6   c                    s*   g | ]\}} j d u rd nt j |qS r7   r=   r   ).0idx_rp   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 u rd nt j |ddqS )NT)Zis_kwr   )r   rF   rp   r>   r?   
<dictcomp>!  s    
z2UserFunctionVariable.bind_args.<locals>.<dictcomp>c                    s"   i | ]\}}|| | d qS r   r>   r   rF   rG   )kwdefaults_sourcesr   r>   r?   r   )  s    r>   ra   cell_contentsN)*r   rI   root_tx	functoolspartialr@   ri   rc   	enumeraterT   rQ   r_   r`   r   rC   zipra   rU   rB   rd   r   bindapply_defaultsrD   	argumentsrH   rP   lenco_freevarsrV   countrJ   r=   r    r   r-   r9   r   
ValueErrorr   ZDeletedVariableZtrack_cell_existing)rq   rM   rw   ry   r   ri   rY   Zdefaults_sourcesZ	fake_funcr5   rE   rZ   r   rO   cellrJ   Zcell_varZclosure_cellZclosure_cell_contentsZcontents_varr>   )r   rq   r   r?   	bind_args  s|   








zUserFunctionVariable.bind_argsr6   r1   rO   c                 C   &   |t v r
t| |S t|| j| j|S r7   )r#   r   GetAttrVariablerj   ri   r=   rq   r6   rO   r>   r>   r?   var_getattr\  s   z UserFunctionVariable.var_getattrc                 C   s   t | j|}tj|S r7   )r   ri   r   r/   r;   r   r>   r>   r?   r   a  s   z%UserFunctionVariable.call_obj_hasattrrw   rx   ry   rz   r-   c           
         sJ  | j tjju rEt| j j|i |}|jd }t|t	s*|
 }td|j d t|ts;| }td| d |j }tj|ddS | jrSt|| j |  ||S |jjjr|jjjszddlm}	 W n typ   d }	Y nw |	d ur| j |	j|	jfv rtjj| t |||W  d    S 1 sw   Y  t |||S )	Nr   z=`nonstrict_trace` expects a callable, but got value of type <>z)
Applying `nonstrict_trace` to function <zl>; however, `nonstrict_trace` currently requires the function to be defined outside `torch.compile` region.
TZnonstrict_traceable)	FSDPState)ri   r   _dynamoZnonstrict_tracerd   r   r   rw   r8   rk   r   r   r   r   rv   r   TorchInGraphFunctionVariabler   invoke_and_store_as_constantrI   Zcurrent_tracerZunder_activation_checkpointZ#allow_side_effects_under_checkpointZ/torch.distributed.fsdp._fully_shard._fsdp_stater   	ExceptionZ_pre_forwardZ_post_forwardrJ   r   r~   )
rq   r6   rw   ry   r5   Zfn_vartypfn_nameri   r   r   r>   r?   r~   g  sL   


 z"UserFunctionVariable.call_functionFr{   Nr   )r   r   r   rb   rk   _nonvar_fieldsclassmethodr   r   r   r|   r   rn   r   r   r   rD   r   r-   r   r   r   r~   __classcell__r>   r>   r   r?   r      sF    
W
r   c                       sF   e Zd Zdd fddZedd Z				
					dddZ  ZS )BuiltinMethodVariableFr{   Nc                    s,   t  jdi | t|tjsJ || _d S Nr>   )r   r   r8   rT   BuiltinMethodTyperi   r   r   r>   r?   r     s   
zBuiltinMethodVariable.__init__c                 C   s0   | j }| j}|tu r|dkpt|tu o|dkS )N__new____contains__)r   r   rC   type	frozenset)objmethod_selfmethod_namer>   r>   r?   is_supported_builtin_method  s
   z1BuiltinMethodVariable.is_supported_builtin_methodr6   r1   rw   rx   ry   rz   r-   c                 C   s@   | j j}| j j}| jot| jd}t|||}|||||S r   )ri   r   r   r=   r   r-   r9   call_method)rq   r6   rw   ry   r   rO   Z
obj_sourceZobj_vtr>   r>   r?   r~     s
   z#BuiltinMethodVariable.call_functionr   r   r   )r   r   r   r   staticmethodr   r~   r   r>   r>   r   r?   r     s    

r   c                
       s   e Zd Zdejded f 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eZdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"ejfd#d$Zd"ee fd%d&Zd'd( Zd)d* Zd+d, Zd-dd.ed/d0d1d2d"d3f
 fd4d5Z  Z S )6LocalGeneratorObjectVariablerN   inline_tracerr1   c                    s(   t  jdi | || _|| _|| _d S r   )r   r   rN   rX   r   )rq   rN   rX   r   ry   r   r>   r?   r     s   
z%LocalGeneratorObjectVariable.__init__c                 C   r   r7   )rN   rp   r>   r>   r?   rn     r   z%LocalGeneratorObjectVariable.get_codec                 C   rl   r7   rm   rp   r>   r>   r?   rr     rs   z)LocalGeneratorObjectVariable.get_filenamec                 C   rl   r7   rt   rp   r>   r>   r?   rv     rs   z%LocalGeneratorObjectVariable.get_namec                 C   s   t r7   )r   rp   r>   r>   r?   r     r   z)LocalGeneratorObjectVariable.get_functionc                 C      dS NFr>   rp   r>   r>   r?   r     r   z%LocalGeneratorObjectVariable.has_selfc                 C      |   S r7   )rv   rp   r>   r>   r?   r     r   z%LocalGeneratorObjectVariable.__name__c                 C   s   | j j d|   dS )N())r   r   rv   rp   r>   r>   r?   __str__  s   z$LocalGeneratorObjectVariable.__str__c              
   C   s   ddl m} ddlm}m}m} | }||}||}||}	|L |1 |	 | |}
|
js7| 	|| _
t| j
| W d    n1 sJw   Y  W d    n1 sYw   Y  W d    d S W d    d S 1 sqw   Y  d S )Nr   )"disallow_side_effects_in_generator)r1    save_and_restart_speculation_log(temporarely_allow_writes_to_output_graph)Ztorch._dynamo.side_effectsr   torch._dynamo.symbolic_convertr1   r   r   Z
current_tx_get_inline_tracergenerator_exhaustedforce_unpack_var_sequenceZremaining_itemsr   ZListIteratorVariablereconstruct)rq   codegenr   r1   r   r   r6   saveZdisallowtemptracerr>   r>   r?   r     s   
P z(LocalGeneratorObjectVariable.reconstructc                 C   s   | j |||S r7   )ri   r   r}   r>   r>   r?   r        z&LocalGeneratorObjectVariable.bind_argsc                 C   r   r7   rX   rp   r>   r>   r?   r     r   z(LocalGeneratorObjectVariable.get_globalsc                 C   r   r7   )rT   GeneratorTyperp   r>   r>   r?   r     r   z(LocalGeneratorObjectVariable.python_typec                 C   s.   ddl m} | jd u r||| g i | _| jS Nr   )InliningInstructionTranslator)r   r  r   build_inline_tracer)rq   r6   r  r>   r>   r?   r     s   
z/LocalGeneratorObjectVariable._get_inline_tracerc                 C   s   |  |}|  rtt| zfz,ttdtd i | W  d    W W td  td O  < S 1 s5w   Y  W n, tyI } z|d }~w t	yP     t
yg } ztjj|   t|d }~ww W td  td O  < d S td  td O  < w )Nr   Zinline_call)r   _is_generator_exhaustedr   StopIterationr	   rD   r$   Zinline_call_r   r   r   r   r   Z
eval_frameZ	skip_codern   r   )rq   r6   r   er>   r>   r?   next_variable  s*   

.z*LocalGeneratorObjectVariable.next_variablec                 C   r   r   r>   r   r>   r>   r?   has_unpack_var_sequence  r   z4LocalGeneratorObjectVariable.has_unpack_var_sequencer{   c                 C   r   NTr>   r   r>   r>   r?   has_force_unpack_var_sequence  r   z:LocalGeneratorObjectVariable.has_force_unpack_var_sequencec                 C   s:   g }	 z
| | | W n ty   t| Y |S w qr7   )appendr  r   r   )rq   r6   rE   r>   r>   r?   r     s   z6LocalGeneratorObjectVariable.force_unpack_var_sequencec              
   C   sL   |  |}z|| W d S  ty% } z|| W Y d }~d S d }~ww r7   )r   Z_raise_exception_variabler   Zexception_handler)rq   r6   excr   r  r>   r>   r?   _setup_exception%  s   
z-LocalGeneratorObjectVariable._setup_exceptionc                 C   s   | j d u p
| j jdkS )Nr   )r   Zinstruction_pointerrp   r>   r>   r?   _is_generator_just_started.  s   z7LocalGeneratorObjectVariable._is_generator_just_startedc                 C      t | jddS )Nr   F)rh   r   rp   r>   r>   r?   r  1  s   z4LocalGeneratorObjectVariable._is_generator_exhaustedr6   rO   rw   rx   ry   rz   r-   c              	      s.  |dkr	|  |S |dkr| S |dkr8|  r)t|r)tdd |D s)tt| | |}|| |  |S |dkr| |}|  sI|  rQd|_	t
d S z | |t
td tjd	krp|jjd
krpd|_	t
d W S W n ty   d|_	t
d  Y S w z|  |rtt| W n| ty   d|_	t
d  Y S  ty   |jd usJ |j Y S w |dkr| |}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 |||| d S )N__next____iter__sendc                 s   s$    | ]}t |to|jd u V  qd S r7   )r8   r/   r   r   r   r>   r>   r?   	<genexpr>G  s
    
z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>closeTr>   )      ZCALL_INTRINSIC_1throwr  r*   r   Z__InternalThrowException)r  r  r   allr   	TypeErrorr   Z	push_manyr  r   r   r/   r  ZExceptionVariableGeneratorExitsysversion_infoZnext_instructionopnamer   RuntimeErrorr   Zsymbolic_resultr   r   r   r   r   r   )rq   r6   rO   rw   ry   r   retvalexc_typer   r>   r?   r   4  sz   












(
>
z(LocalGeneratorObjectVariable.call_method)!r   r   r   rT   CodeTyper   r   rn   rr   rv   r   r   r   __repr__r   r   r   r   r   r  r	  builtinsboolr  rA   r-   r   r  r  r  r   r   r   r>   r>   r   r?   r     sJ    	
	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)r   r   r   rb   r>   r>   r>   r?   r'    s    r'  c                       sV   e Zd ZdZeddef fddZdd Zdd	 Z	
							dddZ	  Z
S )LocalGeneratorFunctionVariablezxfunctions that behaves like iterators

    .. note::

        This is a wrapper around (Nested)UserFunctionVariable
    )generator_clsvtc                   "   t  jdi | || _|| _d S r   )r   r   r*  r)  )rq   r*  r)  ry   r   r>   r?   r     s   
z'LocalGeneratorFunctionVariable.__init__c                 C   s&   || j j v rt| |S t| j|S r7   )r   __dict__keysrh   r*  )rq   rO   r>   r>   r?   __getattr__  s   
z*LocalGeneratorFunctionVariable.__getattr__c                 C   s   ddl m} ||| ||S r  )r   r  r  )rq   r6   rw   ry   r  r>   r>   r?   _build_inline_tracer  s   z3LocalGeneratorFunctionVariable._build_inline_tracerr6   r1   rw   rx   ry   rz   r{   r-   c                 C   sH   t | j s	J | |||}| j }| j }| j|||| jdS r   )r   r*  rn   r/  r   r)  r=   )rq   r6   rw   ry   r   rN   rX   r>   r>   r?   r~      s   

z,LocalGeneratorFunctionVariable.call_functionr   )r   r   r   rb   r   r-   r   r.  r/  r~   r   r>   r>   r   r?   r(    s"    
r(  c                       s,   e Zd ZdZ fddZ fddZ  ZS )3FunctionDecoratedByContextlibContextManagerVariablezm
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager
    c                    s   t  j|fdti| d S )Nr)  )r   r   r'  )rq   r*  ry   r   r>   r?   r   >  s   
z<FunctionDecoratedByContextlibContextManagerVariable.__init__c                    s.   t  |||}t|tjjjsJ d|_|S r
  )r   r/  r8   r   r   Zsymbolic_convertZ&InliningGeneratorInstructionTranslatorZis_generator_from_ctx_manager)rq   r6   rw   ry   r   r   r>   r?   r/  E  s   zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracer)r   r   r   rb   r   r/  r   r>   r>   r   r?   r0  5  s    r0  c                       s   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
dddef fddZ  ZS )UserMethodVariablez$Some unsupported user-defined methodr{   Nc                    s    t  jdd|i| || _d S )Nri   r>   )r   r   r   )rq   ri   r   ry   r   r>   r?   r   V  s   
zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )Nr   z, r   )r   r   ri   r   rp   r>   r>   r?   r$  Z  s   zUserMethodVariable.__repr__c                 C   s   | j gS r7   )r   rp   r>   r>   r?   r|   ]  r   zUserMethodVariable.self_argsc                 C   r   r7   )rT   
MethodTyperp   r>   r>   r?   r   `  r   zUserMethodVariable.python_typer6   r1   rw   rx   ry   rz   r-   c           	         s  ddl m} || jr"g |  |}tj| jdd}||||S |j rTt	| j
tjrTt| jdd}|d urB|drB|dksE| jrS| j
j|| jj||| jd	S ntd uro| jtjju rot| j|| j
g|R |S | jrt| j
j| jj}t|||  ||S t |||S )
Nr
   )is_nonstrict_trace_callableTr   r    z	torch.nn.ztorch.nn.utils.parametrize)constant)Ztrace_rulesr3  ri   r|   r   r   r~   rI   Zis_root_tracerr8   r   ZNNModuleVariablerh   
startswithr   r   r   r0   ZFSDPParamGroupZuse_training_stateZTorchCtxManagerClassVariabler   r   rv   r   )	rq   r6   rw   ry   r3  Z	call_argsvarZmodule_attrri   r   r>   r?   r~   c  s<   
z UserMethodVariable.call_functionc                    s   t   dd  S Nr*   )r   r   rp   r   r>   r?   r     r   z*UserMethodVariable.inspect_parameter_namesrO   c                    sF   | j ot| j |}|dkr| jS |dkrt|| j|S t ||S )Nr   __func__)r=   r   r   r-   r9   ri   r   r   )rq   r6   rO   r=   r   r>   r?   r     s   zUserMethodVariable.var_getattrr   r   )r   r   r   rb   r   r   r$  r|   r   r~   r   r   r   r>   r>   r   r?   r1  S  s"    =r1  c                       <   e Zd Zd fddZ							
		d fddZ  ZS )WrappedUserMethodVariabler{   Nc                    sB   | dd  | dd  t j|j|jfi | || _|| _d S Nri   r   )rL   r   r   ri   r   wrappedcontextrq   r=  r>  ry   r   r>   r?   r     s
   
z"WrappedUserMethodVariable.__init__r6   r1   rw   rx   ry   rz   r-   c                    ,   | j | t |||}| j | |S r7   r>  Zenterr   r~   exitrq   r6   rw   ry   rE   r   r>   r?   r~        z'WrappedUserMethodVariable.call_functionr   r   r   r   r   r   r~   r   r>   r>   r   r?   r;        r;  c                       r:  )WrappedUserFunctionVariabler{   Nc                    s>   | dd  | dd  t j|jfi | || _|| _d S r<  )rL   r   r   ri   r=  r>  r?  r   r>   r?   r     s
   
z$WrappedUserFunctionVariable.__init__r6   r1   rw   rx   ry   rz   r-   c                    r@  r7   rA  rC  r   r>   r?   r~     rD  z)WrappedUserFunctionVariable.call_functionr   r   rE  r>   r>   r   r?   rG    rF  rG  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 r7   )r8   r   TensorVariableZget_real_valuer   )xr>   r>   r?   convert  s   z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS r>   r>   r   rI  rJ  r>   r?   r         z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]	\}}| |qS r>   r>   r   rL  r>   r?   r         z0invoke_and_store_as_constant.<locals>.<dictcomp>r   )rB   rI   Zregister_attr_or_moduler   )r6   ri   rO   rw   ry   resr>   rL  r?   r     s   r   c                       sx   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dd Z  ZS )r   rX   Nr{   c	           
         sz   t  jdi |	 t| tsJ t| tjsJ t|ts#J || _|| _	|| _
|| _|| _|| _|| _|| _d S r   )r   r   r8   r   r   rT   r#  rD   r   rN   rX   rY   r[   r\   rZ   
wrapped_fn)
rq   r   rN   rX   rY   r[   r\   rZ   rP  ry   r   r>   r?   r     s   
z#NestedUserFunctionVariable.__init__c                 C   r   r7   r>   rp   r>   r>   r?   r|     r   z$NestedUserFunctionVariable.self_argsc                 C   s
   | j  S r7   )rN   r   rp   r>   r>   r?   rn     rs   z#NestedUserFunctionVariable.get_codec                 C   r   r7   r   rp   r>   r>   r?   r     r   z&NestedUserFunctionVariable.python_typec                 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   rR   )rZ   r   rT   rQ   rN   r   rX   r   rY   rc   r[   rU   r\   r8   rC   rV   rS   rD   rW   )rq   r]   r\   rS   r>   r>   r?   r     s&   

z'NestedUserFunctionVariable.get_functionc                 C   s
   | j d uS r7   )rZ   rp   r>   r>   r?   has_closure&  rs   z&NestedUserFunctionVariable.has_closurec                 C   r   r   r>   rp   r>   r>   r?   r   )  r   z#NestedUserFunctionVariable.has_selfc                 C   r   r7   r   rp   r>   r>   r?   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 r7   )r)   )r   r   r>   r>   r?   r  6      z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>)rn   rT   rQ   rX   r   r   rY   rC   rB   ranger   r   r[   Zkeys_as_python_constantrU   rd   r   r   r   rD   r   rH   rI   r   rP   r   rZ   )rq   rM   rw   ry   rN   r]   r5   rE   r   rO   r   r>   r>   r?   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 )Nr^   )load_import_fromr   r>   r   r>   r?   <lambda>I      z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>   Fc                           ddS )Nr   wrapsrT  r>   rU  r>   r?   rV  m  rW  r*   r
   T)add_push_nullrN   extend_outputZcreate_load_const_uncheckedrX   r/   r;   r   ru   rY   Zcreate_load_constrZ   r[   r\   r   r   r   rP  r   )rq   r   r\   r>   rU  r?   r   G  sF   





z&NestedUserFunctionVariable.reconstructr7   r   )r   r   r   rk   r   r   r|   rn   r   r   rQ  r   r   r   r   r   r>   r>   r   r?   r     s$    r   c                       sx   e Zd ZddhejZdd fddZdd Zed	d
 Z								dddZ	dddZ
dddefddZ  ZS )SkipFunctionVariabler   reasonNr{   c                    r+  r   )r   r   r   r_  )rq   r   r_  ry   r   r>   r?   r   |     
zSkipFunctionVariable.__init__c                 C   r   r7   r   rp   r>   r>   r?   r     r   z'SkipFunctionVariable.as_python_constantc                 C   s$   t |st|tj | ||dS r   )r'   r   r   r   FUNCTION_MATCHr   r>   r>   r?   r     s   z'SkipFunctionVariable.create_with_sourcer6   r1   rw   rx   ry   rz   r-   c              	   C   s@  t | jddrtdt| jd| j ddgd d S | jtjju rC|dd }|r.|	 }td	d
| d| dd| dgd d S t
| jtjr^d| j d}tjj| t| d S t| jdd}z)t | j}d| d| d}d| dg}	d|vr|	d| d| ddg7 }	W nj ty   ddh}
| jj|
v rd| jj d | d}d!d"g}	nG| jjd ur| jjd#rd$| jj d | d }d%g}	tjj|d& d&|	  nd'| jj d | d(}d)d*g}	tjj|d& d&|	  Y nw |d+krd,}g }	| jr	| jnd-}td.d/| jj d0| d1| ||	d d S )2NZ_torchdynamo_disableFz1Skip calling `torch.compiler.disable()`d functionzSkip calling function `z4` since it was wrapped with `torch.compiler.disable`z(Remove the `torch.compiler.disable` call)Zgb_typer>  explanationhintsmsgz%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.z2Graph break due to unsupported wrapper descriptor zM. Please file an issue on GitHub so the PyTorch team can add support for it. r   z<unknown qualname>z?Dynamo developers have intentionally marked that the function `z` in file `z` should not be traced.zAvoid calling the function `z`.r   zRemove the function `z` or the file `zv` from torch/_dynamo/trace_rules.py. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch._abc	_warningsz6Dynamo does not know how to trace the Python builtin `.zIf you are attempting to call a logging function (e.g. `_warnings.warn`), you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.zKPlease file an issue on GitHub so the PyTorch team can add support for it. Zoptreez*Dynamo cannot trace optree C/C++ function zi Consider using torch.utils._pytree - https://github.com/pytorch/pytorch/blob/main/torch/utils/_pytree.py
z/Dynamo does not know how to trace the builtin `z.` This function is either a Python builtin (e.g. _warnings.warn) or a third-party C/C++ Python extension (perhaps created with pybind).zIf it is a Python builtin, please file an issue on GitHub so the PyTorch team can add support for it and see the next case for a workaround.a  If it is a third-party C/C++ Python extension, please either wrap it into a PyTorch-understood custom operator (see https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html for more details) or, if it is traceable, use `torch.compiler.allow_in_graph`.Z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: )rd   re   r   r   r   r   r   Zgraph_breakgetr   r8   rT   WrapperDescriptorTypeutilsZ	warn_oncer   rh   getfiler  r   r6  joinr_  )rq   r6   rw   ry   Zgraph_break_msgre  qualnamepathrc  rd  Zknown_python_builtin_modulesr_  r>   r>   r?   r~     s   




)
z"SkipFunctionVariable.call_functionc                 C   s   t jt| j|S r7   )r   r/   r;   r   r   r   r>   r>   r?   r     r   z%SkipFunctionVariable.call_obj_hasattrrO   c                 C   r   r7   )r#   r   r   rj   r   r=   r   r>   r>   r?   r     s   z SkipFunctionVariable.var_getattrr7   r   r   r6   r1   )r   r   r   r-   r   r   r   r   r   r~   r   r   r   r   r>   r>   r   r?   r^  u  s*    


q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".
    r{   Nc                    r+  r   )r   r   wrapper_objattr_to_trace)rq   rt  ru  ry   r   r>   r?   r     r`  z$WrapperUserFunctionVariable.__init__r6   r1   c                    sF   || j krt| j| j }| jot| j|}t|||S t ||S r7   )	ru  rh   rt  r=   r   r-   r9   r   r   )rq   r6   rO   r<   r=   r   r>   r?   r     s
   
z'WrapperUserFunctionVariable.var_getattrrw   rx   ry   rz   r-   c                 C   s&   t tj|| t | jg||S r7   )r   r   r   Zgetattr_and_tracer~   r/   ru  r}   r>   r>   r?   r~     s   z)WrapperUserFunctionVariable.call_functionr   rr  r   )r   r   r   rb   r   r   r~   r   r>   r>   r   r?   rs    s    rs  c                  C   s   t j rddlm}  | S i S )Nr   traceable_collective_remaps)r   distributedis_available)torch.distributed._functional_collectivesrw  rv  r>   r>   r?   _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   rx  ry  r{  valuesr   Zimport_sourcer   )r6   ri   Z
inner_nameZpath_sourcer>   r>   r?   _traceable_collectives_source5  s
   

r}  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.
    r{   Nc                   s,   t  j|fi | t|tsJ || _d S r7   )r   r   r8   r   replacement_var)rq   ri   r  ry   r   r>   r?   r   I  s   
z*CollectiveFunctionRewriteVariable.__init__r6   r1   c                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr=   )r  r=   )r~  rewriter   )r6   Zold_fnr=   optionsnew_fnZ
new_sourcer>   r>   r?   r;   N  s   z(CollectiveFunctionRewriteVariable.createc                 C   s   t | o	| t v S r7   )rd   
isfunctionr{  )variabler>   r>   r?   can_rewriteX  s   z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS r7   )r{  r}  )r6   ri   r  r>   r>   r?   r  ^  s   
z)CollectiveFunctionRewriteVariable.rewriterw   rx   ry   rz   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_STRr>   Zasync_opzBCollectiveFunctionRewriteVariable can't support async_op=True for opzUnsupported all_reduce op: )Ztorch.distributedrx  rz  r  rd   r   ri   rD   r   r   r   r   Z
all_reduceZreduce_scatter_tensorZ_reduce_scatter_baserk  r   r   defaultr   r   r/   r;   r  r~   )	rq   r6   rw   ry   distr  r   Zreduce_op_varZ	reduce_opr>   r>   r?   r~   c  s2   	


z/CollectiveFunctionRewriteVariable.call_functionr   rr  r   )r   r   r   rb   r   r   r;   r  r  r~   r   r>   r>   r   r?   r~  >  s$    
	
r~  c                       s.   e Zd Z								d fd	d
Z  ZS )FunctoolsWrapsVariabler6   r1   rw   rx   ry   rz   r{   r-   c                    s6   |st  dkr fdd}t|S t | |S )Nr*   c                    s0   t | tjr| j d dS td|  d d S )Nr   )rP  zfunctools.wraps(r   )r8   r   r   cloner   r   rw   r>   r?   rZ    s   z3FunctoolsWrapsVariable.call_function.<locals>.wraps)r   r   ZLambdaVariabler   r~   )rq   r6   rw   ry   rZ  r   r  r?   r~     s   
z$FunctoolsWrapsVariable.call_functionr   )r   r   r   r~   r   r>   r>   r   r?   r    s    r  c                   @   s.   e Zd Zdd Z									
dddZdS )CollectionsNamedTupleFunctionc                 C   r   r7   r   rp   r>   r>   r?   r     r   z0CollectionsNamedTupleFunction.as_python_constantr6   r1   rw   rx   ry   rz   r{   r-   c                 C   sR   t ||}|r#| jdd |D i dd | D }tj|t dS td d S )Nc                 S      g | ]}|  qS r>   r   rK  r>   r>   r?   r     rM  z?CollectionsNamedTupleFunction.call_function.<locals>.<listcomp>c                 S      i | ]	\}}||  qS r>   r  r   r>   r>   r?   r     rN  z?CollectionsNamedTupleFunction.call_function.<locals>.<dictcomp>)Zmutation_typez!namedtuple with non constant args)r!   ri   rB   r   ZUserDefinedClassVariabler,   r   )rq   r6   rw   ry   constant_argsr   r>   r>   r?   r~     s   
z+CollectionsNamedTupleFunction.call_functionNr   )r   r   r   r   r~   r>   r>   r>   r?   r    s    r  c                       s   e Zd Zdeddf fddZ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de	fddZdd Zdd Z  ZS )FunctoolsPartialVariabler]   r{   Nc                    sP   t  jdi | || _t|tsJ || _t|tsJ || _t	t
| _d S r   )r   r   r]   r8   rA   rw   rD   keywordsr   r   r%   Z
fake_value)rq   r]   rw   r  ry   r   r>   r?   r     s   z!FunctoolsPartialVariable.__init__c                 C   r   r7   )r   r   rp   r>   r>   r?   r     r   z$FunctoolsPartialVariable.python_typec                    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                      rY  )Nr   r   r[  r>   rU  r>   r?   rV    rW  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>r*   F)r\  r]   rw   foreachr  r]  r   r   r|  rC   r-  Zcreate_call_function_kw)rq   r   r-  r>   rU  r?   r     s   
z$FunctoolsPartialVariable.reconstructc                 C   r   r7   r  rp   r>   r>   r?   r     r   z%FunctoolsPartialVariable.get_functionr6   r1   rw   rx   ry   rz   r-   c                 C   s(   | j | }i | j|}| j|||S r7   )rw   r  r]   r~   )rq   r6   rw   ry   Zmerged_argsZmerged_kwargsr>   r>   r?   r~     s   
z&FunctoolsPartialVariable.call_functionrO   c                 C   s   t jttt|S r7   )r   r/   r;   r   r   r   r%   r   r>   r>   r?   r     s   z)FunctoolsPartialVariable.call_obj_hasattrc                 C   sp   | 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	t
| d S )Nr]   rw   r   r  c                 S   s   i | ]
\}}t ||qS r>   )r/   r;   r   r>   r>   r?   r     s    z8FunctoolsPartialVariable.var_getattr.<locals>.<dictcomp>)r=   r   r]   r   ListVariablerw   r  rB   ConstDictVariabler   rf   )rq   r6   rO   r=   rB   r>   r>   r?   r     s   z$FunctoolsPartialVariable.var_getattrc                 C   :   t j| j gdd | jD R i dd | j D S )Nc                 S   r  r>   r  r  r>   r>   r?   r     rM  z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   r  r>   r  r   r>   r>   r?   r     rN  z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)r   r   r]   r   rw   r  rB   rp   r>   r>   r?   r     s   z+FunctoolsPartialVariable.as_python_constantc                 C   r  )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   r  r>   guard_as_python_constant)r   rG   r>   r>   r?   r      rM  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   r  r>   r  r   r>   r>   r?   r     rN  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>)r   r   r]   r  rw   r  rB   rp   r>   r>   r?   r    s   z1FunctoolsPartialVariable.guard_as_python_constantr   )r   r   r   r-   r   r   r   r   r~   r   r   r   r   r  r   r>   r>   r   r?   r    s0    


r  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 )"PolyfilledFunctionVariableri   rP  traceable_fnNr{   .c                 C   r   r7   r>   )r   r>   r>   r?   _get_polyfill_handlers  s   z1PolyfilledFunctionVariable._get_polyfill_handlersc                 C   r   r   )r   r   r   rb  r   r>   r>   r?   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 )Z__torch_dynamo_polyfill__Z__python_implementation__z# does not have a traceable functionr>   )
r   r   ri   r  rk  callablerh   r   rP  r  )rq   ri   ry   handlerZcandidate_attr	candidater  r   r>   r?   r     s    

z#PolyfilledFunctionVariable.__init__c                 C   r   r7   )r  rp   r>   r>   r?   polyfill_fn/  s   z&PolyfilledFunctionVariable.polyfill_fnc                 C   r  )NZ*__torch_dynamo_can_constant_fold_through__F)rh   rP  rp   r>   r>   r?   can_constant_fold_through3     z4PolyfilledFunctionVariable.can_constant_fold_throughc                 C   r   r7   r  rp   r>   r>   r?   r   8  r   z'PolyfilledFunctionVariable.get_functionr6   r1   rw   rx   ry   rz   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  r>   r  rK  r>   r>   r?   r   F  rM  z<PolyfilledFunctionVariable.call_function.<locals>.<listcomp>c                 S   r  r>   r  r   r>   r>   r?   r   G  rN  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 r7   )r8   r   r/   r   intSymNodeVariabler   rK  r>   r>   r?   r  R  s    
z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>r~   c                 s   s    | ]}|  V  qd S r7   as_proxy)r   ar>   r>   r?   r  ]  rR  c                 S   s$   g | ]}t |tjr|jn|jqS r>   )r8   r   r/   r   sym_numrK  r>   r>   r?   r   a  s    
)r  )r  r"   ri   rB   r-   r9   r%  sumr   r8   r   r  TupleVariabler  r  r;   rI   create_proxyr   Zsym_sumrC   r  r~   )rq   r6   rw   ry   rE   Ztraceable_function_variabler>   r>   r?   r~   ;  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 r=   )r~   rh   ri   r&   r=   r   r  )rq   r6   rO   rw   ry   methodr  Zpolyfilled_method_variabler>   r>   r?   r   o  s   z&PolyfilledFunctionVariable.call_methodc                 C   r   r7   r   rp   r>   r>   r?   r     r   z-PolyfilledFunctionVariable.as_python_constantr   rw   rx   ry   rz   r{   r-   )r   r   r   r-   r   r   r   	lru_cacherD   r   r   rT   rQ   r  r   r4   r   propertyr  r  r   r~   r   r   r   r>   r>   r   r?   r    sD    $

4
r  c                   @   s   e Zd Zdd ZdS )TracebackVariablec                 C   s   d S r7   r>   r}   r>   r>   r?   r~     s    zTracebackVariable.call_functionN)r   r   r   r~   r>   r>   r>   r?   r    s    r  c                       s4   e Zd Z fddZdd Zdd Zdd Z  ZS )	SysFunctionVariablec                    s   t  jdi | || _d S r   )r   r   r   )rq   r   ry   r   r>   r?   r     s   
zSysFunctionVariable.__init__c                 C   s`   t |jr|jd }|j}d }t|||t||g}ntd td td g}t|S )N)r   Zexn_vt_stackr"  r-   r9   r   r/   r  )rq   r6   Zexnr   tbrB   r>   r>   r?   exc_info  s   




zSysFunctionVariable.exc_infoc                 C   s   |  |jd S r8  )r  rB   r   r>   r>   r?   	exception  r   zSysFunctionVariable.exceptionc                 C   sB   | j tju r| |S | j tju r| |S td| j j  d S )Nzsys.)r   r  r  r  r   r   r}   r>   r>   r?   r~     s
   

z!SysFunctionVariable.call_function)r   r   r   r   r  r  r~   r   r>   r>   r   r?   r    s
    r  )TMADescriptorMetadataTritonHOPifierc                   @   s   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d Zdd Zdd ZdedefddZdddee ddfddZdefddZd S )!DynamoTritonHOPifierre  r{   c                 C   s   t |r7   )r   )rq   re  r>   r>   r?   raise_unsupported  r   z&DynamoTritonHOPifier.raise_unsupportedmaybe_callablec                 C   s   t |ttfS r7   )r8   r   r   )rq   r  r>   r>   r?   is_callable  r  z DynamoTritonHOPifier.is_callabler<   c                 C   s   |j S r7   ra  )rq   r<   r>   r>   r?   	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  r8   r  r   r   )rq   gridr  r>   r>   r?   
check_grid  s   
zDynamoTritonHOPifier.check_gridc                 C   s&   dd |  D }|||gi }|S )Nc                 S      i | ]\}}t j||qS r>   r   r/   r;   r   r>   r>   r?   r     s    z2DynamoTritonHOPifier.call_grid.<locals>.<dictcomp>)rB   r~   )rq   r  metar6   r>   r>   r?   	call_grid  s   zDynamoTritonHOPifier.call_gridc           	      C   s*   ddl m} |||}||||}|S )Nr*   )SourcelessBuilder)builderr  r;   r~   )	rq   Zuser_fnrw   ry   r6   r  r  Zwrapped_user_functionrE   r>   r>   r?   call_user_defined_fn  s   z)DynamoTritonHOPifier.call_user_defined_fnc                 C   s*   ddl m} ||t|j| |}|S )Nr*   )VariableBuilder)r  r  r   kernel_source_wrap)rq   Zuser_objr6   r  rO   r  Zwrapped_user_objr>   r>   r?   wrap_user_defined_obj  s   z*DynamoTritonHOPifier.wrap_user_defined_objc                 C   s   | |}dd |D }|S )Nc                 S   r  r>   r  )r   configr>   r>   r?   r     rM  z=DynamoTritonHOPifier.maybe_unpack_configs.<locals>.<listcomp>)Zunpack_var_sequence)rq   Zconfigsr6   r>   r>   r?   maybe_unpack_configs  s   
z)DynamoTritonHOPifier.maybe_unpack_configsrE   c                 C   s   |  s	| d | S )Nz`@triton.heuristics must return constant values because configs can only contain constant values.)Zis_python_constantr  r  )rq   rE   r>   r>   r?   maybe_unpack_heuristic_result  s
   z2DynamoTritonHOPifier.maybe_unpack_heuristic_resultr  TritonKernelVariablerw   c                 C   s>   |j d ust|dkr| d t||j|j|d |jdS )Nr*   z7Triton kernels should be called with only a single gridr   )kernel
kernel_idxr  r  )r  r   r  r   r  r  r=   )rq   r  rw   r>   r>   r?   call_getitem  s   z!DynamoTritonHOPifier.call_getitemc                    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.   )r  c                 S   r  r>   r  r   r>   r>   r?   r     s    z1DynamoTritonHOPifier.call_HOP.<locals>.<dictcomp>r   )kernel_side_tabletriton_kernel_wrapper_mutationc                    s$   i | ]\}}t | r|| qS r>   )r8   r   r   r.   r>   r?   r     s    c                    s    i | ]\}}t | s||qS r>   )r8   r   r.   r>   r?   r   $  s    z.Unexpected argument type for a Triton kernel: ri  r~   r>   )r  constant_args_idxr  tma_descriptor_metadatary   )r5  r/   Zdictsr  rA   r-  r8   TMADescriptorVariableto_metadatadata_ptrZfrom_tensorrB   *torch._higher_order_ops.triton_kernel_wrapr  r  r|  Zrealizer   rH  r  r  reprZadd_constant_argsrD   rI   r  r  r  )rq   r  ZgridsZcombined_args_rawr6   r  r  rF   rG   Zcombined_argsr  r  r  Znon_constant_argsr  r  r>   r.   r?   call_HOP  sT   




zDynamoTritonHOPifier.call_HOPN)r   r   r   r   r   r  r   r&  r  r  rC   r   ZfxproxyZProxyr  r  r  r  r  r  r   r  r/   r  r>   r>   r>   r?   r    s$    	

r  c                       s   e Zd ZU ded< ded< ee ed< d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 )r  r2   r  r3   r  r  r   r  r{   Nc                    s4   | dd | _t jdi | t| ||| d S )Nr  r>   )rL   r  r   r    dynamo_triton_hopifier_singletonZinit_variable)rq   r  r  r  ry   r   r>   r?   r   N  s   zTritonKernelVariable.__init__r6   r1   rw   rx   ry   rz   r-   c                 C   s   t | |||S r7   )r  Zcall_triton_kernelr}   r>   r>   r?   r~   S  s   z"TritonKernelVariable.call_functionc                    s>   |dkr
t | |S |dkrt | |||S t ||||S )N__getitem__run)r  r  Zcall_runr   r   )rq   r6   rO   rw   ry   r   r>   r?   r   ]  s
   z TritonKernelVariable.call_methodr   c                 C   s4   ddl m} ddlm} t||r|| S |S )Nr*   r.   )r  )r5  r/   Ztensorr  r8   r;   Zevaluate_expr)rq   r   r/   r  r>   r>   r?   specialize_symbolicl  s
   
z(TritonKernelVariable.specialize_symbolicr   r   r  )r   r   r   rW   r   r  r   r~   r   r   r  r   r>   r>   r   r?   r  H  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   )	r8   r   DataPtrVariabler   r   r  r  r  r  )rq   r  r  r  r  ry   r   r>   r?   r   w  s   
zTMADescriptorVariable.__init__c                 C   s(   dd | j D dd | jD | j fS )Nc                 S   r  r>   r  r   dimr>   r>   r?   r     rM  z5TMADescriptorVariable.to_metadata.<locals>.<listcomp>c                 S   r  r>   r  r  r>   r>   r?   r     rM  )r  r  r  r  rp   r>   r>   r?   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_descriptorZcreate_Zd_tma_descriptor)rT  r   r  r>   r   rq   r>   r?   rV    s    z3TMADescriptorVariable.reconstruct.<locals>.<lambda>r*   F)	r\  r  r   r  r  r  r  r~   r   )rq   r   rw   r>   r  r?   r     s   
z!TMADescriptorVariable.reconstruct)r  r  r  r  r  r  r  r/   )r   r   r   r   r  r   r   r>   r>   r   r?   r  v  s    r  c                       s@   e Zd Zdeddf fddZ						
			dddZ  ZS )CreateTMADescriptorVariablerankr{   Nc                    s(   |dv sJ t  jdi | || _d S )N)r*   r
   r>   )r   r   r  )rq   r  ry   r   r>   r?   r     s   
z$CreateTMADescriptorVariable.__init__r6   r1   rw   rx   ry   rz   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  Z	block_dimr
      Zdim1Zdim0Z
block_dim1r  Z
block_dim0r  r  )r  r  r  r  )r8   r   r  r   r  r   r  )rq   r6   rw   ry   r  r  r  r  r>   r>   r?   r~     s6   
z)CreateTMADescriptorVariable.call_functionr   )r   r   r   r  r   r~   r   r>   r>   r   r?   r    s    	r  r7   rr  )nrb   r%  r   rd   rV   r  rT   collections.abcr   typingr   r   r   r   r   Ztyping_extensionsr   Zunittest.mockr	   r   r4  r   r   Zbytecode_transformationr   r   r   r  r   r   r   r   r   r   r   r   r   r   r   Zguardsr   r   r=   r   r   r   r    rm  r!   r"   r#   r$   r%   r&   r'   r(   r)   baser+   r,   r-   r5  r/   Z#torch.distributed.fsdp._fully_shardr0   ModuleNotFoundErrorr   r1   r  r2   r3   r4   r@   rH   rD   r   rP   r^   rg   rj   rk   r   r   r   r'  r(  r0  r1  r;  rG  r   r   r^  rs  r{  r}  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r>   r>   r>   r?   <module>   s   4,
" J  
>
7Y
  "
	OO # .$