a
    OSicw                     @   s<  d dl 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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mZmZmZ d dlm Z  zd dl!m"Z" W n* e#y   d dl$Z$G d	d
 d
e%Z"Y n0 G dd de%Z&G dd de"Z'G dd de%Z(dd Z)G dd de%Z*dd Z+dd Z,dS )    )	EventListFunctionEventMemRecordsAccMEMORY_EVENT_NAME_filter_name_filter_stack_entry_rewrite_name)
DeviceTypeProfilerActivityProfilerConfigProfilerStatekineto_available_ProfilerResult_disable_profiler_enable_profiler_prepare_profiler_supported_activities_kineto_step)_ExperimentalConfigN)Future)AnyDictListOptional)warn)ContextDecoratorc                   @   s$   e Zd Zdd Zdd Zdd ZdS )r   c                 C   s   t d S NNotImplementedErrorself r!   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/autograd/profiler.py	__enter__   s    zContextDecorator.__enter__c                 C   s   t d S r   r   r    exc_typeexc_valexc_tbr!   r!   r"   __exit__   s    zContextDecorator.__exit__c                    s   t   fdd}|S )Nc                     s6     | i |W  d    S 1 s(0    Y  d S r   r!   )argskwargsfuncr    r!   r"   wrapped"   s    z*ContextDecorator.__call__.<locals>.wrapped)	functoolswraps)r    r,   r-   r!   r+   r"   __call__!   s    zContextDecorator.__call__N)__name__
__module____qualname__r#   r(   r0   r!   r!   r!   r"   r      s   r   c                   @   s   e Zd ZdZd+dddddddddd	ddZdd	 Zd
d Zdd Zdd Zdd Z	dd Z
dd Zdd Zd,ddZejje_dd Zejje_d-eedd d!Zd.d#d$Zejje_d%d& Zejje_ed'd( Zd)d* ZdS )/profilea  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.
            Adds approximately 4us of overhead to each tensor operation.

        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.


    .. 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_cuda = True`` to benchmark
        DataLoaders with ``num_workers > 0``. If you wish to benchmark data loading,
        please use ``use_cuda = False`` or ``num_workers = 0``.

    Example:
        >>> 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record_shapes
with_flopsprofile_memory
with_stackwith_modules
use_kinetouse_cpuexperimental_configc       	         C   s  || _ | j sd S || _d | _d| _|| _|| _|  j| jO  _|| _|| _|| _|	| _	|
d u rdt
 }
|
| _d | _| j	s|sJ d| jrtj std d| _t | _| j	r| jtj tj| _| jr|rtjt vr| j	sJ dtj| _n| jtj t| jdksJ dd S )NFz?Device-only events supported only with Kineto (use_kineto=True)z/CUDA is not available, disabling CUDA profilingz+Legacy CUDA profiling requires use_cpu=Truer   z(No activities specified for the profiler)enabledr5   function_eventsenteredr6   r7   r8   r9   r:   r<   r   r=   kineto_resultstorchcudais_availabler   setkineto_activitiesaddr
   CPUr   KINETOprofiler_kindCUDAr   KINETO_GPU_FALLBACKlen)r    r>   r5   r6   r7   r8   r9   r:   r;   r<   r=   r!   r!   r"   __init__|   sL    
zprofile.__init__c                 C   s"   t | j| j| j| j| j| j| jS r   )r   rJ   r6   r8   r9   r7   r:   r=   r   r!   r!   r"   config   s    zprofile.configc                 C   s,   | j s
d S | jrtd|   |   | S )Nz)Profiler context manager is not reentrant)r>   r@   RuntimeError_prepare_trace_start_tracer   r!   r!   r"   r#      s    zprofile.__enter__c                 C   s   d| _ t|  | j d S NT)r@   r   rO   rF   r   r!   r!   r"   rQ      s    zprofile._prepare_tracec                 C   s   d| _ t|  | j d S rS   )r@   r   rO   rF   r   r!   r!   r"   rR      s    zprofile._start_tracec                 C   sT   | j s
d S | jrtj  t | _| | j}t|| j| j	| j
d| _| j  dS )N)r5   r8   r7   F)r>   r5   rB   rC   synchronizer   rA   _parse_kineto_resultsr   r8   r7   r?   _build_tree)r    r%   r&   r'   Zparsed_resultsr!   r!   r"   r(      s    

zprofile.__exit__c                 C   s   | j d u rdS t| j S Nz#<unfinished torch.autograd.profile>)r?   reprr   r!   r!   r"   __repr__   s    
zprofile.__repr__c                 C   s   | j d u rdS t| j S rW   )r?   strr   r!   r!   r"   __str__   s    
zprofile.__str__c                 C   s   | j d u rtdd S )NzProfiler didn't finish running)r?   rP   r   r!   r!   r"   _check_finish   s    
zprofile._check_finishd   K   c                 C   s,   |    | jd usJ | jj|||||dS )N)sort_by	row_limitmax_src_column_widthheadertop_level_events_only)r\   r?   table)r    r_   r`   ra   rb   rc   r!   r!   r"   rd      s    zprofile.tablec                 C   s,   |    t r| j| n| j|S d S r   )r\   r   rA   saver?   export_chrome_trace)r    pathr!   r!   r"   rf      s    zprofile.export_chrome_traceself_cpu_time_total)rg   metricc                 C   s6   |    | jd usJ d| js(J d| j||S )NExpected profiling resultsz(export_stacks() requires with_stack=True)r\   r?   r9   export_stacks)r    rg   ri   r!   r!   r"   rk      s    zprofile.export_stacksr   c                 C   s(   |    | jd usJ d| j||S Nrj   )r\   r?   key_averages)r    Zgroup_by_input_shapeZgroup_by_stack_nr!   r!   r"   rm     s    zprofile.key_averagesc                 C   s$   |    | jd usJ d| j S rl   )r\   r?   total_averager   r!   r!   r"   rn   	  s    zprofile.total_averagec                 C   s   |    | jdusJ | jjS )zl Returns total time spent on CPU obtained as a sum of
        all self times across all the events.
        N)r\   r?   rh   r   r!   r!   r"   rh     s    zprofile.self_cpu_time_totalc                 C   s  |  }dd | D }t|}dd }dd }g }i }d}	| D ]}
t|
 rZqF|
 | }||
  }|
 |
  }d}d}|
 tj	kr|
|
 |D ],}|||d 7 }|||d 7 }d|d	< q|
 p|
 |
 k}t|
 t|
 dd
t|
 dd
|
 |||
 |
 dd |
 D |
 ||||
 |
 |
 |
 d}|j|	krt|jn|	}	|jtj	kr|js|
 }|dkr||j|j| d|_|| |
 }|dkrF||vrg ||< || | qF|D ]~}|jtj	kr|js|j|v r||j D ]J}|jtjkrZ||j|j|jj |jj!  n|jtj	kr(|j"|_"q(q|D ]|}|d	 s||d  | }|	d	7 }	t|	t#d |d  |||d  g g d||d ||d ddtj	dd}|| q||j$dd d |S )Nc                 S   s    g | ]}|  tkr|d gqS )F)namer   ).0evtr!   r!   r"   
<listcomp>      z1profile._parse_kineto_results.<locals>.<listcomp>c                 S   s$   |   tjtjtjfv r |  S dS Nr   )device_typer	   rH   MKLDNNIDEEPnbytes
mem_recordr!   r!   r"   _cpu_memory_usage  s    
z8profile._parse_kineto_results.<locals>._cpu_memory_usagec                 S   s    |   tjtjfv r|  S dS rt   )ru   r	   rK   HIPrx   ry   r!   r!   r"   _cuda_memory_usage$  s    
z9profile._parse_kineto_results.<locals>._cuda_memory_usager   T   )ro   Zwith_wildcardFc                 S   s   g | ]}t |r|qS r!   )r   )rp   entryr!   r!   r"   rr   J  rs   )idro   
trace_namethreadstart_usend_us
fwd_threadinput_shapesstackscopecpu_memory_usagecuda_memory_usageis_asyncsequence_nrru   device_indexflops)r   ro   r   r   r   r   r   r   r   r   r   r   r   r   ru   r   c                 S   s   | j j| j j gS r   )
time_rangestartendrq   r!   r!   r"   <lambda>  rs   z/profile._parse_kineto_results.<locals>.<lambda>key)%trace_start_useventsr   r   ro   r   duration_usru   r	   rH   Zin_intervalr   start_thread_idend_thread_idr   correlation_idr   fwd_thread_idshapesr   r   r   r   r   r   cuda_elapsed_usappend_kernel	is_legacyappendlinked_correlation_idrK   r   r   r   r   r   sort)r    resultr   Zmem_recordsZmem_records_accr{   r}   r?   Zcuda_corr_mapZ
max_evt_idZkineto_eventZrel_start_usZ
rel_end_usZ
abs_end_usr   r   rz   r   ZfeZ	cuda_timeZcorr_idZf_evtr!   r!   r"   rU     s    








zprofile._parse_kineto_results)T)Nr]   r^   NF)rh   )Fr   )r1   r2   r3   __doc__rN   rO   r#   rQ   rR   r(   rY   r[   r\   rd   r   rf   rZ   rk   rm   rn   propertyrh   rU   r!   r!   r!   r"   r4   *   sB   S 8
	






r4   c                   @   sX   e Zd ZdZdeee dddZdd Zeeedd	d
Z	e
e e
e dddZdS )record_functiona  Context manager/function decorator that adds a label to a block of
    Python code (or function) when running autograd profiler. 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:
        >>> 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()
        ...
        >>> # 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

    N)ro   r)   c                 C   s"   || _ || _d| _td| _d S )NTr~   )ro   r)   run_callbacks_on_exitrB   zeroshandle)r    ro   r)   r!   r!   r"   rN     s    zrecord_function.__init__c                 C   s   t jj| j| j| _| S r   )rB   opsprofilerZ_record_function_enterro   r)   r   r   r!   r!   r"   r#     s    zrecord_function.__enter__)r%   	exc_value	tracebackc                 C   s   | j rtjj| j d S r   )r   rB   r   r   Z_record_function_exitr   )r    r%   r   r   r!   r!   r"   r(     s    zrecord_function.__exit__)futreturnc                 C   s*   | j stdd| _ tjj| j|}|S )a  
        _call_end_callbacks_on_future is meant to be used 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.F)r   rP   rB   r   r   Z_call_end_callbacks_on_jit_futr   )r    r   Zprofiled_futurer!   r!   r"   _call_end_callbacks_on_future  s
    z-record_function._call_end_callbacks_on_future)N)r1   r2   r3   r   rZ   r   rN   r#   r   r(   r   r   r!   r!   r!   r"   r     s
   !	r   c                   @   s*   e Zd ZdZdddZdd Zdd	 Zd
S )	emit_nvtxa  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, default=True): Setting ``enabled=False`` makes this context manager a no-op.
            Default: ``True``.
        record_shapes (bool, optional, default=False): 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.

    Example:
        >>> 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.
    TFc                 C   s   || _ d| _|| _d S NF)r>   r@   r6   )r    r>   r6   r!   r!   r"   rN   3  s    zemit_nvtx.__init__c              	   C   sN   | j s
d S | jrtdd| _tj  tttj	| j
ddddt t  | S )Nz0NVTX annotation context manager is not reentrantTF)r>   r@   rP   rB   rC   rT   r   r   r   NVTXr6   r   rE   r   r!   r!   r"   r#   8  s&    
zemit_nvtx.__enter__c                 C   s   | j s
d S tj  t  dS r   )r>   rB   rC   rT   r   r$   r!   r!   r"   r(   L  s
    
zemit_nvtx.__exit__N)TF)r1   r2   r3   r   rN   r#   r(   r!   r!   r!   r"   r     s   P
r   c                 C   s   t t| S )ztOpens an nvprof trace file and parses autograd annotations.

    Args:
        path (str): path to nvprof trace
    )r   parse_nvprof_trace)rg   r!   r!   r"   load_nvprofT  s    r   c                   @   s    e Zd ZdZdd Zdd ZdS )EnforceUniquez0Raises an error if a key is seen more than once.c                 C   s   t  | _d S r   )rE   seenr   r!   r!   r"   rN   _  s    zEnforceUnique.__init__c                 G   s*   || j v rtdt| | j | d S )Nzduplicate key: )r   rP   rZ   rG   )r    r   r!   r!   r"   seeb  s    
zEnforceUnique.seeN)r1   r2   r3   r   rN   r   r!   r!   r!   r"   r   ]  s   r   c              	   C   s.  dd l }|| }|j|_i }|dD ]}tj|d ||d < q(d}g }i }t }||D ]N}	|	|	d  t
|	d d||	d  |	d |	d	 dd
}
||
 |
||
j< qbd}t }||D ]R}	|	|	d |	d  |	d dksJ ||	d  }
|
|	d d|	d |	d   q|jdd 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
    Z	marker_idro   
start_timeend_time)r   node_idro   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
    Z
runtime_idZcbid   kernel_nameZ
kernel_endZkernel_startc                 S   s   | j jS r   )r   r   r   r!   r!   r"   r     rs   z$parse_nvprof_trace.<locals>.<lambda>r   )sqlite3connectRowZrow_factoryexecuterB   _C	_demangler   r   r   r   r   r   r   )rg   r   connstringsrZmarker_query	functionsZfunctions_mapuniquerowrq   Zkernel_queryr!   r!   r"   r   h  sB    
	


r   c                   C   s
   t   dS )zc Notify kineto so it is aware of iteration boundaries for asynchronous
        trace requests.
    N)r   r!   r!   r!   r"   kineto_step  s    r   )-Ztorch.autograd.profiler_utilr   r   r   r   r   r   r   torch.autogradr	   r
   r   r   r   r   r   r   r   r   r   torch._C._autogradr   rB   
torch.cudatorch.futuresr   typingr   r   r   r   warningsr   
contextlibr   ImportErrorr.   objectr4   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s*   $4  jPr	@