o
    ,h'[                    @   sl  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
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mZ ddlZdd	lmZ d
dlmZmZmZmZ d
dl m!Z!m"Z"m#Z# d
dl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z. d
dl/m0Z0m1Z1 d
dl2m3Z3m4Z4m5Z5m6Z6 d
dl7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?m@Z@ ddlAmBZBmCZCmDZDmEZE ddlFmGZG zddlHmIZI W n eJy   dZIY nw erddlKmLZL ddlMmNZN ddlOmPZPmQZQ ededZRdZSdZTe ZUG dd dZVdedeVfd d!ZWd"d# ZXdsdtd&d'ZYdtd(d)ZZd*e[e\eEf fd+d,Z]d-d. Z^h d/Z_d0d1 Z`G d2d3 d3eEZaG d4d5 d5eaZbG d6d7 d7eaZcG d8d9 d9eEZdG d:d; d;edZeG d<d= d=eaZfG d>d? d?efZgG d@dA dAebZhG dBdC dCehZiG dDdE dEebZjdtdFdGZkG dHdI dIeaZlG dJdK dKelZmG dLdM dMeEZnG dNdO dOenZoG dPdQ dQeEZpG dRdS dSepZqdTdU ZrdtdVdWZsG dXdY dYebZtG dZd[ d[ebZuG d\d] d]ebZvG d^d_ d_eEZwG d`da daeEZxG dbdc dceEZyG ddde deeEZzddflOm{Z{m|Z|m}Z}m~Z~ G dgdh dhe~Ze ZG didj djeEZG dkdl dleEZG dmdn dneEZG dodp dpeEZG dqdr dreEZdS )ua  
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FunctionType)AnyCallableOptionalTYPE_CHECKINGTypeVar)Never)patch)WeakKeyDictionary)get_stack_above_dynamo   )configgraph_break_hints	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_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   )#AsPythonConstantNotImplementedErrorAttributeMutationNewValueMutationNewVariableTrackerConstantVariable)_fsdp_param_group)	PyCodegenInstructionTranslator)TritonGridTypeTritonKernelType_F)bound      c                   @   s(   e Zd ZdefddZdefddZdS )FunctionSpecfuncc                 C   s   |j }|j}|j| _|j| _|j| _|d | j | _|| j| j | _	| j| j	 | _
|| j| j| j  | _| j| j }|jt@ rE|| nd | _|| jrNdnd7 }|jt@ r]|| | _d S d | _d S )Nr/   r   )__code__co_varnamesco_posonlyargcountposonly_countco_argcount	arg_countco_kwonlyargcountkwonly_countposonly_namespos_or_kw_namesall_pos_nameskwonly_namesco_flags
CO_VARARGSvarargs_nameCO_VARKEYWORDS
varkw_name)selfrA   codevnoff rW   \/var/www/html/scripts/venv/lib/python3.10/site-packages/torch/_dynamo/variables/functions.py__init__i   s   "zFunctionSpec.__init__c                 C   sH   |j pd| _|jp
i | _tt| jt| j d  tt| j| _	d S NrW   )
__defaults__defaults__kwdefaults__
kwdefaultsdictziprL   lenrangepos_default_map)rS   rA   rW   rW   rX   update_defaults{   s
   $
zFunctionSpec.update_defaultsN)__name__
__module____qualname__r   rY   rd   rW   rW   rW   rX   r@   h   s    r@   rA   returnc                 C   s&   t | }|d u rt| }|t | < |S N)_spec_cachegetr@   )rA   specrW   rW   rX   	_get_spec   s
   
rm   c                 C   s  t | }||  i }t|}t|jD ]T\}}	|t|k r(t||| ||	< q|	|v rC|	|jv r8t|	 dt||	|	||	< q|	|j
v rb|j
|	 }
d }|rVt||
}t||j|
 |||	< qtd|	 |t|jd  }|jrt|t|||j< n|rtdt| dt|j |jD ]3}	|	|v rt||	|	||	< q|	|jv rd }|rt||	dd}t||j|	 |||	< qtd|	 |jrt||||j< |S |rtdt| |S )	Nz is positional-onlyz&Missing required positional argument: z#Too many positional arguments: got z, expected T)is_kwz(Missing required keyword-only argument: zUnexpected keyword arguments: )rm   rd   r_   	enumeraterL   ra   wrap_bound_argrJ   	TypeErrorpoprc   r$   r\   rP   tuplerM   r^   rR   list)rA   tx	fn_sourceargskwargsrl   barem_kwinameidxdefault_sourceextrakwdefault_sourcerW   rW   rX   bind_args_cached   sP   






r   ru   r9   c                 C   s,   t |tr|S |st| |S tj||S ri   )
isinstancer3   buildr   LazyVariableTrackercreate)ru   valsourcerW   rW   rX   rp      s
   
rp   c                 C   s6   t | D ]\}}t|ttfrt| |||< qd S ri   )rt   itemsr   rs   r_   rp   )ru   resultkvrW   rW   rX   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_cellrr   )parentr   rT   r   r|   new_cellrW   rW   rX   init_cellvars   s   

r   c           
      C   sd   ddl m} || ||||}||_t|tr"ddlm}	 t|	|}|d u s-t|ts-J ||_|S )Nr   r   pairwise)	typesr   r]   r   rs   	itertoolsr   r_   __annotations__)
rT   	f_globalsr|   r\   closurer^   annotationsr   rA   r   rW   rW   rX   _create_nested_fn   s   
r   >   __doc__rB   __closure____globals__r[   r]   r   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 ri   )r"   inspectgetattr_staticAttributeErrorr   fn_known_dunder_attrsgetattrr   r   r   r3   r   )ru   fnr   r|   subobjrW   rW   rX   fn_var_getattr  s   
r   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 ri   get_codeco_filenamerS   rW   rW   rX   get_filename     
z%BaseUserFunctionVariable.get_filenamec                 C   r   ri   r   co_namer   rW   rW   rX   get_name  r   z!BaseUserFunctionVariable.get_nameru   r9   rw   list[VariableTracker]rx   dict[str, VariableTracker]rh   r3   c                 C   s   | | g |  ||S ri   )inline_user_function_return	self_argsrS   ru   rw   rx   rW   rW   rX   call_function  s   z&BaseUserFunctionVariable.call_functionr|   c                 C   sL   d}z	t |  |}W n ty   |dkrt| trd}Y nw tj|S )NFre   T)hasattrget_functionNotImplementedErrorr   NestedUserFunctionVariabler   r5   r   rS   ru   r|   r   rW   rW   rX   call_obj_hasattr'  s   z)BaseUserFunctionVariable.call_obj_hasattrc                 C   s   t t|  jS ri   )rt   r   	signaturer   
parametersr   rW   rW   rX   inspect_parameter_names3     z0BaseUserFunctionVariable.inspect_parameter_namesc                 C      i S ri   rW   rS   ru   rW   rW   rX   closure_vars6     z%BaseUserFunctionVariable.closure_varsNru   r9   rw   r   rx   r   rh   r3   )re   rf   rg   r   r   r   strr3   r   r   r   rW   rW   rW   rX   r     s*    

r   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 functionr   is_constantc                 C      t |tj | ||dS Nr   )r!   
make_guardr    CLOSURE_MATCHclsvaluer   rW   rW   rX   create_with_sourceC  s   z'UserFunctionVariable.create_with_sourceFrh   Nc                    sr   t  jd	i | t|ddrd| _nd| _t|tjtjj	fs-t
d| ddgtjd t|d|}|| _d S )
N_dynamo_marked_constantFTz1can't handle functions not implemented in python z2Dynamo can only handle functions defined in pythonz9Move usage of this function out of `torch.compile` regiongb_typecontextexplanationhints_torchdynamo_inlinerW   )superrY   r   r   r   r   r   torchjitScriptFunctionr   r   INFERENCE_MODEr   r   r   rS   r   r   rx   	__class__rW   rX   rY   H  s    
zUserFunctionVariable.__init__c                    s   t | tr| jS t  S ri   )r-   r   r   r   as_python_constantr   r   rW   rX   r   b  s   

z'UserFunctionVariable.as_python_constantc                 C      g S ri   rW   r   rW   rW   rX   r   h  r   zUserFunctionVariable.self_argsc                 C      | j S ri   r   r   rW   rW   rX   r   k     z!UserFunctionVariable.get_functionc                 C      | j jS ri   )r   rB   r   rW   rW   rX   r   n     zUserFunctionVariable.get_codec                 C      t jS ri   r   r   r   rW   rW   rX   python_typeq  r   z UserFunctionVariable.python_typec                 C   s   t | jdd d uS N__self__)r   r   r   rW   rW   rX   has_selft     zUserFunctionVariable.has_selfc                 C   r   ri   )r   r   r   rW   rW   rX   get_globalsw  r   z UserFunctionVariable.get_globalsc              	   C   sV  | j rJ | j}t|tstd|jj}t||| j||}t	|||j
 | jjp*d}t|t| jj
jks8J tt | jj
j|D ]e\}}	}
|jj}|
|v rU||
 }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|
|}|||	< qC|S )z
        Assume `args` and `kwargs` are VariableTracker arguments for a call to
        this function, create new bindings for initial locals.
        z'Only supports regular Python functions.rW   r   cell_contentsN)r   r   r   r   rq   r   root_txr   r   r   rB   r   ra   co_freevarsr`   r   countr   r%   r"   r3   r   r   
ValueErrorr   DeletedVariabletrack_cell_existing)rS   r   rw   rx   r   r   r   r   r}   r|   cellr   cell_varclosure_cellclosure_cell_contentscontents_varrW   rW   rX   	bind_argsz  sL   




zUserFunctionVariable.bind_argsru   r9   r|   c                 C   &   |t v r
t| |S t|| j| j|S ri   )r(   r   GetAttrVariabler   r   r   rS   ru   r|   rW   rW   rX   var_getattr  s   z UserFunctionVariable.var_getattrc                 C   s   t | j|}tj|S ri   )r   r   r   r5   r   r   rW   rW   rX   r     s   z%UserFunctionVariable.call_obj_hasattrrw   r   rx   r   r3   c              
      sl  | j tjju r?z dd |D }dd | D }tjj|i |j}t|W S  ty> } zt	d| d| |d }~ww | j tjj
u rt| j j|i |}|jd }	t|	ts}|	 }
d|
j d	}td
d| j d| d| d|g tjd t|	ts|	 }d| d}td|  |d| ddgd |	j }tj|ddS | jrt|| j |  ||S |jjjs| j tjjj u rtjj!"| t# $|||W  d    S 1 sw   Y  |jjj%r.|jjj&s.zddl'm(} W n t)y   d }Y nw |d ur.| j |j*|j+fv r.tjj!&| t# $|||W  d    S 1 s)w   Y  t# $|||S )Nc                 S      g | ]}|  qS rW   r   .0argrW   rW   rX   
<listcomp>      z6UserFunctionVariable.call_function.<locals>.<listcomp>c                 S      i | ]	\}}||  qS rW   r  )r  keyr   rW   rW   rX   
<dictcomp>  s    z6UserFunctionVariable.call_function.<locals>.<dictcomp>zCannot convert patch_dynamo_config args/kwargs to constants. Please fix your call to patch_dynamo_config by using simpler inputs. args: z
, kwargs: r   z=`nonstrict_trace` expects a callable, but got value of type <>zTypeError from user codezcall_function(, )r   z(Applying `nonstrict_trace` to function <zk>; however, `nonstrict_trace` currently requires the function to be defined outside `torch.compile` region.zLimitation of `nonstrict_tracezmake sure definition of z is outside z`torch.compile` regionTnonstrict_traceable)	FSDPState),r   r   _dynamopatch_dynamo_configr   changesr   DynamoConfigPatchVariabler0   RuntimeErrornonstrict_tracer   r   bindrw   r   r   r   re   r   r   r   
USER_ERRORr   r   TorchInGraphFunctionVariabler   invoke_and_store_as_constantr   current_tracer,unsafe_allow_externally_visible_side_effectsutils8_disable_side_effect_safety_checks_for_current_subtracerr   2allow_externally_visible_side_effects_in_subtracerr   r   under_activation_checkpoint#allow_side_effects_under_checkpoint/torch.distributed.fsdp._fully_shard._fsdp_stater  	Exception_pre_forward_post_forward)rS   ru   rw   rx   
args_constkwargs_constr  er=   fn_vartypmsgfn_namer   r  r   rW   rX   r     s   


	

 "z"UserFunctionVariable.call_functionFrh   Nr   )re   rf   rg   r   r   _nonvar_fieldsclassmethodr   rY   r   r   r   r   r   r   r   r_   r   r3   r   r  r   r   __classcell__rW   rW   r   rX   r   :  sF    
7
r   c                       sF   e Zd Zdd fddZedd Z				
					dddZ  ZS )BuiltinMethodVariableFrh   Nc                    s,   t  jdi | t|tjsJ || _d S rZ   )r   rY   r   r   BuiltinMethodTyper   r   r   rW   rX   rY     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   re   rs   type	frozenset)objmethod_selfmethod_namerW   rW   rX   is_supported_builtin_method  s
   z1BuiltinMethodVariable.is_supported_builtin_methodru   r9   rw   r   rx   r   r3   c                 C   s@   | j j}| j j}| jot| jd}t|||}|||||S r   )r   r   re   r   r"   r3   r   call_method)rS   ru   rw   rx   r<  r|   
obj_sourceobj_vtrW   rW   rX   r   %  s
   z#BuiltinMethodVariable.call_functionr0  r1  r   )re   rf   rg   rY   staticmethodr>  r   r4  rW   rW   r   rX   r5    s    

r5  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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*d+Zd,d- Zd.d/ Zd0d1 Zd2dd3ed4d5d6d7d$d8f
 fd9d:Z   Z!S )=LocalGeneratorObjectVariablerT   inline_tracerr9   c                    s(   t  jdi | || _|| _|| _d S rZ   )r   rY   rT   r   rD  )rS   rT   r   rD  rx   r   rW   rX   rY   3  s   
z%LocalGeneratorObjectVariable.__init__c                 C   r   ri   )rT   r   rW   rW   rX   r   ?  r   z%LocalGeneratorObjectVariable.get_codec                 C   r   ri   r   r   rW   rW   rX   r   B  r   z)LocalGeneratorObjectVariable.get_filenamec                 C   r   ri   r   r   rW   rW   rX   r   E  r   z%LocalGeneratorObjectVariable.get_namec                 C   s   t ri   )r   r   rW   rW   rX   r   H  r   z)LocalGeneratorObjectVariable.get_functionc                 C      dS NFrW   r   rW   rW   rX   r   K  r   z%LocalGeneratorObjectVariable.has_selfc                 C      |   S ri   )r   r   rW   rW   rX   re   N  r   z%LocalGeneratorObjectVariable.__name__c                 C   s   | j j d|   dS )N(r  )r   re   r   r   rW   rW   rX   __str__Q  s   z$LocalGeneratorObjectVariable.__str__codegenr7   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)r9    save_and_restart_speculation_log(temporarely_allow_writes_to_output_graph)torch._dynamo.side_effectsrK  torch._dynamo.symbolic_convertr9   rL  rM  
current_tx_get_inline_tracergenerator_exhaustedforce_unpack_var_sequenceremaining_itemsr   ListIteratorVariablereconstruct)rS   rJ  rK  r9   rL  rM  ru   savedisallowtemptracerrW   rW   rX   rV  V  s   
P z(LocalGeneratorObjectVariable.reconstructc                 C   s   | j |||S ri   )r   r   r   rW   rW   rX   r   i     z&LocalGeneratorObjectVariable.bind_argsc                 C   r   ri   r   r   rW   rW   rX   r   l  r   z(LocalGeneratorObjectVariable.get_globalsc                 C   r   ri   )r   GeneratorTyper   rW   rW   rX   r   o  r   z(LocalGeneratorObjectVariable.python_typec                 C   s.   ddl m} | jd u r||| g i | _| jS Nr   )InliningInstructionTranslator)rO  r_  rD  build_inline_tracer)rS   ru   r_  rW   rW   rX   rQ  r  s   
z/LocalGeneratorObjectVariable._get_inline_tracerc                 C   s  |  |}|  rtt| ziz,ttdtd i | W  d    W W td  td O  < S 1 s5w   Y  W n/ tyL } zd|_	|d }~w t
yS     tyj } ztjj|   t|d }~ww W td  td O  < d S td  td O  < w )Nunimplementedinline_callT)rQ  _is_generator_exhaustedr   StopIterationr   r_   r)   inline_call_r   rR  r   r   r   r  
eval_frame	skip_coder   r   )rS   ru   rZ  r+  rW   rW   rX   next_variable{  s,   

.z*LocalGeneratorObjectVariable.next_variablec                 C   rE  rF  rW   r   rW   rW   rX   has_unpack_var_sequence  r   z4LocalGeneratorObjectVariable.has_unpack_var_sequencerh   c                 C   rE  NTrW   r   rW   rW   rX   has_force_unpack_var_sequence  r   z:LocalGeneratorObjectVariable.has_force_unpack_var_sequencec                 C   s   g }|  ||j |S ri   )force_apply_to_var_sequenceappend)rS   ru   r   rW   rW   rX   rS    s   z6LocalGeneratorObjectVariable.force_unpack_var_sequenceNc                 C   s4   	 z	||  | W n ty   t| Y d S w qri   )rh  r   r   )rS   ru   r   rW   rW   rX   rl    s   z8LocalGeneratorObjectVariable.force_apply_to_var_sequencec              
   C   sL   |  |}z|| W d S  ty% } z|| W Y d }~d S d }~ww ri   )rQ  _raise_exception_variabler   exception_handler)rS   ru   excrZ  r+  rW   rW   rX   _setup_exception  s   
z-LocalGeneratorObjectVariable._setup_exceptionc                 C   s   | j d u p
| j jdkS )Nr   )rD  instruction_pointerr   rW   rW   rX   _is_generator_just_started  s   z7LocalGeneratorObjectVariable._is_generator_just_startedc                 C      t | jddS )NrR  F)r   rD  r   rW   rW   rX   rc    s   z4LocalGeneratorObjectVariable._is_generator_exhaustedru   r|   rw   r   rx   r   r3   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 ri   )r   r5   r   r  rW   rW   rX   	<genexpr>  s
    
z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>closeTrW   )      CALL_INTRINSIC_1throwrz  r/   r   __InternalThrowException)rh  rs  ra   allr   rq   rQ  	push_manyrc  rR  r   r5   rq  ExceptionVariableGeneratorExitsysversion_infonext_instructionopnamer   r  r   symbolic_resultr   r9  r&  r   r   r?  )rS   ru   r|   rw   rx   rZ  retvalexc_typer   rW   rX   r?    sz   












(
>
z(LocalGeneratorObjectVariable.call_methodrJ  r7   r1  )"re   rf   rg   r   CodeTyper   rY   r   r   r   r   r   rI  __repr__rV  r   r   r   rQ  rh  ri  builtinsboolrk  rt   r3   rS  rl  rq  rs  rc  r   r?  r4  rW   rW   r   rX   rC  2  sL    
	
	rC  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)re   rf   rg   r   rW   rW   rW   rX   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 rZ   )r   rY   r  r  )rS   r  r  rx   r   rW   rX   rY     s   
z'LocalGeneratorFunctionVariable.__init__c                 C   s&   || j j v rt| |S t| j|S ri   )r   __dict__keysr   r  )rS   r|   rW   rW   rX   __getattr__  s   
z*LocalGeneratorFunctionVariable.__getattr__c                 C   s   ddl m} ||| ||S r^  )rO  r_  r`  )rS   ru   rw   rx   r_  rW   rW   rX   _build_inline_tracer  s   z3LocalGeneratorFunctionVariable._build_inline_tracerru   r9   rw   r   rx   r   rh   r3   c                 C   sH   t | j s	J | |||}| j }| j }| j|||| jdS r   )r   r  r   r  r   r  r   )rS   ru   rw   rx   rD  rT   r   rW   rW   rX   r     s   

z,LocalGeneratorFunctionVariable.call_functionr   )re   rf   rg   r   rC  r3   rY   r  r  r   r4  rW   rW   r   rX   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   rY   r  )rS   r  rx   r   rW   rX   rY     s   
z<FunctionDecoratedByContextlibContextManagerVariable.__init__c                    s.   t  |||}t|tjjjsJ d|_|S rj  )r   r  r   r   r  symbolic_convert&InliningGeneratorInstructionTranslatoris_generator_from_ctx_manager)rS   ru   rw   rx   rZ  r   rW   rX   r    s   zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracer)re   rf   rg   r   rY   r  r4  rW   rW   r   rX   r    s    r  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 methodrh   Nc                    s    t  jdd|i| || _d S )Nr   rW   r   rY   r;  )rS   r   r;  rx   r   rW   rX   rY        
zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )NrH  r  r  )r   re   r   r;  r   rW   rW   rX   r    s   zUserMethodVariable.__repr__c                 C      | j gS ri   r;  r   rW   rW   rX   r     r   zUserMethodVariable.self_argsc                 C   r   ri   )r   
MethodTyper   rW   rW   rX   r     r   zUserMethodVariable.python_typeru   r9   rw   r   rx   r   r3   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  rf    z	torch.nn.ztorch.nn.utils.parametrize)constant)trace_rulesr  r   r   r   r  r   r   is_root_tracerr   r;  NNModuleVariabler   
startswithr   r?  re   r6   FSDPParamGroupuse_training_stateTorchCtxManagerClassVariabler   r  r   r   )	rS   ru   rw   rx   r  	call_argsvarmodule_attrr   r   rW   rX   r     s<   
z UserMethodVariable.call_functionc                    s   t   dd  S Nr/   )r   r   r   r   rW   rX   r   !  r   z*UserMethodVariable.inspect_parameter_namesr|   c                    sF   | j ot| j |}|dkr| jS |dkrt|| j|S t ||S )Nr   __func__)r   r"   r;  r3   r   r   r   r  )rS   ru   r|   r   r   rW   rX   r  $  s   zUserMethodVariable.var_getattrr1  r   )re   rf   rg   r   rY   r   r  r   r   r   r   r  r4  rW   rW   r   rX   r    s"    =r  c                       D   e Zd Zd fddZ							
		d fddZdd Z  ZS )WrappedUserMethodVariablerh   Nc                    sB   | dd  | dd  t j|j|jfi | || _|| _d S )Nr   r;  )rr   r   rY   r   r;  wrappedr   rS   r  r   rx   r   rW   rX   rY   .  s
   
z"WrappedUserMethodVariable.__init__ru   r9   rw   r   rx   r   r3   c                    ,   | j | t |||}| j | |S ri   r   enterr   r   exitrS   ru   rw   rx   r   r   rW   rX   r   5     z'WrappedUserMethodVariable.call_functionc                    2      fdd  j  tdd d S )Nc                      
    j S ri   r   rW   rJ  rS   rW   rX   <lambda>A     
 z7WrappedUserMethodVariable.reconstruct.<locals>.<lambda>r/   Fadd_push_nullr  extend_outputr   rS   rJ  rW   r  rX   rV  @     
z%WrappedUserMethodVariable.reconstructr1  r   re   rf   rg   rY   r   rV  r4  rW   rW   r   rX   r  -      r  c                       r  )WrappedUserFunctionVariablerh   Nc                    s2   | dd  t j|jfi | || _|| _d S )Nr   )rr   r   rY   r   r  r   r  r   rW   rX   rY   G  s   
z$WrappedUserFunctionVariable.__init__ru   r9   rw   r   rx   r   r3   c                    r  ri   r  r  r   rW   rX   r   M  r  z)WrappedUserFunctionVariable.call_functionc                    r  )Nc                      r  ri   r  rW   r  rW   rX   r  Y  r  z9WrappedUserFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr  r  rW   r  rX   rV  X  r  z'WrappedUserFunctionVariable.reconstructr1  r   r  rW   rW   r   rX   r  F  s    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 ri   )r   r   TensorVariableget_real_valuer   )xrW   rW   rX   convert_  s   z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS rW   rW   r  r  r  rW   rX   r	  d  r
  z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]	\}}| |qS rW   rW   r  r   r   r  rW   rX   r  e      z0invoke_and_store_as_constant.<locals>.<dictcomp>r   )r   r   register_attr_or_moduler#   )ru   r   r|   rw   rx   resrW   r  rX   r  ^  s   r  c                       s   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de
de
fddZ fddZdd Z fddZdd Zdd Zdd Zd&d"d#Z  ZS )'r   r   Nrh   c	           
         s   |	 dd u r|	jt d t jdi |	 t| ts J t| tj	s*J t|t
s1J || _|| _|| _|| _|| _|| _|| _|| _d S )Nmutation_typer  rW   )rk   updater1   r   rY   r   r   r   r   r  r_   r/  rT   r   r\   r^   r   r   
wrapped_fn)
rS   r/  rT   r   r\   r^   r   r   r  rx   r   rW   rX   rY   t  s   
z#NestedUserFunctionVariable.__init__c                 C   r   ri   rW   r   rW   rW   rX   r     r   z$NestedUserFunctionVariable.self_argsc                 C   s
   | j  S ri   )rT   r   r   rW   rW   rX   r     r   z#NestedUserFunctionVariable.get_codec                 C   r   ri   r   r   rW   rW   rX   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   r   )r   r   r   r   rT   r   r   r/  r\   r[   r^   r]   r   r   rs   r   r   r_   r   )rS   rA   r   r   rW   rW   rX   r     s&   

z'NestedUserFunctionVariable.get_functionru   r9   name_varr   c                 C   s   |j j| |j| td S ri   )r   r   
store_attrr   r5   )rS   ru   r  r   rW   rW   rX   call_setattr  s   z'NestedUserFunctionVariable.call_setattrc                    s,   |dkr| j |g|R  S t ||||S )N__setattr__)r  r   r?  rS   ru   r|   rw   rx   r   rW   rX   r?    s   z&NestedUserFunctionVariable.call_methodc                 C   s
   | j d uS ri   )r   r   rW   rW   rX   has_closure  r   z&NestedUserFunctionVariable.has_closurec                    s    |dkr	| j  S t ||S )Nre   )r/  r   r   const_getattrr  r   rW   rX   r    s   
z(NestedUserFunctionVariable.const_getattrc                 C   rE  rF  rW   r   rW   rW   rX   r     r   z#NestedUserFunctionVariable.has_selfc                 C   r   ri   r\  r   rW   rW   rX   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 ri   )r.   )r  _rW   rW   rX   rx        z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>)r   r   r   r   r/  r   r\   rs   r   rb   ra   r   r^   keys_as_python_constantr]   r   r   r  apply_defaultsr_   	argumentsr   r   r   r   ro   r   )rS   r   rw   rx   rT   rA   r=   r   r}   r|   r   rW   rW   rX   r     s(   
z$NestedUserFunctionVariable.bind_argsrJ  r7   c                    s     fdd  | j   | jg  t| jjj | j	r+ | j	 n	  
d g | jr= | j n	  
d g | jrO | j n	  
d g | jrzz| j }  |g W n tyy    | j Y n
w   
d g  tdd | jr   fdd  | j  tdd  td  tdd d	d
lm} | }|jj| r|jjj|   D ]\}}    |  td  | qd S d S )Nc                      s     tdS )Nr   )load_import_fromre   rW   rJ  rW   rX   r        z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>   Fc                           ddS )N	functoolswrapsr  rW   r  rW   rX   r    r  r/   r   Tr   r8   )r  rT   r  create_load_const_uncheckedr   r5   r   r   r   r\   create_load_constr   r^   r   r   r   r   r  r   rO  r9   rP  r   r   has_pending_mutationstore_attr_mutationsr   dup_topr  )rS   rJ  r   r9   ru   r|   r   rW   r  rX   rV    s`   






z&NestedUserFunctionVariable.reconstructri   r1  r  )re   rf   rg   r   r2  rY   r   r   r   r   r3   r  r?  r  r  r   r   r   rV  r4  rW   rW   r   rX   r   n  s6    
	r   c                       r  )!WrappedNestedUserFunctionVariablerh   Nc              
      s   | dd  | dd  | dd  | dd  | dd  | dd  | dd  | dd  t |j|j|j|j|j|j|j	|j
 || _|| _d S )	Nr/  rT   r   r\   r^   r   r   r  )rr   r   rY   r/  rT   r   r\   r^   r   r   r  r  r   r  r   rW   rX   rY   "  s(   

z*WrappedNestedUserFunctionVariable.__init__ru   r9   rw   r   rx   r   r3   c                    r  ri   r  r  r   rW   rX   r   8  r  z/WrappedNestedUserFunctionVariable.call_functionc                    r  )Nc                      r  ri   r  rW   r  rW   rX   r  D  r  z?WrappedNestedUserFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr  r  rW   r  rX   rV  C  r  z-WrappedNestedUserFunctionVariable.reconstructr1  r   r  rW   rW   r   rX   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   reasonNrh   c                    r  rZ   )r   rY   r   r  )rS   r   r  rx   r   rW   rX   rY   P     
zSkipFunctionVariable.__init__c                 C   r   ri   r   r   rW   rW   rX   r   U  r   z'SkipFunctionVariable.as_python_constantc                 C   s$   t |st|tj | ||dS r   )r,   r!   r   r    FUNCTION_MATCHr   rW   rW   rX   r   X  s   z'SkipFunctionVariable.create_with_sourceru   r9   rw   r   rx   r   r3   c              	   C   s  t | jddr&t | jdd }tdt| jd| j d| ddgd	 d S | jtjju rN|d
d }|r9|	 }tdd| d| dd| dgd	 d S | jtjj
u rh|d
d }|ra|	 }td| tjrddlm} ||| j}t|ts||||S t| jdd}	t| jdd }
|
d u rdnt|
}z&t | j}d|	 d| d}d|	 dg}d|vr|d|	 dd g7 }W na ty#   d!d"h}|
|v rd#| d$|	 d}d%d&g}nA|
d ur|
d'rd(| d$|	 d$}d)g}tjj|d* d*|  nd+| d$|	 d,}d-d.g}tjj|d* d*|  Y nw |	d/kr-d0}g }| jr4| jnd1}td2d3| d4|	 d5| ||d	 d S )6N_torchdynamo_disableF_torchdynamo_disable_msgz1Skip calling `torch.compiler.disable()`d functionzSkip calling function `z>` since it was wrapped with `torch.compiler.disable` (reason: r  z(Remove the `torch.compiler.disable` callr   r.  z%Call to `torch._dynamo.graph_break()`z0Called `torch._dynamo.graph_break()` with args `z`, kwargs ``z$User-inserted graph break. Message: z.Remove the `torch._dynamo.graph_break()` call.z9Skip frame due to `torch._dynamo.skip_frame()`. Message: r/   SourcelessBuilderrg   z<unknown qualname>rf   z<unknown module>z?Dynamo developers have intentionally marked that the function `z` in file `z` should not be traced.zAvoid calling the function `z`.r  z:Apply `@torch._dynamo.dont_skip_tracing` to the function `zw` to force tracing into the function. More graph breaks may occur as a result of attempting to trace into the function.z Please file an issue to PyTorch._abc	_warningsz6Dynamo does not know how to trace the Python builtin `.zIf you are attempting to call a logging function (e.g. `_warnings.warn`), you can try adding it to `torch._dynamo.config.reorderable_logging_functions`.zKPlease file an issue on GitHub so the PyTorch team can add support for it. 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`.allow_in_graphzFound an allow_in_graph decorator to a function which is created inside the parent function that is getting compiled. This is not supported for now.z<missing reason>z,Attempted to call function marked as skippedzmodule: z, qualname: z, skip reason: )r   r   r   r   r   r   r  graph_breakrk   r   
skip_framer   r   dont_skip_tracingbuilderr  r   r   r  r   r   getfilerq   r  r   	warn_oncejoinr  )rS   ru   rw   rx   r.  graph_break_msgskip_frame_msgr  
rebuilt_fnqualname	module_ormodule_namepathr   r   known_python_builtin_modulesr  rW   rW   rX   r   a  s   

	





&
z"SkipFunctionVariable.call_functionc                 C   s   t jt| j|S ri   )r   r5   r   r   r   r  rW   rW   rX   r     r   z%SkipFunctionVariable.call_obj_hasattrr|   c                 C   r   ri   )r(   r   r  r   r   r   r  rW   rW   rX   r    s   z SkipFunctionVariable.var_getattrri   r1  r   ru   r9   )re   rf   rg   r3   r2  rY   r   r3  r   r   r   r   r  r4  rW   rW   r   rX   r  I  s*    


xr  c                       r  )WrappedSkipFunctionVariablerh   Nc                    sD   | dd  | dd  t j|jfd|ji| || _|| _d S )Nr   r  )rr   r   rY   r   r  r  r   r  r   rW   rX   rY     s
   
z$WrappedSkipFunctionVariable.__init__ru   r9   rw   r   rx   r   r3   c                    r  ri   r  r  r   rW   rX   r     r  z)WrappedSkipFunctionVariable.call_functionc                    r  )Nc                      r  ri   r  rW   r  rW   rX   r    r  z9WrappedSkipFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr  r  rW   r  rX   rV    r  z'WrappedSkipFunctionVariable.reconstructr1  r   r  rW   rW   r   rX   r    r  r  c                       sR   e Zd ZdZd fddZd fdd	Z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".
    rh   Nc                    r  rZ   )r   rY   wrapper_objattr_to_trace)rS   r  r  rx   r   rW   rX   rY     r  z$WrapperUserFunctionVariable.__init__ru   r9   c                    sF   || j krt| j| j }| jot| j|}t|||S t ||S ri   )	r  r   r  r   r"   r3   r   r   r  )rS   ru   r|   r   r   r   rW   rX   r  	  s
   
z'WrapperUserFunctionVariable.var_getattrc                 C   r   ri   rW   r   rW   rW   rX   r     r   z%WrapperUserFunctionVariable.self_argsrw   r   rx   r   r3   c                 C   s  t | jdrmt| j| jd }t|ddpd}|jdddd dkrmd	}tjj| tjjj	
d
}|t	jrmtjj }t | }|d j|d jf}	dt|}
d|	d  d|	d  d}|t|
7 }|| |  | }ttj|| t| jg||S )N
cache_inforf   r  r  r/   )maxsplitr   r   a  Dynamo detected a call to a `functools.lru_cache`-wrapped function. Dynamo ignores the cache wrapper and directly traces the wrapped function. Silent incorrectness is only a *potential* risk, not something we have observed. Enable TORCH_LOGS="+dynamo" for a DEBUG stack trace.ztorch._dynamoz)call to a lru_cache wrapped function at: :r  )r   r  r   r  splitr   r  r   r  logging	getLoggerisEnabledForDEBUG_guardsTracingContextextract_stackr   filenamelinenor  	tracebackformat_listr   debugr   r   r   r   getattr_and_tracer   r5   )rS   ru   rw   rx   	target_fnr  r.  dynamo_logger
user_stack	frame_locuser_stack_formatteduser_stack_traceall_argsrW   rW   rX   r     s4   

z)WrapperUserFunctionVariable.call_functionr1  r  r   )	re   rf   rg   r   rY   r  r   r   r4  rW   rW   r   rX   r    s    r  c                       s*   e Zd ZdZd fddZdd Z  ZS )	WrapperUserMethodVariablez
    Similar to WrapperUserFunctionVariable, but for methods. The only delta is
    saving the vt for `self` object of the method which is then used by
    WrapperUserFunctionVariable in `call_function` method.
    rh   Nc                    s    t  j||fi | || _d S ri   r  )rS   r  r  self_objrx   r   rW   rX   rY   D  r  z"WrapperUserMethodVariable.__init__c                 C   r  ri   r  r   rW   rW   rX   r   H  r   z#WrapperUserMethodVariable.self_argsr1  )re   rf   rg   r   rY   r   r4  rW   rW   r   rX   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_collectivesr1  r0  rW   rW   rX   _traceable_collective_remapsL  s   
r5  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   r2  r3  r5  valuesre   import_sourcer"   )ru   r   
inner_namepath_sourcerW   rW   rX   _traceable_collectives_sourceW  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.
    rh   Nc                   s,   t  j|fi | t|tsJ || _d S ri   )r   rY   r   r   replacement_var)rS   r   r<  rx   r   rW   rX   rY   k  s   
z*CollectiveFunctionRewriteVariable.__init__ru   r9   c                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr   )r<  r   )r;  rewriter   )ru   old_fnr   optionsnew_fn
new_sourcerW   rW   rX   r   p  s   z(CollectiveFunctionRewriteVariable.createc                 C   s   t | o	| t v S ri   )r   
isfunctionr5  )variablerW   rW   rX   can_rewritez  s   z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS ri   )r5  r:  )ru   r   r@  rW   rW   rX   r=    s   
z)CollectiveFunctionRewriteVariable.rewriterw   r   rx   r   r3   c           	      C   s   dd l m} ddlm} t| j}t|j|i |j	}d}d|v rA|d 
 rAtd| j d|d|d| j g tjd	 | j|j|j|jfv rs|d
}|d urX|jn|jd
 j}||vritd| tj|| |d
< | j|||S )Nr   )REDUCE_OP_TO_STRrW   async_opz)async_op=True for distributed collectivesz, args=	, kwargs=z3`torch.compile` doesn't support `async_op=True for r   opzUnsupported all_reduce op: )torch.distributedr2  r4  rE  r   r   r   r_   r  r  r   r   r   SUPPORTABLE
all_reducereduce_scatter_tensor_reduce_scatter_baserk   r   r   defaultr   r   r5   r   r<  r   )	rS   ru   rw   rx   distrE  r   reduce_op_var	reduce_oprW   rW   rX   r     s<   	
	

z/CollectiveFunctionRewriteVariable.call_functionr1  r  r   )re   rf   rg   r   rY   rB  r   rD  r=  r   r4  rW   rW   r   rX   r;  `  s$    
	
r;  c                       s.   e Zd Z								d fd	d
Z  ZS )FunctoolsWrapsVariableru   r9   rw   r   rx   r   rh   r3   c                    s6   |st  dkr fdd}t|S t | |S )Nr/   c                    s8   t | tjr| j d dS td|  dg tjd d S )Nr   )r  zfunctools.wrapsz]`torch.compile` can't trace `functools.wraps` on functions defined outside the compile regionr   )r   r   r   cloner   r   rJ  r   rw   rW   rX   r    s   
z3FunctoolsWrapsVariable.call_function.<locals>.wraps)ra   r   LambdaVariabler   r   )rS   ru   rw   rx   r  r   rT  rX   r     s   
z$FunctoolsWrapsVariable.call_functionr   )re   rf   rg   r   r4  rW   rW   r   rX   rR    s    rR  c                   @   s.   e Zd Zdd Z									
dddZdS )CollectionsNamedTupleFunctionc                 C   r   ri   r   r   rW   rW   rX   r     r   z0CollectionsNamedTupleFunction.as_python_constantru   r9   rw   r   rx   r   rh   r3   c                 C   sl   t ||}|r#| jdd |D i dd | D }tj|t dS tdd|d|d	g tjd
 d S )Nc                 S   r  rW   r  r  rW   rW   rX   r	    r
  z?CollectionsNamedTupleFunction.call_function.<locals>.<listcomp>c                 S   r  rW   r  r  rW   rW   rX   r    r  z?CollectionsNamedTupleFunction.call_function.<locals>.<dictcomp>r  znamedtuple constructionzargs=rG  z?`torch.compile` only support certain input types for namedtupler   )	r&   r   r   r   UserDefinedClassVariabler2   r   r   rJ  )rS   ru   rw   rx   constant_argsr   rW   rW   rX   r     s$   

z+CollectionsNamedTupleFunction.call_functionNr   )re   rf   rg   r   r   rW   rW   rW   rX   rV    s    rV  c                       s   e Zd Zdeddf fddZdd Zd 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 )"FunctoolsPartialVariablerA   rh   Nc                    sP   t  jdi | || _t|tsJ || _t|tsJ || _t	t
| _d S rZ   )r   rY   rA   r   rt   rw   r_   keywordsr  partialr*   
fake_value)rS   rA   rw   rZ  rx   r   rW   rX   rY     s   z!FunctoolsPartialVariable.__init__c                 C   r   ri   )r  r[  r   rW   rW   rX   r     r   z$FunctoolsPartialVariable.python_typerJ  r7   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  rW   r  rW   rX   r    r  z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>r/   F)r  rA   rw   foreachrZ  r  r   ra   r6  rs   r  create_call_function_kw)rS   rJ  r  rW   r  rX   rV    s   
z$FunctoolsPartialVariable.reconstructc                 C   rG  ri   r  r   rW   rW   rX   r   	  r   z%FunctoolsPartialVariable.get_functionru   r9   rw   r   rx   r   r3   c                 C   s(   | j | }i | j|}| j|||S ri   )rw   rZ  rA   r   )rS   ru   rw   rx   merged_argsmerged_kwargsrW   rW   rX   r     s   
z&FunctoolsPartialVariable.call_functionr|   c                 C   s   t jttt|S ri   )r   r5   r   r   r  r[  r*   r  rW   rW   rX   r     s   z)FunctoolsPartialVariable.call_obj_hasattrc                 C   s   | j ot| j |}|dkr| jS |dkrtj| j|dS |dkr1dd | j D }tj||dS |t	v r;t
| |S tt| d S )NrA   rw   r   rZ  c                 S   s   i | ]
\}}t ||qS rW   )r5   r   r  rW   rW   rX   r  &  s    z8FunctoolsPartialVariable.var_getattr.<locals>.<dictcomp>)r   r"   rA   r   ListVariablerw   rZ  r   ConstDictVariabler(   r  r   r   )rS   ru   r|   r   r   rW   rW   rX   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  rW   r  r  rW   rW   rX   r	  /  r
  z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   r  rW   r  r  rW   rW   rX   r  0  r  z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)r  r[  rA   r   rw   rZ  r   r   rW   rW   rX   r   ,  s   z+FunctoolsPartialVariable.as_python_constantc                 C   rc  )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   r  rW   guard_as_python_constant)r  r   rW   rW   rX   r	  7  r
  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   r  rW   rd  r  rW   rW   rX   r  8  r  zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>)r  r[  rA   re  rw   rZ  r   r   rW   rW   rX   re  3  s   z1FunctoolsPartialVariable.guard_as_python_constantr  r   )re   rf   rg   r3   rY   r   rV  r   r   r   r   r  r   re  r4  rW   rW   r   rX   rY    s0    



rY  c                       s   e Zd ZdddhejZeejdee	de
f ejf fddZed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_fnrh   .c                 C   r   ri   rW   )r   rW   rW   rX   _get_polyfill_handlersD  s   z1PolyfilledFunctionVariable._get_polyfill_handlersc                 C   r   r   )r!   r   r    r  r   rW   rW   rX   r   I  s   z-PolyfilledFunctionVariable.create_with_sourceNc                    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 functionrW   )
r   rY   r   rh  rk   callabler   r  r  rg  )rS   r   rx   handlercandidate_attr	candidaterg  r   rW   rX   rY   O  s    

z#PolyfilledFunctionVariable.__init__c                 C   r   ri   )rg  r   rW   rW   rX   polyfill_fnf  s   z&PolyfilledFunctionVariable.polyfill_fnc                 C   rt  )N*__torch_dynamo_can_constant_fold_through__F)r   r  r   rW   rW   rX   can_constant_fold_throughj     z4PolyfilledFunctionVariable.can_constant_fold_throughc                 C   rG  ri   r  r   rW   rW   rX   r   o  r   z'PolyfilledFunctionVariable.get_functionru   r9   rw   r   rx   r   r3   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  rW   r  r  rW   rW   rX   r	  }  r
  z<PolyfilledFunctionVariable.call_function.<locals>.<listcomp>c                 S   r  rW   r  r  rW   rW   rX   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 ri   )r   r   r5   r   intSymNodeVariabler   r  rW   rW   rX   rx    s    
z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>r   c                 s   s    | ]}|  V  qd S ri   as_proxy)r  arW   rW   rX   rx    r  c                 S   s$   g | ]}t |tjr|jn|jqS rW   )r   r   r5   r   sym_numr  rW   rW   rX   r	    s    
)rx  )rq  r'   r   r   r3   r   r  sumra   r   r   ra  TupleVariabler  rt  r   r   create_proxyr   sym_sumrs   rg  r   )rS   ru   rw   rx   r   traceable_function_variablerW   rW   rX   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   r   r   r+   r   r"   rf  )rS   ru   r|   rw   rx   methodr?  polyfilled_method_variablerW   rW   rX   r?    s   z&PolyfilledFunctionVariable.call_methodc                 C   r   ri   r   r   rW   rW   rX   r     r   z-PolyfilledFunctionVariable.as_python_constantr   rw   r   rx   r   rh   r3   )re   rf   rg   r3   r2  r3  r  cacher_   r   r   r   r   rh  r   r<   rY   propertyro  rq  r   r   r?  r   r4  rW   rW   r   rX   rf  <  sD    $

4
rf  c                   @   s   e Zd Zdd ZdS )TracebackVariablec                 C   s   d S ri   rW   r   rW   rW   rX   r     s    zTracebackVariable.call_functionNre   rf   rg   r   rW   rW   rW   rX   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 rZ   )r   rY   r   )rS   r   rx   r   rW   rX   rY     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 )Nr  )ra   exn_vt_stackr  r3   r   r   r5   rz  )rS   ru   exnr-  tbr   rW   rW   rX   exc_info  s   




zSysFunctionVariable.exc_infoc                 C   s   |  |jd S r  )r  r   r   rW   rW   rX   	exception  r[  zSysFunctionVariable.exceptionc                 C   s0   | j tju r| |S | j tju sJ | |S ri   )r   r  r  r  r   rW   rW   rX   r     s   

z!SysFunctionVariable.call_function)re   rf   rg   rY   r  r  r   r4  rW   rW   r   rX   r    s
    r  ) create_tma_experimental_metadatacreate_tma_stable_metadata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 )!DynamoTritonHOPifierr.  rh   c                 C   s   t |ri   )r   )rS   r.  rW   rW   rX   raise_unsupported  r   z&DynamoTritonHOPifier.raise_unsupportedmaybe_callablec                 C   s   t |ttfS ri   )r   r   r   )rS   r  rW   rW   rX   is_callable  rr  z DynamoTritonHOPifier.is_callabler   c                 C   s   |j S ri   r  )rS   r   rW   rW   rX   	get_value  r   zDynamoTritonHOPifier.get_value.c                 C   sB   ddl m} t||r| S tddt| dg tjd d S )Nr/   )BaseListVariablez/unsupported grid type for triton hop check_gridzgrid type = z;`torch.compile` only supports list-like grid for check_gridr   )listsr  r   rv  r   r9  r   rJ  )rS   gridr  rW   rW   rX   
check_grid  s   

zDynamoTritonHOPifier.check_gridc                 C   s&   dd |  D }|||gi }|S )Nc                 S      i | ]\}}t j||qS rW   r   r5   r   r  rW   rW   rX   r    s    z2DynamoTritonHOPifier.call_grid.<locals>.<dictcomp>)r   r   )rS   r  metaru   rW   rW   rX   	call_grid  s   zDynamoTritonHOPifier.call_gridc           	      C   s*   ddl m} |||}||||}|S )Nr/   r  )r  r  r   r   )	rS   user_fnrw   rx   ru   rC  r  wrapped_user_functionr   rW   rW   rX   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)rS   user_objru   rC  r|   r  wrapped_user_objrW   rW   rX   wrap_user_defined_obj  s   z*DynamoTritonHOPifier.wrap_user_defined_objc                 C   s   | |}dd |D }|S )Nc                 S   r  rW   rd  )r  r   rW   rW   rX   r	     r
  z=DynamoTritonHOPifier.maybe_unpack_configs.<locals>.<listcomp>)unpack_var_sequence)rS   configsru   rW   rW   rX   maybe_unpack_configs  s   
z)DynamoTritonHOPifier.maybe_unpack_configsr   c                 C   s   |  s	| d | S )Nz`@triton.heuristics must return constant values because configs can only contain constant values.)is_python_constantr  re  )rS   r   rW   rW   rX   maybe_unpack_heuristic_result$  s
   z2DynamoTritonHOPifier.maybe_unpack_heuristic_resultrC  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  ra   r  r9  r  r  r   )rS   rC  rw   rW   rW   rX   call_getitem.  s   z!DynamoTritonHOPifier.call_getitemc                    s*  ddl m  ddlm} i }t| D ]}|| }t|ttfr-|	 ||< |
 ||< qdd | D }	ddlm}
m}  fdd| D } fd	d|	 D }| D ]}| }t|tjtjfss| d
t| d qY|
|}||t}|jd|d|j|||| d td S )Nr/   r4   )rb  c                 S   r  rW   r  r  rW   rW   rX   r  S  s    z1DynamoTritonHOPifier.call_HOP.<locals>.<dictcomp>r   )kernel_side_tabletriton_kernel_wrapper_mutationc                    s$   i | ]\}}t | r|| qS rW   )r   r   r  r4   rW   rX   r  `  s    c                    s    i | ]\}}t | s||qS rW   )r   r  r4   rW   rX   r  e  s    z.Unexpected argument type for a Triton kernel: r  r   rW   )r  constant_args_idxr  tma_descriptor_metadatarx   )r  r5   dictsrb  rt   r  r   !TMADescriptorExperimentalVariableTMADescriptorStableVariableto_metadata
get_tensorr   *torch._higher_order_ops.triton_kernel_wrapr  r  r6  realizer   r  rt  r  repradd_constant_argsr_   r   r{  r  rv  )rS   rC  gridscombined_args_rawru   rb  r  r   r   combined_argsr  r  rX  non_constant_argsr  r  rW   r4   rX   call_HOP@  sX   



zDynamoTritonHOPifier.call_HOPN)re   rf   rg   r   r
   r  r   r  r  r  rs   r   fxproxyProxyr  r  r  r  r  r  r   r  r5   r  rW   rW   rW   rX   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  r:   r  r;   r  r  r"   r  rh   Nc                    s4   | dd | _t jdi | t| ||| d S )Nr  rW   )rr   r  r   rY    dynamo_triton_hopifier_singletoninit_variable)rS   r  r  r  rx   r   rW   rX   rY     s   zTritonKernelVariable.__init__ru   r9   rw   r   rx   r   r3   c                 C   s   t | |||S ri   )r  call_triton_kernelr   rW   rW   rX   r     s   z"TritonKernelVariable.call_functionc                    s>   |dkr
t | |S |dkrt | |||S t ||||S )N__getitem__run)r  r  call_runr   r?  r  r   rW   rX   r?    s
   z TritonKernelVariable.call_methodr  c                 C   s4   ddl m} ddlm} t||r|| S |S )Nr/   r4   )rt  )r  r5   tensorrt  r   r   evaluate_expr)rS   r  r5   rt  rW   rW   rX   specialize_symbolic  s
   
z(TritonKernelVariable.specialize_symbolicr1  r   r  )re   rf   rg   r   r   rs  rY   r   r?  r   r  r4  rW   rW   r   rX   r    s.   
 

r  c                       sH   e Zd Z								d fdd	Zd
d ZdddZdd Z  ZS )r  data_ptrvariables.DataPtrVariabledimslist[ConstantVariable]
block_dimselement_sizer5   c                    s>   t |tjsJ t jdi | || _|| _|| _|| _d S rZ   )	r   r   DataPtrVariabler   rY   r  r  r  r  )rS   r  r  r  r  rx   r   rW   rX   rY     s   
z*TMADescriptorExperimentalVariable.__init__c                 C   s*   t dd | jD dd | jD | j S )Nc                 S   r  rW   ru  r  dimrW   rW   rX   r	    r
  zATMADescriptorExperimentalVariable.to_metadata.<locals>.<listcomp>c                 S   r  rW   ru  r  rW   rW   rX   r	    r
  )r  r  r  r  rv  r   rW   rW   rX   r    s
   z-TMADescriptorExperimentalVariable.to_metadatarJ  r7   c                    sX      fdd j  g jjj} |  t|d d d S )Nc                      s     ddtj dS )Nz$triton.tools.experimental_descriptorcreate_d_tma_descriptor)r  ra   r  rW   r  rW   rX   r    s    z?TMADescriptorExperimentalVariable.reconstruct.<locals>.<lambda>r/   F)	r  r  rV  r  r  r  r]  r   ra   )rS   rJ  rw   rW   r  rX   rV    s   
z-TMADescriptorExperimentalVariable.reconstructc                 C   r   ri   )r  from_tensorr   rW   rW   rX   r    r   z,TMADescriptorExperimentalVariable.get_tensor)r  r  r  r  r  r  r  r5   r  re   rf   rg   rY   r  rV  r  r4  rW   rW   r   rX   r    s    
r  c                       sB   e Zd Z				d fddZdd ZdddZdddZ  ZS )r  r  variables.TensorVariableblock_shapevariables.ListVariablec                    s2   t |tjsJ t jdi | || _|| _d S rZ   )r   r   r  r   rY   r  r  )rS   r  r  rx   r   rW   rX   rY     s   
z$TMADescriptorStableVariable.__init__c                 C   s   t | j S ri   )r  r  rv  r   rW   rW   rX   r    rr  z'TMADescriptorStableVariable.to_metadatarJ  r7   c                    s@      fdd  d | j   | j  d d S )Nc                      r  )Nztriton.tools.tensor_descriptorTensorDescriptorr  rW   r  rW   rX   r    s    z9TMADescriptorStableVariable.reconstruct.<locals>.<lambda>r  r   )r  load_methodr  rV  r  r?  r  rW   r  rX   rV    s   


z'TMADescriptorStableVariable.reconstructrh   c                 C   r   ri   )r  r   rW   rW   rX   r    r   z&TMADescriptorStableVariable.get_tensor)r  r  r  r  r  )rh   r  r  rW   rW   r   rX   r    s    
r  c                       s@   e Zd Zdeddf fddZ						
			dddZ  ZS )'CreateTMADescriptorExperimentalVariablerankrh   Nc                    s(   |dv sJ t  jdi | || _d S )N)r/   r   rW   )r   rY   r  )rS   r  rx   r   rW   rX   rY    	  s   
z0CreateTMADescriptorExperimentalVariable.__init__ru   r9   rw   r   rx   r   r3   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>   r  	block_dimr      dim1dim0
block_dim1rz  
block_dim0r  r  )r  r  r  r  )r   r   r  r   r  ra   r  )rS   ru   rw   rx   r  r  r  r  rW   rW   rX   r   		  s6   
z5CreateTMADescriptorExperimentalVariable.call_functionr   )re   rf   rg   rs  rY   r   r4  rW   rW   r   rX   r    s    	r  c                   @   s&   e Zd Z								dd	d
ZdS )!CreateTMADescriptorStableVariableru   r9   rw   r   rx   r   rh   r3   c                 C   s<   d|v r|d n|d }d|v r|d n|d }t ||dS )Nr  r   r  r/   )r  r  )r  )rS   ru   rw   rx   r  r  rW   rW   rX   r   5	  s   z/CreateTMADescriptorStableVariable.call_functionNr   r  rW   rW   rW   rX   r  4	  s    r  ri   r  )r   r  r  r   r   r  r  r#  r   collections.abcr   r   typingr   r   r   r   r	   typing_extensionsr
   unittest.mockr   weakrefr   r   torch._dynamo.excr   r  r   r   r   r   bytecode_transformationr   r   r   rp  r   r   r   r   r   r   r   r   r   r   guardsr    r!   r   r"   r#   r$   r%   r   r&   r'   r(   r)   r*   r+   r,   r-   r.   baser0   r1   r2   r3   r  r5   #torch.distributed.fsdp._fully_shardr6   ModuleNotFoundErrortorch._dynamo.codegenr7   rO  r9   r  r:   r;   r<   rO   rQ   rj   r@   rm   r   rp   r   r_   r   r   r   r   r   r   r   r5  rC  r  r  r  r  r  r  r  r   r  r  r  r  r.  r5  r:  r;  rR  rV  rY  rf  r  r  r  r  r  r  r  r  r  r  r  r  r  rW   rW   rW   rX   <module>   s   0,5
" [  
B
7Y
 4( A
	TQ ! .'!5