o
    "i'                     @   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Zd dl	m
Z
 d dlm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 Zedddd Zdd Zeee
ddZeded eeddZed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d'ej#j$fd(d)Z%ed'ej#j$fd*d+Z&ed'ej#j$fd,d-Z'ed'ej#j$fd.d/Z(e j)G d0d1 d1Z*d'ej#j$fd2d3Z+G d4d5 d5Z,dS )6    N)import_module)AnyListOptional)#min_cut_rematerialization_partition)_guards)config)
ts_compile   )aot_autograd)register_debug_backendc                 C   s   | j S N)forwardgmfake_tensor_inputs r   ^/home/ubuntu/SoloSpeech/.venv/lib/python3.10/site-packages/torch/_dynamo/backends/debugging.pyeager   s   r   c                    s    fdd}|S )Nc               
      s4   z |  W S  t y } ztjjd|d }~ww )Nz7Unexpected exception when running generated GraphModule)	Exceptiontorch_dynamoexcTorchDynamoException)argser   r   r   inner   s   
zeager_noexcept.<locals>.innerr   r   r   r   r   r   r   eager_noexcept   s   r   c                    s4   ddl m}  fdd}||dd| }|  |S )Nr   )make_fxc                     s   t j j|  S r   r   fxInterpreterrunr   r   r   r   runnable_gm.      z'pre_dispatch_eager.<locals>.runnable_gmT)pre_dispatch)"torch.fx.experimental.proxy_tensorr    print_readable)r   r   r    r&   pre_dispatch_gmr   r   r   pre_dispatch_eager*   s
   r,   c                    s   ddl m   fdd}|S )Nr   )SchemaCheckModec                     s<      t jj|  W  d    S 1 sw   Y  d S r   r!   r%   r-   r   r   r   r   >   s   $zeager_debug.<locals>.inner)#torch._subclasses.schema_check_moder-   r   r   r.   r   eager_debug7   s   r0   ts)namec                 C   s   t j| S r   )r   jitscriptr   r   r   r   torchscriptE   s   r5   c                    s    fdd}d|_ |S )Nc                    s   t j | S r   )r   r"   r#   	boxed_runr%   fx_gr   r   r$   L   r'   zboxed_nop.<locals>.runT)_boxed_call)r8   example_inputsr$   r   r7   r   	boxed_nopK   s   r;   T)fw_compilerpartition_fnkeep_inference_input_mutations	aot_eager)r2   compiler_fn)r<   r>   aot_eager_default_partitionerc              	   C   sT   t jdd tttdd tjtddd| |W  d    S 1 s#w   Y  d S )NT)unlift_effect_tokensc                   S   s   t d S )Nztorch._inductor.compile_fx)r   select_decomp_tabler   r   r   r   <lambda>o   s    z,aot_eager_decomp_partition.<locals>.<lambda>inductor)compiler)r<   bw_compilerdecompositionsr=   )functorch_configpatchr   r;   	functoolspartialr   r   r   r   r   aot_eager_decomp_partitionh   s   $rM   )r<   aot_tsc                   @      e Zd ZdS )ReluCompileErrorN__name__
__module____qualname__r   r   r   r   rP          rP   c                   @   rO   )TestingOnlyCompileErrorNrQ   r   r   r   r   rV      rU   rV   r   c                 C   s"   | j jD ]
}|jtjkrtq| S r   )graphnodestargetr   relurP   r   r:   noder   r   r   relu_compile_error_TESTING_ONLY   s
   r]   c                 C   s4   | j jD ]}|jtjkrtj|_d|_q|   | S )N)FReluRuntimeError)rW   rX   rY   r   rZ   _assertr   	recompiler[   r   r   r   relu_runtime_error_TESTING_ONLY   s   ra   c                 C   s>   | j jD ]}|jtjkrtj|_|jd df|_q|   | S )Nr   r
   )rW   rX   rY   r   rZ   addr   r`   r[   r   r   r    relu_accuracy_error_TESTING_ONLY   s   rc   c                 C   s8   | j jD ]	}|jdkr nq| S |D ]}|jstq| S )Ncall_function)rW   rX   opis_leafrV   )r   r:   r\   tr   r   r   #non_leaf_compile_error_TESTING_ONLY   s   
rh   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   sX  d| j  d}|d| j d7 }|d| j d7 }|d7 }t| jD ])\}}|d|d  d7 }|d	|j d7 }|d
7 }|jD ]
}|d| d7 }q@q"| jd urv|d7 }t| jD ]\}}|d|d  d7 }|D ]
}|d| d7 }qjqZ| jd ur|d7 }t| jD ]\}}|d|d  d7 }|dt	| 7 }q| j
d ur|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: )rk   rl   rn   	enumeraterm   reason
user_stackro   rp   strrq   )	selfoutputidxbreak_reasonframe_summaryopsre   iguardr   r   r   __str__   s4   



zExplainOutput.__str__)rR   rS   rT   __doc__r   r   r"   GraphModule__annotations__intr   ro   r   Noderp   r   Guardrq   rv   r   r   r   r   r   ri      s   
 ri   c                 C   sT   | |  dd | jjD }|t|7 }| | | jjr#| | 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 )rd   )re   rY   ).0r\   r   r   r   
<listcomp>  s    z)_explain_graph_detail.<locals>.<listcomp>)appendrW   rX   lencompile_subgraph_reasongraph_break)r   rj   rn   ro   rm   r|   r   r   r   _explain_graph_detail   s   

r   c                   @   s8   e Zd ZdZdd ZdejjfddZde	f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   )registryr   backendrj   rn   rm   )rw   r   r   r   r   r   __init__#  s
   

zExplainWithBackend.__init__r   c                 C   s2   t || j| jg | j\}| _| _}| _| ||S r   )r   rj   rn   rm   r   )rw   r   r:   _r   r   r   __call__+  s   zExplainWithBackend.__call__returnc                 C   s(   t | j}t| j||d | j| j}|S )Nr
   )r   rj   ri   rm   rn   )rw   rk   rx   r   r   r   rx   1  s   
zExplainWithBackend.outputN)rR   rS   rT   r   r   r   r"   r   r   ri   rx   r   r   r   r   r   
  s
    r   )-dataclassesrK   	importlibr   typingr   r   r   r   functorch.compiler   r   torch._functorchr   rI   torch._functorch.compilersr	   commonr   r   r   register_backendr   r   r,   r0   r5   r;   r?   rA   rM   rN   r   rP   rV   r"   r   r]   ra   rc   rh   	dataclassri   r   r   r   r   r   r   <module>   sr   





	
	
0
