a
    h'[                    @   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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 eJy   dZIY n0 erddlKmLZL ddlMmNZN ddlOmPZPmQZQ ededZRdZSdZTe ZUG dd dZVeeVddd ZWd!d" ZXdrd#d$d%d&ZYd#d$d'd(ZZe[e\eEf d)d*d+Z]d,d- Z^h d.Z_d/d0 Z`G d1d2 d2eEZaG d3d4 d4eaZbG d5d6 d6eaZcG d7d8 d8eEZdG d9d: d:edZeG d;d< d<eaZfG d=d> d>efZgG d?d@ d@ebZhG dAdB dBehZiG dCdD dDebZjd#d$dEdFZkG dGdH dHeaZlG dIdJ dJelZmG dKdL dLeEZnG dMdN dNenZoG dOdP dPeEZpG dQdR dRepZqdSdT Zrd#d$dUdVZsG dWdX dXebZtG dYdZ dZebZuG d[d\ d\ebZvG d]d^ d^eEZwG d_d` d`eEZxG dadb dbeEZyG dcdd ddeEZzddelOm{Z{m|Z|m}Z}m~Z~ G dfdg dge~Ze ZG dhdi dieEZG djdk dkeEZG dldm dmeEZG dndo doeEZG dpdq dqeEZdS )sa  
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edddZed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@ r|| nd | _|| jrdnd7 }|jt@ r|| nd | _d S )Nr/   r   )__code__co_varnamesco_posonlyargcountposonly_countco_argcount	arg_countco_kwonlyargcountZkwonly_countposonly_namesZpos_or_kw_namesall_pos_nameskwonly_namesco_flags
CO_VARARGSvarargs_nameCO_VARKEYWORDS
varkw_name)selfrA   codeZvnoff rT   O/var/www/auris/lib/python3.9/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 )NrT   )
__defaults__defaults__kwdefaults__
kwdefaultsdictziprJ   lenrangepos_default_map)rQ   rA   rT   rT   rU   update_defaults{   s
    $zFunctionSpec.update_defaultsN)__name__
__module____qualname__r   rV   r`   rT   rT   rT   rU   r@   h   s   r@   rA   returnc                 C   s&   t | }|d u r"t| }|t | < |S N)_spec_cachegetr@   )rA   specrT   rT   rU   	_get_spec   s
    
rj   c                 C   s  t | }||  i }t|}t|jD ]\}}	|t|k rPt||| ||	< q(|	|v r|	|jv rpt|	 dt||	|	||	< q(|	|j
v r|j
|	 }
d }|rt||
}t||j|
 |||	< q(td|	 q(|t|jd  }|jrt|t|||j< n$|r(tdt| dt|j |jD ]p}	|	|v rRt||	|	||	< nJ|	|jv rd }|rvt||	dd}t||j|	 |||	< ntd|	 q.|jrt||||j< n|rtdt| |S )	Nz is positional-onlyz&Missing required positional argument: z#Too many positional arguments: got z, expected T)Zis_kwz(Missing required keyword-only argument: zUnexpected keyword arguments: )rj   r`   r[   	enumeraterJ   r]   wrap_bound_argrI   	TypeErrorpopr_   r$   rX   rN   tuplerK   rZ   rP   list)rA   txZ	fn_sourceargskwargsri   baZrem_kwinameidxZdefault_sourceextraZkwdefault_sourcerT   rT   rU   bind_args_cached   sN    






ry   r9   rq   c                 C   s0   t |tr|S |st| |S tj||S d S rf   )
isinstancer3   buildr   LazyVariableTrackercreate)rq   valsourcerT   rT   rU   rl      s
    
rl   c                 C   s6   t | D ]$\}}t|ttfrt| |||< qd S rf   )rp   itemsr{   ro   r[   rl   )rq   resultkvrT   rT   rU   wrap_args_kwargs   s    r   )r   c                 C   sB   | j j}|jD ].}| }||v r4|||| |||< 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_cellrn   )parentr   rR   r   rv   Znew_cellrT   rT   rU   init_cellvars   s    
r   c           
      C   sd   ddl m} || ||||}||_t|trDddlm}	 t|	|}|d u sZt|tsZJ ||_|S )Nr   r   pairwise)	typesr   rY   r{   ro   	itertoolsr   r[   __annotations__)
rR   	f_globalsrv   rX   closurerZ   annotationsr   rA   r   rT   rT   rU   _create_nested_fn   s    
r   >   __closure__rW   rB   __globals____doc__rY   r   c                 C   sl   |ot ||}zt||}W n ty:   tt|  Y n0 |tv rNt||}|r`tj	||S t
| |S rf   )r"   inspectgetattr_staticAttributeErrorr   fn_known_dunder_attrsgetattrr   r}   r~   r3   r|   )rq   fnr   rv   ZsubobjrT   rT   rU   fn_var_getattr  s    
r   c                   @   sR   e Zd Zdd Zdd Zddddd	d
dZdeedddZdd Z	dd Z
dS )BaseUserFunctionVariablec                 C   s
   |   jS rf   get_codeco_filenamerQ   rT   rT   rU   get_filename  s    z%BaseUserFunctionVariable.get_filenamec                 C   s
   |   jS rf   r   co_namer   rT   rT   rU   get_name  s    z!BaseUserFunctionVariable.get_namer9   list[VariableTracker]dict[str, VariableTracker]r3   rq   rr   rs   re   c                 C   s   | | g |  ||S rf   )Zinline_user_function_return	self_argsrQ   rq   rr   rs   rT   rT   rU   call_function  s    z&BaseUserFunctionVariable.call_functionrq   rv   re   c                 C   sL   d}zt |  |}W n( ty>   |dkr:t| tr:d}Y n0 tj|S )NFra   T)hasattrget_functionNotImplementedErrorr{   NestedUserFunctionVariabler   r5   r~   rQ   rq   rv   r   rT   rT   rU   call_obj_hasattr'  s    
z)BaseUserFunctionVariable.call_obj_hasattrc                 C   s   t t|  jS rf   )rp   r   	signaturer   
parametersr   rT   rT   rU   inspect_parameter_names3  s    z0BaseUserFunctionVariable.inspect_parameter_namesc                 C   s   i S rf   rT   rQ   rq   rT   rT   rU   closure_vars6  s    z%BaseUserFunctionVariable.closure_varsN)ra   rb   rc   r   r   r   strr3   r   r   r   rT   rT   rT   rU   r     s   	r   c                       s   e Zd ZdZddhejZedd Zd(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eeef dddZdedddZdeedd d!Zdd"d#d$d% fd&d'Z  ZS ))UserFunctionVariablez-Some unsupported user-defined global functionr   is_constantc                 C   s   t |tj | ||dS Nr   )r!   
make_guardr    ZCLOSURE_MATCHclsvaluer   rT   rT   rU   create_with_sourceC  s    z'UserFunctionVariable.create_with_sourceFNre   c                    sr   t  jf i | t|ddr&d| _nd| _t|tjtjj	fsZt
d| ddgtjd t|d|}|| _d S )	NZ_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Zgb_typecontextexplanationhintsZ_torchdynamo_inline)superrV   r   r   r{   r   r   torchZjitZScriptFunctionr   r   ZINFERENCE_MODEr   r   r   rQ   r   r   rs   	__class__rT   rU   rV   H  s     zUserFunctionVariable.__init__c                    s   t | tr| jS t  S rf   )r-   r   r   r   as_python_constantr   r   rT   rU   r   b  s    
z'UserFunctionVariable.as_python_constantc                 C   s   g S rf   rT   r   rT   rT   rU   r   h  s    zUserFunctionVariable.self_argsc                 C   s   | j S rf   r   r   rT   rT   rU   r   k  s    z!UserFunctionVariable.get_functionc                 C   s   | j jS rf   )r   rB   r   rT   rT   rU   r   n  s    zUserFunctionVariable.get_codec                 C   s   t jS rf   r   r   r   rT   rT   rU   python_typeq  s    z UserFunctionVariable.python_typec                 C   s   t | jdd d uS N__self__)r   r   r   rT   rT   rU   has_selft  s    zUserFunctionVariable.has_selfc                 C   s   | j jS rf   )r   r   r   rT   rT   rU   get_globalsw  s    z UserFunctionVariable.get_globalsc              	   C   sZ  | j r
J | j}t|ts"td|jj}t||| j||}t	|||j
 | jjpTd}t|t| jj
jkspJ tt | jj
j|D ]\}}	}
|jj}|
|v r||
 }n| jrtt| jd|}t|d}zt||
j|}W n ty   t }Y n0 |||
|}n>zt||
j}W n ty<   t }Y n0 |d|
|}|||	< q|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.rT   r   cell_contentsN)r   r   r{   r   rm   r   root_txry   r   r   rB   r   r]   co_freevarsr\   r   countr   r%   r"   r3   r|   r   
ValueErrorr   ZDeletedVariableZtrack_cell_existing)rQ   r   rr   rs   r   r   r   r   rw   rv   cellr   Zcell_varZclosure_cellZclosure_cell_contentsZcontents_varrT   rT   rU   	bind_argsz  sH    




zUserFunctionVariable.bind_argsr9   rq   rv   c                 C   s&   |t v rt| |S t|| j| j|S rf   )r(   r   GetAttrVariabler   r   r   rQ   rq   rv   rT   rT   rU   var_getattr  s    z UserFunctionVariable.var_getattrr   c                 C   s   t | j|}tj|S rf   )r   r   r   r5   r~   r   rT   rT   rU   r     s    z%UserFunctionVariable.call_obj_hasattrr   r   r3   r   c              
      s  | j tjju rz@dd |D }dd | D }tjj|i |j}t|W S  ty } z"t	d| d| |W Y d }~n
d }~0 0 | j tjj
u r\t| j j|i |}|jd }	t|	ts
|	 }
d|
j d	}td
d| j d| d| d|g tjd t|	tsH|	 }d| d}td|  |d| ddgd |	j }tj|ddS | jrzt|| j |  ||S |jjjs| j tjjj u rtjj!"|  t# $|||W  d    S 1 s0    Y  |jjj%rx|jjj&sxzddl'm(} W n t)y   d }Y n0 |d urx| j |j*|j+fv rxtjj!&|  t# $|||W  d    S 1 sn0    Y  t# $|||S )Nc                 S   s   g | ]}|  qS rT   r   .0argrT   rT   rU   
<listcomp>      z6UserFunctionVariable.call_function.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS rT   r   )r   keyr   rT   rT   rU   
<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Znonstrict_traceable)	FSDPState),r   r   _dynamoZpatch_dynamo_configr   changesr   ZDynamoConfigPatchVariabler0   RuntimeErrorZnonstrict_tracer   r   bindrr   r{   r   r   ra   r   r   r   Z
USER_ERRORr   r   TorchInGraphFunctionVariabler   invoke_and_store_as_constantr   Zcurrent_tracerZ,unsafe_allow_externally_visible_side_effectsutilsZ8_disable_side_effect_safety_checks_for_current_subtracerr   Z2allow_externally_visible_side_effects_in_subtracerr   r   Zunder_activation_checkpointZ#allow_side_effects_under_checkpointZ/torch.distributed.fsdp._fully_shard._fsdp_stater   	ExceptionZ_pre_forwardZ_post_forward)rQ   rq   rr   rs   Z
args_constZkwargs_constr   er=   Zfn_vartypmsgfn_namer   r   r   rT   rU   r     s    
	

0
0z"UserFunctionVariable.call_function)F)ra   rb   rc   r   r   _nonvar_fieldsclassmethodr   rV   r   r   r   r   r   r   r   r[   r   r3   r   r   r   r   __classcell__rT   rT   r   rU   r   :  s4   
7r   c                       sD   e Zd Zddd fddZedd Zdd	d
ddddZ  ZS )BuiltinMethodVariableFNr   c                    s,   t  jf i | t|tjs"J || _d S rf   )r   rV   r{   r   BuiltinMethodTyper   r   r   rT   rU   rV     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   ra   ro   type	frozenset)objmethod_selfmethod_namerT   rT   rU   is_supported_builtin_method  s
    z1BuiltinMethodVariable.is_supported_builtin_methodr9   r   r   r3   r   c                 C   s@   | j j}| j j}| jo t| jd}t|||}|||||S r   )r   r   ra   r   r"   r3   r|   call_method)rQ   rq   rr   rs   r  rv   Z
obj_sourceZobj_vtrT   rT   rU   r   %  s
    z#BuiltinMethodVariable.call_function)F)ra   rb   rc   rV   staticmethodr  r   r   rT   rT   r   rU   r     s   
r   c                       s  e Zd Zeje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eZddddZdd Zdd Zdd Zdd Zdd  Zd!d" Zejd#d$d%Zee d#d&d'Zd(d#d)d*Zd+d, Zd-d. Zd/d0 Zded1d2d3d4 fd5d6Z   Z!S )7LocalGeneratorObjectVariabler9   )rR   inline_tracerc                    s(   t  jf i | || _|| _|| _d S rf   )r   rV   rR   r   r	  )rQ   rR   r   r	  rs   r   rT   rU   rV   3  s    z%LocalGeneratorObjectVariable.__init__c                 C   s   | j S rf   )rR   r   rT   rT   rU   r   ?  s    z%LocalGeneratorObjectVariable.get_codec                 C   s
   |   jS rf   r   r   rT   rT   rU   r   B  s    z)LocalGeneratorObjectVariable.get_filenamec                 C   s
   |   jS rf   r   r   rT   rT   rU   r   E  s    z%LocalGeneratorObjectVariable.get_namec                 C   s   t d S rf   )r   r   rT   rT   rU   r   H  s    z)LocalGeneratorObjectVariable.get_functionc                 C   s   dS NFrT   r   rT   rT   rU   r   K  s    z%LocalGeneratorObjectVariable.has_selfc                 C   s   |   S rf   )r   r   rT   rT   rU   ra   N  s    z%LocalGeneratorObjectVariable.__name__c                 C   s   | j j d|   dS )N(r   )r   ra   r   r   rT   rT   rU   __str__Q  s    z$LocalGeneratorObjectVariable.__str__r7   codegenc              
   C   s   ddl m} ddlm}m}m} | }||}||}||}	| |b |	> | |}
|
jsn| 	|| _
t| j
| W d    n1 s0    Y  W d    n1 s0    Y  W d    n1 s0    Y  d S )Nr   )"disallow_side_effects_in_generator)r9    save_and_restart_speculation_log(temporarely_allow_writes_to_output_graph)Ztorch._dynamo.side_effectsr  torch._dynamo.symbolic_convertr9   r  r  
current_tx_get_inline_tracergenerator_exhaustedforce_unpack_var_sequenceZremaining_itemsr   ZListIteratorVariablereconstruct)rQ   r  r  r9   r  r  rq   saveZdisallowtemptracerrT   rT   rU   r  V  s    
z(LocalGeneratorObjectVariable.reconstructc                 C   s   | j |||S rf   )r   r   r   rT   rT   rU   r   i  s    z&LocalGeneratorObjectVariable.bind_argsc                 C   s   | j S rf   r   r   rT   rT   rU   r   l  s    z(LocalGeneratorObjectVariable.get_globalsc                 C   s   t jS rf   )r   GeneratorTyper   rT   rT   rU   r   o  s    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   rq   r  rT   rT   rU   r  r  s    
z/LocalGeneratorObjectVariable._get_inline_tracerc                 C   s$  |  |}|  rtt| zzXttdtd i0 | W  d    W W td  td O  < S 1 sj0    Y  W nz ty } zd|_	|W Y d }~nVd }~0  t
y    Y n< ty } z$tjj|   t|W Y d }~n
d }~0 0 W td  td O  < ntd  td O  < 0 d S )NZunimplementedZinline_callT)r  _is_generator_exhaustedr   StopIterationr   r[   r)   Zinline_call_r   r  r   r   r   r   Z
eval_frameZ	skip_coder   r   )rQ   rq   r  r   rT   rT   rU   next_variable{  s"    

z*LocalGeneratorObjectVariable.next_variablec                 C   s   dS r
  rT   r   rT   rT   rU   has_unpack_var_sequence  s    z4LocalGeneratorObjectVariable.has_unpack_var_sequencer   c                 C   s   dS NTrT   r   rT   rT   rU   has_force_unpack_var_sequence  s    z:LocalGeneratorObjectVariable.has_force_unpack_var_sequencec                 C   s   g }|  ||j |S rf   )force_apply_to_var_sequenceappend)rQ   rq   r   rT   rT   rU   r    s    z6LocalGeneratorObjectVariable.force_unpack_var_sequenceNc                 C   s8   z||  | W q  ty0   t| Y q4Y q 0 q d S rf   )r"  r   r   )rQ   rq   r   rT   rT   rU   r&    s
    z8LocalGeneratorObjectVariable.force_apply_to_var_sequencec              
   C   sL   |  |}z|| W n. tyF } z|| W Y d }~n
d }~0 0 d S rf   )r  Z_raise_exception_variabler   Zexception_handler)rQ   rq   excr  r   rT   rT   rU   _setup_exception  s
    
z-LocalGeneratorObjectVariable._setup_exceptionc                 C   s   | j d u p| j jdkS )Nr   )r	  Zinstruction_pointerr   rT   rT   rU   _is_generator_just_started  s    z7LocalGeneratorObjectVariable._is_generator_just_startedc                 C   s   t | jddS )Nr  F)r   r	  r   rT   rT   rU   r     s    z4LocalGeneratorObjectVariable._is_generator_exhaustedr   r   r3   )rq   rv   rr   rs   re   c              	      sB  |dkr|  |S |dkr| S |dkrp|  rRt|rRtdd |D sRtt| | |}|| |  |S |dkrt| |}|  s|  rd|_	t
d S z@| |t
td tjd	kr|jjd
krd|_	t
d W S W n$ ty   d|_	t
d  Y S 0 z|  |r"tt| W nL tyH   d|_	t
d  Y S  typ   |jd usfJ |j Y S 0 n|dkr,| |}z*| |t|dkr|d n|d  W n ty    Y n0 |  |}tdtfi }z"| |t
|d |  | W n t|y   Y n0 tt| |S t |||| d S )N__next____iter__sendc                 s   s"   | ]}t |to|jd u V  qd S rf   )r{   r5   r   r   rT   rT   rU   	<genexpr>  s   z;LocalGeneratorObjectVariable.call_method.<locals>.<genexpr>closeTrT   )      ZCALL_INTRINSIC_1throwr0  r/   r   Z__InternalThrowException)r"  r*  r]   allr   rm   r  Z	push_manyr   r  r   r5   r)  ZExceptionVariableGeneratorExitsysversion_infoZnext_instructionopnamer   r   r   Zsymbolic_resultr   r   r   r   r   r  )rQ   rq   rv   rr   rs   r  retvalexc_typer   rT   rU   r    sp    










*
>
z(LocalGeneratorObjectVariable.call_method)"ra   rb   rc   r   CodeTyper   rV   r   r   r   r   r   r  __repr__r  r   r   r   r  r"  r#  builtinsboolr%  rp   r3   r  r&  r)  r*  r   r   r  r   rT   rT   r   rU   r  2  s<   		r  c                   @   s   e Zd ZdZdS )4ContextlibContextManagerLocalGeneratorObjectVariablez
    .. note::

        This is only used when the function is annotated with @contextlib.contextmanager

        It is a special case of a generator function as we do not allow return a context manager
        from a torch.compile function.
    N)ra   rb   rc   r   rT   rT   rT   rU   r>  r  s   r>  c                       sP   e Zd ZdZeded fddZdd Zdd	 Zd
ddddddZ	  Z
S )LocalGeneratorFunctionVariablezxfunctions that behaves like iterators

    .. note::

        This is a wrapper around (Nested)UserFunctionVariable
    )generator_cls)vtc                   s"   t  jf i | || _|| _d S rf   )r   rV   rA  r@  )rQ   rA  r@  rs   r   rT   rU   rV     s    z'LocalGeneratorFunctionVariable.__init__c                 C   s&   || j j v rt| |S t| j|S rf   )r   __dict__keysr   rA  )rQ   rv   rT   rT   rU   __getattr__  s    
z*LocalGeneratorFunctionVariable.__getattr__c                 C   s   ddl m} ||| ||S r  )r  r  r  )rQ   rq   rr   rs   r  rT   rT   rU   _build_inline_tracer  s    z3LocalGeneratorFunctionVariable._build_inline_tracerr9   r   r   r3   r   c                 C   sH   t | j sJ | |||}| j }| j }| j|||| jdS r   )r   rA  r   rE  r   r@  r   )rQ   rq   rr   rs   r	  rR   r   rT   rT   rU   r     s    

z,LocalGeneratorFunctionVariable.call_function)ra   rb   rc   r   r  r3   rV   rD  rE  r   r   rT   rT   r   rU   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   rV   r>  )rQ   rA  rs   r   rT   rU   rV     s    z<FunctionDecoratedByContextlibContextManagerVariable.__init__c                    s.   t  |||}t|tjjjs$J d|_|S r$  )r   rE  r{   r   r   Zsymbolic_convertZ&InliningGeneratorInstructionTranslatorZis_generator_from_ctx_manager)rQ   rq   rr   rs   r  r   rT   rU   rE    s    zHFunctionDecoratedByContextlibContextManagerVariable._build_inline_tracer)ra   rb   rc   r   rV   rE  r   rT   rT   r   rU   rF    s   rF  c                       s|   e Zd ZdZdd fddZedddZdd	 Zd
d Zddddd fddZ	 fddZ
ded fddZ  ZS )UserMethodVariablez$Some unsupported user-defined methodNr   c                    s    t  jf d|i| || _d S Nr   r   rV   r  )rQ   r   r  rs   r   rT   rU   rV     s    zUserMethodVariable.__init__c                 C   s   | j j d| j d| j dS )Nr  r   r   )r   ra   r   r  r   rT   rT   rU   r;    s    zUserMethodVariable.__repr__c                 C   s   | j gS rf   r  r   rT   rT   rU   r     s    zUserMethodVariable.self_argsc                 C   s   t jS rf   )r   
MethodTyper   rT   rT   rU   r     s    zUserMethodVariable.python_typer9   r   r   r3   r   c           	         s  ddl m} || jrDg |  |}tj| jdd}||||S |j rt	| j
tjrt| jdd}|d ur|dr|dks| jr| j
j|| jj||| jd	S n6td ur| jtjju rt| j|| j
g|R |S | jrt| j
j| jj}t|||  ||S t |||S )
Nr   )is_nonstrict_trace_callableTr   rb    z	torch.nn.ztorch.nn.utils.parametrize)constant)Ztrace_rulesrL  r   r   r   r   r   r   Zis_root_tracerr{   r  ZNNModuleVariabler   
startswithr   r  ra   r6   ZFSDPParamGroupZuse_training_stateZTorchCtxManagerClassVariabler   r   r   r   )	rQ   rq   rr   rs   rL  Z	call_argsvarZmodule_attrr   r   rT   rU   r     sB    
z UserMethodVariable.call_functionc                    s   t   dd  S Nr/   )r   r   r   r   rT   rU   r   !  s    z*UserMethodVariable.inspect_parameter_namesr   c                    sF   | j ot| j |}|dkr | jS |dkr8t|| j|S t ||S )Nr   __func__)r   r"   r  r3   r|   r   r   r   )rQ   rq   rv   r   r   rT   rU   r   $  s    zUserMethodVariable.var_getattr)ra   rb   rc   r   rV   r   r;  r   r   r   r   r   r   rT   rT   r   rU   rG    s   =rG  c                       sB   e Zd Zdd fddZddddd	 fd
dZdd Z  ZS )WrappedUserMethodVariableNr   c                    sB   | dd  | dd  t j|j|jfi | || _|| _d S )Nr   r  )rn   r   rV   r   r  wrappedr   rQ   rT  r   rs   r   rT   rU   rV   .  s
    z"WrappedUserMethodVariable.__init__r9   r   r   r3   r   c                    s,   | j | t |||}| j | |S rf   r   Zenterr   r   exitrQ   rq   rr   rs   r   r   rT   rU   r   5  s    z'WrappedUserMethodVariable.call_functionc                    s2      fdd  j  tdd d S )Nc                      s
    j S rf   r   rT   r  rQ   rT   rU   <lambda>A  r   z7WrappedUserMethodVariable.reconstruct.<locals>.<lambda>r/   Fadd_push_nullrT  extend_outputr   rQ   r  rT   rZ  rU   r  @  s    
z%WrappedUserMethodVariable.reconstructra   rb   rc   rV   r   r  r   rT   rT   r   rU   rS  -  s   	rS  c                       sB   e Zd Zdd fddZddddd	 fd
dZdd Z  ZS )WrappedUserFunctionVariableNr   c                    s2   | dd  t j|jfi | || _|| _d S rH  )rn   r   rV   r   rT  r   rU  r   rT   rU   rV   G  s    z$WrappedUserFunctionVariable.__init__r9   r   r   r3   r   c                    s,   | j | t |||}| j | |S rf   rV  rX  r   rT   rU   r   M  s    z)WrappedUserFunctionVariable.call_functionc                    s2      fdd  j  tdd d S )Nc                      s
    j S rf   rY  rT   rZ  rT   rU   r[  Y  r   z9WrappedUserFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr\  r_  rT   rZ  rU   r  X  s    
z'WrappedUserFunctionVariable.reconstructr`  rT   rT   r   rU   ra  F  s   ra  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 rf   )r{   r   TensorVariableZget_real_valuer   )xrT   rT   rU   convert_  s    z-invoke_and_store_as_constant.<locals>.convertc                    s   g | ]} |qS rT   rT   r   rc  rd  rT   rU   r   d  r   z0invoke_and_store_as_constant.<locals>.<listcomp>c                    s   i | ]\}}| |qS rT   rT   r   r   r   rf  rT   rU   r   e  r   z0invoke_and_store_as_constant.<locals>.<dictcomp>r   )r   r   Zregister_attr_or_moduler#   )rq   r   rv   rr   rs   resrT   rf  rU   r   ^  s    r   c                       s   e Zd ZdhejZd"dd fddZdd Zdd	 Zd
d Zdd Z	de
e
d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 d!Z  ZS )#r   r   Nr   c	           
         s   |	 dd u r|	jt d t jf i |	 t| ts@J t| tj	sTJ t|t
sbJ || _|| _|| _|| _|| _|| _|| _|| _d S )Nmutation_typeri  )rh   updater1   r   rV   r{   r   r   r   r:  r[   r   rR   r   rX   rZ   r   r   
wrapped_fn)
rQ   r   rR   r   rX   rZ   r   r   rl  rs   r   rT   rU   rV   t  s    z#NestedUserFunctionVariable.__init__c                 C   s   g S rf   rT   r   rT   rT   rU   r     s    z$NestedUserFunctionVariable.self_argsc                 C   s
   | j  S rf   )rR   r   r   rT   rT   rU   r     s    z#NestedUserFunctionVariable.get_codec                 C   s   t jS rf   r   r   rT   rT   rU   r     s    z&NestedUserFunctionVariable.python_typec                 C   s   | j r
tt| j | j| j }| jr8| j |_	| j
rJ| j
 |_| jr| j }t|tr|ddlm} t||}t|tsJ ||_|S )Nr   r   )r   r   r   r   rR   r   r   r   rX   rW   rZ   rY   r   r{   ro   r   r   r[   r   )rQ   rA   r   r   rT   rT   rU   r     s&    

z'NestedUserFunctionVariable.get_functionr9   )rq   name_varr   c                 C   s   |j j| |j| td S rf   )r   r   
store_attrr   r5   )rQ   rq   rm  r   rT   rT   rU   call_setattr  s    z'NestedUserFunctionVariable.call_setattrc                    s,   |dkr| j |g|R  S t ||||S )N__setattr__)ro  r   r  rQ   rq   rv   rr   rs   r   rT   rU   r    s    z&NestedUserFunctionVariable.call_methodc                 C   s
   | j d uS rf   )r   r   rT   rT   rU   has_closure  s    z&NestedUserFunctionVariable.has_closurec                    s    |dkr| j  S t ||S )Nra   )r   r   r   const_getattrr   r   rT   rU   rs    s    
z(NestedUserFunctionVariable.const_getattrc                 C   s   dS r
  rT   r   rT   rT   rU   r     s    z#NestedUserFunctionVariable.has_selfc                 C   s   | j S rf   r  r   rT   rT   rU   r     s    z&NestedUserFunctionVariable.get_globalsc                 C   s   |   }t|| j| j | jr,t| jjnd tdd t	t
|   jD }| jrb| j |_t|j|i |}|  t|j }t|jj| t||| t|jD ](\}}	|	|vsJ | jj| }
|
||	< q|S )Nc                 s   s   | ]}t d V  qd S rf   )r.   )r   _rT   rT   rU   r.    r   z7NestedUserFunctionVariable.bind_args.<locals>.<genexpr>)r   r   r   r   r   r   rX   ro   r   r^   r]   r   rZ   Zkeys_as_python_constantrY   r   r   r   apply_defaultsr[   	argumentsr   r   r   r   rk   r   )rQ   r   rr   rs   rR   rA   r=   r   rw   rv   r   rT   rT   rU   r     s(    
z$NestedUserFunctionVariable.bind_argsr7   r  c                    s     fdd  | j   | jg  t| jjj | j	rV | j	 n  
d g | jrz | j n  
d g | jr | j n  
d g | jrz | j }  |g W n ty    | j Y n0 n  
d g  tdd | jrj   fdd  | j  tdd  td  tdd d	d
lm} | }|jj| r|jjj|   D ]2\}}    |  td  | qd S )Nc                      s     tdS )Nr   )load_import_fromra   rT   r  rT   rU   r[    r   z8NestedUserFunctionVariable.reconstruct.<locals>.<lambda>   Fc                      s     ddS )N	functoolswrapsrw  rT   r  rT   rU   r[    r   r/   r   Tr   r8   )r]  rR   r^  Zcreate_load_const_uncheckedr   r5   r~   r   r   rX   Zcreate_load_constr   rZ   r   r   r   r   rl  r   r  r9   r  r   r   Zhas_pending_mutationZstore_attr_mutationsr   Zdup_toprn  )rQ   r  r   r9   rq   rv   r   rT   r  rU   r    sV    





z&NestedUserFunctionVariable.reconstruct)N)ra   rb   rc   r   r   rV   r   r   r   r   r3   ro  r  rr  rs  r   r   r   r  r   rT   rT   r   rU   r   n  s.    	r   c                       sB   e Zd Zdd fddZddddd	 fd
dZdd Z  ZS )!WrappedNestedUserFunctionVariableNr   c              
      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   rR   r   rX   rZ   r   r   rl  )rn   r   rV   r   rR   r   rX   rZ   r   r   rl  rT  r   rU  r   rT   rU   rV   "  s(    
z*WrappedNestedUserFunctionVariable.__init__r9   r   r   r3   r   c                    s,   | j | t |||}| j | |S rf   rV  rX  r   rT   rU   r   8  s    z/WrappedNestedUserFunctionVariable.call_functionc                    s2      fdd  j  tdd d S )Nc                      s
    j S rf   rY  rT   rZ  rT   rU   r[  D  r   z?WrappedNestedUserFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr\  r_  rT   rZ  rU   r  C  s    
z-WrappedNestedUserFunctionVariable.reconstructr`  rT   rT   r   rU   r|  !  s   r|  c                       sx   e Zd ZddhejZddd fddZdd Zed	d
 ZdddddddZ	ddddZ
dedddZ  ZS )SkipFunctionVariabler   reasonNr   c                    s"   t  jf i | || _|| _d S rf   )r   rV   r   r~  )rQ   r   r~  rs   r   rT   rU   rV   P  s    zSkipFunctionVariable.__init__c                 C   s   | j S rf   r   r   rT   rT   rU   r   U  s    z'SkipFunctionVariable.as_python_constantc                 C   s$   t |st|tj | ||dS r   )r,   r!   r   r    FUNCTION_MATCHr   rT   rT   rU   r   X  s    z'SkipFunctionVariable.create_with_sourcer9   r   r   r3   r   c              	   C   s  t | jddrLt | jdd }tdt| jd| j d| ddgd	 nP| jtjju r|d
d }|rr|	 }tdd| d| dd| dgd	 n | jtjj
u r|d
d }|r|	 }td| ntjrddlm} ||| j}t|ts||||S t| jdd}	t| jdd }
|
d u r:dnt|
}zNt | j}d|	 d| d}d|	 dg}d|vr|d|	 dd g7 }W n tyT   d!d"h}|
|v rd#| d$|	 d}d%d&g}n|
d ur|
d'rd(| d$|	 d$}d)g}tjj|d* d*|  n6d+| d$|	 d,}d-d.g}tjj|d* d*|  Y n0 |	d/krhd0}g }| jrv| jnd1}td2d3| d4|	 d5| ||d	 d S )6NZ_torchdynamo_disableFZ_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/   SourcelessBuilderrc   z<unknown qualname>rb   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. 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: )r   r   r   r   r   r   r   Zgraph_breakrh   r   Z
skip_framer   r   Zdont_skip_tracingbuilderr  r~   r{   r}  r   r   getfilerm   rO  r   	warn_oncejoinr~  )rQ   rq   rr   rs   r   Zgraph_break_msgZskip_frame_msgr  Z
rebuilt_fnqualnameZ	module_ormodule_namepathr   r   Zknown_python_builtin_modulesr~  rT   rT   rU   r   a  s    

	






"
z"SkipFunctionVariable.call_functionrz   c                 C   s   t jt| j|S rf   )r   r5   r~   r   r   r   rT   rT   rU   r     s    z%SkipFunctionVariable.call_obj_hasattrr   c                 C   s&   |t v rt| |S t|| j| j|S rf   )r(   r   r   r   r   r   r   rT   rT   rU   r     s    z SkipFunctionVariable.var_getattr)N)ra   rb   rc   r3   r   rV   r   r   r   r   r   r   r   r   rT   rT   r   rU   r}  I  s    

xr}  c                       sB   e Zd Zdd fddZddddd	 fd
dZdd Z  ZS )WrappedSkipFunctionVariableNr   c                    sD   | dd  | dd  t j|jfd|ji| || _|| _d S )Nr   r~  )rn   r   rV   r   r~  rT  r   rU  r   rT   rU   rV     s
    z$WrappedSkipFunctionVariable.__init__r9   r   r   r3   r   c                    s,   | j | t |||}| j | |S rf   rV  rX  r   rT   rU   r     s    z)WrappedSkipFunctionVariable.call_functionc                    s2      fdd  j  tdd d S )Nc                      s
    j S rf   rY  rT   rZ  rT   rU   r[    r   z9WrappedSkipFunctionVariable.reconstruct.<locals>.<lambda>r/   Fr\  r_  rT   rZ  rU   r    s    
z'WrappedSkipFunctionVariable.reconstructr`  rT   rT   r   rU   r    s   	r  c                       sT   e Zd ZdZdd fddZdd fdd	Zd
d Zdddd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".
    Nr   c                    s"   t  jf i | || _|| _d S rf   )r   rV   wrapper_objattr_to_trace)rQ   r  r  rs   r   rT   rU   rV     s    z$WrapperUserFunctionVariable.__init__r9   rz   c                    sF   || j kr8t| j| j }| jo(t| j|}t|||S t ||S rf   )	r  r   r  r   r"   r3   r|   r   r   )rQ   rq   rv   r   r   r   rT   rU   r   	  s
    
z'WrapperUserFunctionVariable.var_getattrc                 C   s   g S rf   rT   r   rT   rT   rU   r     s    z%WrapperUserFunctionVariable.self_argsr   r   r3   r   c                 C   s  t | jdrt| j| jd }t|ddp*d}|jdddd dkrd	}tjj| tjjj	
d
}|t	jrtjj }t | }|d j|d jf}	dt|}
d|	d  d|	d  d}|t|
7 }|| |  | }ttj|| t| jg||S )N
cache_inforb   rM  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DEBUGZ_guardsZTracingContextextract_stackr   filenamelinenor  	tracebackformat_listr   debugr   r   r   r   Zgetattr_and_tracer   r5   )rQ   rq   rr   rs   Z	target_fnr  r   Zdynamo_loggerZ
user_stackZ	frame_locZuser_stack_formattedZuser_stack_traceall_argsrT   rT   rU   r     s0    

z)WrapperUserFunctionVariable.call_function)	ra   rb   rc   r   rV   r   r   r   r   rT   rT   r   rU   r    s   r  c                       s.   e Zd ZdZd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.
    Nr   c                    s    t  j||fi | || _d S rf   rI  )rQ   r  r  Zself_objrs   r   rT   rU   rV   D  s    z"WrapperUserMethodVariable.__init__c                 C   s   | j gS rf   rJ  r   rT   rT   rU   r   H  s    z#WrapperUserMethodVariable.self_args)ra   rb   rc   r   rV   r   r   rT   rT   r   rU   r  =  s   r  c                  C   s   t j rddlm}  | S i S )Nr   traceable_collective_remaps)r   distributedis_available)torch.distributed._functional_collectivesr  r  rT   rT   rU   _traceable_collective_remapsL  s    
r  c                 C   s>   t j sJ d|t  v s$J |j}| d}t||S )NzIllegal invocation.z)torch.distributed._functional_collectives)r   r  r  r  valuesra   Zimport_sourcer"   )rq   r   Z
inner_nameZpath_sourcerT   rT   rU   _traceable_collectives_sourceW  s
    
r  c                       sj   e Zd ZdZdd fddZedddd	Zed
d ZeddddZdddddddZ	  Z
S )!CollectiveFunctionRewriteVariablea  
    Some of the torch.distributed.* collective APIs are possible to rewrite to 'traceable' collectives.

    This class provides both a way to check if a function is remappable, and perform the remapping.

    In the case that a function is 'remappable' but only for some combinations of call-time arguments,
    we check the args at `call_function` time and fall back to graph-breaking if needed.  This is no worse
    than status-quo as we currently graph-break on all distributed.* collectives.
    Nr   c                   s,   t  j|fi | t|ts"J || _d S rf   )r   rV   r{   r   replacement_var)rQ   r   r  rs   r   rT   rU   rV   k  s    z*CollectiveFunctionRewriteVariable.__init__r9   rz   c                 K   s6   t | |\}}t |ft|fd|i||d|S )Nr   )r  r   )r  rewriter   )rq   Zold_fnr   optionsnew_fnZ
new_sourcerT   rT   rU   r~   p  s    z(CollectiveFunctionRewriteVariable.createc                 C   s   t | o| t v S rf   )r   
isfunctionr  )variablerT   rT   rU   can_rewritez  s    z-CollectiveFunctionRewriteVariable.can_rewritec                 C   s   t  | }|t| |fS rf   )r  r  )rq   r   r  rT   rT   rU   r    s    
z)CollectiveFunctionRewriteVariable.rewriter   r   r3   r   c           	      C   s   dd l m} ddlm} t| j}t|j|i |j	}d}d|v r|d 
 rtd| j d|d|d| j g tjd	 | j|j|j|jfv r|d
}|d ur|jn
|jd
 j}||vrtd| tj|| |d
< | j|||S )Nr   )REDUCE_OP_TO_STRrT   Z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: )Ztorch.distributedr  r  r  r   r   r   r[   r   rv  r   r   r   SUPPORTABLEZ
all_reduceZreduce_scatter_tensorZ_reduce_scatter_baserh   r   r   defaultr   r   r5   r~   r  r   )	rQ   rq   rr   rs   distr  r   Zreduce_op_varZ	reduce_oprT   rT   rU   r     s<    	
	

z/CollectiveFunctionRewriteVariable.call_function)ra   rb   rc   r   rV   r  r~   r  r  r   r   rT   rT   r   rU   r  `  s   
	
r  c                       s(   e Zd Zddddd fddZ  ZS )FunctoolsWrapsVariabler9   r   r   r3   r   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   )rl  zfunctools.wrapsz]`torch.compile` can't trace `functools.wraps` on functions defined outside the compile regionr   )r{   r   r   cloner   r   r  r   rr   rT   rU   rz    s    z3FunctoolsWrapsVariable.call_function.<locals>.wraps)r]   r   ZLambdaVariabler   r   )rQ   rq   rr   rs   rz  r   r  rU   r     s    
z$FunctoolsWrapsVariable.call_function)ra   rb   rc   r   r   rT   rT   r   rU   r    s
   r  c                   @   s(   e Zd Zdd Zddddddd	Zd
S )CollectionsNamedTupleFunctionc                 C   s   | j S rf   r   r   rT   rT   rU   r     s    z0CollectionsNamedTupleFunction.as_python_constantr9   r   r   r3   r   c                 C   sl   t ||}|rF| 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   s   g | ]}|  qS rT   r   re  rT   rT   rU   r     r   z?CollectionsNamedTupleFunction.call_function.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS rT   r   rg  rT   rT   rU   r     r   z?CollectionsNamedTupleFunction.call_function.<locals>.<dictcomp>rj  znamedtuple constructionzargs=r  z?`torch.compile` only support certain input types for namedtupler   )	r&   r   r   r   ZUserDefinedClassVariabler2   r   r   r  )rQ   rq   rr   rs   constant_argsr   rT   rT   rU   r     s$    
z+CollectionsNamedTupleFunction.call_functionN)ra   rb   rc   r   r   rT   rT   rT   rU   r    s   r  c                       s   e Zd Zedd fddZdd Zddd	d
Zdd ZdddddddZde	edddZ
de	dddZdd Zdd Z  ZS )FunctoolsPartialVariableNrd   c                    sP   t  jf i | || _t|ts&J || _t|ts:J || _t	t
| _d S rf   )r   rV   rA   r{   rp   rr   r[   keywordsry  partialr*   Z
fake_value)rQ   rA   rr   r  rs   r   rT   rU   rV     s    z!FunctoolsPartialVariable.__init__c                 C   s   t jS rf   )ry  r  r   rT   rT   rU   r     s    z$FunctoolsPartialVariable.python_typer7   r  c                    s      fdd  | j | jr. | j | jsR tt| jd d d S  | j  t	| j
 }  t|t| j d |d d S )Nc                      s     ddS )Nry  r  r{  rT   r  rT   rU   r[    r   z6FunctoolsPartialVariable.reconstruct.<locals>.<lambda>r/   F)r]  rA   rr   foreachr  r^  r   r]   r  ro   rC  Zcreate_call_function_kw)rQ   r  rC  rT   r  rU   r    s    
z$FunctoolsPartialVariable.reconstructc                 C   s   |   S rf   r   r   rT   rT   rU   r   	  s    z%FunctoolsPartialVariable.get_functionr9   r   r   r3   r   c                 C   s(   | j | }i | j|}| j|||S rf   )rr   r  rA   r   )rQ   rq   rr   rs   Zmerged_argsZmerged_kwargsrT   rT   rU   r     s    
z&FunctoolsPartialVariable.call_functionr   c                 C   s   t jttt|S rf   )r   r5   r~   r   ry  r  r*   r   rT   rT   rU   r     s    z)FunctoolsPartialVariable.call_obj_hasattrr   c                 C   s   | j ot| j |}|dkr | jS |dkr8tj| j|dS |dkrbdd | j D }tj||dS |t	v rvt
| |S tt| d S )NrA   rr   r   r  c                 S   s   i | ]\}}t ||qS rT   )r5   r~   rg  rT   rT   rU   r   &  r   z8FunctoolsPartialVariable.var_getattr.<locals>.<dictcomp>)r   r"   rA   r   ListVariablerr   r  r   ConstDictVariabler(   r   r   r   )rQ   rq   rv   r   r   rT   rT   rU   r     s    z$FunctoolsPartialVariable.var_getattrc                 C   s:   t j| j gdd | jD R i dd | j D S )Nc                 S   s   g | ]}|  qS rT   r   r   rT   rT   rU   r   /  r   z?FunctoolsPartialVariable.as_python_constant.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS rT   r   rg  rT   rT   rU   r   0  r   z?FunctoolsPartialVariable.as_python_constant.<locals>.<dictcomp>)ry  r  rA   r   rr   r  r   r   rT   rT   rU   r   ,  s    z+FunctoolsPartialVariable.as_python_constantc                 C   s:   t j| j gdd | jD R i dd | j D S )zcSimilar to as_python_constant(), but add ID_MATCH guards to try to force things to become constantsc                 S   s   g | ]}|  qS rT   guard_as_python_constant)r   r   rT   rT   rU   r   7  r   zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS rT   r  rg  rT   rT   rU   r   8  r   zEFunctoolsPartialVariable.guard_as_python_constant.<locals>.<dictcomp>)ry  r  rA   r  rr   r  r   r   rT   rT   rU   r  3  s    z1FunctoolsPartialVariable.guard_as_python_constant)ra   rb   rc   r3   rV   r   r  r   r   r   r   r   r   r  r   rT   rT   r   rU   r    s   r  c                       s   e Zd ZdddhejZeejee	de
f ejf dddZedd	 Zed
d fddZeedddZdd Zdd ZdddddddZddddddZdd Z  ZS ) PolyfilledFunctionVariabler   rl  traceable_fn.r   c                 C   s   i S rf   rT   )r   rT   rT   rU   _get_polyfill_handlersD  s    z1PolyfilledFunctionVariable._get_polyfill_handlersc                 C   s   t |tj | ||dS r   )r!   r   r    r  r   rT   rT   rU   r   I  s    z-PolyfilledFunctionVariable.create_with_sourceN)r   re   c                    s   t  jf i | || _|  ||}t|sDJ d| d| dD ](}t||d }|rHt|shJ |} qqHt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 function)
r   rV   r   r  rh   callabler   r   rl  r  )rQ   r   rs   handlerZcandidate_attr	candidater  r   rT   rU   rV   O  s    
z#PolyfilledFunctionVariable.__init__c                 C   s   | j S rf   )r  r   rT   rT   rU   polyfill_fnf  s    z&PolyfilledFunctionVariable.polyfill_fnc                 C   s   t | jddS )NZ*__torch_dynamo_can_constant_fold_through__F)r   rl  r   rT   rT   rU   can_constant_fold_throughj  s    z4PolyfilledFunctionVariable.can_constant_fold_throughc                 C   s   |   S rf   r   r   rT   rT   rU   r   o  s    z'PolyfilledFunctionVariable.get_functionr9   r   r   r3   r   c              
   C   s   |   rFt||rF| jdd |D i dd | D }t||S | jtju rt|dkr|st	|d t
jt
jfrtdd |d jD rt
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   s   g | ]}|  qS rT   r   re  rT   rT   rU   r   }  r   z<PolyfilledFunctionVariable.call_function.<locals>.<listcomp>c                 S   s   i | ]\}}||  qS rT   r   rg  rT   rT   rU   r   ~  r   z<PolyfilledFunctionVariable.call_function.<locals>.<dictcomp>r/   r   c                 s   s>   | ]6}t |tjrt |jtp4t |tjo4| tu V  qd S rf   )r{   r   r5   r   intSymNodeVariabler   re  rT   rT   rU   r.    s   z;PolyfilledFunctionVariable.call_function.<locals>.<genexpr>r   c                 s   s   | ]}|  V  qd S rf   as_proxy)r   arT   rT   rU   r.    r   c                 S   s$   g | ]}t |tjr|jn|jqS rT   )r{   r   r5   r   sym_numre  rT   rT   rU   r     s   
)r  )r  r'   r   r   r3   r|   r<  sumr]   r{   r   r  TupleVariabler3  r  r~   r   create_proxyr   Zsym_sumro   r  r   )rQ   rq   rr   rs   r   Ztraceable_function_variablerT   rT   rU   r   r  sL    


z(PolyfilledFunctionVariable.call_functionrr   rs   re   c                 C   s   |dkr|  |||S t| j|d }|d usBJ d| d| j t|s`J d| d| j i }| jrzt| 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"   r  )rQ   rq   rv   rr   rs   methodr  Zpolyfilled_method_variablerT   rT   rU   r    s    z&PolyfilledFunctionVariable.call_methodc                 C   s   | j S rf   r   r   rT   rT   rU   r     s    z-PolyfilledFunctionVariable.as_python_constant)ra   rb   rc   r3   r   r   ry  cacher[   r   r   r   r   r  r   r<   rV   propertyr  r  r   r   r  r   r   rT   rT   r   rU   r  <  s4   $
8r  c                   @   s   e Zd Zdd ZdS )TracebackVariablec                 C   s   d S rf   rT   r   rT   rT   rU   r     r   zTracebackVariable.call_functionNra   rb   rc   r   rT   rT   rT   rU   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f i | || _d S rf   )r   rV   r   )rQ   r   rs   r   rT   rU   rV     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  )r]   Zexn_vt_stackr9  r3   r|   r   r5   r  )rQ   rq   Zexnr   tbr   rT   rT   rU   exc_info  s    



zSysFunctionVariable.exc_infoc                 C   s   |  |jd S rQ  )r  r   r   rT   rT   rU   	exception  s    zSysFunctionVariable.exceptionc                 C   s0   | j tju r| |S | j tju s&J | |S rf   )r   r5  r  r  r   rT   rT   rU   r     s    
z!SysFunctionVariable.call_function)ra   rb   rc   rV   r  r  r   r   rT   rT   r   rU   r    s   r  ) create_tma_experimental_metadatacreate_tma_stable_metadataTMADescriptorMetadataTritonHOPifierc                   @   s   e Zd ZeedddZeedddZeeddd	Z	e
ejjjd
f dddZdd Zdd Zdd Zdd ZeedddZdee ddddZedddZdS ) DynamoTritonHOPifier)r   re   c                 C   s   t |d S rf   )r   )rQ   r   rT   rT   rU   raise_unsupported  s    z&DynamoTritonHOPifier.raise_unsupported)maybe_callablere   c                 C   s   t |ttfS rf   )r{   r   r   )rQ   r  rT   rT   rU   is_callable  s    z DynamoTritonHOPifier.is_callable)r   re   c                 C   s   |j S rf   r  )rQ   r   rT   rT   rU   	get_value  s    zDynamoTritonHOPifier.get_value.r   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{   r  r   r   r   r  )rQ   gridr  rT   rT   rU   
check_grid  s    
zDynamoTritonHOPifier.check_gridc                 C   s&   dd |  D }|||gi }|S )Nc                 S   s   i | ]\}}t j||qS rT   r   r5   r~   rg  rT   rT   rU   r     r   z2DynamoTritonHOPifier.call_grid.<locals>.<dictcomp>)r   r   )rQ   r  metarq   rT   rT   rU   	call_grid  s    zDynamoTritonHOPifier.call_gridc           	      C   s*   ddl m} |||}||||}|S )Nr/   r  )r  r  r~   r   )	rQ   Zuser_fnrr   rs   rq   r  r  Zwrapped_user_functionr   rT   rT   rU   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_objrq   r  rv   r  Zwrapped_user_objrT   rT   rU   wrap_user_defined_obj  s    z*DynamoTritonHOPifier.wrap_user_defined_objc                 C   s   | |}dd |D }|S )Nc                 S   s   g | ]}|  qS rT   r  )r   r   rT   rT   rU   r      r   z=DynamoTritonHOPifier.maybe_unpack_configs.<locals>.<listcomp>)Zunpack_var_sequence)rQ   Zconfigsrq   rT   rT   rU   maybe_unpack_configs  s    
z)DynamoTritonHOPifier.maybe_unpack_configs)r   re   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   r   rT   rT   rU   maybe_unpack_heuristic_result$  s
    z2DynamoTritonHOPifier.maybe_unpack_heuristic_resultTritonKernelVariable)r  rr   re   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  rr   rT   rT   rU   call_getitem.  s    z!DynamoTritonHOPifier.call_getitemc                    s*  ddl m  ddlm} i }t| D ]2}|| }t|ttfr(|	 ||< |
 ||< q(dd | D }	ddlm}
m}  fdd| D } fd	d|	 D }| D ]4}| }t|tjtjfs| d
t| d q|
|}||t}|jd|d|j|||| d td S )Nr/   r4   )r  c                 S   s   i | ]\}}t j||qS rT   r  rg  rT   rT   rU   r   S  s   z1DynamoTritonHOPifier.call_HOP.<locals>.<dictcomp>r   )kernel_side_tabletriton_kernel_wrapper_mutationc                    s$   i | ]\}}t | r|| qS rT   )r{   r   rg  r4   rT   rU   r   `  s   
c                    s    i | ]\}}t | s||qS rT   )r{   rg  r4   rT   rU   r   e  s   
z.Unexpected argument type for a Triton kernel: r  r   rT   )r  constant_args_idxr  tma_descriptor_metadatars   )rN  r5   Zdictsr  rp   rC  r{   !TMADescriptorExperimentalVariableTMADescriptorStableVariableto_metadata
get_tensorr   *torch._higher_order_ops.triton_kernel_wrapr  r  r  Zrealizer   rb  r  r  reprZadd_constant_argsr[   r   r  r  r  )rQ   r  ZgridsZcombined_args_rawrq   r  r  r   r   Zcombined_argsr  r  r  Znon_constant_argsr   r  rT   r4   rU   call_HOP@  sT    



zDynamoTritonHOPifier.call_HOPN)ra   rb   rc   r   r
   r  r   r=  r  r  ro   r   ZfxproxyZProxyr  r  r  r  r  r  r   r  r5   r  rT   rT   rT   rU   r    s   	r  c                       s   e Zd ZU ded< ded< ee ed< ded< dd	 fd
dZdddddddZdddd fddZe	e	dddZ
  ZS )r  r:   r  r;   r  r  r"   r  Nr   c                    s4   | dd | _t jf i | t| ||| d S )Nr  )rn   r  r   rV    dynamo_triton_hopifier_singletonZinit_variable)rQ   r  r  r  rs   r   rT   rU   rV     s    zTritonKernelVariable.__init__r9   r   r   r3   r   c                 C   s   t | |||S rf   )r
  Zcall_triton_kernelr   rT   rT   rU   r     s    z"TritonKernelVariable.call_functionr  c                    s>   |dkrt | |S |dkr,t | |||S t ||||S )N__getitem__run)r
  r  Zcall_runr   r  rq  r   rT   rU   r    s
    z TritonKernelVariable.call_method)r   re   c                 C   s4   ddl m} ddlm} t||r0|| S |S )Nr/   r4   )r  )rN  r5   tensorr  r{   r~   Zevaluate_expr)rQ   r   r5   r  rT   rT   rU   specialize_symbolic  s
    
z(TritonKernelVariable.specialize_symbolic)ra   rb   rc   r   r   r  rV   r   r  r   r  r   rT   rT   r   rU   r    s   
r  c                       sF   e Zd Zddddd fddZdd Zd	d
ddZdd Z  ZS )r  zvariables.DataPtrVariablezlist[ConstantVariable]r5   data_ptrdims
block_dimselement_sizec                    s>   t |tjsJ t jf i | || _|| _|| _|| _d S rf   )	r{   r   DataPtrVariabler   rV   r  r  r  r  )rQ   r  r  r  r  rs   r   rT   rU   rV     s    z*TMADescriptorExperimentalVariable.__init__c                 C   s*   t dd | jD dd | jD | j S )Nc                 S   s   g | ]}|  qS rT   r  r   dimrT   rT   rU   r     r   zATMADescriptorExperimentalVariable.to_metadata.<locals>.<listcomp>c                 S   s   g | ]}|  qS rT   r  r  rT   rT   rU   r     r   )r  r  r  r  r  r   rT   rT   rU   r    s
    z-TMADescriptorExperimentalVariable.to_metadatar7   r  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_descriptorZcreate_Zd_tma_descriptor)rw  r]   r  rT   rZ  rT   rU   r[    s   z?TMADescriptorExperimentalVariable.reconstruct.<locals>.<lambda>r/   F)	r]  r  r  r  r  r  r  r   r]   )rQ   r  rr   rT   rZ  rU   r    s    
z-TMADescriptorExperimentalVariable.reconstructc                 C   s   | j jS rf   )r  from_tensorr   rT   rT   rU   r    s    z,TMADescriptorExperimentalVariable.get_tensorra   rb   rc   rV   r  r  r  r   rT   rT   r   rU   r    s   r  c                       sH   e Zd Zddd fddZdd Zdd	d
dZddddZ  ZS )r  zvariables.TensorVariablezvariables.ListVariabler  block_shapec                    s2   t |tjsJ t jf i | || _|| _d S rf   )r{   r   rb  r   rV   r  r  )rQ   r  r  rs   r   rT   rU   rV     s    z$TMADescriptorStableVariable.__init__c                 C   s   t | j S rf   )r  r  r  r   rT   rT   rU   r    s    z'TMADescriptorStableVariable.to_metadatar7   r  c                    s@      fdd  d | j   | j  d d S )Nc                      s     ddS )Nztriton.tools.tensor_descriptorZTensorDescriptorr{  rT   r  rT   rU   r[    s   z9TMADescriptorStableVariable.reconstruct.<locals>.<lambda>r  r   )r]  Zload_methodr  r  r  r  r_  rT   r  rU   r    s    


z'TMADescriptorStableVariable.reconstructr   c                 C   s   | j S rf   )r  r   rT   rT   rU   r    s    z&TMADescriptorStableVariable.get_tensorr  rT   rT   r   rU   r    s   r  c                       s8   e Zd Zedd fddZddddd	d
dZ  ZS )'CreateTMADescriptorExperimentalVariableN)rankre   c                    s(   |dv sJ t  jf i | || _d S )N)r/   r   )r   rV   r  )rQ   r  rs   r   rT   rU   rV    	  s    z0CreateTMADescriptorExperimentalVariable.__init__r9   r   r   r3   r   c                 C   s0  d|v r|d n|d }t |tjs6td| j d| jdkrt|t| dksXJ d|v rh|d n|d g}d|v r|d n|d	 g}nxt|t| d
ksJ d|v r|d n|d d|v r|d n|d	 g}d|v r|d n|d d|v r|d n|d g}d|v r|d n|d }t||||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  Z	block_dimr      Zdim1Zdim0Z
block_dim1r0  Z
block_dim0r  r  r  )r{   r   r  r   r  r]   r  )rQ   rq   rr   rs   r  r  r  r  rT   rT   rU   r   		  s6    
z5CreateTMADescriptorExperimentalVariable.call_function)ra   rb   rc   r  rV   r   r   rT   rT   r   rU   r    s   r  c                   @   s    e Zd ZdddddddZdS )	!CreateTMADescriptorStableVariabler9   r   r   r3   r   c                 C   s<   d|v r|d n|d }d|v r(|d n|d }t ||dS )Nr  r   r  r/   r  )r  )rQ   rq   rr   rs   r  r  rT   rT   rU   r   5	  s    z/CreateTMADescriptorStableVariable.call_functionNr  rT   rT   rT   rU   r  4	  s
   r  )N)r   r<  ry  r   r   r  r5  r  r   collections.abcr   r   typingr   r   r   r   r	   Ztyping_extensionsr
   Zunittest.mockr   weakrefr   r   Ztorch._dynamo.excr   rM  r   r   r   r   Zbytecode_transformationr   r   r   r(  r   r   r   r   r   r   r   r   r   r   Zguardsr    r!   r   r"   r#   r$   r%   r   r&   r'   r(   r)   r*   r+   r,   r-   r.   baser0   r1   r2   r3   rN  r5   Z#torch.distributed.fsdp._fully_shardr6   ModuleNotFoundErrorZtorch._dynamo.codegenr7   r  r9   r  r:   r;   r<   rM   rO   rg   r@   rj   ry   rl   r   r[   r   r   r   r   r   r   r   r   r  r>  r?  rF  rG  rS  ra  r   r   r|  r}  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r
  r  r  r  r  r  rT   rT   rT   rU   <module>   s   0,
5" [  B
7
Y 4( A	TQ ! .'!5