
    Ph%              	       2   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
        Zed        Zed        Z ed      d        Zd Z eee	      Z ede        ee      Z ede        eeed  ej4                  e	d            Z ede        ee      Z ede        G d de      Z G d de      Zed e
j@                  jB                  fd!       Z"ed e
j@                  jB                  fd"       Z#ed e
j@                  jB                  fd#       Z$ed e
j@                  jB                  fd$       Z%e jL                   G d% d&             Z'd e
j@                  jB                  fd'Z( G d( d)      Z)y)*    N)import_module)AnyListOptional)#min_cut_rematerialization_partition)_guards)
ts_compile   )aot_autograd)register_debug_backendc                     | S N gmfake_tensor_inputss     kC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\torch/_dynamo/backends/debugging.pyeagerr      s    I    c                 X     ddl m}  fd}  ||d      | }|j                          |S )Nr   )make_fxc                  Z    t        j                  j                        j                  |  S r   torchfxInterpreterrun)argsr   s    r   runnable_gmz'pre_dispatch_eager.<locals>.runnable_gm   s#    xx##B'++T22r   T)pre_dispatch)"torch.fx.experimental.proxy_tensorr   print_readable)r   r   r   r   pre_dispatch_gms   `    r   pre_dispatch_eagerr$      s3    :3 >gk=?QRO""$r   c                 "     ddl m  fd}|S )Nr   )SchemaCheckModec                              5  t        j                  j                        j                  |  cd d d        S # 1 sw Y   y xY wr   r   )r   r&   r   s    r   innerzeager_debug.<locals>.inner,   s2    88''+//6 s	   +>A)#torch._subclasses.schema_check_moder&   )r   r   r(   r&   s   `  @r   eager_debugr*   %   s    C
7 Lr   ts)namec                 @    t         j                  j                  |       S r   )r   jitscriptr   s     r   torchscriptr0   3   s    99Br   c                        fd}d|_         |S )Nc                 `    t         j                  j                        j                  |       S r   )r   r   r   	boxed_run)r   fx_gs    r   r   zboxed_nop.<locals>.run:   s#    xx##D)33D99r   T)_boxed_call)r4   example_inputsr   s   `  r   	boxed_nopr7   9   s    : COJr   )fw_compilerpartition_fn	aot_eager)r,   compiler_fn)r8   aot_eager_default_partitionerc                  4    t        d      j                         S )Nztorch._inductor.compile_fx)r   select_decomp_tabler   r   r   <lambda>r?   V   s    =$r   inductor)compiler)r8   bw_compilerdecompositionsr9   aot_eager_decomp_partitionaot_tsc                       e Zd Zy)ReluCompileErrorN__name__
__module____qualname__r   r   r   rG   rG   k       r   rG   c                       e Zd Zy)TestingOnlyCompileErrorNrH   r   r   r   rN   rN   o   rL   r   rN   r   c                     | j                   j                  D ])  }|j                  t        j                  k(  s!t                | S r   )graphnodestargetr   relurG   r   r6   nodes      r   relu_compile_error_TESTING_ONLYrV   s   s4    ;;%**$"$$  Ir   c                     | j                   j                  D ]<  }|j                  t        j                  k(  s!t        j
                  |_        d|_        > | j                          | S )N)FReluRuntimeError)rP   rQ   rR   r   rS   _assertr   	recompilerT   s      r   relu_runtime_error_TESTING_ONLYr[   {   sF    ;;%**$--DK3DI  LLNIr   c                     | j                   j                  D ]K  }|j                  t        j                  k(  s!t        j
                  |_        |j                  d   df|_        M | j                          | S )Nr   r
   )rP   rQ   rR   r   rS   addr   rZ   rT   s      r    relu_accuracy_error_TESTING_ONLYr^      sS    ;;%**$))DK1q)DI  LLNIr   c                     | j                   j                  D ]  }|j                  dk(  s n | S |D ]  }|j                  rt	                | S )Ncall_function)rP   rQ   opis_leafrN   )r   r6   rU   ts       r   #non_leaf_compile_error_TESTING_ONLYrd      sM     77o%  	yy)++  Ir   c                      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 Zy)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                    d| j                    d}|d| j                   dz  }|d| j                   dz  }|dz  }t        | j                        D ]C  \  }}|d|dz    dz  }|d	|j
                   dz  }|d
z  }|j                  D ]  }|d| dz  } E | j                  >|dz  }t        | j                        D ]!  \  }}|d|dz    dz  }|D ]  }|d| dz  } # | j                  ?|dz  }t        | j                        D ]"  \  }}|d|dz    dz  }|dt        |       z  }$ | j                  |d| j                   dz  }|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: )rh   ri   rk   	enumeraterj   reason
user_stackrl   rm   strrn   )	selfoutputidxbreak_reasonframe_summaryopsra   iguards	            r   __str__zExplainOutput.__str__   s    !1!1 2"5'(>(>'?rBBJt}}oR00$$!*4+=+=!>CAwc22F\%8%8$9<<F))F!-!8!8F=/44 "9	 "? )((F%d&8&89SF3q5'--BRDm+F  :
 ??&o%F%doo65HQqSE--DU-- 7 )(:(:';2>>Fr   )rI   rJ   rK   __doc__r   r   r   GraphModule__annotations__intr   rl   r   Noderm   r   Guardrn   rt   r}   r   r   r   rf   rf      s    
 %%&&  M37M8D/0704Jgmm,-4#'M8C='r   rf   c                 V   |j                  |        | j                  j                  D cg c]  }|j                  dk(  s|j                    }}|t        |      z  }|j                  |       | j                  j                  r|j                  | j                         | ||||fS c c}w )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.
    r`   )appendrP   rQ   ra   rR   lencompile_subgraph_reasongraph_break)r   rg   rk   rl   rj   rU   rz   s          r   _explain_graph_detailr      s    ( MM"#%88>>
P>4TWW5O4;;>C
PCH	!!--R778vx== Qs
   B&B&c                   V    e Zd ZdZd Zdej                  j                  fdZde	fdZ
y)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                 T    ddl m}  ||      | _        g | _        d| _        g | _        y )Nr
   )lookup_backendr   )registryr   backendrg   rk   rj   )ru   r   r   s      r   __init__zExplainWithBackend.__init__  s'    ,%g.r   r   c                     t        || j                  | j                  g | j                        \  }| _        | _        }| _        | j	                  ||      S r   )r   rg   rk   rj   r   )ru   r   r6   _s       r   __call__zExplainWithBackend.__call__  sK    @UT]]B0B0BA
=DK4+= ||B//r   returnc                     t        | j                        }t        | j                  ||dz
  | j                  | j                        }|S )Nr
   )r   rg   rf   rj   rk   )ru   rh   rv   s      r   rv   zExplainWithBackend.output  sB    $++&KK!OMM
 r   N)rI   rJ   rK   r~   r   r   r   r   r   rf   rv   r   r   r   r   r      s.    0 0588// 0
 
r   r   )*dataclasses	functools	importlibr   typingr   r   r   functorch.compiler   r   r   torch._functorch.compilersr	   commonr   r   r   register_backendr   r$   r*   r0   r7   r:   r<   partialrD   rE   	ExceptionrG   rN   r   r   rV   r[   r^   rd   	dataclassrf   r   r   r   r   r   <module>r      s     # & & A   1   @
   	 	 
 
 t   
 (K	 ky 9 , C  	(6S * #""+j  	%3M 
*	- hF 3	y 		i 	 (<(<   (<(<   )=)=   EHH,@,@   - - -`>><1 1r   