a
    8SicwS                     @   s"  d dl Z d dl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 d dlmZ d dlZd dlm  mZ d dlmZmZ d dlmZ dd	 ZG d
d deZG dd deZd d de e e e e e
dddZ!e edddZ"de#ee# e$dddZ%G dd deZ&dS )    N)Enum)partial)AnyCallableDictIterableListOptionalTuple)warn)ProfilerActivitykineto_available)_ExperimentalConfigc                   C   s
   t j S )a  
    Returns a set of supported profiler tracing activities.

    Note: profiler uses CUPTI library to trace on-device CUDA kernels.
    In case when CUDA is enabled but CUPTI is not available, passing
    ``ProfilerActivity.CUDA`` to profiler results in using the legacy CUDA
    profiling code (same as in the legacy ``torch.autograd.profiler``).
    This, in turn, results in including CUDA time in the profiler table output,
    but not in the JSON trace.
    )torchautograd_supported_activities r   r   S/var/www/html/django/DPS/env/lib/python3.9/site-packages/torch/profiler/profiler.pysupported_activities   s    r   c                	   @   s   e Zd ZdZddddddddeee  eeeeeee dddZ	dd Z
d	d
 Zdd Zdd Zdd ZedddZd%eedddZd&eedddZdd Zeeddd Zeedd!d"Zd#d$ ZdS )'_KinetoProfilea  Low-level profiler wrap the autograd profile

    Args:
        activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
            ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``.
            Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA.
        record_shapes (bool): save information about operator's input shapes.
        profile_memory (bool): track tensor memory allocation/deallocation.
        with_stack (bool): record source information (file and line number) for the ops.
        with_flops (bool): use formula to estimate the FLOPS of specific operators
            (matrix multiplication and 2D convolution).
        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.

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

    .. note::
        This API is an experimental and subject to change in future.

        Enabling shape and stack tracing results in additional overhead.
        When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
        that may further prevent certain optimizations that depend on the reference count and introduce
        extra tensor copies.
    NF
activitiesrecord_shapesprofile_memory
with_stack
with_flopswith_modulesexperimental_configc                C   sB   |rt |nt | _|| _|| _|| _|| _|| _|| _d | _	d S N)
setr   r   r   r   r   r   r   r   profiler)selfr   r   r   r   r   r   r   r   r   r   __init__<   s    
z_KinetoProfile.__init__c                 C   s   |    |   d S r   )prepare_tracestart_tracer!   r   r   r   startO   s    z_KinetoProfile.startc                 C   s   |    d S r   )
stop_tracer%   r   r   r   stopS   s    z_KinetoProfile.stopc                 C   sH   t jtj| jv tj| jv | j| j| j| j	| j
d| jd	| _| j  d S )NT)	use_cudause_cpur   r   r   r   r   
use_kinetor   )profprofiler   CUDAr   CPUr   r   r   r   r   r   r    _prepare_tracer%   r   r   r   r#   V   s    

z_KinetoProfile.prepare_tracec                 C   s@   | j d usJ | j   t r<|  }|r<| dt| d S )NZdistributedInfo)r    _start_tracer   _get_distributed_infoadd_metadata_jsonjsondumps)r!   Z	dist_infor   r   r   r$   d   s    
z_KinetoProfile.start_tracec                 C   s"   | j d usJ | j d d d  d S r   )r    __exit__r%   r   r   r   r'   m   s    z_KinetoProfile.stop_trace)pathc              	   C   s   | j s
J |drtjdddd}|  | j |j}t|jF}t|d}|	| W d   n1 sr0    Y  W d   n1 s0    Y  t
|j |S | j |S dS )zD
        Exports the collected trace in Chrome JSON format.
        .gzzw+tz.jsonF)suffixdeletewtN)r    endswithtempfileNamedTemporaryFilecloseexport_chrome_tracenameopengzip
writelinesosremove)r!   r7   fpZretvaluefinfoutr   r   r   r@   q   s    

Fz"_KinetoProfile.export_chrome_traceself_cpu_time_total)r7   metricc                 C   s   | j s
J | j ||S )a  Save stack traces in a file in a format suitable for visualization.

        Args:
            path (str): save stacks file to this location;
            metric (str): metric to use: "self_cpu_time_total" or "self_cuda_time_total"

        .. note::
            Example of using FlameGraph tool:

            - git clone https://github.com/brendangregg/FlameGraph
            - cd FlameGraph
            - ./flamegraph.pl --title "CPU time" --countname "us." profiler.stacks > perf_viz.svg
        )r    export_stacks)r!   r7   rK   r   r   r   rL      s    
z_KinetoProfile.export_stacksr   )group_by_input_shapegroup_by_stack_nc                 C   s   | j s
J | j ||S )a  Averages events, grouping them by operator name and (optionally) input shapes and
        stack.

        .. note::
            To use shape/stack functionality make sure to set record_shapes/with_stack
            when creating profiler context manager.
        )r    key_averages)r!   rM   rN   r   r   r   rO      s    
z_KinetoProfile.key_averagesc                 C   s   | j s
J | j jS )z
        Returns the list of unaggregated profiler events,
        to be used in the trace callback or after the profiling is finished
        )r    function_eventsr%   r   r   r   events   s    
z_KinetoProfile.events)keyvaluec                 C   s&   d| dd d }tj|| dS )zo
        Adds a user defined metadata with a string key and a string value
        into the trace file
        "z\"N)replacer   r   _add_metadata_json)r!   rR   rS   Zwrapped_valuer   r   r   add_metadata   s    z_KinetoProfile.add_metadatac                 C   s   t j|| dS )zs
        Adds a user defined metadata with a string key and a valid json value
        into the trace file
        N)r   r   rV   )r!   rR   rS   r   r   r   r3      s    z _KinetoProfile.add_metadata_jsonc                 C   s8   dd l m} | r| s d S | | | dS )Nr   )backendrank
world_size)Ztorch.distributeddistributedis_availableis_initializedget_backendget_rankget_world_size)r!   distr   r   r   r2      s    z$_KinetoProfile._get_distributed_info)rJ   )Fr   )__name__
__module____qualname____doc__r	   r   r   boolr   r"   r&   r(   r#   r$   r'   strr@   rL   intrO   rQ   rW   r3   r2   r   r   r   r   r      s:    
	r   c                   @   s    e Zd ZdZdZdZdZdZdS )ProfilerActionzG
    Profiler actions that can be taken at the specified intervals
    r            N)rb   rc   rd   re   NONEWARMUPRECORDRECORD_AND_SAVEr   r   r   r   ri      s
   ri   )repeat
skip_first)waitwarmupactiverq   rr   returnc                    s`   t td fdd}dkrDdkrD dkrDdkrDdksLJ ddkr\td |S )a  
    Returns a callable that can be used as profiler ``schedule`` argument. The profiler will skip
    the first ``skip_first`` steps, then wait for ``wait`` steps, then do the warmup for the next ``warmup`` steps,
    then do the active recording for the next ``active`` steps and then repeat the cycle starting with ``wait`` steps.
    The optional number of cycles is specified with the ``repeat`` parameter, the zero value means that
    the cycles will continue until the profiling is finished.
    )steprv   c                    s   | dksJ | k rt jS | 8 }    }dkrH| | krHt jS | | }|k r^t jS | k rpt jS ||d k rt jS t jS d S )Nr   rj   )ri   rm   rn   ro   rp   )rw   Z	num_stepsZmod_stepru   rq   rr   rs   rt   r   r   schedule_fn   s    zschedule.<locals>.schedule_fnr   z#Invalid profiler schedule argumentsz>Profiler won't be using warmup, this can skew profiler results)rh   ri   r   )rs   rt   ru   rq   rr   ry   r   rx   r   schedule   s    rz   )_rv   c                 C   s   t jS )zy
    Default profiler behavior - immediately starts recording the events,
    keeps doing it on every profiler step.
    )ri   ro   )r{   r   r   r   _default_schedule_fn   s    r|   F)dir_nameworker_nameuse_gzipc                    s8   ddl ddlddldd fdd}|S )a  
    Outputs tracing files to directory of ``dir_name``, then that directory can be
    directly delivered to tensorboard as logdir.
    ``worker_name`` should be unique for each worker in distributed scenario,
    it will be set to '[hostname]_[pid]' by default.
    r   N)rv   c                    s   j  s>zj dd W n ty<   td  Y n0 sZd t dt	
 d }r~|d }| j  | d S )NT)exist_okzCan't create directory: z{}_{}z{}.{}.pt.trace.jsoni  r8   )r7   isdirmakedirs	ExceptionRuntimeErrorformatgethostnamerg   getpidrh   timer@   join)r,   	file_namer}   rE   socketr   r   r~   r   r   
handler_fn   s    z-tensorboard_trace_handler.<locals>.handler_fn)rE   r   r   )r}   r~   r   r   r   r   r   tensorboard_trace_handler   s
    r   c                       s   e Zd ZdZddddddddddd
eee  eeege	f  eede
f  eeeeeee ee d
 fddZdd	 Zd
d Zdd Zdd Zdd Zdd Zdd Z  ZS )r-   a  Profiler context manager.

    Args:
        activities (iterable): list of activity groups (CPU, CUDA) to use in profiling, supported values:
            ``torch.profiler.ProfilerActivity.CPU``, ``torch.profiler.ProfilerActivity.CUDA``.
            Default value: ProfilerActivity.CPU and (when available) ProfilerActivity.CUDA.
        schedule (callable): callable that takes step (int) as a single parameter and returns
            ``ProfilerAction`` value that specifies the profiler action to perform at each step.
        on_trace_ready (callable): callable that is called at each step when ``schedule``
            returns ``ProfilerAction.RECORD_AND_SAVE`` during the profiling.
        record_shapes (bool): save information about operator's input shapes.
        profile_memory (bool): track tensor memory allocation/deallocation.
        with_stack (bool): record source information (file and line number) for the ops.
        with_flops (bool): use formula to estimate the FLOPs (floating point operations) of specific operators
            (matrix multiplication and 2D convolution).
        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.
        experimental_config (_ExperimentalConfig) : A set of experimental options
            used for Kineto library features. Note, backward compatibility is not guaranteed.

        use_cuda (bool):
            .. deprecated:: 1.8.1
                use ``activities`` instead.

    .. note::
        Use :func:`~torch.profiler.schedule` to generate the callable schedule.
        Non-default schedules are useful when profiling long training jobs
        and allow the user to obtain multiple traces at the different iterations
        of the training process.
        The default schedule simply records all the events continuously for the
        duration of the context manager.

    .. note::
        Use :func:`~torch.profiler.tensorboard_trace_handler` to generate result files for TensorBoard:

        ``on_trace_ready=torch.profiler.tensorboard_trace_handler(dir_name)``

        After profiling, result files can be found in the specified directory. Use the command:

        ``tensorboard --logdir dir_name``

        to see the results in TensorBoard.
        For more information, see
        `PyTorch Profiler TensorBoard Plugin <https://github.com/pytorch/kineto/tree/master/tb_plugin>`__

    .. note::
        Enabling shape and stack tracing results in additional overhead.
        When record_shapes=True is specified, profiler will temporarily hold references to the tensors;
        that may further prevent certain optimizations that depend on the reference count and introduce
        extra tensor copies.

    Examples:

    .. code-block:: python

        with torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ]
        ) as p:
            code_to_profile()
        print(p.key_averages().table(
            sort_by="self_cuda_time_total", row_limit=-1))

    Using the profiler's ``schedule``, ``on_trace_ready`` and ``step`` functions:

    .. code-block:: python

        # Non-default profiler schedule allows user to turn profiler on and off
        # on different iterations of the training loop;
        # trace_handler is called every time a new trace becomes available
        def trace_handler(prof):
            print(prof.key_averages().table(
                sort_by="self_cuda_time_total", row_limit=-1))
            # prof.export_chrome_trace("/tmp/test_trace_" + str(prof.step_num) + ".json")

        with torch.profiler.profile(
            activities=[
                torch.profiler.ProfilerActivity.CPU,
                torch.profiler.ProfilerActivity.CUDA,
            ],

            # In this example with wait=1, warmup=1, active=2,
            # profiler will skip the first step/iteration,
            # start warming up on the second, record
            # the third and the forth iterations,
            # after which the trace will become available
            # and on_trace_ready (when set) is called;
            # the cycle repeats starting with the next step

            schedule=torch.profiler.schedule(
                wait=1,
                warmup=1,
                active=2),
            on_trace_ready=trace_handler
            # on_trace_ready=torch.profiler.tensorboard_trace_handler('./log')
            # used when outputting for tensorboard
            ) as p:
                for iter in range(N):
                    code_iteration_to_profile(iter)
                    # send a signal to the profiler that the next iteration has started
                    p.step()
    NF)
r   rz   on_trace_readyr   r   r   r   r   r   r)   .c       
      '      s.  |rt |nt }|
d urJtd |
r4|tj ntj|v rJ|tj t|dks^J dt j	|||||||	d |r|| _
d| _nt| _
d| _|| _d| _| 
| j| _d | _tjtjfg tjtjf| jgtjtjf| j| jgtjtjf| j| jgtjtjfttd| j| jgtjtjfg tjtjf| jgtjtjf| jgtjtjfttd| jgtjtjfttd	| jgtjtjfg tjtjfg tjtjf| j| jgtjtjf| j| j| jgtjtjf| j| j| j| jgtjtjf| j| j| j| jgtjd f| j| jgtjd f| j| jgtjd f| j| jgi| _d S )
Nz7use_cuda is deprecated, use activities argument insteadr   z"No valid profiler activities foundr   TFz+Incorrect schedule: WARMUP followed by NONEz+Incorrect schedule: RECORD followed by NONEz-Incorrect schedule: RECORD followed by WARMUP)r   r   r   addr   r.   rF   lensuperr"   rz   record_stepsr|   r   step_numcurrent_actionstep_rec_fnri   rm   rn   r#   ro   r$   rp   r   r'   _trace_ready
action_map)r!   r   rz   r   r   r   r   r   r   r   r)   Zactivities_set	__class__r   r   r"   z  s    






zprofile.__init__c                 C   s   |    | S r   )r&   r%   r   r   r   	__enter__  s    zprofile.__enter__c                 C   s   |    d S r   )r(   )r!   exc_typeexc_valexc_tbr   r   r   r6     s    zprofile.__exit__c                 C   s:   |  tj| j | jr6tdt| j | _	| j	
  d S )NProfilerStep#)_transit_actionri   rm   r   r   r,   record_functionrg   r   r   r   r%   r   r   r   r&     s    zprofile.startc                 C   s.   | j r| jr| jd d d  | | jd  d S r   )r   r   r6   r   r   r%   r   r   r   r(     s    zprofile.stopc                 C   s   | j r| jr| jddd | j}| j}|  jd7  _| | j| _| || j t  | j r~t	dt
| | _| j  dS )zP
        Signals the profiler that the next profiling step has started.
        Nrj   r   )r   r   r6   r   r   rz   r   r,   kineto_stepr   rg   r   )r!   prev_actionZcur_stepr   r   r   rw     s    zprofile.stepc                 C   s   | j r|  |  d S r   )r   r%   r   r   r   r     s    zprofile._trace_readyc                 C   s(   | j ||f}|r$|D ]
}|  qd S r   )r   get)r!   r   r   action_listactionr   r   r   r     s    zprofile._transit_action)rb   rc   rd   re   r	   r   r   r   rh   ri   r   rf   r   r"   r   r6   r&   r(   rw   r   r   __classcell__r   r   r   r   r-     s<   o
Ur-   )NF)'rC   r4   rE   r=   enumr   	functoolsr   typingr   r   r   r   r   r	   r
   warningsr   r   torch.autograd.profilerr   r    r,   torch.autogradr   r   Ztorch._C._autogradr   r   objectr   ri   rh   rz   r|   rg   rf   r   r-   r   r   r   r   <module>   s&   $ $
  