U
    ªÊ¹j $  ã                   @   sÐ  d dl Z d dlZd dlmZ d dlmZmZmZ d dl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 ed
d„ ƒZedd„ ƒZedd„ ƒZedd�dd„ ƒZdd„ Zeee	d�Zeded� eed�Zeded� eeedd„ eje	dd�d�Zed ed� eed�Zed!ed� G d"d#„ d#eƒZG d$d%„ d%eƒZee
j j!d&œd'd(„ƒZ"ee
j j!d&œd)d*„ƒZ#ee
j j!d&œd+d,„ƒZ$ee
j j!d&œd-d.„ƒZ%e j&G d/d0„ d0ƒƒZ'e
j j!d&œd1d2„Z(G d3d4„ d4ƒZ)dS )5é    N)Úimport_module)ÚAnyÚListÚOptional)Ú#min_cut_rematerialization_partition)Ú_guards)Ú
ts_compileé   )Úaot_autograd)Úregister_debug_backendc                 C   s   | S ©N© ©ÚgmÚfake_tensor_inputsr   r   ú_/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/_dynamo/backends/debugging.pyÚeager   s    r   c                    s4   ddl m} ‡ fdd„}||dd�|Ž }| ¡  |S )Nr   )Úmake_fxc                     s   t j ˆ ¡j| Ž S r   ©ÚtorchÚfxÚInterpreterÚrun©Úargs©r   r   r   Úrunnable_gm   s    z'pre_dispatch_eager.<locals>.runnable_gmT)Zpre_dispatch)Z"torch.fx.experimental.proxy_tensorr   Zprint_readable)r   r   r   r   Zpre_dispatch_gmr   r   r   Úpre_dispatch_eager   s
    r   c                    s   ddl m‰  ‡ ‡fdd„}|S )Nr   )ÚSchemaCheckModec               
      s0   ˆ ƒ �  t j ˆ¡j| Ž W  5 Q R £ S Q R X d S r   r   r   ©r   r   r   r   Úinner,   s    zeager_debug.<locals>.inner)Z#torch._subclasses.schema_check_moder   )r   r   r    r   r   r   Úeager_debug%   s    r!   Úts)Únamec                 C   s   t j | ¡S r   )r   ZjitÚscriptr   r   r   r   Útorchscript3   s    r%   c                    s   ‡ fdd„}d|_ |S )Nc                    s   t j ˆ ¡ | ¡S r   )r   r   r   Z	boxed_runr   ©Úfx_gr   r   r   :   s    zboxed_nop.<locals>.runT)Z_boxed_call)r'   Úexample_inputsr   r   r&   r   Ú	boxed_nop9   s    r)   )Úfw_compilerÚpartition_fnÚ	aot_eager)r#   Zcompiler_fn)r*   Úaot_eager_default_partitionerc                   C   s   t dƒ ¡ S )Nztorch._inductor.compile_fx)r   Zselect_decomp_tabler   r   r   r   Ú<lambda>V   s   ÿr.   Zinductor)Úcompiler)r*   Zbw_compilerZdecompositionsr+   Úaot_eager_decomp_partitionÚaot_tsc                   @   s   e Zd ZdS )ÚReluCompileErrorN©Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r2   k   s   r2   c                   @   s   e Zd ZdS )ÚTestingOnlyCompileErrorNr3   r   r   r   r   r7   o   s   r7   r   c                 C   s$   | j jD ]}|jtjkrtƒ ‚q| S r   )ÚgraphÚnodesÚtargetr   Úrelur2   ©r   r(   Únoder   r   r   Úrelu_compile_error_TESTING_ONLYs   s    r>   c                 C   s4   | j jD ]}|jtjkrtj|_d|_q|  ¡  | S )N)FZReluRuntimeError)r8   r9   r:   r   r;   Z_assertr   Ú	recompiler<   r   r   r   Úrelu_runtime_error_TESTING_ONLY{   s    r@   c                 C   s>   | j jD ](}|jtjkrtj|_|jd df|_q|  ¡  | S )Nr   r	   )r8   r9   r:   r   r;   Úaddr   r?   r<   r   r   r   Ú relu_accuracy_error_TESTING_ONLY…   s    rB   c                 C   s:   | j jD ]}|jdkr q q| S |D ]}|js$tƒ ‚q$| S )NÚcall_function)r8   r9   ÚopZis_leafr7   )r   r(   r=   Útr   r   r   Ú#non_leaf_compile_error_TESTING_ONLY�   s    
rF   c                   @   sŒ   e Zd ZU dZeejj ed< e	ed< e	ed< ee
 ed< e	ed< dZeeejj  ed< dZeeej  ed	< dZee ed
< dd„ ZdS )ÚExplainOutputzu
    This is the output of :func:`torch._dynamo.explain()`
    There is no reason to create this class directly.
    ÚgraphsÚgraph_countÚgraph_break_countÚbreak_reasonsÚop_countNÚops_per_graphÚ
out_guardsÚcompile_timesc           	      C   s^  d| j › d�}|d| j› d�7 }|d| j› d�7 }|d7 }t| jƒD ]R\}}|d|d › d�7 }|d	|j› d�7 }|d
7 }|jD ]}|d|› d�7 }q€qD| jd k	rì|d7 }t| jƒD ]6\}}|d|d › d�7 }|D ]}|d|› d�7 }qÔq´| jd k	�r<|d7 }t| jƒD ]0\}}|d|d › d�7 }|dt	|ƒ› �7 }�q
| j
d k	�rZ|d| j
› d�7 }|S )NzGraph Count: Ú
zGraph Break Count: z
Op Count: zBreak Reasons:
z  Break Reason r	   z:
z    Reason: z    User Stack:
z      zOps per Graph:
z  Ops z    zOut Guards:
z  Guard zCompile Times: )rI   rJ   rL   Ú	enumeraterK   ÚreasonZ
user_stackrM   rN   ÚstrrO   )	ÚselfÚoutputÚidxZbreak_reasonÚframe_summaryÚopsrD   ÚiÚguardr   r   r   Ú__str__±   s0    

zExplainOutput.__str__)r4   r5   r6   Ú__doc__r   r   r   ÚGraphModuleÚ__annotations__Úintr   rM   r   ÚNoderN   r   ZGuardrO   rS   r[   r   r   r   r   rG   Ÿ   s   
ÿrG   c                 C   sT   |  | ¡ dd„ | jjD ƒ}|t|ƒ7 }|  |¡ | jjrF|  | j¡ | ||||fS )a¨  
    This function is a utility which processes a torch.fx.GraphModule and
    accumulates information about its ops, graph breaks, and other details. It
    is intended to be used by the ExplainWithBackend class and
    `torch._dynamo.explain()` to provide details from Dynamo's graph capture.

    Parameters:
        gm (torch.fx.GraphModule): The GraphModule to be processed.
        graphs (list): A list that accumulates all the GraphModules processed.
        op_count (int): The total count of operations in all GraphModules processed so far.
        ops_per_graph (list): A list that accumulates the operations of each GraphModule.
        break_reasons (list): A list that accumulates the reasons for breaks in each GraphModule.

    Returns:
        tuple: A tuple containing the processed GraphModule, the updated lists of graphs,
               operations per graph, and break reasons, and the updated operation count.
    c                 S   s   g | ]}|j d kr|j‘qS )rC   )rD   r:   )Ú.0r=   r   r   r   Ú
<listcomp>å   s     
 z)_explain_graph_detail.<locals>.<listcomp>)Úappendr8   r9   ÚlenZcompile_subgraph_reasonZgraph_break)r   rH   rL   rM   rK   rX   r   r   r   Ú_explain_graph_detailÐ   s    

re   c                   @   s8   e Zd ZdZdd„ Zejjdœdd„Ze	dœdd	„Z
d
S )ÚExplainWithBackenda  
    This class is intended to be used as a backend for `torch.compile`. It is
    composable with other backends. When used in this way, it accumulates
    information about graph breaks, ops, and other info and provides a string
    representation summarizing this information.

    Attributes:
        backend (str): The name of the backend to use for optimization.
        graphs (list): A list of the graphs captured by TorchDynamo.
        op_count (int): The total number of operations in all optimized graphs.
        break_reasons (list): A list of graph break reasons with stack traces.

    Example Usage:
        def fn(x):
            x = torch.sigmoid(x)
            return x

        torch._dynamo.reset()
        eb = ExplainWithBackend("inductor")
        optimized_fn = torch.compile(fn, backend=eb)
        result = optimized_fn(torch.randn(5))
        print(eb.output())
    c                 C   s,   ddl m} ||ƒ| _g | _d| _g | _d S )Nr	   )Úlookup_backendr   )Úregistryrg   ÚbackendrH   rL   rK   )rT   ri   rg   r   r   r   Ú__init__  s
    
zExplainWithBackend.__init__r   c                 C   s2   t || j| jg | jƒ\}| _| _}| _|  ||¡S r   )re   rH   rL   rK   ri   )rT   r   r(   Ú_r   r   r   Ú__call__  s        ÿzExplainWithBackend.__call__)Úreturnc                 C   s(   t | jƒ}t| j||d | j| jƒ}|S )Nr	   )rd   rH   rG   rK   rL   )rT   rI   rU   r   r   r   rU     s    
ûzExplainWithBackend.outputN)r4   r5   r6   r\   rj   r   r   r]   rl   rG   rU   r   r   r   r   rf   î   s   rf   )*ÚdataclassesÚ	functoolsÚ	importlibr   Útypingr   r   r   Zfunctorch.compiler   r   r   Ztorch._functorch.compilersr   Úcommonr
   rh   r   Zregister_backendr   r   r!   r%   r)   r,   r-   Úpartialr0   r1   Ú	Exceptionr2   r7   r   r]   r>   r@   rB   rF   Ú	dataclassrG   re   rf   r   r   r   r   Ú<module>   st   




 ÿ
 ÿ ÿø ÿ
	
1ÿ