
    Vh                         U d Z 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
  G d d      Zeeeeeef   eee      ee   gdf   Ze
ed<    G d	 d
      Z G d d      Zy)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.
    N)Iterator)AnyCallableOptional)	TypeAliasc                   Z    e Zd ZdZddefdZdededdfdZdefd	Zde	e
eef      fd
Zy)TopNz_
    Helper to record a list of metrics, keeping only the top N "most expensive" elements.
    at_mostc                      || _         g | _        y N)r
   heap)selfr
   s     M/home/dcms/DCMS/lib/python3.12/site-packages/torch/_dynamo/metrics_context.py__init__zTopN.__init__   s    +-	    keyvalreturnNc                     t        | j                        | j                  k  rt        j                  nt        j
                  } || j                  ||f       y r   )lenr   r
   heapqheappushheappushpop)r   r   r   fns       r   addzTopN.add    s8    "499~<U^^%BSBS
499sCj!r   c                 ,    t        | j                        S r   )r   r   r   s    r   __len__zTopN.__len__%   s    499~r   c                 >    d t        | j                  d      D        S )Nc              3   *   K   | ]  \  }}||f  y wr    ).0r   r   s      r   	<genexpr>z TopN.__iter__.<locals>.<genexpr>)   s     KxsCc
Ks   T)reverse)sortedr   r   s    r   __iter__zTopN.__iter__(   s    K6$))T+JKKr   )   )__name__
__module____qualname____doc__intr   r   r   r   r   tupler&   r!   r   r   r	   r	      sT    . ."s " " "
 L(5c?3 Lr   r	   
OnExitTypec            	          e Zd ZdefdZddZdeee      dee   de	ddfd	Z
defd
ZdededdfdZddede	deddfdZdedede	ddfdZddeee	f   deddfdZdeee	f   ddfdZdede	ddfdZdede	deddfdZy)MetricsContexton_exitc                 <    || _         i | _        d| _        d| _        y)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r   r1   s     r   r   zMetricsContext.__init__3   s!      (*#$r   r   c                     | j                   dk(  r i | _        t        j                         | _        | xj                   dz  c_         | S )z/
        Initialize metrics recording.
        r      )r6   r4   timetime_nsr5   r   s    r   	__enter__zMetricsContext.__enter__?   s8     ;;!DM"&,,.Dqr   exc_type	exc_value
_tracebackNc                     | xj                   dz  c_         | j                   dk\  sJ | j                   dk(  r>t        j                         }| j                  | j                  || j
                  ||       yy)z>
        At exit, call the provided on_exit function.
        r9   r   N)r6   r:   r;   r3   r5   r4   )r   r=   r>   r?   end_time_nss        r   __exit__zMetricsContext.__exit__K   sa     	q{{a;;!,,.KMM##[$--9 r   c                      | j                   dkD  S )z4
        True if we've entered the context.
        r   )r6   r   s    r   in_progresszMetricsContext.in_progress\   s     {{Qr   metricvaluec                     | j                   dk(  rt        d| d      || j                  vrd| j                  |<   | j                  |xx   |z  cc<   y)7
        Increment a metric by a given amount.
        r   zCannot increment  outside of a MetricsContextNr6   RuntimeErrorr4   r   rE   rF   s      r   	incrementzMetricsContext.incrementb   sT     ;;!!26(:VWXX&$%DMM&!f&r   	overwritec                     | j                   dk(  rt        d| d      || j                  v r|st        d| d      || j                  |<   y)z
        Set a metric to a given value. Raises if the metric has been assigned previously
        in the current context.
        r   Cannot set rI   zMetric 'z-' has already been set in the current contextNrJ   )r   rE   rF   rN   s       r   setzMetricsContext.setl   s]    
 ;;!VH4PQRRT]]"96("OP  !&fr   r   c                     | j                   dk(  rt        d| d      || j                  vri | j                  |<   || j                  |   |<   y)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   rP   rI   NrJ   )r   rE   r   rF   s       r   set_key_valuezMetricsContext.set_key_valuey   sR     ;;!VH4PQRR&$&DMM&!%*fc"r   valuesc                     | j                   dk(  rt        d      | j                  j                         |j                         z  }|r|st        d| d      | j                  j	                  |       y)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
Metric(s) z- have already been set in the current contextN)r6   rK   r4   keysupdate)r   rT   rN   existings       r   rX   zMetricsContext.update   sl     ;;!RSS==%%'&++-7IXJ&ST  	V$r   c                 z    | j                   dk(  rt        d      | j                   dk(  r| j                  |       yy)zA
        Update, but only when at the outermost context.
        r   rV   r9   N)r6   rK   rX   )r   rT   s     r   update_outerzMetricsContext.update_outer   s9     ;;!RSS;;!KK r   c                     | j                   dk(  rt        d| d      || j                  vrt               | j                  |<   | j                  |   j	                  |       y)z8
        Records a metric as a set() of values.
        r   zCannot add rI   N)r6   rK   r4   rQ   r   rL   s      r   
add_to_setzMetricsContext.add_to_set   sX     ;;!VH4PQRR&$'EDMM&!f!!%(r   r   c                     | j                   dk(  ry|| j                  vrt               | j                  |<   | j                  |   j                  ||       y)z;
        Records a metric as a TopN set of values.
        r   N)r6   r4   r	   r   )r   rE   r   r   s       r   	add_top_nzMetricsContext.add_top_n   sH     ;;!&$(FDMM&!f!!#s+r   )r   r0   )F)r(   r)   r*   r.   r   r<   r   typeBaseExceptionr   rB   boolrD   strr,   rM   rQ   rS   dictrX   r[   r]   r_   r!   r   r   r0   r0   2   s-   

 

4./ M* 	
 
"T ' 'C 'D '&# &c &d &t &+C +c +# +$ +%T#s(^ % % % 4S>  d  ) )S )T ), ,# ,C ,D ,r   r0   c            	       H    e Zd ZdefdZdededeeee	f      ddfdZ
d
d	Zy)RuntimeMetricsContextr1   c                 .    || _         i | _        d| _        y)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)r3   r4   r5   r7   s     r   r   zRuntimeMetricsContext.__init__   s      (*#$r   rE   rF   extrar   Nc                 .   | j                   st        j                         | _        || j                   vrd| j                   |<   | j                   |xx   |z  cc<   |r:|j	                         D ]&  \  }}|| j                   vs||| j                   |<   ( yy)rH   r   N)r4   r:   r;   r5   items)r   rE   rF   rh   kvs         r   rM   zRuntimeMetricsContext.increment   s     }}"&,,.D&$%DMM&!f& )1DMM)am'(DMM!$) r   c                     | j                   rEt        j                         }| j                  | j                  || j                   dd       i | _         yy)zW
        Call the on_exit function with the metrics gathered so far and reset.
        N)r4   r:   r;   r3   r5   )r   rA   s     r   finishzRuntimeMetricsContext.finish   sA     ==,,.KMM$--{DMM4QUVDM r   )r   N)r(   r)   r*   r.   r   rc   r,   r   rd   r   rM   rn   r!   r   r   rf   rf      sE    %
 %))"%).6tCH~.F)	)$r   rf   )r+   r   r:   collections.abcr   typingr   r   r   typing_extensionsr   r	   r,   rd   rc   r`   ra   r.   __annotations__r0   rf   r!   r   r   <module>rs      s      $ * * 'L L* !#tCH~x](;<h}>UV

I , ,D$ $r   