o
    NeyE                     @   s  d dl mZ ddlmZ ddlmZ d dlZd dlZd dlZd dl	m
Z
 g dZg dZe
d	d
dddedddZedddZe
d	d
ddddd Ze
d	d
dddd ddZe
d	d
dddd!ddZe
d	d
ddde			d"ddZed#ddZdS )$    )print_function   )core)signature_safe_contextmanagerN)
deprecated)cuda_profilerreset_profilerprofilerstart_profilerstop_profiler)ZgpustarttimestampZgpuendtimestampZ
gridsize3dZthreadblocksizeZstreamidzenableonstart 0Zconckerneltracez2.3.0zpaddle.profiler.ProfilerzIPlease use new profiler tool, this profiler tool is no longer maintained.)ZsinceZ	update_tolevelreasonc                 C   s   t d)a\  
    API cuda_profiler has been abandoned. If you have relevant requirements, you can use `paddle.utils.profiler.start_profiler` and `paddle.utils.profiler.stop_profiler`.
    The relevant reference documents are as follows:
    <https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/utils/profiler/start_profiler_en.html#start-profiler>
    <https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/utils/profiler/stop_profiler_en.html#stop-profiler>
    <https://www.paddlepaddle.org.cn/documentation/docs/en/advanced_guide/performance_improving/analysis_tools/timeline_en.html>
    aB  API cuda_profiler has been abandoned. If you have relevant requirements, you can use `paddle.utils.profiler.start_profiler` and `paddle.utils.profiler.stop_profiler`.
The relevant reference documents are as follows:
<https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/utils/profiler/start_profiler_en.html#start-profiler>
<https://www.paddlepaddle.org.cn/documentation/docs/en/api/paddle/utils/profiler/stop_profiler_en.html#stop-profiler>
<https://www.paddlepaddle.org.cn/documentation/docs/en/advanced_guide/performance_improving/analysis_tools/timeline_en.html>)RuntimeError)output_fileZoutput_modeconfig r   ED:\Projects\ConvertPro\env\Lib\site-packages\paddle/fluid/profiler.pyr   )   s   r   c              	   c   sV    |st  }t |  t | zdV  W t | t   dS t | t   w )a  
    The NPU profiler.

    This fuctions is used to profile NPU program by NPU runtime application
    programming interface. The profiling result will be written into
    `output_file`. The users can set set the NPU profiling config by `config` argument.

    After getting the profiling result file, users can use
    `tools provided by Ascend <https://support.huaweicloud.com/tg-Inference-cann/atlasprofiling_16_0006.html>`_
    to load this output file to visualize results.

    Args:
        output_file (str) : The output file name, the result will be
            written into this file. It should be absolute path.
        config (list<str>, optional) : NPU profile config. For more details, please
            refer to `User Guide <https://support.huaweicloud.com/tg-Inference-cann/atlasprofiling_16_0006.html>`_ .

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler
            import numpy as np

            epoc = 8
            dshape = [4, 3, 28, 28]
            data = fluid.data(name='data', shape=[None, 3, 28, 28], dtype='float32')
            conv = fluid.layers.conv2d(data, 20, 3, stride=[1, 1], padding=[1, 1])

            place = fluid.NPUPlace(0)
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())

            output_file = 'npu.txt'
            with profiler.npu_profiler(output_file) as npu_prof:
                for i in range(epoc):
                    input = np.random.random(dshape).astype('float32')
                    exe.run(fluid.default_main_program(), feed={'data': input})
            # then use  NPU profiler tools to load this output file
            # to visualize results.
    N)r   Znpu_prof_create_configZnpu_prof_initZnpu_prof_startZnpu_prof_stopZnpu_prof_finalize)r   r   r   r   r   npu_profiler=   s   -




r   c                   C   s   t   dS )a!  
    Clear the previous time record. It works for
    `fluid.profiler.start_profiler`, `fluid.profiler.stop_profiler`,
    and `fluid.profiler.profiler`.

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler
            with profiler.profiler('CPU', 'total', '/tmp/profile'):
                for iter in range(10):
                    if iter == 2:
                        profiler.reset_profiler()
                    # ...
    N)r   r   r   r   r   r   r   x   s   r   Defaultc                 C   s   t  rdS | dvrtd| dkrt jj}n| dkr t jj}nt jj}|dvr,td|dkr5t jj}n|d	kr>t jj	}nt jj
}t | t | dS )
a.  
    Enable the profiler. Uers can use `fluid.profiler.start_profiler` and
    `fluid.profiler.stop_profiler` to profile, which is equal to the usage
    of `fluid.profiler.profiler` interface.

    Args:
        state (str) : The profiling state, which should be one of 'CPU', 'GPU'
            or 'All'. 'CPU' means only profiling CPU; 'GPU' means profiling
            both CPU and GPU; 'All' means profiling both CPU and GPU, and
            generates timeline as well.
        tracer_option (str, optional) : tracer_option can be one of ['Default', 'OpDetail', 'AllOpDetail'], it
            can control the profile level and print the different level profile result. `Default` option print
            the different Op type profiling result and the `OpDetail` option print the detail profiling
            result of different op types such as compute and data transform, `AllOpDetail` option
            print the detail profiling result of different op name same as `OpDetail`.

    Raises:
        ValueError: If `state` is not in ['CPU', 'GPU', 'All'] or `tracer_option`
            is not in ['Default', 'OpDetail', 'AllOpDetail'].

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler

            profiler.start_profiler('GPU')
            for iter in range(10):
                if iter == 2:
                    profiler.reset_profiler()
                # except each iteration
            profiler.stop_profiler('total', '/tmp/profile')

            profiler.start_profiler('GPU', "OpDetail")
            for iter in range(10):
                if iter == 2:
                    profiler.reset_profiler()
                # except each iteration
            profiler.stop_profiler('total', '/tmp/profile')
    N)CPUGPUZAllz*The state must be 'CPU' or 'GPU' or 'All'.r   r   )r   OpDetailZAllOpDetailz;tracer option must be 'Default', 'OpDetail', 'AllOpDetail'.r   r   )r   is_profiler_enabled
ValueErrorZProfilerStateZkCUDAZkCPUZkAllZTracerOptionkDefaultZ	kOpDetailZkAllOpDetailZset_tracer_optionZenable_profiler)statetracer_optionZ
prof_stateZprof_tracer_optionr   r   r   r
      s(   1




r
   /tmp/profilec                 C   sj   t  sdS | du rdn| } | dvrtdt jjt jjt jjt jjt jjt jj	d}t 
||  | dS )a  
    Stop the profiler. Uers can use `fluid.profiler.start_profiler` and
    `fluid.profiler.stop_profiler` to profile, which is equal to the usage
    of `fluid.profiler.profiler` interface.

    Args:
        sorted_key (str, optional) : The order of profiling results, which
            should be one of None, 'calls', 'total', 'max', 'min' or 'ave'.
            Default is None, means the profiling results will be printed
            in the order of first end time of events.
            The `calls` means sorting by the number of calls.
            The `total` means sorting by the total execution time.
            The `max` means sorting by the maximum execution time.
            The `min` means sorting by the minimum execution time.
            The `ave` means sorting by the average execution time.
            and write it into `profile_path`. The default profile_path is `/tmp/profile`.
        profile_path (str, optional) : If state == 'All', it will generate timeline,

    Raises:
        ValueError: If `sorted_key` is not in
            ['calls', 'total', 'max', 'min', 'ave'].

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler

            profiler.start_profiler('GPU')
            for iter in range(10):
                if iter == 2:
                    profiler.reset_profiler()
                # except each iteration
            profiler.stop_profiler('total', '/tmp/profile')
    Ndefault)r   ZcallstotalmaxminZavezJThe sorted_key must be None or in 'calls', 'total', 'max', 'min' and 'ave')r   r   r   ZEventSortingKeyr   ZkCallsZkTotalZkMaxZkMinZkAveZdisable_profiler)
sorted_keyprofile_pathZkey_mapr   r   r   r      s   ,
r   c              	   c   s0    t | | zdV  W t|| dS t|| w )ab  
    The profiler interface. This profiler can be used to profile both CPU and GPU program.

    Args:
        state (str) : The profiling state, which should be one of 'CPU', 'GPU'
            or 'All'. 'CPU' means only profiling CPU; 'GPU' means profiling
            both CPU and GPU; 'All' means profiling both CPU and GPU, and
            generates timeline as well.
        sorted_key (str, optional) : The order of profiling results, which
            should be one of None, 'calls', 'total', 'max', 'min' or 'ave'.
            Default is None, means the profiling results will be printed
            in the order of first end time of events.
            The `calls` means sorting by the number of calls.
            The `total` means sorting by the total execution time.
            The `max` means sorting by the maximum execution time.
            The `min` means sorting by the minimum execution time.
            The `ave` means sorting by the average execution time.
        profile_path (str, optional) : If state == 'All', it will generate timeline,
            and write it into `profile_path`. The default profile_path is `/tmp/profile`.
        tracer_option (str, optional) : tracer_option can be one of ['Default', 'OpDetail', 'AllOpDetail'], it
            can control the profile level and print the different level profile result. `Default` option print
            the different Op type profiling result and the `OpDetail` option print the detail profiling
            result of different op types such as compute and data transform, `AllOpDetail` option
            print the detail profiling result of different op name same as `OpDetail`.

    Raises:
        ValueError: If `state` is not in ['CPU', 'GPU', 'All']. If `sorted_key` is
            not in ['calls', 'total', 'max', 'min', 'ave'].

    Examples:

        .. code-block:: python

            # required: gpu
            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler
            import numpy as np
            import paddle
            paddle.enable_static()

            epoc = 8
            dshape = [4, 3, 28, 28]
            data = fluid.data(name='data', shape=[None, 3, 28, 28], dtype='float32')
            conv = fluid.layers.conv2d(data, 20, 3, stride=[1, 1], padding=[1, 1])

            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())

            with profiler.profiler('CPU', 'total', '/tmp/profile', 'Default') as prof:
                for i in range(epoc):
                    input = np.random.random(dshape).astype('float32')
                    exe.run(fluid.default_main_program(), feed={'data': input})

    Examples Results:

        .. code-block:: text

            #### Examples Results ####
            #### 1) sorted_key = 'total', 'calls', 'max', 'min', 'ave' ####
            # The only difference in 5 sorted_key results is the following sentence:
            # "Sorted by number of xxx in descending order in the same thread."
            # The reason is that in this example, above 5 columns are already sorted.
            ------------------------->     Profiling Report     <-------------------------

            Place: CPU
            Time unit: ms
            Sorted by total time in descending order in the same thread
            #Sorted by number of calls in descending order in the same thread
            #Sorted by number of max in descending order in the same thread
            #Sorted by number of min in descending order in the same thread
            #Sorted by number of avg in descending order in the same thread

            Event                       Calls       Total       Min.        Max.        Ave.        Ratio.
            thread0::conv2d             8           129.406     0.304303    127.076     16.1758     0.983319
            thread0::elementwise_add    8           2.11865     0.193486    0.525592    0.264832    0.016099
            thread0::feed               8           0.076649    0.006834    0.024616    0.00958112  0.000582432

            #### 2) sorted_key = None  ####
            # Since the profiling results are printed in the order of first end time of Ops,
            # the printed order is feed->conv2d->elementwise_add
            ------------------------->     Profiling Report     <-------------------------

            Place: CPU
            Time unit: ms
            Sorted by event first end time in descending order in the same thread

            Event                       Calls       Total       Min.        Max.        Ave.        Ratio.
            thread0::feed               8           0.077419    0.006608    0.023349    0.00967738  0.00775934
            thread0::conv2d             8           7.93456     0.291385    5.63342     0.99182     0.795243
            thread0::elementwise_add    8           1.96555     0.191884    0.518004    0.245693    0.196998
    N)r
   r   )r   r"   r#   r   r   r   r   r	     s
   
gr	   Tc                 c   s    z7| |krt   t   | |krt t|  dV  W | |k r%t   | |kr5t   |r7t  dS dS dS | |k rAt   | |krPt   |rQt  w w w )a  
    A range profiler interface (not public yet).

    Examples:

        .. code-block:: python

            model = Model()
            for i in range(max_iter):
                paddle.fluid.profiler._nvprof_range(i, 10, 20):
                    out = model(in)
    N)	r   Znvprof_startZnvprof_enable_record_eventZnvprof_nvtx_pushstrZnvprof_nvtx_popZnvprof_stopsysexit)Ziter_idstartendZexit_after_profr   r   r   _nvprof_range  s0   
r)   )NN)N)r   )Nr   )Nr   r   )T)
__future__r    r   wrapped_decoratorr   ossixr%   Zpaddle.utils.deprecatedr   __all__ZNVPROF_CONFIGr   r   r   r
   r   r	   r)   r   r   r   r   <module>   sj   :
D9g