
    7hT                         % S r SSKrSSKrSSKrSSKJr  SSKJrJrJ	r	  SSK
Jr  \R                  " \5      r " S S5      r\\\\\\4   \	\\      \	\   /S4   r\\S'    " S	 S
5      r " S S5      rg)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                   l    \ rS rSrSrSS\4S jjrS\S\SS4S	 jrS\4S
 jr	S\
\\\4      4S jrSrg)TopN   zW
Helper to record a list of metrics, keeping only the top N "most expensive" elements.
at_mostc                     Xl         / U l        g Nr   heap)selfr   s     W/var/www/fran/franai/venv/lib/python3.13/site-packages/torch/_dynamo/metrics_context.py__init__TopN.__init__    s    +-	    keyvalreturnNc                     [        U R                  5      U R                  :  a  [        R                  O[        R
                  nU" U R                  X!45        g r   )lenr   r   heapqheappushheappushpop)r   r   r   fns       r   addTopN.add$   s6    "499~<U^^%BSBS
499sj!r   c                 ,    [        U R                  5      $ r   )r   r   r   s    r   __len__TopN.__len__)   s    499~r   c                 8    S [        U R                  SS9 5       $ )Nc              3   ,   #    U  H
  u  pX!4v   M     g 7fr    ).0r   r   s      r   	<genexpr> TopN.__iter__.<locals>.<genexpr>-   s     K+Jxs
+Js   T)reverse)sortedr   r!   s    r   __iter__TopN.__iter__,   s    K6$))T+JKKr   r   )   )__name__
__module____qualname____firstlineno____doc__intr   r   r   r"   r   tupler,   __static_attributes__r&   r   r   r	   r	      sT    . ."s " " "
 L(5c?3 Lr   r	   
OnExitTypec            	       $   \ rS rSrS\4S jrSS jrS\\\	      S\\	   S\
SS	4S
 jrS\4S jrS\S\SS	4S jrSS\S\
S\SS	4S jjrS\S\S\
SS	4S jrSS\\\
4   S\SS	4S jjrS\\\
4   SS	4S jrS\S\
SS	4S jrS\S\
S\SS	4S jrSrg	)MetricsContext6   on_exitc                 :    Xl         0 U l        SU l        SU l        g)a)  
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   r;   s     r   r   MetricsContext.__init__7   s      (*#$r   r   c                     U R                   S:X  a!  0 U l        [        R                  " 5       U l        U =R                   S-  sl         U $ )z
Initialize metrics recording.
r      )r@   r>   timetime_nsr?   r!   s    r   	__enter__MetricsContext.__enter__C   s8     ;;!DM"&,,.Dqr   exc_type	exc_value
_tracebackNc                 8   U =R                   S-  sl         U R                   S:  d   eU R                   S:X  a>   [        R                  " 5       nU R                  U R                  X@R
                  X5        gg! [         a    [        R                  S5         gf = f)z.
At exit, call the provided on_exit function.
rD   r   z0Unexpected exception logging compilation metricsN)	r@   rE   rF   r=   r?   r>   	Exceptionlog	exception)r   rI   rJ   rK   end_time_nss        r   __exit__MetricsContext.__exit__O   s     	q{{a;;!R"lln''mmX   RPQRs   <A7 7BBc                      U R                   S:  $ )z$
True if we've entered the context.
r   )r@   r!   s    r   in_progressMetricsContext.in_progressc   s     {{Qr   metricvaluec                     U R                   S:X  a  [        SU S35      eXR                  ;  a  SU R                  U'   U R                  U==   U-  ss'   g)'
Increment a metric by a given amount.
r   zCannot increment  outside of a MetricsContextNr@   RuntimeErrorr>   r   rV   rW   s      r   	incrementMetricsContext.incrementi   sR     ;;!!26(:VWXX&$%DMM&!f&r   	overwritec                     U R                   S:X  a  [        SU S35      eXR                  ;   a  U(       d  [        SU S35      eX R                  U'   g)zj
Set a metric to a given value. Raises if the metric has been assigned previously
in the current context.
r   Cannot set rZ   zMetric 'z-' has already been set in the current contextNr[   )r   rV   rW   r`   s       r   setMetricsContext.sets   sY    
 ;;!VH4PQRR]]"96("OP  !&fr   r   c                     U R                   S:X  a  [        SU S35      eXR                  ;  a  0 U R                  U'   X0R                  U   U'   g)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   rb   rZ   Nr[   )r   rV   r   rW   s       r   set_key_valueMetricsContext.set_key_value   sN     ;;!VH4PQRR&$&DMM&!%*fc"r   valuesc                     U R                   S:X  a  [        S5      eU R                  R                  5       UR                  5       -  nU(       a  U(       d  [        SU S35      eU R                  R	                  U5        g)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)r@   r\   r>   keysupdate)r   rh   r`   existings       r   rl   MetricsContext.update   sl     ;;!RSS==%%'&++-7IXJ&ST  	V$r   c                 ~    U R                   S:X  a  [        S5      eU R                   S:X  a  U R                  U5        gg)z1
Update, but only when at the outermost context.
r   rj   rD   N)r@   r\   rl   )r   rh   s     r   update_outerMetricsContext.update_outer   s9     ;;!RSS;;!KK r   c                     U R                   S:X  a  [        SU S35      eXR                  ;  a  [        5       U R                  U'   U R                  U   R	                  U5        g)z(
Records a metric as a set() of values.
r   zCannot add rZ   N)r@   r\   r>   rc   r   r]   s      r   
add_to_setMetricsContext.add_to_set   sV     ;;!VH4PQRR&$'EDMM&!f!!%(r   r   c                     U R                   S:X  a  gXR                  ;  a  [        5       U R                  U'   U R                  U   R                  X#5        g)z+
Records a metric as a TopN set of values.
r   N)r@   r>   r	   r   )r   rV   r   r   s       r   	add_top_nMetricsContext.add_top_n   sD     ;;!&$(FDMM&!f!!#+r   )r@   r>   r=   r?   )r   r9   )F)r/   r0   r1   r2   r7   r   rG   r   typeBaseExceptionr   rQ   boolrT   strr4   r^   rc   rf   dictrl   rp   rs   rv   r6   r&   r   r   r9   r9   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   r9   c            
       \    \ rS rSrS\4S jr SS\S\S\\	\\
4      SS4S	 jjrSS
 jrSrg)RuntimeMetricsContext   r;   c                 ,    Xl         0 U l        SU l        g)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)r=   r>   r?   rA   s     r   r   RuntimeMetricsContext.__init__   s      (*#$r   NrV   rW   extrar   c                 N   U R                   (       d  [        R                  " 5       U l        XR                   ;  a  SU R                   U'   U R                   U==   U-  ss'   U(       a>  UR	                  5        H)  u  pEX@R                   ;  d  M  Uc  M  XPR                   U'   M+     gg)rY   r   N)r>   rE   rF   r?   items)r   rV   rW   r   kvs         r   r^   RuntimeMetricsContext.increment   sy     }}"&,,.D&$%DMM&!f&MM)am'(MM!$ & r   c                    U R                   (       aF   [        R                  " 5       nU R                  U R                  XR                   SS5        0 U l         gg! [
         a    [        R                  S5         N*f = f! 0 U l         f = f)zG
Call the on_exit function with the metrics gathered so far and reset.
Nz,Unexpected exception logging runtime metrics)r>   rE   rF   r=   r?   rM   rN   rO   )r   rP   s     r   finishRuntimeMetricsContext.finish   sr     ==#"lln''mmT4 !#   NLMN !#s#   =A A;8A> :A;;A> >	B)r>   r=   r?   r   )r   N)r/   r0   r1   r2   r7   r   r{   r4   r   r|   r   r^   r   r6   r&   r   r   r~   r~      sL    %
 % JN))"%).6tCH~.F)	)$#r   r~   )r3   r   loggingrE   collections.abcr   typingr   r   r   typing_extensionsr   	getLoggerr/   rN   r	   r4   r|   r{   rx   ry   r7   __annotations__r9   r~   r&   r   r   <module>r      s       $ * * ' !L L* !#tCH~x](;<h}>UV

I B, B,J*# *#r   