
    %Vji"                    >   U d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
 ddlmZmZ e
rddlmZ ddlmZ  ej        e          Z G d d	          Zeeeeeef         e	ee                  e	e         gdf         Zd
ed<    G d d          Z G d d          ZdS )a[  Metrics collection and management system for Dynamo.

This module provides context managers for gathering and reporting metrics during
compilation and runtime.

It includes two main components:
- MetricsContext: A context manager for collecting metrics during compilation, supporting
  nested contexts and various metric types (counters, sets, key-value pairs)
- RuntimeMetricsContext: A specialized context for runtime metrics collection that doesn't
  require explicit context management

The metrics system enables comprehensive monitoring and analysis of both compilation and
execution performance.
    )annotationsN)AnyCallableOptionalTYPE_CHECKING)Self	TypeAlias)Iterator)CapturedTracebackc                  4    e Zd ZdZdddZddZddZddZdS )TopNz_
    Helper to record a list of metrics, keeping only the top N "most expensive" elements.
       at_mostintc                "    || _         g | _        d S N)r   heap)selfr   s     W/root/voice-cloning/.venv/lib/python3.11/site-packages/torch/_dynamo/metrics_context.py__init__zTopN.__init__'   s    +-			    keyr   valreturnNonec                    t          | j                  | j        k     rt          j        nt          j        } || j        ||f           d S r   )lenr   r   heapqheappushheappushpop)r   r   r   fns       r   addzTopN.add+   sB    "49~~<<U^^%BS
49sCj!!!!!r   c                *    t          | j                  S r   )r   r   r   s    r   __len__zTopN.__len__0   s    49~~r   Iterator[tuple[Any, int]]c                B    d t          | j        d          D             S )Nc              3  $   K   | ]\  }}||fV  d S r    ).0r   r   s      r   	<genexpr>z TopN.__iter__.<locals>.<genexpr>4   s*      KKxsCc
KKKKKKr   T)reverse)sortedr   r$   s    r   __iter__zTopN.__iter__3   s%    KK6$)T+J+J+JKKKKr   N)r   )r   r   )r   r   r   r   r   r   )r   r   )r   r&   )__name__
__module____qualname____doc__r   r"   r%   r.   r)   r   r   r   r   "   sy         . . . . ." " " "
   L L L L L Lr   r   r	   
OnExitTypec                  r    e Zd Zd&dZd'dZd(dZd)dZd*dZd+dZd,d-dZ	d.dZ
d,d/d Zd0d!Zd1d"Zd2d$Zd%S )3MetricsContexton_exitr3   c                L    || _         i | _        d| _        d| _        g | _        dS )aQ  
        Use this class as a contextmanager to create a context under which to accumulate
        a set of metrics, e.g., metrics gathered during a compilation. On exit of the
        contextmanager, call the provided 'on_exit' function and pass a dictionary of
        all metrics set during the lifetime of the contextmanager.
        r   N)_on_exit_metrics_start_time_ns_level_editsr   r6   s     r   r   zMetricsContext.__init__>   s,      (*#$@Br   r   r   c                z    | j         dk    ri | _        t          j                    | _        | xj         dz  c_         | S )z/
        Initialize metrics recording.
        r      )r;   r9   timetime_nsr:   r$   s    r   	__enter__zMetricsContext.__enter__K   s;     ;!DM"&,..Dqr   exc_typeOptional[type[BaseException]]	exc_valueOptional[BaseException]
_tracebackr   r   c                   | xj         dz  c_         | j         dk    sJ | j         dk    rd	 t          j                    }|                     | j        || j        ||           dS # t          $ r t                              d           Y dS w xY wdS )z>
        At exit, call the provided on_exit function.
        r?   r   z0Unexpected exception logging compilation metricsN)	r;   r@   rA   r8   r:   r9   	Exceptionlog	exception)r   rC   rE   rG   end_time_nss        r   __exit__zMetricsContext.__exit__W   s     	q{a;!R"lnn'dmXy      R R RPQQQQQQR s   6A" "$B
	B
boolc                    | j         dk    S )z4
        True if we've entered the context.
        r   )r;   r$   s    r   in_progresszMetricsContext.in_progressk   s     {Qr   metricstrvaluer   c                    | j         dk    rt          d| d          || j        vr
d| j        |<   | j        |xx         |z  cc<   dS )7
        Increment a metric by a given amount.
        r   zCannot increment  outside of a MetricsContextNr;   RuntimeErrorr9   r   rQ   rS   s      r   	incrementzMetricsContext.incrementq   sh     ;!W6WWWXXX&&$%DM&!f&r   predset[str]c                V    dd                     fd| j        D                       z   S )Nz

c              3  |   K   | ]6\  }}|z  
d d                     |                                          z   V  7dS )zPrevious Traceback:
 N)joinformat)r*   ekr[   s      r   r+   z/MetricsContext._render_edits.<locals>.<genexpr>|   s^       $
 $
14x$
#bggahhjj&9&99$
 $
 $
 $
 $
 $
r   )r`   r<   )r   r[   s    `r   _render_editszMetricsContext._render_edits{   sH     $
 $
 $
 $
$
 $
 $
 
 
 
 	
r   F	overwritec                    | j         dk    rt          d| d          || j        v r,|s*t          |                     |h          d| dz             | j                            t          j        d          |hf           || j        |<   dS )	z
        Set a metric to a given value. Raises if the metric has been assigned previously
        in the current context.
        r   Cannot set rV   z

RuntimeError: Metric 'z]' has already been set in the current context (see above for current and previous traceback).r?   skipN)r;   rX   r9   rd   r<   appendr   extract)r   rQ   rS   re   s       r   setzMetricsContext.set   s    
 ;!QVQQQRRRT]""9"""F8,,Bv B B BB  
 	-51===xHIII %fr   r   c                    | j         dk    rt          d| d          || j        vr
i | j        |<   || j        |         |<   dS )a=  
        Treats a give metric as a dictionary and set the k and value within it.
        Note that the metric must be a dictionary or not present.

        We allow this to be called multiple times (i.e. for features, it's not uncommon
        for them to be used multiple times within a single compilation).
        r   rg   rV   NrW   )r   rQ   r   rS   s       r   set_key_valuezMetricsContext.set_key_value   s[     ;!QVQQQRRR&&$&DM&!%*fc"""r   valuesdict[str, Any]c                   | j         dk    rt          d          | j                                        |                                z  }|rJ|sHt          |                     t          |                                                    d| dz             | j                            t          j	        d          t          |                                          f           | j        
                    |           dS )z
        Set multiple metrics directly. This method does NOT increment. Raises if any
        metric has been assigned previously in the current context and overwrite is
        not set to True.
        r   1Cannot update metrics outside of a MetricsContextz

RuntimeError: Metric(s) z_ have already been set in the current context.  (see above for current and previous traceback).r?   rh   N)r;   rX   r9   keysrd   rl   r<   rj   r   rk   update)r   ro   re   existings       r   rt   zMetricsContext.update   s     ;!RSSS=%%''&++--7 	I 	""3v{{}}#5#566B B B BB  
 	-51===s6;;==?Q?QRSSSV$$$$$r   c                ~    | j         dk    rt          d          | j         dk    r|                     |           dS dS )zA
        Update, but only when at the outermost context.
        r   rr   r?   N)r;   rX   rt   )r   ro   s     r   update_outerzMetricsContext.update_outer   sM     ;!RSSS;!KK r   c                    | j         dk    rt          d| d          || j        vrt                      | j        |<   | j        |                             |           dS )z8
        Records a metric as a set() of values.
        r   zCannot add rV   N)r;   rX   r9   rl   r"   rY   s      r   
add_to_setzMetricsContext.add_to_set   si     ;!QVQQQRRR&&$'EEDM&!f!!%(((((r   r   c                    | j         dk    rdS || j        vrt                      | j        |<   | j        |                             ||           dS )z;
        Records a metric as a TopN set of values.
        r   N)r;   r9   r   r"   )r   rQ   r   r   s       r   	add_top_nzMetricsContext.add_top_n   sV     ;!F&&$(FFDM&!f!!#s+++++r   Nr6   r3   )r   r   )rC   rD   rE   rF   rG   r   r   r   )r   rN   )rQ   rR   rS   r   r   r   )r[   r\   r   rR   )F)rQ   rR   rS   r   re   rN   r   r   )rQ   rR   r   rR   rS   r   r   r   )ro   rp   re   rN   r   r   )ro   rp   r   r   )rQ   rR   rS   r   r   r   )rQ   rR   r   r   r   r   r   r   )r/   r0   r1   r   rB   rM   rP   rZ   rd   rl   rn   rt   rw   ry   r{   r)   r   r   r5   r5   =   s       C C C C
 
 
 
R R R R(   ' ' ' '
 
 
 
& & & & & + + + +% % % % %$       ) ) ) ), , , , , ,r   r5   c                  *    e Zd ZddZ	 dddZddZdS )RuntimeMetricsContextr6   r3   c                0    || _         i | _        d| _        dS )z
        Similar to MetricsContext, but used to gather the runtime metrics that are
        decoupled from compilation, where there's not a natural place to insert a
        context manager.
        r   N)r8   r9   r:   r=   s     r   r   zRuntimeMetricsContext.__init__   s       (*#$r   NrQ   rR   rS   r   extraOptional[dict[str, Any]]r   r   c                    | j         st          j                    | _        || j         vr
d| j         |<   | j         |xx         |z  cc<   |r/|                                D ]\  }}|| j         vr|
|| j         |<   dS dS )rU   r   N)r9   r@   rA   r:   items)r   rQ   rS   r   rc   vs         r   rZ   zRuntimeMetricsContext.increment   s     } 	1"&,..D&&$%DM&!f& 	) ) )1DM))am'(DM!$	) 	)) )r   c                   | j         rw	 t          j                    }|                     | j        || j         dd           n*# t
          $ r t                              d           Y nw xY wi | _         dS # i | _         w xY wdS )zW
        Call the on_exit function with the metrics gathered so far and reset.
        Nz,Unexpected exception logging runtime metrics)r9   r@   rA   r8   r:   rI   rJ   rK   )r   rL   s     r   finishzRuntimeMetricsContext.finish   s     = 		##"lnn'dmT4     N N NLMMMMMN !#""""		# 		#s(   6A  A3  $A'$A3 &A''A3 3	A<r|   r   )rQ   rR   rS   r   r   r   r   r   )r   r   )r/   r0   r1   r   rZ   r   r)   r   r   r~   r~      s\        % % % % JN) ) ) ) )$# # # # # #r   r~   )r2   
__future__r   r   loggingr@   typingr   r   r   r   typing_extensionsr   r	   collections.abcr
   torch.utils._tracebackr   	getLoggerr/   rJ   r   r   dictrR   typeBaseExceptionr3   __annotations__r5   r~   r)   r   r   <module>r      s     # " " " " "    9 9 9 9 9 9 9 9 9 9 9 9 - - - - - - - -  )(((((( 4 4 4 4 4 4 g!!L L L L L L L L* !#tCH~x](;<h}>UV

    P, P, P, P, P, P, P, P,f*# *# *# *# *# *# *# *# *# *#r   