
    Pg                         U d dl Z d dlmZ d dlmZ d dlmZ d dlmZm	Z	m
Z
mZmZ d dlmZ d dlZd dlZd dlmZ d dlmZ d d	lmZmZmZmZmZmZmZmZmZmZm Z m!Z! d d
l"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z* d dl+m,Z, g dZ-	 d dl.m/Z0 da3e4e5d<   de4fdZ6d Z7d Z8e G d d             Z9 G d d      Z: G d de0      Z; G d d      Z< G d d      Z=d  Z> G d! d"      Z?d# Z@ G d$ d%      ZAy# e1$ r d dl2Z2 G d d      Z0Y {w xY w)&    N)defaultdict)	dataclass)perf_counter_ns)AnyDictIterableListOptional)warn)_get_privateuse1_backend_name)_ExperimentalConfig)_disable_profiler_enable_profiler_kineto_step_prepare_profiler_ProfilerResult_supported_activities_toggle_collection_dynamic
DeviceTypekineto_availableProfilerActivityProfilerConfigProfilerState)_filter_name_filter_stack_entry_rewrite_name	EventListFunctionEventMEMORY_EVENT_NAMEMemRecordsAccOUT_OF_MEMORY_EVENT_NAME)Future)profilerecord_functionemit_itt	emit_nvtxload_nvprofEnforceUniqueparse_nvprof_traceKinetoStepTrackerr   r   r    )ContextDecoratorc                       e Zd Zd Zd Zd Zy)_ContextDecoratorc                     t         NNotImplementedErrorselfs    ^/var/www/html/suriana-translation/venv/lib/python3.12/site-packages/torch/autograd/profiler.py	__enter__z_ContextDecorator.__enter__=       %%    c                     t         r/   r0   r3   exc_typeexc_valexc_tbs       r4   __exit__z_ContextDecorator.__exit__@   r6   r7   c                 F     t        j                         fd       }|S )Nc                  D    5   | i |cd d d        S # 1 sw Y   y xY wr/    )argskwargsfuncr3   s     r4   wrappedz+_ContextDecorator.__call__.<locals>.wrappedD   s(     1001 1 1s   )	functoolswraps)r3   rC   rD   s   `` r4   __call__z_ContextDecorator.__call__C   s%    __T"1 #1 Nr7   N)__name__
__module____qualname__r5   r=   rG   r@   r7   r4   r-   r-   <   s    	&	&	r7   r-   F_is_profiler_enabledenablec                     | a y r/   )rK   )rL   s    r4   _set_is_profiler_enabledrN   Q   s    !r7   c                      t        d       y )NTrN   r@   r7   r4   _run_on_profiler_startrQ   V   s
    T"r7   c                      t        d       y NFrP   r@   r7   r4   _run_on_profiler_stoprT   Z   s
    U#r7   c                   t    e Zd ZU dZdZeed<   dZeed<   dZ	eed<   dZ
eed<   dZeed<   dZeed<   dZeed	<   y
)_ProfilerStatszHProfiler timing and stats used by developers to catch issues/regressionsr   profiling_window_duration_secnumber_of_events!profiler_prepare_call_duration_us profiler_enable_call_duration_us!profiler_disable_call_duration_usparse_kineto_call_duration_us+function_events_build_tree_call_duration_usN)rH   rI   rJ   __doc__rW   float__annotations__rX   intrY   rZ   r[   r\   r]   r@   r7   r4   rV   rV   ^   sR    N+,!5,c-.%s.,-$c--.%s.)*!3*78/8r7   rV   c                      e Zd ZdZ	 dddddddddddddddZd Zd Zd d	Zd
 Zd Z	d Z
d Zd Zd Zd Zed        Z	 	 	 	 	 	 	 d!dZej"                  j                  e_        d Zej&                  j                  e_        d"dedefdZdedee   fdZd#dZej4                  j                  e_        d Zej6                  j                  e_        ed        ZdefdZy)$r#   a  Context manager that manages autograd profiler state and holds a summary of results.

    Under the hood it just records events of functions being executed in C++ and
    exposes those events to Python. You can wrap any code into it and it will
    only report runtime of PyTorch functions.
    Note: profiler is thread local and is automatically propagated into the async tasks

    Args:
        enabled (bool, optional): Setting this to False makes this context manager a no-op.

        use_cuda (bool, optional): Enables timing of CUDA events as well
            using the cudaEvent API. (will be deprecated)

        use_device (str, optional): Enables timing of device events.
            Adds approximately 4us of overhead to each tensor operation when use cuda.
            The valid devices options are 'cuda', 'xpu', 'mtia' and 'privateuseone'.

        record_shapes (bool, optional): If shapes recording is set, information
            about input dimensions will be collected. This allows one to see which
            dimensions have been used under the hood and further group by them
            using prof.key_averages(group_by_input_shape=True). Please note that
            shape recording might skew your profiling data. It is recommended to
            use separate runs with and without shape recording to validate the timing.
            Most likely the skew will be negligible for bottom most events (in a case
            of nested function calls). But for higher level functions the total
            self cpu time might be artificially increased because of the shape
            collection.

        with_flops (bool, optional): If with_flops is set, the profiler will estimate
            the FLOPs (floating point operations) value using the operator's input shape.
            This allows one to estimate the hardware performance. Currently,
            this option only works for the matrix multiplication and 2D convolution operators.

        profile_memory (bool, optional): track tensor memory allocation/deallocation.

        with_stack (bool, optional): record source information (file and line number) for the ops.

        with_modules (bool): record module hierarchy (including function names)
            corresponding to the callstack of the op. e.g. If module A's forward call's
            module B's forward which contains an aten::add op,
            then aten::add's module hierarchy is A.B
            Note that this support exist, at the moment, only for TorchScript models
            and not eager mode models.

        use_kineto (bool, optional): experimental, enable profiling with Kineto profiler.

        use_cpu (bool, optional): profile CPU events; setting to ``False`` requires
            ``use_kineto=True`` and can be used to lower the overhead for GPU-only profiling.

        experimental_config (_ExperimentalConfig) : A set of experimental options
            used by profiler libraries like Kineto. Note, backward compatibility is not guaranteed.

        acc_events (bool): Enable the accumulation of FunctionEvents across multiple profiling cycles


    .. warning:
        Enabling memory profiling or source attribution incurs additional profiler
        overhead

    .. warning:
        This context managers should not be called recursively, i.e. no nested
        instances are allowed

    .. warning:
        Due to some CUDA multiprocessing limitations (multiprocessing-cuda-note_),
        one cannot use the profiler with ``use_device = 'cuda'`` to benchmark
        DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
        please use ``use_device = None`` or ``num_workers = 0``.

    Example:
        >>> # xdoctest: +SKIP
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
        >>> x = torch.randn((1, 1), requires_grad=True)
        >>> with torch.autograd.profiler.profile() as prof:
        >>>     for _ in range(100):  # any normal python code, really!
        >>>         y = x ** 2
        >>>         y.backward()
        >>> # NOTE: some columns were removed for brevity
        >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
        -----------------------------------  ---------------  ---------------  ---------------
        Name                                 Self CPU total   CPU time avg     Number of Calls
        -----------------------------------  ---------------  ---------------  ---------------
        mul                                  32.048ms         32.048ms         200
        pow                                  27.041ms         27.041ms         200
        PowBackward0                         9.727ms          55.483ms         100
        torch::autograd::AccumulateGrad      9.148ms          9.148ms          100
        torch::autograd::GraphRoot           691.816us        691.816us        100
        -----------------------------------  ---------------  ---------------  ---------------

    TFN)use_cuda
use_devicerecord_shapes
with_flopsprofile_memory
with_stackwith_modules
use_kinetouse_cpuexperimental_config
acc_eventscustom_trace_id_callbackc                d   || _         | j                   sy || _        | j                  rt        dt        d       d| _        n|| _        d | _        d | _        d| _        d| _        || _	        || _
        | xj                  | j                  z  c_	        || _        || _        || _        |
| _        || _        |
t!               }|| _        d | _        d| _        d| _        t+               | _        || _        d| _        | j                  s	|	sJ d       | j                  g d	}t3               d
k7  r|j5                  t3                      | j                  |vr t        d| j                   d       d | _        | j                  dk(  r7t6        j8                  j;                         st        d       d| _        d | _        | j                  dk(  r0t6        j<                  j;                         st        d       d | _        t?               | _         | j                  r)| j@                  jC                  tD        jF                         tH        jJ                  | _&        | j                  dk(  rq|	rtD        jN                  tQ               vr*| j                  sJ d       tH        jR                  | _&        nl| j@                  jC                  tD        jN                         nA| j                  dk(  rM|	rtD        jT                  tQ               v sJ d       | j@                  jC                  tD        jT                         n| j                  dk(  rM|	rtD        jV                  tQ               v sJ d       | j@                  jC                  tD        jV                         n| j                  }| j                  d
k7  rn|	rtD        jX                  tQ               vr)| j                  sJ d       tH        jZ                  | _&        n)| j@                  jC                  tD        jX                         t]        | j@                        dkD  sJ d       y )Nz]The attribute `use_cuda` will be deprecated soon, please use ``use_device = 'cuda'`` instead.   )
stacklevelcudaFr    z?Device-only events supported only with Kineto (use_kineto=True))rr   xpumtiaprivateuseonezThe z is not a valid device option.z/CUDA is not available, disabling CUDA profilingrt   z-XPU is not available, disabling XPU profilingz+Legacy CUDA profiling requires use_cpu=TruezOLegacy XPU profiling is not supported. Requires use_kineto=True on XPU devices.ru   zQLegacy MTIA profiling is not supported. Requires use_kineto=True on MTIA devices.z4Legacy custombackend profiling requires use_cpu=Truez(No activities specified for the profiler)/enabledrc   r   FutureWarningrd   _function_events_old_function_events_needs_processingenteredre   rf   rg   rh   ri   rk   rm   r   rl   kineto_resultsprofiling_start_time_nsprofiling_end_time_nsrV   _statsrn   trace_idr   appendtorchrr   is_availablert   setkineto_activitiesaddr   CPUr   KINETOprofiler_kindCUDAr   KINETO_GPU_FALLBACKXPUMTIAPrivateUse1KINETO_PRIVATEUSE1_FALLBACKlen)r3   rw   rc   rd   re   rf   rg   rh   ri   rj   rk   rl   rm   rn   VALID_DEVICE_OPTIONSs                  r4   __init__zprofile.__init__   s   " %|| ==>	 .4DO(DO599=!!&*$doo-,$($&"5"7#6 9='($%&"$&(@%||QPQ ??&#: ,./A$++,I,KL&::tDOO,,JKL"&&(1H1H1JFG %"&%'		0F0F0HDE"&!$<<""&&'7';';<*11??f$!1!6!6>S>U!U||R%RR|%2%F%F"&&**+;+@+@A__%/337L7NNa`aN""&&'7';';<__&/448M8OOcbcO""&&'7'<'<=__(T__-O#//7L7NN LLJIJ %2%N%N"&&**+;+G+GH &&'!+	65	6+r7   c                 F    t        j                         }|j                  dS )N032X)uuiduuid4ra   )r3   uuid_raws     r4   default_trace_idzprofile.default_trace_id7  s    ::<,,t$%r7   c                 Z    | j                   r| j                         S | j                         S r/   )rn   r   r2   s    r4   create_trace_idzprofile.create_trace_id=  s)    ((0022$$&&r7   c           
          |r| j                         }|| _        t        | j                  | j                  | j
                  | j                  | j                  | j                  | j                  | j                        S r/   )
r   r   r   r   re   rg   rh   rf   ri   rl   )r3   r   r   s      r4   configzprofile.configB  si    ++-H$DMOOOO$$MM	
 		
r7   c                     | j                   sy | j                  rt        d      | j                          | j	                          | S )Nz)Profiler context manager is not reentrant)rw   r|   RuntimeError_prepare_trace_start_tracer2   s    r4   r5   zprofile.__enter__R  s<    ||<<JKKr7   c                     d| _         t               }t        | j                  d      | j                         t               }t        ||z
  dz        | j                  _        y )NTr     )r|   r   r   r   r   ra   r   rY   r3   t0t1s      r4   r   zprofile._prepare_trace[  sN    $++d+;T=S=ST8;R"W<L8M5r7   c                     d| _         t                t               }t        | j	                  d      | j
                         t               }t        ||z
  dz        | j                  _        || _	        y )NTFr   r   )
r|   rQ   r   r   r   r   ra   r   rZ   r~   r   s      r4   r   zprofile._start_traceb  s\     U;T=S=ST7:BGt;K7L4')$r7   c                    | j                   sy | j                  rPt        t        | j                        r6t	        t        | j                        }t        |d      r|j                          | j                  r| j                  r| j                  | _        d | _        d| _	        t               }t               | _        t               }t        ||z
  dz        | j                  _        || _        t#                | j                   | j$                  z
  dz  dz  | j                  _        | j                  r| j)                          y)NsynchronizeTr   g      ?g    eAF)rw   rd   hasattrr   getattrr   ry   rm   rz   r{   r   r   r}   ra   r   r[   r   rT   r~   rW   _ensure_function_events)r3   r:   r;   r<   device_moduler   r   s          r4   r=   zprofile.__exit__k  s    ||??wudoo>#E4??;M}m4))+  T__(,(=(=D% $!%/18;R"W<L8M5%'" ''$*F*FF#MPSS 	1 ??((*r7   c                 ~    | j                   r| j                          | j                  yt        | j                        S Nz#<unfinished torch.autograd.profile>)r{   r   ry   reprr2   s    r4   __repr__zprofile.__repr__  s7    !!((*  (8D))**r7   c                 ~    | j                   r| j                          | j                  yt        | j                        S r   )r{   r   ry   strr2   s    r4   __str__zprofile.__str__  s7    !!((*  (84(())r7   c                    | j                   yd| _        t               }g }| j                  r| j	                  | j                        }t               }t        ||z
  dz        | j                  _        t        || j                  | j                  | j                        | _         t               }| j                   j                          t               }t        ||z
  dz        | j                  _        t        | j                         | j                  _        | j                   r?| j"                  r3| j                   D ]  }| j                   j%                  |        d| _        | j                   t'        d      y)z*Process function events lazily if requiredNFr   )rd   rg   rf   zProfiler didn't finish running)ry   r{   r   r}   _parse_kineto_resultsra   r   r\   r   rd   rg   rf   _build_treer]   r   rX   rz   rm   r   r   )r3   r   parsed_resultsr   evts        r4   r   zprofile._ensure_function_events  sA     ,!&!778K8KLN47bD8H4I1 )..	!
 ))+BErBwRVFVBW?'*4+@+@'A$$$00 2%%,,S12(,D%  (?@@ )r7   c                 j    | j                   | j                  r| j                          | j                   S r/   )ry   r{   r   r2   s    r4   function_eventszprofile.function_events  s.      (D,B,B((*$$$r7   c           	          | j                          | j                  J | j                  j                  |||||||      S )N)sort_by	row_limitmax_src_column_widthmax_name_column_widthmax_shapes_column_widthheadertop_level_events_only)r   ry   table)r3   r   r   r   r   r   r   r   s           r4   r   zprofile.table  sU     	$$&$$000$$**!5"7$;"7 + 
 	
r7   c                     t               r| j                  j                  |       y| j                          | j                  j                  |      S )z
        Exports the collected trace in Chrome JSON format. If kineto is enabled, only
        last cycle in schedule is exported.
        N)r   r}   saver   ry   export_chrome_trace)r3   paths     r4   r   zprofile.export_chrome_trace  sA    
 $$T*((*((<<TBBr7   r   metricc                     | j                          | j                  J d       | j                  sJ d       | j                  j                  ||      S )NExpected profiling resultsz(export_stacks() requires with_stack=True)r   ry   rh   export_stacks)r3   r   r   s      r4   r   zprofile.export_stacks  sQ    $$&$$0N2NN0J JJ$$224@@r7   rw   
activitiesc                 ,    t        |t        |            S )zY
        Toggles the collection of activities for the current profiler instance.
        )r   r   )r3   rw   r   s      r4   toggle_collection_dynamicz!profile.toggle_collection_dynamic  s     *'3z?CCr7   c                     | j                          | j                  J d       | j                  j                  ||      S Nr   )r   ry   key_averages)r3   group_by_input_shapegroup_by_stack_ns      r4   r   zprofile.key_averages  sE    $$&$$0N2NN0$$11 "2
 	
r7   c                 |    | j                          | j                  J d       | j                  j                         S r   )r   ry   total_averager2   s    r4   r   zprofile.total_average  s;    $$&$$0N2NN0$$2244r7   c                 j    | j                          | j                  J | j                  j                  S )zsReturns total time spent on CPU.

        The total time is a sum of all self times across all the events.
        )r   ry   self_cpu_time_totalr2   s    r4   r   zprofile.self_cpu_time_total  s4     	$$&$$000$$888r7   resultc                     |j                         |j                         D cg c]  }|j                         t        k(  s|dg  }}|j                         D cg c]  }|j                         t        k(  s| }}t        |      }d d g }g }i }d|j                         D ]  }	t        |	j                               r|	j                         z
  }
|	j                         z
  }|	j                         }d}d}|	j                         t        j                  k(  rL|j                  |	j                         dz  |dz        D ]#  }| |d         z  }| |d         z  }d|d<   % |	j                         xs! |	j                         |	j                         k7  }t!        d&i d|	j#                         d	t%        |	j                         d
      dt%        |	j                         d
      d|	j                         d|
dz  d|dz  d|	j'                         d|	j)                         d|	j+                         d|	j-                         d|	j/                         D cg c]  }t1        |      r| c}d|	j3                         d j4                  d|d|d|d|	j7                         d|	j                         d|	j9                         d|	j;                         d|	j=                         d|	j?                         }tA        |jB                        |j                  t        j                  k(  r|j                  s j4                  dk(  rD|	jE                         }|dkD  r|jG                  |j                  |j8                  |       d|_$        nR j4                  d k(  rC|	jK                         }|dkD  r.|jG                  |j                  |j8                  |       d|_$        |jM                  |       |	jO                         }|dkD  r||vrg ||<   ||   jM                  |       |dk(  r|jM                  |       tQ        d!| d"       |D ]  }|j                  t        j                  k(  s"|j                  r/|jB                  |v s>||jB                     D ]  }|j                  t        jR                  k(  s|j                  t        jT                  k(  rS|jG                  |j                  |j8                  |jV                  jX                  |jV                  jZ                  z
         |j                  t        j                  k(  s|j\                  |_.           fd#}|D ])  }|d   r	dz   ||d         }|jM                  |       + |D ]   }dz   ||      }|jM                  |       " |j_                  d$ %       |S c c}w c c}w c c}w )'NFc                     | j                         t        j                  t        j                  t        j                  fv r| j                         S dS Nr   )device_typer   r   MKLDNNIDEEPnbytes
mem_records    r4   _cpu_memory_usagez8profile._parse_kineto_results.<locals>._cpu_memory_usage  sM     ))+NNJ$5$5z7G7GHI !!# 	r7   c                     | j                         t        j                  t        j                  t        j                  fv r| j                         S dS r   )r   r   r   r   HIPr   r   s    r4   _device_memory_usagez;profile._parse_kineto_results.<locals>._device_memory_usage!  sK     ))+OOZ%;%;Z^^LM !!# 	r7   r   r   T   idname)r   with_wildcard
trace_namethreadstart_usend_us
fwd_threadinput_shapesconcrete_inputskwinputsstackscoperd   cpu_memory_usagedevice_memory_usageis_asyncsequence_nrr   device_indexdevice_resource_idflopsis_user_annotationrv   rr   zGot negative correlation id z in profiler post processingc                 N   | j                         z
  }t        di dd| j                         dd d| j                         d|dz  d|dz  d| j                         d	g d
g dddj                  d |       d |       dddddt
        j                  dd}|S )Nr   r   r   r   r   r   r   r   r   r   r   r   rd   r   r   r   Fr   r   r   r@   )start_nsr   r   start_thread_idrd   r   r   )r   rel_start_nsfer   r   
max_evt_idr3   trace_start_nss      r4   "createFunctionEventForMemoryEventszIprofile._parse_kineto_results.<locals>.createFunctionEventForMemoryEvents  s    <<>N:L XXZ   **,	
 &, $d* ..0      ?? "33!7 %9$=    'NN!" #B& Ir7   c                 \    | j                   j                  | j                   j                   gS r/   )
time_rangestartendr   s    r4   <lambda>z/profile._parse_kineto_results.<locals>.<lambda>  s"    S^^11CNN4F4F3FG r7   keyr@   )0r  eventsr   r   r!   r    r   r   end_nsr   r   r   in_intervalr   r  end_thread_idr   correlation_idr   fwd_thread_idshapesr   r   r   r   r   rd   r   r   r   r   r   maxr   privateuse1_elapsed_usappend_kernel	is_legacycuda_elapsed_usr   linked_correlation_idr   r   r   r  r
  r	  r   sort)r3   r   r   mem_recordsoom_recordsmem_records_accall_function_eventsfrontend_function_eventsdevice_corr_mapkineto_eventr  
rel_end_ns
abs_end_nsr   r   r   r   entryr  privateuse1_time	cuda_timecorr_idf_evtr  
oom_recordr   r   r  r  s   `                        @@@@r4   r   zprofile._parse_kineto_results  s     ..0$*MMO
 sxxzEV7VS%L
 
 "==?
chhj<T.TC
 
 (4		 ! $& :<
"MMO J	LL--/0'002^CL%,,.?J%,,.J "#'')Z^^;"1"="= ))+d2J4E# )J %(9*Q-(HH$'+?
1+NN'$(JqM) $,,. ,,.,2L2L2NN   ..0"(9(9(;4P )l.?.?.AQVW $335	
 &, "D( (557 *002 !- < < > &..0 ".!3!3!5*51   #((*!"  ??#$ "2%& %8'( ")* )446+, )446-. *668/0 $0#B#B#D12 #((*34 $0#B#B#D5B8 Z/J~~/??o5'3'J'J'L$'!+(("//CST'+__. , < < >I 1}(("//9M'+&&r*"88:G{/1/1OG,(//3A(//3"27);WX QJ	Z + 	1B*..0EE_,,RUU3 1E))Z__< ,,
0F0FF((!JJ!..!,,0053C3C3I3II
 **jnn< (*yy1	1,	 	0 & 	/Ja=a
7
1F#**2.		/ & 	+J!OJ3J?B&&r*	+
 	  G 	! 	
 #"U

~s   W"W"W'<W''W,)T)F)Nd   K   7   P   NF)r   )Fr   )rH   rI   rJ   r^   r   r   r   r   r5   r   r   r=   r   r   r   propertyr   r   r   r   r   r   boolr   r   r   r   r   r   r   r   r@   r7   r4   r#   r#   j   sa   Yz o6  !%o6b&'

 N*@+*AB % %   "#
, OO++EM	C #,"?"?"G"GA# As ADD)12B)CD
 %1199L5
 &33;;M9 9n#O n#r7   r#   c                   ^    e Zd ZdZddedee   fdZd Zdeded	efd
Z	de
e   de
e   fdZy)r$   aj  Context manager/function decorator that adds a label to a code block/function when running autograd profiler.
    Label will only appear if CPU activity tracing is enabled.

    It is useful when tracing the code profile.

    Args:
        name (str): Label assigned to the block of code.
        node_id (int): ID of node, for distributed profiling. Unset in
        non-distributed cases.

    Example:
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
        >>> x = torch.randn((1, 1), requires_grad=True)
        >>> with torch.autograd.profiler.profile() as prof:
        ...     y = x ** 2
        ...     with torch.autograd.profiler.record_function("label-z"): # label the block
        ...         z = y ** 3
        ...     y.backward()
        ...
        >>> # xdoctest: +IGNORE_WANT
        >>> # NOTE: some columns were removed for brevity
        >>> print(prof.key_averages().table(sort_by="self_cpu_time_total"))
        -----------------------------------  ---------------  ---------------  ---------------
        Name                                 Self CPU total %  CPU time avg     Number of Calls
        -----------------------------------  ---------------  ---------------  ---------------
        pow                                  60.77%           47.470us         3
        mul                                  21.73%           25.465us         2
        PowBackward0                         12.03%           121.891us        1
        torch::autograd::AccumulateGrad      2.70%            6.324us          1
        label-z                              2.13%            12.421us         1
        torch::autograd::GraphRoot           0.64%            1.503us          1
        -----------------------------------  ---------------  ---------------  ---------------
        Self CPU time total: 234.344us
        CUDA time total: 0.000us

    Nr   rA   c                     || _         || _        d| _        t        j                  j                  t        d   d       | _        y )NTz&torch.classes.profiler._RecordFunction)r   rA   run_callbacks_on_exitr   jitannotater
   record)r3   r   rA   s      r4   r   zrecord_function.__init__  s;    	#'	+/" ii((=>
r7   c                     t         j                  j                  j                  | j                  | j
                        | _        | S r/   )r   opsprofiler_record_function_enter_newr   rA   r7  r2   s    r4   r5   zrecord_function.__enter__  s2    ii((CCIItyy
 r7   r:   	exc_value	tracebackc                    | j                   sy | j                  }|J t        j                  j	                         s[t        j
                  j                         5  t        j                  j                  j                  j                  |       d d d        y t        j                  j                  j                  |       y # 1 sw Y   y xY wr/   )r4  r7  r   r5  is_scripting_CDisableTorchFunctionSubclassr9  r:  _record_function_exit_RecordFunction)r3   r:   r<  r=  r7  s        r4   r=   zrecord_function.__exit__  s    )) !!! yy%%'668 Q		""88HHPQ Q II44V<Q Qs   4CC
futreturnc                    | j                   st        d      d| _         | j                  }|J t        j                  j                         s]t        j                  j                         5  t        j                  j                  j                  j                  ||      }ddd       |S t        j                  j                  j                  ||      }|S # 1 sw Y   S xY w)av  Use for profiling async calls that return a future.

        Calling this function will extend recording beyond this scope, until the future is
        satisfied. It is useful for profiling the end to end time of asynchronous calls.
        This function should only be called once to attach the callback onto the future, and
        will throw if called multiple times.

        Args:
            fut: (torch._C.Future): future for which to schedule
            callback for.

        Returns:
            A future that completes with the value of the passed in future when
            the profiling callbacks have ran.

        z6_call_end_callbacks_on_future can only be called once.FN)r4  r   r7  r   r5  r?  r@  rA  r9  r:  _call_end_callbacks_on_jit_futrC  )r3   rD  r7  profiled_futures       r4   _call_end_callbacks_on_futurez-record_function._call_end_callbacks_on_future  s    $ ))WXX &+" !!! yy%%'668 II&&EEUU    $ii00OOO  s   +5CC r/   )rH   rI   rJ   r^   r   r
   r   r5   r   r=   r"   rI  r@   r7   r4   r$   r$     sY    #J	
S 	
 	
= = = = * * *r7   r$   c                   $    e Zd ZdZddZd Zd Zy)r%   a  Context manager that makes every autograd operation emit an ITT range.

    It is useful when running the program under Intel(R) VTune Profiler::

        vtune <--vtune-flags> <regular command here>

    The Instrumentation and Tracing Technology (ITT) API enables your application to generate and
    control the collection of trace data during its execution across different Intel tools.
    This context manager is to annotate Intel(R) VTune Profiling trace. With help of this context manager,
    you will be able to see labled ranges in Intel(R) VTune Profiler GUI.

    .. warning:
        This context manager should not be called recursively, i.e. at most one
        instance should be enabled at any given time.

    Args:
        enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op.
            Default: ``True``.
        record_shapes (bool, optional): If ``record_shapes=True``, the itt range wrapping
            each autograd op will append information about the sizes of Tensor arguments received
            by that op, in the following format:
            ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]``
            Non-tensor arguments will be represented by ``[]``.
            Arguments will be listed in the order they are received by the backend op.
            Please note that this order may not match the order in which those arguments were passed
            on the Python side.  Also note that shape recording may increase the overhead of itt range creation.
            Default: ``False``

    Example:
        >>> # xdoctest: +SKIP("Undefined variables")
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
        >>> with torch.autograd.profiler.emit_itt():
        ...     model(x)

    c                 .    || _         d| _        || _        y rS   rw   r|   re   r3   rw   re   s      r4   r   zemit_itt.__init__W      *r7   c                     | j                   sy | j                  rt        d      d| _        t                t	        t        t        j                  | j                  ddddt                     t                      | S )Nz/ITT annotation context manager is not reentrantTF)rw   r|   r   rQ   r   r   r   ITTre   r   r   r2   s    r4   r5   zemit_itt.__enter__\  sn    ||<<PQQ !!""#% E	
 r7   c                 F    | j                   sy t                t                yrS   )rw   r   rT   r9   s       r4   r=   zemit_itt.__exit__q  s    ||r7   NTFrH   rI   rJ   r^   r   r5   r=   r@   r7   r4   r%   r%   2  s    "H+
*r7   r%   c                   $    e Zd ZdZddZd Zd Zy)r&   a7  Context manager that makes every autograd operation emit an NVTX range.

    It is useful when running the program under nvprof::

        nvprof --profile-from-start off -o trace_name.prof -- <regular command here>

    Unfortunately, there's no way to force nvprof to flush the data it collected
    to disk, so for CUDA profiling one has to use this context manager to annotate
    nvprof traces and wait for the process to exit before inspecting them.
    Then, either NVIDIA Visual Profiler (nvvp) can be used to visualize the timeline, or
    :func:`torch.autograd.profiler.load_nvprof` can load the results for inspection
    e.g. in Python REPL.

    .. warning:
        This context manager should not be called recursively, i.e. at most one
        instance should be enabled at any given time.

    Args:
        enabled (bool, optional): Setting ``enabled=False`` makes this context manager a no-op.
            Default: ``True``.
        record_shapes (bool, optional): If ``record_shapes=True``, the nvtx range wrapping
            each autograd op will append information about the sizes of Tensor arguments received
            by that op, in the following format:
            ``[[arg0.size(0), arg0.size(1), ...], [arg1.size(0), arg1.size(1), ...], ...]``
            Non-tensor arguments will be represented by ``[]``.
            Arguments will be listed in the order they are received by the backend op.
            Please note that this order may not match the order in which those arguments were passed
            on the Python side.  Also note that shape recording may increase the overhead of nvtx range creation.
            Default: ``False``

    Example:
        >>> # xdoctest: +SKIP("undefined variables")
        >>> # xdoctest: +REQUIRES(env:TORCH_DOCTEST_AUTOGRAD_PROFILER)
        >>> with torch.cuda.profiler.profile():
        ...     model(x)  # Warmup CUDA memory allocator and profiler
        ...     with torch.autograd.profiler.emit_nvtx():
        ...         model(x)

    **Forward-backward correlation**

    When viewing a profile created using :class:`emit_nvtx` in the Nvidia Visual Profiler,
    correlating each backward-pass op with the corresponding forward-pass op can be difficult.
    To ease this task, :class:`emit_nvtx` appends sequence number information to the ranges it
    generates.

    During the forward pass, each function range is decorated with ``seq=<N>``.  ``seq`` is a running
    counter, incremented each time a new backward Function object is created and stashed for backward.
    Thus, the ``seq=<N>`` annotation associated with each forward function range tells you that
    if a backward Function object is created by this forward function,
    the backward object will receive sequence number N.
    During the backward pass, the top-level range wrapping each C++ backward Function's
    ``apply()`` call is decorated with ``stashed seq=<M>``.  ``M`` is the sequence number that
    the backward object was created with.  By comparing ``stashed seq`` numbers in backward with ``seq``
    numbers in forward, you can track down which forward op created each backward Function.

    Any functions executed during the backward pass are also decorated with ``seq=<N>``.  During
    default backward (with ``create_graph=False``) this information is irrelevant, and in fact,
    ``N`` may simply be 0 for all such functions.  Only the top-level ranges associated with
    backward Function objects' ``apply()`` methods are useful, as a way to correlate these Function
    objects with the earlier forward pass.

    **Double-backward**

    If, on the other hand, a backward pass with ``create_graph=True`` is underway (in other words,
    if you are setting up for a double-backward), each function's execution during backward
    is given a nonzero, useful ``seq=<N>``.  Those functions may themselves create Function objects
    to be executed later during double-backward, just as the original functions in the forward pass did.
    The relationship between backward and double-backward is conceptually the same as the relationship
    between forward and backward: The functions still emit current-sequence-number-tagged ranges,
    the Function objects they create still stash those sequence numbers, and during the eventual
    double-backward, the Function objects' ``apply()`` ranges are still tagged with ``stashed seq``
    numbers, which can be compared to `seq` numbers from the backward pass.

    .. warning:
        The sequence number is thread-local, and some forward functions don't create an associated
        backward Function object (instead delegating that to sub-functions further down the call chain).
        For these reasons, the correspondence of stashed sequence numbers in
        backward Function ``apply()`` ranges with `seq` numbers in forward-pass ranges is
        not guaranteed to be 1 to 1.  The sequence numbers alone may not be enough to fully
        disambiguate which forward function created which
        backward Function object.  You may need to make a judgment based on analytic knowledge of what
        the expected correspondence should be.
    c                 .    || _         d| _        || _        y rS   rL  rM  s      r4   r   zemit_nvtx.__init__  rN  r7   c                 2   | j                   sy | j                  rt        d      d| _        t        j                  j                          t                t        t        t        j                  | j                  ddddt                     t                      | S )Nz0NVTX annotation context manager is not reentrantTF)rw   r|   r   r   rr   r   rQ   r   r   r   NVTXre   r   r   r2   s    r4   r5   zemit_nvtx.__enter__  s~    ||<<QRR

  """"#% E	
 r7   c                     | j                   sy t        j                  j                          t	                t                yrS   )rw   r   rr   r   r   rT   r9   s       r4   r=   zemit_nvtx.__exit__  s+    ||

 r7   NrR  rS  r@   r7   r4   r&   r&   y  s    Rh+
,r7   r&   c                 *    t        t        |             S )zsOpen an nvprof trace file and parses autograd annotations.

    Args:
        path (str): path to nvprof trace
    )r   r)   )r   s    r4   r'   r'     s     '-..r7   c                       e Zd ZdZd Zd Zy)r(   z0Raises an error if a key is seen more than once.c                 "    t               | _        y r/   )r   seenr2   s    r4   r   zEnforceUnique.__init__  s    E	r7   c                     || j                   v rt        dt        |      z         | j                   j                  |       y)zP
        Observe a key and raise an error if it is seen multiple times.
        zduplicate key: N)r\  r   r   r   )r3   r  s     r4   seezEnforceUnique.see  s5     $))03s8;<<		cr7   N)rH   rI   rJ   r^   r   r^  r@   r7   r4   r(   r(     s    :r7   r(   c           	         dd l }|j                  |       }|j                  |_        i }|j	                  d      D ]*  }t
        j                  j                  |d         ||d   <   , d}g }i }t               }|j	                  |      D ]V  }	|j                  |	d          t        |	d   d||	d      |	d   |	d	   d
      }
|j                  |
       |
||
j                  <   X d}t               }|j	                  |      D ]K  }	|j                  |	d   |	d          |	d   dk(  sJ ||	d      }
|
j                  |	d   d|	d   |	d   z
         M |j                  d        |S )Nr   z)SELECT _id_ as id, value FROM StringTablevaluer   a&  
    SELECT
        start.id AS marker_id, start.name, start.timestamp AS start_time, end.timestamp AS end_time
    FROM
        CUPTI_ACTIVITY_KIND_MARKER AS start INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
        ON start.id = end.id
    WHERE
        start.name != 0 AND end.name = 0
    	marker_idr   
start_timeend_time)r   node_idr   r   r   r   a  
    SELECT
        start.id AS marker_id, start.name, start.timestamp, end.timestamp,
        runtime._id_ AS runtime_id, runtime.cbid, runtime.start AS runtime_start, runtime.end AS runtime_end,
        kernel.start AS kernel_start, kernel.end AS kernel_end, kernel.name AS kernel_name
    FROM
        CUPTI_ACTIVITY_KIND_MARKER AS start
        INNER JOIN CUPTI_ACTIVITY_KIND_MARKER AS end
            ON start.id = end.id
        INNER JOIN CUPTI_ACTIVITY_KIND_RUNTIME as runtime
            ON (start.timestamp < runtime.start AND runtime.end < end.timestamp)
        INNER JOIN CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL AS kernel
            ON kernel.correlationId = runtime.correlationId
    
runtime_idcbid   kernel_name
kernel_endkernel_startc                 .    | j                   j                  S r/   )r  r	  r  s    r4   r  z$parse_nvprof_trace.<locals>.<lambda>I  s    3>>#7#7 r7   r  )sqlite3connectRowrow_factoryexecuter   r@  	_demangler(   r^  r   r   r   r  r  )r   rl  connstringsrmarker_query	functionsfunctions_mapuniquerowr   kernel_querys               r4   r)   r)   
  s   ??4 D{{D G\\EF : 88--aj9$:L IM_F||L) $

3{#$;V%&z?
 	 #cff$L _F||L) 


3{#S%676{c!!!C,-3|#4s>7J#J	

 NN7N8r7   c                       e Zd ZU dZdZ ee      Zee	ef   e
d<   ede	fd       Zede	defd       Zede	defd       Zedefd	       Zy
)r*   a  Provides an abstraction for incrementing the step count globally.

    Previously, we only had one place to mark that a step() has occurred
    in the program via pytorch profiler step(). We will now add step hooks
    in the Optimizer class https://github.com/pytorch/pytorch/issues/88446

    - This could mean programs that already call profiler.step() every
      iteration can end up double incrementing step count.
    - If a model uses multiple optimizers we can also have double or more
      counting of the step.

    We fix this by adding a layer of abstraction before calling step()
    to the kineto library. The idea is to maintain steps per requester in a dict:

    .. code-block::

        {
           "ProfilerStep": 100,  # triggered by profiler step() call
           "Optimizer1Step": 100,   # Optimizer 1 or 2 are just examples, could be SGD, Adam etc
           "Optimizer2Step": 100,
        }

    To figure out the global step count just take the max of dict values (100).

    If one of the count increments the max will go up.

    .. code-block::

        {
           "ProfilerStep": 100,
           "Optimizer1Step": 101,   # Optimizer1 got incremented first say
           "Optimizer2Step": 100,
        }

    Then global step count is 101
    We only call the kineto step() function when global count increments.

    NOTE: Please do not use the KinetoStepTracker in modules beside the Optimizer
    for now. The result could be incorrect increments of the step count.
    r   
_step_dict	requesterc                 6    | j                   | j                  |<   y)z3
        Initialize for a given requester.
        N)_current_stepr|  clsr}  s     r4   init_step_countz!KinetoStepTracker.init_step_countz  s    
 %($5$5y!r7   rE  c                 >    | j                   j                  |d      duS )z+
        Remove a given requester.
        N)r|  popr  s     r4   erase_step_countz"KinetoStepTracker.erase_step_count  s     
 ~~!!)T2$>>r7   c                    || j                   vr| j                  |       | j                   |xx   dz  cc<   t        | j                   j                               }|| j                  kD  r[|| j                  z
  }|dkD  r%t        d| j                   d| j                           t        d|      D ]  }t                 || _        | j                  S )zIncrements the step count for the requester.

        Additionally if the max over all step counts has incremented then
        trigger the _kineto_step() returns global step count
        r   z?Profiler step count has increased more than 1 - current_step = z step dict =  r   )r|  r  r  valuesr  r   ranger   )r  r}  new_stepdelta_s        r4   increment_stepz KinetoStepTracker.increment_step  s     CNN*	*y!Q&!s~~,,./c'''s000Eqy&&)&7&7%8s~~FVX 1e_  (C   r7   c                     | j                   S )z7
        Get the latest step for any requester
        )r  )r  s    r4   current_stepzKinetoStepTracker.current_step  s    
    r7   N)rH   rI   rJ   r^   r  r   ra   r|  r   r   r`   classmethodr  r1  r  r  r  r@   r7   r4   r*   r*   M  s    'R M!,S!1JS#X16 6 6 ? ? ? ? !s !s ! !. !S ! !r7   r*   )Br   collectionsr   dataclassesr   timer   typingr   r   r   r	   r
   warningsr   r   
torch.cudatorch._Cr   torch._C._profilerr   torch.autogradr   r   r   r   r   r   r   r   r   r   r   r   torch.autograd.profiler_utilr   r   r   r   r   r   r    r!   torch.futuresr"   __all__
contextlibr+   r-   ImportErrorrE   rK   r1  r`   rN   rQ   rT   rV   r#   r$   r%   r&   r'   r(   r)   r*   r@   r7   r4   <module>r     s    # !   6 6    2 2   	 	 	 !@, # d ""T "
#$ 9 9 9Q	# Q	#hq' qhD DNv vr/ @FX! X!i    s   ;C' 'C=<C=