
    9i"                       % S r SSKJr  SSKrSSKrSSKrSSKJrJrJ	r	J
r
  SSKJrJr  \
(       a  SSKJr  SSKJr  \R$                  " \5      r " S S	5      r\\\\\\4   \	\\      \	\   /S4   rS
\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.
    )annotationsN)AnyCallableOptionalTYPE_CHECKING)Self	TypeAlias)Iterator)CapturedTracebackc                  D    \ rS rSrSrS	S
S jjrSS jrSS jrSS jrSr	g)TopN"   zW
Helper to record a list of metrics, keeping only the top N "most expensive" elements.
c                    Xl         / U l        g Nat_mostheap)selfr   s     ]/var/www/html/land-doc-ocr/venv/lib/python3.13/site-packages/torch/_dynamo/metrics_context.py__init__TopN.__init__'   s    +-	    c                    [        U R                  5      U R                  :  a  [        R                  O[        R
                  nU" U R                  X!45        g r   )lenr   r   heapqheappushheappushpop)r   keyvalfns       r   addTopN.add+   s6    "499~<U^^%BSBS
499sj!r   c                ,    [        U R                  5      $ r   )r   r   r   s    r   __len__TopN.__len__0   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>4   s     K+Jxs
+Js   T)reverse)sortedr   r$   s    r   __iter__TopN.__iter__3   s    K6$))T+JKKr   r   N)   )r   int)r   r   r   r2   returnNone)r3   r2   )r3   zIterator[tuple[Any, int]])
__name__
__module____qualname____firstlineno____doc__r   r!   r%   r/   __static_attributes__r)   r   r   r   r   "   s    ."
Lr   r   r	   
OnExitTypec                      \ rS rSrSS jrSS jr        SS jrSS jrSS jrSS jr	SSS jjr
SS	 jrSSS
 jjrSS jrSS jrSS jrSrg)MetricsContext=   c                H    Xl         0 U l        SU l        SU l        / 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_editsr   on_exits     r   r   MetricsContext.__init__>   s&      (*#$@B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      )rC   rA   timetime_nsrB   r$   s    r   	__enter__MetricsContext.__enter__K   s8     ;;!DM"&,,.Dqr   c                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.
rI   r   z0Unexpected exception logging compilation metricsN)	rC   rJ   rK   r@   rB   rA   	Exceptionlog	exception)r   exc_type	exc_value
_tracebackend_time_nss        r   __exit__MetricsContext.__exit__W   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   )rC   r$   s    r   in_progressMetricsContext.in_progressk   s     {{Qr   c                    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rC   RuntimeErrorrA   r   metricvalues      r   	incrementMetricsContext.incrementq   sR     ;;!!26(:VWXX&$%DMM&!f&r   c                T   ^ SSR                  U4S jU R                   5       5      -   $ )Nz

c              3     >#    U  H5  u  pUT-  (       d  M  S SR                  UR                  5       5      -   v   M7     g7f)zPrevious Traceback:
 N)joinformat)r*   ekpreds      r   r+   /MetricsContext._render_edits.<locals>.<genexpr>|   s8      $
#4x :#bggahhj&99#s
   A )A )rh   rD   )r   rl   s    `r   _render_editsMetricsContext._render_edits{   s,     $
$
 
 
 	
r   c                .   U R                   S:X  a  [        SU S35      eXR                  ;   a)  U(       d"  [        U R                  U15      SU S3-   5      eU R                  R                  [        R                  " SS9U145        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 r]   z

RuntimeError: Metric 'z]' has already been set in the current context (see above for current and previous traceback).rI   skipN)rC   r_   rA   rn   rD   appendr   extract)r   ra   rb   	overwrites       r   setMetricsContext.set   s    
 ;;!VH4PQRR]]"9""F8,.vh 7B BB 
 	-551=xHI %f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   rq   r]   Nr^   )r   ra   r   rb   s       r   set_key_valueMetricsContext.set_key_value   sN     ;;!VH4PQRR&$&DMM&!%*fc"r   c                   U R                   S:X  a  [        S5      eU R                  R                  5       UR                  5       -  nU(       a?  U(       d8  [        U R	                  [        UR                  5       5      5      SU S3-   5      eU R                  R                  [        R                  " SS9[        UR                  5       5      45        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

RuntimeError: Metric(s) z_ have already been set in the current context.  (see above for current and previous traceback).rI   rr   N)rC   r_   rA   keysrn   rw   rD   rt   r   ru   update)r   valuesrv   existings       r   r   MetricsContext.update   s     ;;!RSS==%%'&++-7I""3v{{}#560
 ;B BB 
 	-551=s6;;=?QRS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   r}   rI   N)rC   r_   r   )r   r   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 r]   N)rC   r_   rA   rw   r!   r`   s      r   
add_to_setMetricsContext.add_to_set   sV     ;;!VH4PQRR&$'EDMM&!f!!%(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)rC   rA   r   r!   )r   ra   r   r   s       r   	add_top_nMetricsContext.add_top_n   sD     ;;!&$(FDMM&!f!!#+r   )rD   rC   rA   r@   rB   NrF   r;   )r3   r   )rR   zOptional[type[BaseException]]rS   zOptional[BaseException]rT   r   r3   r4   )r3   bool)ra   strrb   r2   r3   r4   )rl   zset[str]r3   r   )F)ra   r   rb   r   rv   r   r3   r4   )ra   r   r   r   rb   r   r3   r4   )r   dict[str, Any]rv   r   r3   r4   )r   r   r3   r4   )ra   r   rb   r   r3   r4   )ra   r   r   r   r   r2   r3   r4   )r5   r6   r7   r8   r   rL   rV   rY   rc   rn   rw   rz   r   r   r   r   r:   r)   r   r   r=   r=   =   sj    C
R/R +R 	R
 
R('
& +%$ ),r   r=   c                  F    \ rS rSrSS jr S       S	S jjrS
S jrSrg)RuntimeMetricsContext   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@   rA   rB   rE   s     r   r   RuntimeMetricsContext.__init__   s      (*#$r   Nc                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)r\   r   N)rA   rJ   rK   rB   items)r   ra   rb   extrark   vs         r   rc   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)rA   rJ   rK   r@   rB   rO   rP   rQ   )r   rU   s     r   finishRuntimeMetricsContext.finish   sr     ==#"lln''mmT4 !#   NLMN !#s#   =A A;8A> :A;;A> >	B)rA   r@   rB   r   r   )ra   r   rb   r2   r   zOptional[dict[str, Any]]r3   r4   )r3   r4   )r5   r6   r7   r8   r   rc   r   r:   r)   r   r   r   r      s8    % JN))"%).F)	)$#r   r   )r9   
__future__r   r   loggingrJ   typingr   r   r   r   typing_extensionsr   r	   collections.abcr
   torch.utils._tracebackr   	getLoggerr5   rP   r   r2   dictr   typeBaseExceptionr;   __annotations__r=   r   r)   r   r   <module>r      s    #    9 9 - ( 4 !L L* !#tCH~x](;<h}>UV

I P, P,f*# *#r   