
    rhT                         U d Z ddl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  ej                  e      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     p/var/www/html/ai-insurance-compliance-backend/venv/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__7   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__C   s8     ;;!DM"&,,.Dqr   exc_type	exc_value
_tracebackNc                 4   | xj                   dz  c_         | j                   dk\  sJ | j                   dk(  r?	 t        j                         }| j                  | j                  || j
                  ||       yy# t        $ r t        j                  d       Y yw xY w)z>
        At exit, call the provided on_exit function.
        r9   r   z0Unexpected exception logging compilation metricsN)	r6   r:   r;   r3   r5   r4   	Exceptionlog	exception)r   r=   r>   r?   end_time_nss        r   __exit__zMetricsContext.__exit__O   s     	q{{a;;!R"lln''dmmXy   RPQRs   =A6 6BBc                      | j                   dkD  S )z4
        True if we've entered the context.
        r   )r6   r   s    r   in_progresszMetricsContext.in_progressc   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   rH   rI   s      r   	incrementzMetricsContext.incrementi   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 rL   zMetric 'z-' has already been set in the current contextNrM   )r   rH   rI   rQ   s       r   setzMetricsContext.sets   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   rS   rL   NrM   )r   rH   r   rI   s       r   set_key_valuezMetricsContext.set_key_value   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   rN   r4   keysupdate)r   rW   rQ   existings       r   r[   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   rY   r9   N)r6   rN   r[   )r   rW   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 rL   N)r6   rN   r4   rT   r   rO   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   rH   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   rE   boolrG   strr,   rP   rT   rV   dictr[   r^   r`   rb   r!   r   r   r0   r0   6   s2   

 

R4./R M*R 	R
 
R(T ' 'C 'D '&# &c &d &t &+C +c +# +$ +%T#s(^ % % % 4S>  d  ) )S )T ), ,# ,C ,D ,r   r0   c            
       L    e Zd ZdefdZ	 d
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   NrH   rI   extrar   c                 .   | j                   st        j                         | _        || j                   vrd| j                   |<   | j                   |xx   |z  cc<   |r:|j	                         D ]&  \  }}|| j                   vs||| j                   |<   ( yy)rK   r   N)r4   r:   r;   r5   items)r   rH   rI   rk   kvs         r   rP   zRuntimeMetricsContext.increment   s     }}"&,,.D&$%DMM&!f& )1DMM)am'(DMM!$) r   c                    | j                   rF	 t        j                         }| j                  | j                  || j                   dd       i | _         yy# t
        $ r t        j                  d       Y )w xY w# i | _         w xY w)zW
        Call the on_exit function with the metrics gathered so far and reset.
        Nz,Unexpected exception logging runtime metrics)r4   r:   r;   r3   r5   rA   rB   rC   )r   rD   s     r   finishzRuntimeMetricsContext.finish   st     ==#"lln''dmmT4 !#   NLMN !#s#   =A A52A8 4A55A8 8	Br   )r   N)r(   r)   r*   r.   r   rf   r,   r   rg   r   rP   rq   r!   r   r   ri   ri      sL    %
 % JN))"%).6tCH~.F)	)$#r   ri   )r+   r   loggingr:   collections.abcr   typingr   r   r   typing_extensionsr   	getLoggerr(   rB   r	   r,   rg   rf   rc   rd   r.   __annotations__r0   ri   r!   r   r   <module>rx      s       $ * * ' g!L L* !#tCH~x](;<h}>UV

I B, B,J*# *#r   