U
    9%ep                     @   sn  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 d dlmZmZmZmZmZ d dlm Z m!Z! d d	l"m#Z#m$Z$ d
dddddgZ%dZ&dd
 Z'G dd d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(Z0G dd dZ1dS )!    N)Enum)partial)AnyCallableDictIterableListOptionalTuple)warn)_get_privateuse1_backend_name)_add_execution_trace_observer!_disable_execution_trace_observer _enable_execution_trace_observer_ExperimentalConfig _remove_execution_trace_observer)kineto_availableProfilerActivity)MemoryProfileMemoryProfileTimelinesupported_activitiesProfilerActionscheduletensorboard_trace_handlerprofileExecutionTraceObserverZProfilerStepc                   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autogradZ_supported_activities r   r   V/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/torch/profiler/profiler.pyr   #   s    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ed%d&d'Zd-eee dd(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 experimental and subject to change in the 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 | _
d | _t }|dkr^|| _d S )NZprivateuseone)setr   r"   r#   r&   r$   r%   r'   r(   profilermem_tl
use_devicer   )	selfr"   r#   r$   r%   r&   r'   r(   Zprivateuse1_backendr   r   r   __init__P   s    z_KinetoProfile.__init__c                 C   s   |    |   d S N)prepare_tracestart_tracer-   r   r   r   starti   s    z_KinetoProfile.startc                 C   s   |    d S r/   )
stop_tracer2   r   r   r   stopm   s    z_KinetoProfile.stopc                 C   sT   t jtj| jktj| jktj| jkd | j| j| j	| j
| jd| jd| _| j  d S )NT)use_cudaZuse_cpuZuse_mtiar,   r#   r&   r$   r%   r'   Z
use_kinetor(   )profr   r   CUDAr"   ZCPUZMTIAr#   r&   r$   r%   r'   r(   r*   Z_prepare_tracer2   r   r   r   r0   p   s    


z_KinetoProfile.prepare_tracec                 C   s   | j d k	st| j   | jr*| dd | jr<| dd | jrN| dd | jr`| dd | jrr| dd t	 r| 
 }|r| dt| ttdrd	d lm  m} |jjrdtjd
< | d
d d S )Nr$   1r%   r#   r'   r&   ZdistributedInfo	_inductorr   ZDISABLE_CUPTI_LAZY_REINIT)r*   AssertionErrorZ_start_tracer$   add_metadata_jsonr%   r#   r'   r&   r   _get_distributed_infojsondumpshasattrr   Ztorch._inductor.configr:   configZtritonZ
cudagraphsosenviron)r-   Z	dist_infoZinductor_configr   r   r   r1      s*    


z_KinetoProfile.start_tracec                 C   s"   | j d k	st| j d d d  d S r/   )r*   r;   __exit__r2   r   r   r   r4      s    z_KinetoProfile.stop_trace)pathc              
   C   s   | j s
t|drtjdddd}|  | j |j}t|j(}t	|d}|
| W 5 Q R X W 5 Q R X t|j |S | j |S dS )zD
        Exports the collected trace in Chrome JSON format.
        .gzw+t.jsonFsuffixdeletewtN)r*   r;   endswithtempfileNamedTemporaryFilecloseexport_chrome_tracenameopengzip
writelinesrB   remove)r-   rE   fpZretvaluefinfoutr   r   r   rQ      s    

z"_KinetoProfile.export_chrome_traceself_cpu_time_total)rE   metricc                 C   s   | j s
t| 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*   r;   export_stacks)r-   rE   r[   r   r   r   r\      s    
z_KinetoProfile.export_stacksr   )group_by_input_shapegroup_by_stack_nc                 C   s   | j s
t| 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*   r;   key_averages)r-   r]   r^   r   r   r   r_      s    

z_KinetoProfile.key_averagesc                 C   s   | j s
t| 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*   r;   Zfunction_eventsr2   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-   ra   rb   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   re   )r-   ra   rb   r   r   r   r<      s    z _KinetoProfile.add_metadata_jsonc                 C   s8   dd l m} | r| s d S | | | dS )Nr   )backendZrankZ
world_size)Ztorch.distributeddistributedis_availableZis_initializedget_backendZget_rankZget_world_size)r-   distr   r   r   r=      s    z$_KinetoProfile._get_distributed_inforeturnc                    sT   d} fdd|D }|r.t d| d jd k	rD jjd k	sHtt jjS )N)r#   r$   r%   c                    s    g | ]}t  |s| d qS )z=True)getattr).0ir2   r   r   
<listcomp>   s     
 z2_KinetoProfile._memory_profile.<locals>.<listcomp>z, z required for memory profiling.)
ValueErrorjoinr*   Zkineto_resultsr;   r   )r-   requiredmissingr   r2   r   _memory_profile   s    z_KinetoProfile._memory_profile)rE   devicerm   c              
   C   s
  |dkr"| j r"| j dkr"| j d }|dkr<tj r8dnd}t|  | _|drd| j|| n|drt	j
dd	d
d}|  |dr| j|j| n| j|j| t|j(}t|d}|| W 5 Q R X W 5 Q R X t|j n| j|| dS )a  Extract the memory information from the memory profile collected
        tree for a given device, and export a timeline plot consisting of
        [times, [sizes by category]], where times are timestamps and sizes
        are memory usage for each category. The memory timeline plot will
        be saved a JSON (by default) or gzipped JSON.

        Input: (path of file, device)
        Output: File written as JSON or gzipped JSON
        Ncudaz:0zcuda:0cpuz.htmlrF   rG   rH   FrI   zraw.json.gzrL   )r,   r   rx   ri   r   rv   r+   rM   Zexport_memory_timeline_htmlrN   rO   rP   Zexport_memory_timeline_rawrR   export_memory_timelinerS   rT   rU   rB   rV   )r-   rE   rw   rW   rX   rY   r   r   r   rz      s$    



z%_KinetoProfile.export_memory_timeline)rZ   )Fr   )N)__name__
__module____qualname____doc__r	   r   r   boolr   r.   r3   r5   r0   r1   r4   strrQ   r\   intr_   r`   rf   r<   r=   r   rv   rz   r   r   r   r   r    1   sH   !
    	r    c                   @   s    e Zd ZdZdZdZdZdZdS )r   zG
    Profiler actions that can be taken at the specified intervals
    r            N)r{   r|   r}   r~   NONEWARMUPRECORDRECORD_AND_SAVEr   r   r   r   r   $  s
   )repeat
skip_first)waitwarmupactiver   r   rm   c                    s`   t td fdd}dkrDdkrD dkrDdkrDdksLt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.
    )steprm   c                    s   | dkst | 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   r   )r;   r   r   r   r   r   )r   Z	num_stepsZmod_stepr   r   r   r   r   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)r   r   r;   r   )r   r   r   r   r   r   r   r   r   r   /  s     )_rm   c                 C   s   t jS )zy
    Default profiler behavior - immediately starts recording the events,
    keeps doing it on every profiler step.
    )r   r   )r   r   r   r   _default_schedule_fnW  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   Nrl   c              
      s   j  sPzj dd W n0 tk
rN } ztd  |W 5 d }~X Y nX sj  d   d  d}r|d }| j 	 | d S )NT)exist_okzCan't create directory: r   .z.pt.trace.jsonrF   )
rE   isdirmakedirs	ExceptionRuntimeErrorgethostnamegetpidtime_nsrQ   rs   )r7   e	file_namer   rB   sockettimer   r   r   r   
handler_fnl  s     z-tensorboard_trace_handler.<locals>.handler_fn)rB   r   r   )r   r   r   r   r   r   r   r   _  s
    	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, repeat=1,
            # 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,
                repeat=1),
            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"   r   on_trace_readyr#   r$   r%   r&   r'   r(   r6   .c       
      '      s:  |rt |nt }|
d k	rJtd |
r4|tj ntj|krJ|tj t|dks^t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| _tjt  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   r8   rV   lenr;   superr.   r   record_stepsr   r   step_numcurrent_actionstep_rec_fnr   r   r   r0   r   r1   r   r   r4   _trace_ready
action_mapr7   KinetoStepTrackerZinit_step_countPROFILER_STEP_NAME)r-   r"   r   r   r#   r$   r%   r&   r'   r(   r6   Zactivities_set	__class__r   r   r.     s    


 
 



 
 
 


 
 



 
 
?zprofile.__init__c                 C   s   |    | S r/   )r3   r2   r   r   r   	__enter__\  s    zprofile.__enter__c                 C   s   |    tjt d S r/   )r5   r7   r   Zerase_step_countr   )r-   exc_typeexc_valexc_tbr   r   r   rD   `  s    zprofile.__exit__c                 C   s:   |  tj| j | jr6tdt| j | _	| j	
  d S )NProfilerStep#)_transit_actionr   r   r   r   r7   record_functionr   r   r   r   r2   r   r   r   r3   d  s    zprofile.startc                 C   s.   | j r| jr| jd d d  | | jd  d S r/   )r   r   rD   r   r   r2   r   r   r   r5   l  s    zprofile.stopc                 C   s   | j r| jr| jddd | j}| j}|  jd7  _| | j| _| || j tj	t
 | j rtdt| | _| j  dS )zP
        Signals the profiler that the next profiling step has started.
        Nr   r   )r   r   rD   r   r   r   r   r7   r   Zincrement_stepr   r   r   r   )r-   prev_actionZcur_stepr   r   r   r   q  s    zprofile.stepc                 C   s   | j r|  |  d S r/   )r   r2   r   r   r   r     s    zprofile._trace_readyc                 C   s(   | j ||f}|r$|D ]
}|  qd S r/   )r   get)r-   r   r   Zaction_listactionr   r   r   r     s    zprofile._transit_action)r{   r|   r}   r~   r	   r   r   r   r   r   r   r   r   r.   r   rD   r3   r5   r   r   r   __classcell__r   r   r   r   r   ~  s<   q
oc                   @   sh   e Zd ZdZdd Zdd ZedddZd	d
 Ze	dd Z
dd Zdd Zdd ZedddZdS )r   a  Execution Trace Observer

    Each process can have a single ExecutionTraceObserver instance. The observer
    can be added to record function callbacks via calling register_callback()
    explicitly. Without calling unregister_callback(), repeated calls to
    register_callback() will not add additional observers to record function
    callbacks. Once an ExecutionTraceObserver is created, the start() and stop()
    methods control when the event data is recorded.

    Deleting or calling unregister_callback() will remove the observer from the
    record function callbacks, finalize the output file, and will stop
    incurring any overheads.
    c                 C   s   d| _ d| _dS )z1
        Initializes the default states.
        FN)_registered_execution_trace_runningr2   r   r   r   r.     s    zExecutionTraceObserver.__init__c                 C   s   |    dS )zO
        Calls unregister_callback() to make sure to finalize outputs.
        N)unregister_callbackr2   r   r   r   __del__  s    zExecutionTraceObserver.__del__)output_file_pathc                 C   s   | j s|| _t|| _ dS )zz
        Adds ET observer to record function callbacks. The the data will be
        written to output_file_path.
        N)r   _output_file_pathr   )r-   r   r   r   r   register_callback  s    z(ExecutionTraceObserver.register_callbackc                 C   s   | j r|   t  d| _ dS )zE
        Removes ET observer from record function callbacks.
        FN)r   r5   r   r2   r   r   r   r     s    z*ExecutionTraceObserver.unregister_callbackc                 C   s   | j S )z^
        Returns True if the execution trace observer is registered, otherwise False.
        )r   r2   r   r   r   is_registered  s    z$ExecutionTraceObserver.is_registeredc                 C   s   | j S )zK
        Returns True if the observer is running, otherwise False.
        )r   r2   r   r   r   
is_running  s    z!ExecutionTraceObserver.is_runningc                 C   s   | j r| jst  d| _dS )z$
        Starts to capture.
        TN)r   r   r   r2   r   r   r   r3     s    zExecutionTraceObserver.startc                 C   s   | j rt  d| _ dS )z#
        Stops to capture.
        FN)r   r   r2   r   r   r   r5     s    zExecutionTraceObserver.stoprl   c                 C   s   | j r| jS tddS )z/
        Returns the output file name.
        z^A callback to the ET profiler needs to be registered first before getting the output file pathN)r   r   r   r2   r   r   r   get_output_file_path  s
    z+ExecutionTraceObserver.get_output_file_pathN)r{   r|   r}   r~   r.   r   r   r   r   propertyr   r   r3   r5   r   r   r   r   r   r     s   		
)NF)2rT   r>   rB   rN   enumr   	functoolsr   typingr   r   r   r   r   r	   r
   warningsr   r   Ztorch.autograd.profilerr   r*   r7   Ztorch._Cr   Ztorch._C._profilerr   r   r   r   r   Ztorch.autogradr   r   Ztorch.profiler._memory_profilerr   r   __all__r   r   r    r   r   r   r   r   r   r   r   r   r   r   r   r   <module>   s^   $ t     (	       