U
    ªÊ¹jñÉ  ã                   @  sj  U d dl m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
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 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 m!Z! d dl"Z"d dl#Z"d dl$m%  m&Z' d dl(Z"d dl"m)Z) d d	l*m+Z+ d d
l,m-Z- d dl.m/Z/m0Z0 d dl1m2Z2m3Z3 d dl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z: ddl;m<Z< e�rœd dl=m>Z>m?Z?m@Z@mAZAmBZBmCZC n<eDe"jEjFjGƒD ],ZHeH Id¡�r¾�qªeJe"jEjFjGeHƒeKƒ eH< �qªddlLmMZMmNZNmOZOmPZPm%Z% ddlQmRZRmSZSmTZTmUZU ddlVmWZW ddlmXZX ddl%mYZY e Ze[¡Z\d dl]m^Z^ d dl_m`Z` e% a¡ ZbejcZdd dleZed dlfmgZg G dd„ deƒZhehjiZje
 k¡ Zldamdend < e oe7¡eeeepƒƒd!ƒhZqed"d#ƒZrd$d%d&œd'd(„ZsG d)d*„ d*e"jtjuƒZvd+d,„ Zwd-d.„ Zxd/d0„ Zyejzdnd2d3d4œd5d6„ƒZ{G d7d8„ d8ƒZ|G d9d:„ d:e|ƒZ}G d;d<„ d<e|ƒZ~G d=d>„ d>e|ƒZd?d@„ Z€dAdBœdCdD„Z�edd1ddfdAdBœdEdF„Z‚dGdH„ ZƒG dIdJ„ dJejcƒZ„dKdL„ Z…dMdN„ Z†dod1ddd1ddPœdQdR„Z‡e!dSdTƒdUdV„ ƒZˆG dWdX„ dXe"j6j‰jŠƒZ‹G dYdZ„ dZeƒZŒd[d\„ Z�d]d^„ ZŽd1d1dd_dd1dTd`œdad3d3dbdcddd3d3dedfœ	dgdh„Z�e<ddƒd1dddiœdjdk„Z�G dldm„ dmƒZ‘dS )pé    )ÚannotationsN)Ú
namedtuple)ÚEnum)ÚdirnameÚjoin)
ÚAnyÚCallableÚDictÚListÚ
NamedTupleÚOptionalÚSetÚTupleÚTYPE_CHECKINGÚUnion)Úpatch)Ú_guards)Úfake_tensor)Ú
Constraint)Úmake_fxÚmaybe_disable_fake_tensor_mode)Ú_PyTreeCodeGenÚ_PyTreeInfo)ÚDistributedDataParallelé   )ÚGraphModuleé   )Ú
CompilerFnÚlookup_backend)ÚHooks)Ú
reset_codeÚset_eval_frameÚset_guard_error_hookÚset_guard_fail_hookÚ	skip_codeÚunsupportedÚ__)ÚconfigÚconvert_frameÚexternal_utilsÚ	skipfilesÚutils)ÚCondOpArgsMismatchErrorÚResetRequiredÚ	UserErrorÚUserErrorType)Úinstall_generation_tagging_init)ÚDynamoCallback)Úcompile_times)Úenable_python_dispatcher)Ú_disable_current_modes)ÚConstraintViolationErrorc                   @  s   e Zd ZdZdS )ÚUnsetr   N)Ú__name__Ú
__module__Ú__qualname__Útoken© r;   r;   úW/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/_dynamo/eval_frame.pyr6   S   s   r6   zOptional[CompilerFn]Úmost_recent_backendz+onnx/_internal/fx/dynamo_graph_extractor.pyÚ
CacheEntryzcheck_fn, codeztypes.CodeTypezList[CacheEntry])ÚcodeÚreturnc                 C  s    t jjj | ¡}tttj|ƒƒS )zN
    Given a code object, retrieve the cache entries stored in this code.
    )	ÚtorchÚ_CÚ_dynamoÚ
eval_frameÚ_debug_get_cache_entry_listÚlistÚmapr>   Ú_make)r?   Z
cache_listr;   r;   r<   rE   e   s    rE   c                      sZ   e Zd ZdZddœ‡ fdd„Zdd„ Zdd	„ Zd
d„ Zdd„ Zdd„ Z	‡ fdd„Z
‡  ZS )ÚOptimizedModulezx
    Wraps the original nn.Module object and later patches its
    forward method to optimized self.forward method.
    ztorch.nn.Module)Úmodc                   s"   t ƒ  ¡  || _|| _|  ¡  d S ©N)ÚsuperÚ__init__Ú	_orig_modÚ
dynamo_ctxÚ_initialize)ÚselfrJ   rO   ©Ú	__class__r;   r<   rM   s   s    
zOptimizedModule.__init__c                 C  sj   t | jjtjƒr:t t | jj¡¡r:|  	t
 | j¡¡| _n|  	| jj¡| _t| jdƒrf| j| _| j| _d S )NÚ_initialize_hook)Ú
isinstancerN   ÚforwardÚtypesÚ
MethodTyper*   ÚcheckÚinspectÚgetsourcefilerO   r)   Úwrap_inlineÚ__call__ÚhasattrÚ_forwardÚ_call_lazy_check©rQ   r;   r;   r<   rP   z   s    ÿzOptimizedModule._initializec                 C  s&   t | jƒ}| dd ¡ | dd ¡ |S )NrV   r]   )ÚdictÚ__dict__Úpop©rQ   Ústater;   r;   r<   Ú__getstate__‹   s    
zOptimizedModule.__getstate__c                 C  s   || _ |  ¡  d S rK   )rc   rP   re   r;   r;   r<   Ú__setstate__‘   s    zOptimizedModule.__setstate__c                 C  s   |dkr| j d S t| j|ƒS )NrN   )Z_modulesÚgetattrrN   )rQ   Únamer;   r;   r<   Ú__getattr__•   s    
zOptimizedModule.__getattr__c                 O  s8   t | jdƒr,t|ƒdkst‚| j | j|¡ | j||ŽS )NrT   r   )r^   rN   ÚlenÚAssertionErrorZ_infer_parametersr_   )rQ   ÚargsÚkwargsr;   r;   r<   r`   š   s    z OptimizedModule._call_lazy_checkc                   s&   | j  ¡ ‰ ˆ ‡ fdd„tƒ  ¡ D ƒ S )Nc                   s   g | ]}|ˆ kr|‘qS r;   r;   )Ú.0Úattr©Zorig_mod_attrsr;   r<   Ú
<listcomp>¦   s     z+OptimizedModule.__dir__.<locals>.<listcomp>)rN   Ú__dir__rL   ra   rR   rr   r<   rt   ¤   s    
ÿzOptimizedModule.__dir__)r7   r8   r9   Ú__doc__rM   rP   rg   rh   rk   r`   rt   Ú__classcell__r;   r;   rR   r<   rI   m   s   
rI   c                 C  sn   t | tjƒrt| ƒ nTt| dƒr,t| jƒ n>tt| ddƒdƒrLt| jjƒ nddlm	} |ƒ  t
 d| ¡ dS )zA
    Make sure f.__code__ is not cached to force a recompile
    Ú__code__rV   Nr   ©Úresetz#could not determine __code__ for %s)rU   rW   ÚCodeTyper    r^   rw   ri   rV   Ú ry   ÚlogÚwarning)Úfry   r;   r;   r<   Úremove_from_cache«   s    

r   c                   C  s   d S rK   r;   r;   r;   r;   r<   Únothing¼   s    r€   c                 C  s&   | }t |dƒr"|j}t|ƒst‚q|S )zä
    In case of nesting of _TorchDynamoContext calls, find the innermost
    function. TorchDynamo caches on fn.__code__ object, so its necessary to find
    the innermost function to pass on the optimize, run, disable etc.
    Ú_torchdynamo_orig_callable)r^   r�   Úcallablerm   )ÚfnZunaltered_fnr;   r;   r<   Úinnermost_fnÀ   s
    
r„   FzOptional[bool]Úbool©ÚenableÚexportc              	   c  sX   | d krd V  nD| r4t jdd�� d V  W 5 Q R X n t jddd�� d V  W 5 Q R X d S )NF)Úassume_static_by_defaultT)Úautomatic_dynamic_shapesr‰   )r'   r   r†   r;   r;   r<   Úenable_dynamicÍ   s     ÿr‹   c                      sN   e Zd Zeeedfddddœddœ‡ fdd„Zdd	„ Zd
d„ Zdd„ Z‡  Z	S )Ú_TorchDynamoContextFN©rˆ   ÚdynamicÚcompiler_configr1   ©Úcallbackc          	        s`   t ƒ  ¡  t|ƒs&|dks&|d ks&t‚|| _t| _|| _|| _|| _	|| _
|| _|| _|ƒ  d S ©NF)rL   rM   r‚   rm   r‘   ÚunsetÚpriorÚon_enterÚextra_ctx_ctorÚ	first_ctxrˆ   rŽ   r�   )	rQ   r‘   r•   Úbackend_ctx_ctorÚpatch_fnr—   rˆ   rŽ   r�   rR   r;   r<   rM   Ý   s    
z_TorchDynamoContext.__init__c                 C  sT   t jrtdƒ‚|  ¡  t| jƒ| _|  ¡ | _| j 	¡  t
| j| jƒ| _| j 	¡  d S )NzÒtorch._dynamo.optimize(...) is used with a context manager. Please refer to https://pytorch.org/tutorials/intermediate/torch_compile_tutorial.html to use torch._dynamo.optimize(...) as an annotation/decorator. )r'   Zraise_on_ctx_manager_usageÚRuntimeErrorr•   r!   r‘   r”   r–   Úbackend_ctxÚ	__enter__r‹   rŽ   rˆ   Údynamic_ctxra   r;   r;   r<   rœ   õ   s    ÿ

z_TorchDynamoContext.__enter__c                 C  sB   | j tk	st‚t| j ƒ t| _ | j |||¡ | j |||¡ d S rK   )r”   r“   rm   r!   r�   Ú__exit__r›   )rQ   Úexc_typeÚexc_valÚexc_tbr;   r;   r<   rž     s
    
z_TorchDynamoContext.__exit__c                   sN  ‡fdd„}t ˆƒ‰tˆtjjƒrPˆ}t|ˆƒ}|j|_t|dƒrFt	‚||_
|S tˆƒs\t	‚zt ˆ¡}W n tk
r‚   d }Y nX |d ks–t |¡r¸tˆddƒdkr¸|tkr¸t ˆ¡‰ˆj‰ˆj‰ˆj‰ t ˆ¡‡ ‡‡‡‡fdd„ƒ}tˆtƒrúd	|_nˆ|_ˆ|_t|dƒ�rt	‚||_
ˆd
k�rJtˆdƒ�s@tt d¡ƒ‚d	t ˆj!< |S )Nc                     s   ˆ j S rK   )r�   r;   ra   r;   r<   Úget_compiler_config  s    z9_TorchDynamoContext.__call__.<locals>.get_compiler_configr¢   r7   r{   )Z
_call_implZ_wrapped_call_implc                    sœ   t ˆtƒs0tjj ¡ r0tjr&tdƒ‚n
ˆ| |ŽS ˆƒ  t	ˆƒ}ˆ ƒ }| 
¡  tˆjˆjƒ}| 
¡  zˆ| |ŽW ¢S t	|ƒ | d d d ¡ | d d d ¡ X d S )NzvDetected that you are using FX to symbolically trace a dynamo-optimized function. This is not supported at the moment.)rU   ÚDisableContextrA   ÚfxÚ_symbolic_traceZis_fx_tracingr'   Zerror_on_nested_fx_tracerš   r!   rœ   r‹   rŽ   rˆ   rž   )rn   ro   r”   r›   r�   ©r˜   r‘   rƒ   r•   rQ   r;   r<   Ú_fn3  s(    ÿ
þÿ
z)_TorchDynamoContext.__call__.<locals>._fnTr’   rw   aÏ  

                        torch._dynamo.optimize is called on a non function object.
                        If this is a callable class, please wrap the relevant code into a function and optimize the
                        wrapper function.

                        >> class CallableClass:
                        >>     def __init__(self):
                        >>         super().__init__()
                        >>         self.relu = torch.nn.ReLU()
                        >>
                        >>     def __call__(self, x):
                        >>         return self.relu(torch.sin(x))
                        >>
                        >>     def print_hello(self):
                        >>         print("Hello world")
                        >>
                        >> mod = CallableClass()

                        If you want to optimize the __call__ function and other code, wrap that up in a function

                        >> def wrapper_fn(x):
                        >>     y = mod(x)
                        >>     return y.sum()

                        and then optimize the wrapper_fn

                        >> opt_wrapper_fn = torch._dynamo.optimize(wrapper_fn)
                        )"r„   rU   rA   ÚnnÚModulerI   rV   r�   r^   rm   r¢   r‚   rZ   r[   Ú	TypeErrorr*   rY   ri   ÚDONT_WRAP_FILESr)   r\   r‘   r•   r–   Ú	functoolsÚwrapsr£   Z_torchdynamo_disableZ_torchdynamo_inlinerš   ÚtextwrapÚdedentÚalways_optimize_code_objectsrw   )rQ   rƒ   r¢   rJ   Únew_modÚfilenamer§   r;   r¦   r<   r]     sV    

ÿÿýû


ÿÿ!
z_TorchDynamoContext.__call__)
r7   r8   r9   r€   Únull_contextrM   rœ   rž   r]   rv   r;   r;   rR   r<   rŒ   Ü   s   úörŒ   c                      s4   e Zd Zedd„ ƒZdddddœ‡ fdd„Z‡  ZS )	ÚOptimizeContextc                 C  s   | |kp| d k S rK   r;   )ÚoldÚnewr;   r;   r<   Ú_different_backendˆ  s    z"OptimizeContext._different_backendFNr�   c             
     s6   ‡ fdd„}t |ƒ‰ tƒ j|||tj||||d� d S )Nc                     s2   t  tˆ ¡r$tjrtƒ ‚n
t d¡ ˆ atƒ  d S )Nz`changing options to `torch.compile()` may require calling `torch._dynamo.reset()` to take effect)	r´   r·   r=   r'   Zraise_on_backend_changer-   ÚwarningsÚwarnr0   r;   ©Úcompiler_fnr;   r<   r•   –  s    ÿz*OptimizeContext.__init__.<locals>.on_enter)r‘   r•   r˜   r™   r—   rˆ   rŽ   r�   )r„   rL   rM   ÚTorchPatcherr   )rQ   r‘   r˜   r—   rˆ   rŽ   r�   r•   rR   rº   r<   rM   Œ  s    
øzOptimizeContext.__init__)F)r7   r8   r9   Ústaticmethodr·   rM   rv   r;   r;   rR   r<   r´   ‡  s   
 üør´   c                      s   e Zd Z‡ fdd„Z‡  ZS )ÚRunOnlyContextc                   s   dd„ }t ƒ jd|d� d S )Nc                   S  s   t jjj jd7  _d S )Nr   )rA   rC   Úmutation_guardZGenerationTrackerZ
generationr;   r;   r;   r<   r•   ³  s    z)RunOnlyContext.__init__.<locals>.on_enterF)r‘   r•   ©rL   rM   )rQ   r•   rR   r;   r<   rM   ±  s    zRunOnlyContext.__init__©r7   r8   r9   rM   rv   r;   r;   rR   r<   r¾   °  s   r¾   c                      s   e Zd Z‡ fdd„Z‡  ZS )r£   c                   s   t ƒ jd d� d S )Nr�   rÀ   ra   rR   r;   r<   rM   º  s    zDisableContext.__init__rÁ   r;   r;   rR   r<   r£   ¹  s   r£   c                 C  sB   t jdk rdS t | ¡D ]}|jdkr|jd   S qtdƒ‚d S )N)é   é   r   ÚRESUMEr   z$RESUME instruction not found in code)ÚsysÚversion_infoÚdisÚget_instructionsÚopnameÚoffsetrš   )r?   Úinstr;   r;   r<   Úfirst_real_inst_idx¾  s    

rÌ   r   ©Úhooksc                   s"   t  ˆ ¡‡ ‡fdd„ƒ}ˆ |_|S )Nc                   s   |d k	st ‚| jt| jƒks0t | jj¡s0tjrJt	 
d| jj| jj¡ d S | jjdkrf| jjdkrfd S tjrØt ¡ }|rØt�V ddlm} ||jˆ jd�}tˆ dƒs¬t dƒ‚ˆ  |j¡}|| |ˆ|ƒW  5 Q R £ S Q R X t�: tƒ �( ˆ | |ˆ|ƒW  5 Q R £ W  5 Q R £ S Q R X W 5 Q R X d S )	Nzskipping %s %sz<string>Ú__new__r   )ÚDDPOptimizer)Úbucket_bytes_capZbackend_compile_fnÚ_clone_with_backendzJDDPOptimizer only supports callback fns that know how to clone themselves.)rm   Úf_lastirÌ   Úf_coder*   rY   Úco_filenamer'   Údisabler|   ÚdebugÚco_nameZoptimize_ddpr   Z_get_active_ddp_moduleÚcompile_lockZ"torch._dynamo.backends.distributedrÐ   rÑ   r�   r^   rÒ   Ú
compile_fnr4   )ÚframeÚcache_entryZframe_stateZ
ddp_modulerÐ   Zddp_optimizerZhijacked_callback©r‘   rÎ   r;   r<   Úcatch_errorsÈ  s@    þýüþ ÿþÿ z*catch_errors_wrapper.<locals>.catch_errors)r¬   r­   r�   )r‘   rÎ   rÞ   r;   rÝ   r<   Úcatch_errors_wrapperÇ  s    #rß   c                 C  s   t t| |ƒ|d|||d�S )NT)r˜   r—   rˆ   rŽ   r�   )r´   rß   )rÚ   rÎ   r˜   rˆ   rŽ   r�   r;   r;   r<   Ú_optimize_catch_errorsð  s    úrà   c                 C  sD   ddl m} t| dƒr| j}nt| tƒr.| }nd }t| ƒ} || |ƒS )Nr   )Úwrap_backend_debugÚcompiler_name)Zrepro.after_dynamorá   r^   râ   rU   Ústrr   )r»   rá   Zcompiler_strr;   r;   r<   Úget_compiler_fn  s    

rä   c                   @  s   e Zd Zdd„ ZdS )Ú_NullDecoratorc                 C  s   t |ƒst‚|S rK   )r‚   rm   )rQ   rƒ   r;   r;   r<   r]     s    z_NullDecorator.__call__N)r7   r8   r9   r]   r;   r;   r;   r<   rå     s   rå   c                   C  s(   t jdkrtdƒ‚t jdkr$tdƒ‚d S )NÚwin32z+Windows not yet supported for torch.compile)rÂ   é   z0Python 3.12+ not yet supported for torch.compile)rÅ   Úplatformrš   rÆ   r;   r;   r;   r<   Úcheck_if_dynamo_supported  s    

ré   c                   C  s(   zt ƒ  W dS  tk
r"   Y dS X d S )NTF)ré   Ú	Exceptionr;   r;   r;   r<   Úis_dynamo_supported  s
    rë   Úinductor)ÚnopythonÚguard_export_fnÚguard_fail_fnrÖ   rŽ   c                C  sŽ   t ƒ  t||d�}tj d¡ |s4tj dd¡dkr:tƒ S t	| ƒ} t
| dtƒ}|r`t| ||d�S ttj| |d�|||t| d	ƒr†|  ¡ nd
d�S )aŸ  
    The main entrypoint of TorchDynamo.  Do graph capture and call
    backend() to optimize extracted graphs.

    Args:
        backend: One of the two things:
            - Either, a function/callable taking a torch.fx.GraphModule and
            example_inputs and returning a python callable that runs the
            graph faster.
            One can also provide additional context for the backend, like
            torch.jit.fuser("fuser2"), by setting the backend_ctx_ctor attribute.
            See AOTAutogradMemoryEfficientFusionWithContext for the usage.
            - Or, a string backend name in `torch._dynamo.list_backends()`
        nopython: If True, graph breaks will be errors and there will
            be a single whole-program graph.
        disable: If True, turn this decorator into a no-op
        dynamic: If True, upfront compile as dynamic a kernel as possible.  If False,
            disable all dynamic shapes support (always specialize).  If None, automatically
            detect when sizes vary and generate dynamic kernels upon recompile.

    Example Usage::

        @torch._dynamo.optimize()
        def toy_example(a, b):
            ...
    ©rî   rï   ztorch._dynamo.optimizeZTORCHDYNAMO_DISABLEr{   Ú1r˜   )rŽ   rÎ   rÍ   r¢   N)rŽ   r�   )ré   r   rA   rB   Ú_log_api_usage_onceÚosÚenvironÚgetrå   rä   ri   r³   Úoptimize_assertrà   r(   r^   r¢   )Úbackendrí   rî   rï   rÖ   rŽ   rÎ   r˜   r;   r;   r<   Úoptimize$  s,    #ýÿ
ùrø   z&torch._dynamo.symbolic_convert.explainTc                   s0   ‡ fdd„}|s|r(t  d¡ |||ŽS |S d S )Nc               	     s8  ddl m} |ƒ  g ‰g ‰ d‰g ‰g ‰ddœ‡ ‡‡‡fdd„}‡fdd	„}tt› d
�d ƒ�" t|d|d�ˆƒ}|| |Ž W 5 Q R X tˆƒ}i }ˆ D ]}|jd }	||t|	ƒ< q’d}
t| 	¡ ƒD ]>\}}d 
t |j¡¡}|d › d|j› d|› d�}|
|7 }
q¾|d }tdd�}|ƒ  ddlm} |ˆ||ˆ ˆˆˆ|ƒS )Nr   rx   r   útorch.fx.GraphModule©Úgmc                   s,   ddl m} || ˆˆˆˆ ƒ\} ‰‰‰‰ | jS )Nr   )Ú_explain_graph_detail)Úbackends.debuggingrü   rV   )rû   Úexample_inputsrü   )Úbreak_reasonsÚgraphsÚop_countÚops_per_graphr;   r<   Ú"dynamo_graph_accumulating_compilerw  s        ÿzBexplain.<locals>.inner.<locals>.dynamo_graph_accumulating_compilerc                   s   ˆ   | ¡ d S rK   )Úextend©Úguards©Ú
out_guardsr;   r<   Úguard_export_print‡  s    z2explain.<locals>.inner.<locals>.guard_export_printú.most_recent_backendF)rí   rî   éÿÿÿÿr{   z
. Reason: z
   User Stack: Ú
rã   )Úrepr)ÚExplainOutput)r{   ry   r   r7   rø   rl   Z
user_stackr  Ú	enumerateÚvaluesr   Ú	tracebackÚformat_listÚreasonr2   rý   r  )rn   ro   ry   r  r	  Úopt_fZgraph_countZdeduped_reasonsr  Zinnermost_frameZformatted_listÚidxZbreak_reasonZformatted_stackÚmsgZgraph_break_countZcompile_timer  ©r~   )rÿ   r   r  r  r  r<   Úinnerk  sT    ýü


øzexplain.<locals>.innerzäexplain(f, *args, **kwargs) is deprecated, use explain(f)(*args, **kwargs) instead.  If you don't migrate, we may break your explain call in the future if your user defined kwargs conflict with future kwargs added to explain(f).©r¸   r¹   )r~   Ú
extra_argsÚextra_kwargsr  r;   r  r<   Úexplaini  s    Jÿ
r  c                      sN   e Zd Zddddddddœ‡ fdd	„Zd
d„ Z‡ fdd„Z‡ fdd„Z‡  ZS )ÚFlattenInputOutputSignatureNrù   z
Tuple[Any]z	List[int]zList[torch.Tensor]z$Optional[fake_tensor.FakeTensorMode])ÚmÚ	flat_argsÚ matched_input_elements_positionsÚ!matched_output_elements_positionsÚexample_fake_inputsÚ	fake_modec           
        sÄ   t ƒ  |¡ ‡ fdd„t|ƒD ƒ}g ˆ_tdt|ƒƒD ]n}t ƒ  d|› �di ¡}	||krj|| |	jjd< n.|d k	r˜t	|| t
jƒr˜| || ¡|	jjd< ˆj |	¡ q6‡fdd„|D ƒˆ_|ˆ_d S )	Nc                   s   i | ]\}}|ˆ | “qS r;   r;   )rp   ZixÚval)r"  r;   r<   Ú
<dictcomp>Ì  s   ÿ z8FlattenInputOutputSignature.__init__.<locals>.<dictcomp>r   Úargr;   r$  c                 3  s   | ]}ˆ j | V  qd S rK   )Únew_args©rp   Úira   r;   r<   Ú	<genexpr>Ü  s     z7FlattenInputOutputSignature.__init__.<locals>.<genexpr>)rL   rM   r  r'  Úrangerl   ÚplaceholderÚnodeÚmetarU   rA   ÚTensorÚfrom_tensorÚappendÚold_args_genr!  )
rQ   r  r  r   r!  r"  r#  Zmatched_input_elements_to_faker)  r&  rR   )r"  rQ   r<   rM   Á  s    	
þz$FlattenInputOutputSignature.__init__c                 C  sN   t | jƒ}d| jjkr*| jjd |jjd< d| jjkrJ| jjd |jjd< |S )Nr$  Ztensor_dict)Únextr2  Úcurrent_noder.  r-  )rQ   Útargetrn   ro   r&  r;   r;   r<   r,  ß  s    
z'FlattenInputOutputSignature.placeholderc                   s8   |d }|| j •‰ ‡ fdd„| jD ƒ}tƒ  ||fi ¡S )Nr   c                   s   g | ]}ˆ | ‘qS r;   r;   r(  ©Úlookupr;   r<   rs   ê  s     z6FlattenInputOutputSignature.output.<locals>.<listcomp>)r'  r!  rL   Úoutput)rQ   r5  rn   ro   Zdynamo_result_flatZnew_result_flatrR   r6  r<   r8  ç  s    
z"FlattenInputOutputSignature.outputc                   s6   || _ tƒ  |¡}d| j jkr2| j jd |jjd< |S )Nr$  )r4  rL   Úrun_noder.  r-  )rQ   ÚnÚrrR   r;   r<   r9  í  s
    z$FlattenInputOutputSignature.run_node)N)r7   r8   r9   rM   r,  r8  r9  rv   r;   r;   rR   r<   r  À  s
    ùr  c                   @  s   e Zd ZU ded< ded< dS )ÚExportResultrù   Zgraph_moduleúSet[_guards.Guard]r  N)r7   r8   r9   Ú__annotations__r;   r;   r;   r<   r<  õ  s   
r<  c           
      C  s  g }| j jD ]Ø}|jdkrt|dƒs(t‚|j}| j |¡}|d krDqt|ƒdksTt‚d }|D ]}t|ƒdkrnq\|} qxq\|d kr�| 	¡ › d�}nJd 
t |¡¡}d}	t|ƒdkrÄdt|ƒd › d�}	| 	¡ › d	|› |	› �}| |¡ q|�rttjd
d 
|¡ ƒ‚d S )Nr,  Ú_dynamo_sourcer   z, a closed over free variabler{   r   z(elided z more accesses)z, accessed at:
a�  Cannot export model which references tensors that are neither buffers/parameters/constants nor are direct inputs.  For each tensor, if you'd like this tensor to be an explicit input, add it as a dummy argument to the top-level model definition you are exporting; if you would like its value to be embedded as an exported constant, wrap its access in a function marked with @assume_constant_result.

z

)ÚgraphZnodesÚopr^   rm   r?  Ú_source_to_user_stacksrõ   rl   rj   r   r  r  r1  r.   r/   ZINVALID_INPUT)
r@  Zinput_errorsr-  ÚsourceZuser_stacksÚstackÚsr  ÚtbÚextrar;   r;   r<   Úcheck_signature_rewritableü  s<    
úþrH  c	                 C  s¬   t  ||¡\}	}
dd„ }|d|id|id�}t  |¡\}}|d k	sFt‚|t|ƒ|dœd|id�}t||||||ƒ ¡ }dd	œd
d„}tt|| |	|
ƒ||ƒƒ|j	_
| ¡  |S )Nc           
   
   S  sB  d  dd„ |  ¡ D ƒ¡}dd„ |  ¡ D ƒ}g }tƒ }t|ƒD ]\}}||t|ƒ< q<| ¡ D ]â\}}	t|	ƒD ]Ð\}}t|tjƒrøt 	|¡dkrøt|ƒ|kr¬| 
|t|ƒ ¡ nJt| ¡ ƒ|krÔ| 
|t| ¡ ƒ ¡ n"t|› d|› dt|ƒ› d|› �ƒ‚qjt|ƒ|k�r(t|› d|› dt|ƒ› d|› �ƒ‚| 
|t|ƒ ¡ qjqZ|S )	Nz or c                 S  s0   g | ](\}}|d  d  dd„ |D ƒ¡ d ‘qS )ú (z, c                 S  s   g | ]}t t|ƒƒ‘qS r;   )rã   Útype)rp   r&  r;   r;   r<   rs   6  s     zJrewrite_signature.<locals>.produce_matching.<locals>.<listcomp>.<listcomp>ú))r   )rp   Údescrn   r;   r;   r<   rs   5  s   ÿz?rewrite_signature.<locals>.produce_matching.<locals>.<listcomp>c                 S  s   g | ]}|D ]}|‘qqS r;   r;   )rp   rn   r&  r;   r;   r<   rs   :  s       r   z #rI  z) is not among )r   Úitemsr  rb   r  ÚidrU   rA   r/  Znumelr1  Úitemrm   rJ  )
ÚsourcesÚ
candidatesZsource_typesZsource_argsZmatched_elements_positionsZdict_of_source_argsr)  r&  Zcandidate_descZcandidate_argsr;   r;   r<   Úproduce_matching3  s8    þÿÿÿÿz+rewrite_signature.<locals>.produce_matchingúoriginal argszgraph-captured input)rP  rQ  )zgraph-captured outputsrS  ztraced resultz	List[str])r@   c                   s
  ddœdd„}|| ƒ‰ ˆ j d t|ƒ… }t|ƒtˆ j ƒkrvˆ jd k	sLtdƒ‚|‡ fdd„tdt|ƒt|ƒ ƒD ƒ7 }nLt|ƒtˆ j ƒk rÂˆ j t|ƒtˆ jpœg ƒ … D ]}||ks¦td	|› �ƒ‚q¦|t| ¡ ƒ7 }ˆ jD ],}ˆ j	päi }||ksØ||ksØtd
|› �ƒ‚qØ|S )Nzinspect.Signature)Úsigc           
   	   S  s²   t | j ¡ ƒ}dd„ |D ƒ}dd„ |D ƒ}tdd„ |D ƒd ƒ}tdd„ |D ƒd ƒ}tdd„ |D ƒƒ}dd	„ |D ƒ}i }| jr†d
| ji}|D ]}	|	j||	j< qŠt 	|||||||¡S )Nc                 S  s    g | ]}|j tjjkr|j‘qS r;   )ÚkindrZ   Ú	ParameterÚPOSITIONAL_OR_KEYWORDrj   ©rp   Úpr;   r;   r<   rs   v  s   þz_rewrite_signature.<locals>.argument_names.<locals>.signature_to_fullargspec.<locals>.<listcomp>c                 S  s    g | ]}|j tjjkr|j‘qS r;   )rU  rZ   rV  ÚKEYWORD_ONLYrj   rX  r;   r;   r<   rs   {  s     c                 s  s"   | ]}|j tjjkr|jV  qd S rK   )rU  rZ   rV  ÚVAR_POSITIONALrj   rX  r;   r;   r<   r*    s      z^rewrite_signature.<locals>.argument_names.<locals>.signature_to_fullargspec.<locals>.<genexpr>c                 s  s"   | ]}|j tjjkr|jV  qd S rK   )rU  rZ   rV  ÚVAR_KEYWORDrj   rX  r;   r;   r<   r*  ƒ  s      c                 s  s0   | ](}|j tjjkr|jtjjk	r|jV  qd S rK   )rU  rZ   rV  rW  ÚdefaultÚemptyrX  r;   r;   r<   r*  ‡  s   ýc                 S  s2   i | ]*}|j tjjkr|jtjjk	r|j|j“qS r;   )rU  rZ   rV  rZ  r]  r^  rj   rX  r;   r;   r<   r%  �  s
   ý z_rewrite_signature.<locals>.argument_names.<locals>.signature_to_fullargspec.<locals>.<dictcomp>r@   )
rF   Ú
parametersr  r3  ÚtupleÚreturn_annotationÚ
annotationrj   rZ   ÚFullArgSpec)
rT  Úparamsrn   Ú
kwonlyargsÚvarargsÚvarkwÚdefaultsÚkwonlydefaultsr   Z	parameterr;   r;   r<   Úsignature_to_fullargspecr  sF    þÿþþþþ
      ÿzKrewrite_signature.<locals>.argument_names.<locals>.signature_to_fullargspeczMore arguments than expectedc                   s   g | ]}ˆ j › d |› �‘qS )Ú_)rf  r(  ©Zfullargspecr;   r<   rs   §  s   ÿz=rewrite_signature.<locals>.argument_names.<locals>.<listcomp>r   zMissing argument zMissing keyword only argument )
rn   rl   rf  rm   r+  rh  rF   Úkeysre  ri  )Úf_sigrn   ro   rj  Z
input_strsZunprovided_argZ
kwonly_argri  r;   rl  r<   Úargument_namesq  s0    ,þ
 ÿ


ÿÿþz)rewrite_signature.<locals>.argument_names)ÚpytreeZtree_unflattenÚtree_flattenrm   rF   r  Z	transformr   r   r@  Z_codegenZ	recompile)rn  r@  r#  r  Úin_specr"  Úgraph_captured_inputZgraph_captured_outputZdynamo_traced_resultÚ	orig_argsZorig_kwargsrR  r   Zflat_results_tracedZout_spec_tracedr!  Z	new_graphro  r;   r;   r<   Úrewrite_signature&  s@    $þþûú
R
ýÿru  Úsymbolic)Ú
aten_graphÚpre_dispatchÚdecomposition_tableÚtracing_modeÚconstraintsr‰   Úsame_signaturezCallable[..., Any]z9Optional[Dict[torch._ops.OpOverload, Callable[..., Any]]]rã   zOptional[List[Constraint]]zCallable[..., ExportResult])	r~   rw  rx  ry  rz  r{  r‰   r|  r@   c                  sF   | ‰|‰ ‡ ‡‡‡‡‡‡‡fdd„}
|s*|	r>t  d¡ |
||	ŽS |
S dS )aí  
    Export an input function f to a format that can be executed outside of PyTorch using the FX graph.

    Args:
        f (callable): A PyTorch function to be exported.

        aten_graph (bool): If True, exports a graph with ATen operators.
        If False, exports a graph with Python operators. Default is False.

        pre_dispatch (bool): If True, exports a graph with ATen operators,
        but before any logic in the PyTorch dispatcher has run.
        This can be useful if you want to apply further transformations on a graph before running it
        through autograd, autocast, or any other functionalities that are integrated into the dispatcher.
        This flag is only valid if aten_graph=True is set.
        Default is False.

        decomposition_table (dict): A dictionary that maps operators to their decomposition functions.
        Required if aten_graph or tracing_mode is specified. Default is None.

        tracing_mode (str): If "symbolic", turn on dynamic shapes support. Default is "symbolic".

        same_signature (bool): If True, rewrite the returned graph's signature to be the same as f.

    Returns:
        A function that given args and kwargs, returns a tuple of (graph, guards)
        Graph: An FX graph representing the execution of the input PyTorch function with the provided arguments and options.
        Guards: The guards we accumulated during tracing f above

    Raises:
        AssertionError: If decomposition_table is specified without setting aten_graph=True,
        or if graph breaks during tracing in export.

        AssertionError: If Dynamo input and output is not consistent with traced input/output.

    Note - this headerdoc was authored by ChatGPT, with slight modifications by the author.
    c                    s¤  ˆ}ˆ}t ƒ  tj d¡ ˆ
d k	r.ˆs.tdƒ‚ˆr>ˆs>tdƒ‚t|ƒ}t|tjjƒrZ|j	n|}t
 |¡}d ‰d ‰d ‰d ‰d ‰ddœ‡fdd„}g ‰ dd	œ‡ ‡‡‡‡fd
d„}t | |f¡\}}	t|ƒ d }
ˆdkrÖd}tt› d�d ƒ�z tjd|dddd��Z t|t|d d�dˆ	d�|ƒ}z|| |Ž}W n( tk
�rP } z|}
W 5 d }~X Y nX W 5 Q R X W 5 Q R X t|ƒ tˆdd ƒ }d k	�rZ|j }d k	�rZt t
 |¡¡�sZ| ¡  | ¡  | |¡}| ¡ }|�rÞd|› d|› �}|
�rø|
jd | f|
_n|�rt|ƒ}
nt  d|¡ |j! "¡ D ]:}t|t#j$ƒ�rtd %t& '|j(| ¡¡› d|› d�ƒ}
�q|
�rd|
‚ˆd k	�svtdƒ‚t)ˆdƒ�s†t‚ˆd k	�s˜tdƒ‚ˆd k	�s¦t‚ˆ�r´t*ˆƒ ‡fdd„ˆ D ƒ}ˆ�r^‡fd d!„}t+ƒ �z t,ƒ �h ˆ�X zt-|ˆ
d"dˆdd#�|Ž ‰W n4 t.k
�r> } zt/t0j1t2|ƒƒ‚W 5 d }~X Y nX W 5 Q R X W 5 Q R X W 5 Q R X ˆ�r|t3|ˆˆ||	|ˆˆ|ƒ	‰ˆ	�r�d$d„ ˆ	D ƒng ˆj4d%< t5ˆˆƒS )&Nztorch._dynamo.exportzaSpecifying a decomposition_table table or tracing mode is illegal without setting aten_graph=Truez7pre_dispatch=True can only be used when aten_graph=Truer=  r  c                   s   ˆ d kst dƒ‚| ‰ d S )Nz3whole graph export entails exactly one guard export)rm   r  r  r;   r<   r	    s
    ÿþz1export.<locals>.inner.<locals>.guard_export_printrù   rú   c                   s6   ˆd kst dƒ‚| ‰t ¡ ‰|‰ ‡‡‡‡fdd„}|S )Nz\Tried to emit a second graph during export. Tracing through 'f' must produce a single graph.c            	   
     sÊ   | ‰ˆd k	st ‚tˆjdd�ƒ}tˆjdd�ƒ}t | ¡d k	rHt | ¡nˆ }|�p tƒ �^ t|ƒt|ƒ–}tƒ }| ¡ D ]\}}|j|dd�||< qxt	 
|j| ¡}tj ˆ||¡‰W 5 Q R X W 5 Q R X ˆS )NF)Zremove_duplicateT)Zstatic_shapes)rm   rb   Únamed_parametersÚnamed_buffersr   Údetect_fake_moder3   rM  r0  rp  Ztree_maprA   ÚfuncZfunctional_call)	Zgraph_inputsr}  r~  Zambient_fake_modeZparams_and_buffersZfake_params_buffersrj   ÚvalueZfake_graph_inputs)r#  r@  rs  Úgraph_captured_resultr;   r<   Úresult_capturing_wrapper3  s8    ÿýþ ÿ ÿ  ÿzhexport.<locals>.inner.<locals>.dynamo_normalization_capturing_compiler.<locals>.result_capturing_wrapper)rm   r   r  )rû   Zinner_example_inputsrƒ  )rþ   r#  r@  rs  r‚  r;   r<   Ú'dynamo_normalization_capturing_compiler!  s    ÿþ%zFexport.<locals>.inner.<locals>.dynamo_normalization_capturing_compilerrv  Tr
  F)Zspecialize_intr‰   rŠ   Z capture_dynamic_output_shape_opsZcapture_scalar_outputsrð   )rÎ   rˆ   Úexport_constraintsÚ	shape_envzuSome dynamic dimensions need to be specialized because the constraints inferred for them are too complex to specify.
r  r   z#Summary of dimension constraints:%sr{   zk
It appears that you're trying to set a constraint on a value which we evaluated to have a static value of z1. Scroll up to see where this constraint was set.zZFailed to produce a graph during tracing. Tracing through 'f' must produce a single graph.rB  z'Failed to produce guards during tracingc                   s   g | ]}ˆ   |¡‘qS r;   )r0  )rp   Út)r#  r;   r<   rs   ®  s     z)export.<locals>.inner.<locals>.<listcomp>c               
     s6   t jj ¡ �  t j ˆ ¡j| Ž W  5 Q R £ S Q R X d S rK   )rA   r¤   r  Zpreserve_node_metaZInterpreterÚrun)rn   )r@  r;   r<   Úgraph_with_interpreter²  s    z5export.<locals>.inner.<locals>.graph_with_interpreterÚreal)ry  rz  Z_allow_non_fake_inputsrx  Z_allow_fake_constantc                 S  s   g | ]
}|j ‘qS r;   )Zserializable_spec)rp   Ú
constraintr;   r;   r<   rs   Ô  s     Zinput_shape_constraints)6ré   rA   rB   rò   rm   r„   rU   r¨   r©   rV   rZ   Ú	signaturerp  rq  r   r   r7   r'   rö   r   r5   ri   Údim_constraintsr*   rY   r[   ZsolveZ remove_redundant_dynamic_resultsZprettify_resultsÚforced_specializationsrn   r|   ÚinfoZvar_to_rangerm  ÚsympyÚIntegerr   r  r  Zvar_to_stackr^   rH  r   r3   r   r,   r.   r/   ZDYNAMIC_CONTROL_FLOWrã   ru  r.  r<  )rn   ro   r~   r‰   Zcall_to_inspectZoriginal_signaturer	  r„  r  rr  Zconstraint_violation_errorr  Zresult_tracedÚer†  r�  r  rŽ  Úkr"  r‰  ©Z_assume_static_by_defaultÚ_frw  r{  ry  rx  r|  rz  )rþ   r#  r@  rs  r‚  r  r<   r    sø    ÿþ
;ûþùø
*ÿþý
ÿÿ
þ ÿÿþÿúù@÷ÿýzexport.<locals>.innerzàexport(f, *args, **kwargs) is deprecated, use export(f)(*args, **kwargs) instead.  If you don't migrate, we may break your export call in the future if your user defined kwargs conflict with future kwargs added to export(f).Nr  )r~   rw  rx  ry  rz  r{  r‰   r|  r  r  r  r;   r”  r<   rˆ   Î  s    3 Xÿ
rˆ   )rÎ   rˆ   r…  rŽ   c                C  s2   t | ƒ} t| dtƒ}ttj| ||d�||||d�S )zF
    The same as `torch._dynamo.optimize(backend, nopython=True)`
    r˜   )rˆ   r…  )rˆ   rŽ   )rä   ri   r³   rà   r(   Zconvert_frame_assert)r÷   rÎ   rˆ   r…  rŽ   r˜   r;   r;   r<   rö   æ  s      ÿùrö   c                   @  s.   e Zd Zee d¡dd„ ƒƒZedd„ ƒZdS )r¼   Nc                  C  s  ddl m}  | tjjƒtj_| tjjƒtj_| tjjƒtj_| tjjj	jƒtjjj	_tj
j d¡ ddlm}m}m}m}m}m}m}m}m}	m}
m}m}m} |||||||||	|
|||h}|||	|h}|D ]t}|j d¡d }d|› �}d	|› �}t||ƒ�r ||k�r t||| t||ƒƒƒ t||ƒrÌt||| t||ƒƒƒ qÌd
d„ tjj  !¡ D ƒ}tjj"tjj#tjj$h}|D ]j}||k�rŒ| |j%ƒ|_%t|dƒ�r¤| |j&ƒ|_&t|j%ddƒ}|�rÒt|j%dd ƒ}|�rÒ||_%d|j%_'�qrtj(j)j* +¡  tj(j)j* ,¡  tj(j)j- .¡  d S )Nr   )rÖ   Fr   )ÚadadeltaÚadagradÚadamÚadamaxÚadamwÚasgdÚlbfgsÚnadamÚradamÚrmspropÚrpropÚsgdÚsparse_adamÚ.r  Z_multi_tensor_Z_fused_c                 S  s(   g | ] }t  |¡rt|tjjƒr|‘qS r;   )rZ   ÚisclassÚ
issubclassrA   ÚoptimZ	Optimizer)rp   Úoptr;   r;   r<   rs   L  s   
 þz&TorchPatcher.patch.<locals>.<listcomp>Ú_init_groupÚhookedÚ__wrapped__T)/Z
decoratorsrÖ   rA   ZjitÚtraceZtrace_moduleZ_get_trace_graphr¤   r¥   ZTracerÚdistributionsÚDistributionZset_default_validate_argsr¦  r–  r—  r˜  r™  rš  r›  rœ  r�  rž  rŸ  r   r¡  r¢  r7   Úsplitr^   Úsetattrri   rc   r  Z
SparseAdamZRAdamZLBFGSÚstepr¨  r©  rC   Ú	variablesÚlistsZ"_register_dynamo_list_to_tree_specZ#_register_dynamo_tuple_to_tree_specZdictsZ"_register_dynamo_dict_to_tree_spec)rÖ   r–  r—  r˜  r™  rš  r›  rœ  r�  rž  rŸ  r   r¡  r¢  Zoptimizer_modulesZ!disabled_multi_tensor_opt_modulesZopt_modÚopt_nameZmulti_tensor_fn_nameZfused_fn_nameZoptimizer_classesZexcluded_optimizer_classesr§  r©  Zunwrapped_stepr;   r;   r<   r     sˆ    
ÿ<óü

ÿþý
  ÿ
þý
zTorchPatcher.patchc                   s   ‡ fdd„}|S )Nc                    s   t jdtdd� ˆ | |ŽS )NÚignoreztorch.distributed)ÚcategoryÚmodule)r¸   ÚfilterwarningsÚUserWarning)rn   ro   ©rƒ   r;   r<   Úinner_fnq  s      ÿzBTorchPatcher.suppress_torch_distributed_warnings.<locals>.inner_fnr;   )rƒ   rº  r;   r¹  r<   Ú#suppress_torch_distributed_warningso  s    z0TorchPatcher.suppress_torch_distributed_warnings)r7   r8   r9   r½   r¬   Ú	lru_cacher   r»  r;   r;   r;   r<   r¼     s
   kr¼   )NF)rì   )’Ú
__future__r   Ú
contextlibrÇ   r¬   rZ   Úloggingró   rÅ   r®   Ú	threadingr  rW   r¸   Úcollectionsr   Úenumr   Úos.pathr   r   Útypingr   r   r	   r
   r   r   r   r   r   r   Zunittest.mockr   rA   Ztorch.fxZtorch.utils._pytreer+   Z_pytreerp  Ztorch.utils.checkpointr   Ztorch._subclassesr   Ztorch.exportr   Z"torch.fx.experimental.proxy_tensorr   r   Ztorch.fx.graphr   r   Ztorch.nn.parallel.distributedr   r¤   r   Zbackends.registryr   r   rÎ   r   Ztorch._C._dynamo.eval_framer    r!   r"   r#   r$   r%   ÚdirrB   rC   rD   rj   Ú
startswithri   Úglobalsr{   r'   r(   r)   r*   Úexcr,   r-   r.   r/   r¿   r0   r1   r2   Ú	getLoggerr7   r|   Ztorch._dispatch.pythonr3   Ztorch.utils._python_dispatchr4   ZExactWeakKeyDictionaryr°   Únullcontextr³   r�  Z%torch.fx.experimental.symbolic_shapesr5   r6   r:   r“   ÚRLockrÙ   r=   r>  r[   Ú__file__r«   r>   rE   r¨   r©   rI   r   r€   r„   Úcontextmanagerr‹   rŒ   r´   r¾   r£   rÌ   rß   rà   rä   rå   ré   rë   rø   r  ÚinterpreterZTransformerr  r<  rH  ru  rˆ   rö   r¼   r;   r;   r;   r<   Ú<module>   sÞ    0"	
ý
> ,)		,ú	 ÿùE
V5* ,õ"  ú