
    N j;                        S r SSKJr  SSKJr  SSKJrJr  \(       a  SSKr\ " S S5      5       r	\ " S S	5      5       r
 " S
 S5      rg)a  
Dynamo Profiler - tracks where Dynamo spends time during compilation.

This module provides profiling functionality for Dynamo tracing, showing per-function
cumtime (inclusive) and tottime (exclusive) in a cProfile-compatible format.
The output can be visualized with tools like snakeviz.

Usage:
    # Enable via config (prints pstats output):
    torch._dynamo.config.dynamo_profiler = True

    # Or save to file for snakeviz:
    torch._dynamo.config.dynamo_profiler = "/tmp/dynamo.prof"
    # Then: snakeviz /tmp/dynamo.prof
    )annotations)	dataclass)AnyTYPE_CHECKINGNc                  (   \ rS rSr% SrS\S'   S\S'   S\S'   S\S'   S\S	'   S\S
'   S\S'   SrS\S'   SrS\S'   SrS\S'   Sr	S\S'   Sr
S\S'   \SS j5       r\S S j5       r\S S j5       r\S S j5       r\S!S j5       r\S"S j5       rS#S jrSrg)$FunctionTraceTiming   a  
Timing data for a single inlined function trace.

Follows cProfile conventions:
- cumtime: total time in function including all subcalls (inclusive)
- tottime: time in function excluding subcalls (exclusive)
- caller info: who called this function (for building call graph)
str	func_namefilenameintfirstlineno
cumtime_ns
tottime_nsbytecode_countinline_depthN
str | Nonecaller_func_namecaller_filenamez
int | Nonecaller_firstlinenoTboolis_primitive_call  tuple[tuple[str, str, int], ...]
call_stackc                    U R                   $ Nr   selfs    n/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/torch/_dynamo/dynamo_profiler.pytrace_time_ns!FunctionTraceTiming.trace_time_ns=   s        c                     U R                   S-  $ Ng    .Ar   r   s    r!   trace_time_ms!FunctionTraceTiming.trace_time_msA       $$r$   c                     U R                   S-  $ r&   r   r   s    r!   
cumtime_msFunctionTraceTiming.cumtime_msE   r)   r$   c                     U R                   S-  $ r&   )r   r   s    r!   
tottime_msFunctionTraceTiming.tottime_msI   r)   r$   c                    U R                   b5  U R                  =(       d    SU R                  =(       d    SU R                   4$ g)z/Return caller as a pstats-compatible key tuple.N r   )r   r   r   r   s    r!   
caller_keyFunctionTraceTiming.caller_keyM   sD       ,$$*'',1%% 
 r$   c                H    U R                   U R                  U R                  4$ )z6Return this function as a pstats-compatible key tuple.)r   r   r   r   s    r!   func_keyFunctionTraceTiming.func_keyX   s     t//@@r$   c                    SU R                    SU R                   SU R                   SU R                  S SU R                  S SU R
                   SU R                   S	3$ )
NzFunctionTraceTiming(z at :z
, cumtime=.2fzms, tottime=zms, bytecode=z, depth=))r   r   r   r+   r.   r   r   r   s    r!   __repr__FunctionTraceTiming.__repr__]   sp    "4>>"2$t}}oQtGWGWFX Ys+<7L M++,HT5F5F4GqJ	
r$   )returnr   )r=   float)r=   ztuple[str, int, str] | None)r=   ztuple[str, int, str])r=   r
   )__name__
__module____qualname____firstlineno____doc____annotations__r   r   r   r   r   propertyr"   r'   r+   r.   r2   r5   r;   __static_attributes__r   r$   r!   r   r      s     NMOO#'j'"&OZ&%)
) #t" 46J05   % % % % % %   A A
r$   r   c                  Z    \ rS rSr% SrS\S'   S\S'   S\S'   S\S'   S\S	'   S
rS\S'   Srg)ProfilerStackEntrye   z@Stack entry for tracking function timing in the Dynamo profiler.r
   r   r   r   r   start_time_nschild_time_nsTr   r   r   N)r?   r@   rA   rB   rC   rD   r   rF   r   r$   r!   rH   rH   e   s,    JNM"t"r$   rH   c                      \ rS 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	 jrSS
 jr S     SS jjr S     SS jjr S     SS jjrSrg)DynamoProfilerStateq   z:State for Dynamo profiler tracking function trace timings.c                     / U l         / U l        g r   )timingsstackr   s    r!   __init__DynamoProfilerState.__init__t   s    24/1
r$   c                :    U R                   R                  U5        g)z)Record timing data for a traced function.N)rP   append)r    timings     r!   record_timing!DynamoProfilerState.record_timingx   s    F#r$   c                    U R                   $ )zGet all recorded timings.)rP   r   s    r!   get_timingsDynamoProfilerState.get_timings|   s    ||r$   c                   ^^^ [        UUU4S jU R                   5       5      (       + nU R                  R                  [        TTTUSUS95        g)z'Push a new entry onto the timing stack.c              3     >#    U  H@  nUR                   T:H  =(       a%    UR                  T:H  =(       a    UR                  T:H  v   MB     g 7fr   r   r   r   ).0entryr   r   r   s     r!   	<genexpr>+DynamoProfilerState.push.<locals>.<genexpr>   sN      
 $ OOy( 1(*1!![01 $s   AAr   )r   r   r   rJ   rK   r   N)anyrQ   rU   rH   )r    r   r   r   rJ   is_primitives    ```  r!   pushDynamoProfilerState.push   sU    
  
 	
 
 
 	

#!'+".		
r$   c                Z    U R                   (       a  U R                   R                  5       $ g)z(Pop the top entry from the timing stack.N)rQ   popr   s    r!   rh   DynamoProfilerState.pop   s    ::::>>##r$   c                l    U R                   (       a#  U R                   S   =R                  U-  sl        gg)zGAdd the child's cumulative time to the parent's child_time accumulator.N)rQ   rK   )r    child_cumtime_nss     r!   add_child_time"DynamoProfilerState.add_child_time   s(    ::JJrN((,<<( r$   c                    U R                   (       a2  U R                   S   nUR                  UR                  UR                  4$ g)zLGet the current caller (top of stack) as (func_name, filename, firstlineno).rk   N)rQ   r   r   r   )r    r`   s     r!   get_current_caller&DynamoProfilerState.get_current_caller   s4    ::JJrNEOOU^^U5F5FGGr$   c                :    [        S U R                   5       5      $ )zOGet the full current call stack as tuple of (func_name, filename, firstlineno).c              3  f   #    U  H'  oR                   UR                  UR                  4v   M)     g 7fr   r^   )r_   r`   s     r!   ra   5DynamoProfilerState.get_call_stack.<locals>.<genexpr>   s&      
NXU__enne.?.?@js   /1)tuplerQ   r   s    r!   get_call_stack"DynamoProfilerState.get_call_stack   s      
NRjj
 
 	
r$   Nc                   SSK nSSKnSSKnSSKnUR	                  [
        5      n0 n0 n	U R                   GH]  n
U
R                  U
R                  U
R                  4nX;  a  SSSSS.X'   0 X'   X   nUS==   S-  ss'   US==   U
R                  S-  -  ss'   U
R                  (       a'  US	==   S-  ss'   US
==   U
R                  S-  -  ss'   U
R                  c  M  U
R                  U
R                  =(       d    SU
R                  =(       d    S4nXU   ;  a  SSSSS.X   U'   X   U   nUS==   S-  ss'   US==   U
R                  S-  -  ss'   US
==   U
R                  S-  -  ss'   U
R                  (       d  GMP  US	==   S-  ss'   GM`     U(       Ga  [!        UR#                  5       S SS9n[%        S5        [%        SS SS	S SSS SS
S S35        [%        S5        SnSnU Hn  u  u  nnnnUS   nUS	   nUS   S-  nUS
   S-  nUU-  nUU-  nSU;   a  UR'                  S5      S   OUn[%        US SUS SUS SUS SU SU SU S35        Mp     [%        S5        [%        S[)        U R                  5       S[)        U5       35        [%        S US! S"US! S#35        [+        U	R-                  5       5       H"  nX    H  nX;  d  M
  SSSSS.X'   0 X'   M     M$     0 nUR#                  5        HM  u  p0 nX   R#                  5        H  u  pUS   US	   US   US
   4UU'   M     US	   US   US   US
   U4UU'   MO     UR/                  5       nUR1                  5         UR3                  5         UR4                  " UUR7                  5       S$9nUUl        [;        S% UR=                  5        5       5      Ul        [;        S& UR=                  5        5       5      Ul         [;        S' UR=                  5        5       5      Ul!        U(       a$  URE                  U5        URG                  S(UU5        U$ ))zGenerate pstats.Stats object from recorded timings.

Args:
    output_file: Optional file path to save the stats.
    print_raw: If True, print raw aggregate timings before returning.
r   Ng        )ncallspcallstottimecumtimery      r{   g    eArz   r|   r1   c                    U S   S   $ )Nr}   r|   r   )xs    r!   <lambda>5DynamoProfilerState.generate_pstats.<locals>.<lambda>   s    !A$y/r$   T)keyreversez 
=== Aggregate Timings (raw) ===z>8 z>12z
  functionzP--------------------------------------------------------------------------------i  /rk   z>10.2fzms zms  z (r8   r:   zTotal timings: z, unique functions: zSum tottime: r9   zms, Sum cumtime: ms)streamc              3  *   #    U  H	  oS    v   M     g7f)r}   Nr   r_   ss     r!   ra   6DynamoProfilerState.generate_pstats.<locals>.<genexpr>;  s     B.A!.A   c              3  *   #    U  H	  oS    v   M     g7f)r   Nr   r   s     r!   ra   r   <  s     A-@t-@r   c              3  *   #    U  H	  oS    v   M     g7f)   Nr   r   s     r!   ra   r   =  s     ?+>aqT+>r   z/Saved pstats to %s. Visualize with: snakeviz %s)$cProfileiologgingpstats	getLoggerr?   rP   r   r   r   r   r   r   r   r   r   sorteditemsprintsplitlenlistkeysProfileenabledisableStatsStringIOstatssumvaluestotal_calls
prim_callstotal_tt
dump_statsinfo)r    output_file	print_rawr   r   r   r   log
aggregatedcaller_edgestr   aggr2   edgesorted_itemstotal_cumtimetotal_tottimer   linenor   ry   rz   r{   r|   
short_file
stats_dictcallersdummy_profiler   s                                 r!   generate_pstats#DynamoProfilerState.generate_pstats   s    	) BD
  	 A::q}}akk:C$""	#
 %'!/CMQM	NallS00N""H"I!,,"44   ,%%((-A&&,"

 #%66"#"##&#&	5L%j1 $(4X!#Y1<<##55 Y1<<##55&&&Na'NS V !  "(A4L 56B-q"QyoQyoZX (OMM6B2-69sXXi.4/i.4/((8;xX^^C04X
bk6"+Qwv.>c'&AQQU kJ<q; 7C (O!#dll"3!44HZHYZ c22CMRUCVVXY ))+,C*/
/"#"##&#&	.J* 02L, 0 -  	 #((*HCQSG$0$5$;$;$= 
NNOO	'
# %> HHIIJsO +& !((*]2;;=A Bj.?.?.ABBAZ->->-@AA?:+<+<+>??[)HHA r$   c           	        SSK nSSKnSSKnUR                  S5      (       d  [	        S5        gUR                  S5      (       d  [	        S5        gUc  UR                  SS5      S   S	-   n UR                  SS
SSSSU/UR                  UR                  S9nUR                  SSSU/UR                  UR                  UR                  S9nUR                  R                  5         UR                  5       u  pUR                  5       u  pUR                  S:w  a  [	        SU
R                  5        35        gUR                  S:w  a  [	        SU	R                  5        35        gUR                  R                  U5      (       d  [	        SU 35        g[	        SU 35        U$ ! [         a  n[	        SU 35         SnAgSnAff = f)aC  Generate an SVG call graph from a profile file using gprof2dot and graphviz.

Args:
    profile_file: Path to the pstats profile file.
    svg_file: Optional path for the output SVG. If not provided, uses
        profile_file with .svg extension.

Returns:
    Path to the generated SVG file, or None if generation failed.
r   N	gprof2dotz8gprof2dot not found. Install with: pip install gprof2dotdotz3graphviz 'dot' not found. Install graphviz package..r}   z.svgz-fr   z"--node-label=total-time-percentagez!--node-label=self-time-percentagez--node-label=total-time)stdoutstderrz-Tsvgz-o)stdinr   r   zgprof2dot failed: zgraphviz dot failed: zSVG file was not created: zSVG call graph saved to: zFailed to generate SVG: )osshutil
subprocesswhichr   rsplitPopenPIPEr   closecommunicate
returncodedecodepathisfile	Exception)r    profile_filesvg_filer   r   r   r   r   _dot_errgprof2dot_erres               r!   generate_svg DynamoProfilerState.generate_svgI  s    	||K((LM||E""GH#**3215>H,	"((87-  "! ) I ""x0&&!!	 # C ""$*JA(446A##q(()=)=)?(@A ~~"-gnn.>-?@A77>>(++28*=>-hZ89O 	,QC01	s+   -C
F$ 8,F$ %.F$ F$ $
G.GGc                @   SSK nU R                  (       d  gU R                  USS9n[        S5        UR                  Ul        UR                  S5      R                  5         U(       a6  [        SU 35        [        SU 35        U(       a  U R                  U5        ggg)	zPrint profiler stats to stdout and optionally save to file.

Args:
    output_file: Optional path to save the pstats profile.
    generate_svg: If True and output_file is provided, also generate an SVG
        call graph using gprof2dot and graphviz.
r   NT)r   z!
=== Dynamo Profiler (pstats) ===
cumulativez
Profile saved to: zVisualize with: snakeviz )	sysrP   r   r   r   r   
sort_statsprint_statsr   )r    r   r   r   r   s        r!   r   DynamoProfilerState.dump_stats  s     	||$$[D$A23zz&224(67-k];<!!+. 	 r$   )rQ   rP   )r=   None)rV   r   r=   r   )r=   zlist[FunctionTraceTiming])
r   r
   r   r
   r   r   rJ   r   r=   r   )r=   zProfilerStackEntry | None)rl   r   r=   r   )r=   ztuple[str, str, int] | None)r=   r   )NF)r   r   r   r   r=   zpstats.Statsr   )r   r
   r   r   r=   r   )NT)r   r   r   r   r=   r   )r?   r@   rA   rB   rC   rR   rW   rZ   re   rh   rm   rp   rv   r   r   r   rF   r   r$   r!   rM   rM   q   s    D2$

(+
:=
NQ
	
,=

 AFY%Y9=Y	Yx 9=HH+5H	HV DH/%/<@/	/ /r$   rM   )rC   
__future__r   dataclassesr   typingr   r   r   r   rH   rM   r   r$   r!   <module>r      s_     # ! %  F
 F
 F
R # # #{/ {/r$   