profiler.py 10.8 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15 16
from __future__ import print_function

17
from . import core
S
rename  
sneaxiy 已提交
18
from .wrapped_decorator import signature_safe_contextmanager
19
import os
M
minqiyang 已提交
20
import six
D
dangqingqing 已提交
21

X
Xin Pan 已提交
22 23 24 25
__all__ = [
    'cuda_profiler', 'reset_profiler', 'profiler', 'start_profiler',
    'stop_profiler'
]
D
dangqingqing 已提交
26

D
dangqingqing 已提交
27
NVPROF_CONFIG = [
28 29 30 31 32 33
    "gpustarttimestamp",
    "gpuendtimestamp",
    "gridsize3d",
    "threadblocksize",
    "streamid",
    "enableonstart 0",
D
dangqingqing 已提交
34
    "conckerneltrace",
35 36 37
]


S
rename  
sneaxiy 已提交
38
@signature_safe_contextmanager
D
dangqingqing 已提交
39 40 41 42 43 44 45
def cuda_profiler(output_file, output_mode=None, config=None):
    """The CUDA profiler.
    This fuctions is used to profile CUDA program by CUDA runtime application
    programming interface. The profiling result will be written into
    `output_file` with Key-Value pair format or Comma separated values format.
    The user can set the output mode by `output_mode` argument and set the
    counters/options for profiling by `config` argument. The default config
46
    is ['gpustarttimestamp', 'gpuendtimestamp', 'gridsize3d',
D
dangqingqing 已提交
47
    'threadblocksize', 'streamid', 'enableonstart 0', 'conckerneltrace'].
D
Dang Qingqing 已提交
48 49 50
    Then users can use NVIDIA Visual Profiler
    (https://developer.nvidia.com/nvidia-visual-profiler) tools to load this
    this output file to visualize results.
D
dangqingqing 已提交
51 52 53 54 55 56

    Args:
        output_file (string) : The output file name, the result will be
            written into this file.
        output_mode (string) : The output mode has Key-Value pair format and
            Comma separated values format. It should be 'kvp' or 'csv'.
57 58
        config (list of string) : The profiler options and counters can refer
            to "Compute Command Line Profiler User Guide".
D
Dang Qingqing 已提交
59 60 61 62 63 64 65 66 67 68

    Raises:
        ValueError: If `output_mode` is not in ['kvp', 'csv'].

    Examples:

        .. code-block:: python

            import paddle.fluid as fluid
            import paddle.fluid.profiler as profiler
69
            import numpy as np
D
Dang Qingqing 已提交
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

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

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

            output_file = 'cuda_profiler.txt'
            with profiler.cuda_profiler(output_file, 'csv') as nvprof:
                for i in range(epoc):
                    input = np.random.random(dshape).astype('float32')
                    exe.run(fluid.default_main_program(), feed={'data': input})
            # then use  NVIDIA Visual Profiler (nvvp) to load this output file
            # to visualize results.
D
dangqingqing 已提交
87 88 89
    """
    if output_mode is None:
        output_mode = 'csv'
D
dangqingqing 已提交
90 91 92
    if output_mode not in ['kvp', 'csv']:
        raise ValueError("The output mode must be 'kvp' or 'csv'.")
    config = NVPROF_CONFIG if config is None else config
93 94
    config_file = 'nvprof_config_file'
    with open(config_file, 'wb') as fp:
M
minqiyang 已提交
95
        fp.writelines([six.b("%s\n" % item) for item in config])
96
    core.nvprof_init(output_file, output_mode, config_file)
D
dangqingqing 已提交
97
    # Enables profiler collection by the active CUDA profiling tool.
D
dangqingqing 已提交
98
    core.nvprof_start()
D
dangqingqing 已提交
99 100
    yield
    # Disables profiler collection.
D
dangqingqing 已提交
101
    core.nvprof_stop()
102
    os.remove(config_file)
103 104 105


def reset_profiler():
D
Dang Qingqing 已提交
106 107 108 109 110 111 112 113 114 115
    """
    Clear the previous time record. This interface does not work for
    `fluid.profiler.cuda_profiler`, it only works for
    `fluid.profiler.start_profiler`, `fluid.profiler.stop_profiler`,
    and `fluid.profiler.profiler`.

    Examples:

        .. code-block:: python

116
            import paddle.fluid as fluid
D
Dang Qingqing 已提交
117
            import paddle.fluid.profiler as profiler
118
            with profiler.profiler('CPU', 'total', '/tmp/profile'):
D
Dang Qingqing 已提交
119 120 121 122
                for iter in range(10):
                    if iter == 2:
                        profiler.reset_profiler()
                    # ...
123
    """
124 125 126
    core.reset_profiler()


X
Xin Pan 已提交
127
def start_profiler(state):
D
Dang Qingqing 已提交
128 129 130 131
    """
    Enable the profiler. Uers can use `fluid.profiler.start_profiler` and
    `fluid.profiler.stop_profiler` to insert the code, except the usage of
    `fluid.profiler.profiler` interface.
X
Xin Pan 已提交
132 133 134 135 136

    Args:
        state (string) : The profiling state, which should be 'CPU', 'GPU'
            or 'All'. 'CPU' means only profile CPU. 'GPU' means profiling
            GPU as well. 'All' also generates timeline.
D
Dang Qingqing 已提交
137 138 139 140 141 142 143 144

    Raises:
        ValueError: If `state` is not in ['CPU', 'GPU', 'All'].

    Examples:

        .. code-block:: python

145
            import paddle.fluid as fluid
D
Dang Qingqing 已提交
146 147 148 149 150 151 152 153
            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')
X
Xin Pan 已提交
154 155 156
    """
    if core.is_profiler_enabled():
        return
X
Xin Pan 已提交
157 158 159 160 161 162 163 164 165 166 167 168
    if state not in ['CPU', 'GPU', "All"]:
        raise ValueError("The state must be 'CPU' or 'GPU' or 'All'.")
    if state == "GPU":
        prof_state = core.ProfilerState.kCUDA
    elif state == "CPU":
        prof_state = core.ProfilerState.kCPU
    else:
        prof_state = core.ProfilerState.kAll
    core.enable_profiler(prof_state)


def stop_profiler(sorted_key=None, profile_path='/tmp/profile'):
D
Dang Qingqing 已提交
169 170 171 172
    """
    Stop the profiler. Uers can use `fluid.profiler.start_profiler` and
    `fluid.profiler.stop_profiler` to insert the code, except the usage of
    `fluid.profiler.profiler` interface.
X
Xin Pan 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185

    Args:
        sorted_key (string) : If None, the profiling results will be printed
            in the order of first end time of events. Otherwise, the profiling
            results will be sorted by the this flag. This flag should be one
            of 'calls', 'total', 'max', 'min' or 'ave'.
            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 (string) : If state == 'All', it will write a profile
            proto output file.
D
Dang Qingqing 已提交
186 187 188 189 190 191 192 193 194

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

    Examples:

        .. code-block:: python

195
            import paddle.fluid as fluid
D
Dang Qingqing 已提交
196 197 198 199 200 201 202 203
            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')
X
Xin Pan 已提交
204 205 206
    """
    if not core.is_profiler_enabled():
        return
X
Xin Pan 已提交
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
    sorted_key = 'default' if sorted_key is None else sorted_key
    if sorted_key not in ['default', 'calls', 'total', 'max', 'min', 'ave']:
        raise ValueError("The sorted_key must be None or in 'calls', 'total', "
                         "'max', 'min' and 'ave'")
    key_map = {
        'default': core.EventSortingKey.kDefault,
        'calls': core.EventSortingKey.kCalls,
        'total': core.EventSortingKey.kTotal,
        'max': core.EventSortingKey.kMax,
        'min': core.EventSortingKey.kMin,
        'ave': core.EventSortingKey.kAve,
    }
    # TODO(qingqing) : redirect C++ ostream to Python stream.
    # with core.ostream_redirect(stdout=True, stderr=True):
    core.disable_profiler(key_map[sorted_key], profile_path)


S
rename  
sneaxiy 已提交
224
@signature_safe_contextmanager
X
Xin Pan 已提交
225
def profiler(state, sorted_key=None, profile_path='/tmp/profile'):
226
    """The profiler interface.
227
    Different from cuda_profiler, this profiler can be used to profile both CPU
Q
qiaolongfei 已提交
228
    and GPU program. By default, it records the CPU and GPU operator kernels,
229
    if you want to profile other program, you can refer the profiling tutorial
D
Dang Qingqing 已提交
230 231 232 233
    to add more records in C++ code.

    If the state == 'All', a profile proto file will be written to
    `profile_path`. This file records timeline information during the execution.
234
    Then users can visualize this file to see the timeline, please refer
D
Dang Qingqing 已提交
235
    https://github.com/PaddlePaddle/Paddle/blob/develop/doc/fluid/howto/optimization/timeline.md
236 237

    Args:
D
dangqingqing 已提交
238 239 240
        state (string) : The profiling state, which should be 'CPU' or 'GPU',
            telling the profiler to use CPU timer or GPU timer for profiling.
            Although users may have already specified the execution place
Q
qiaolongfei 已提交
241
            (CPUPlace/CUDAPlace) in the beginning, for flexibility the profiler
D
dangqingqing 已提交
242
            would not inherit this place.
243 244 245 246 247
        sorted_key (string) : If None, the profiling results will be printed
            in the order of first end time of events. Otherwise, the profiling
            results will be sorted by the this flag. This flag should be one
            of 'calls', 'total', 'max', 'min' or 'ave'.
            The `calls` means sorting by the number of calls.
248 249 250 251
            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.
X
Xin Pan 已提交
252 253
        profile_path (string) : If state == 'All', it will write a profile
            proto output file.
D
Dang Qingqing 已提交
254 255 256 257 258 259 260 261 262

    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

263
            import paddle.fluid as fluid
D
Dang Qingqing 已提交
264
            import paddle.fluid.profiler as profiler
265
            import numpy as np
D
Dang Qingqing 已提交
266

267 268 269 270 271 272 273 274 275 276 277 278 279
            epoc = 8
            dshape = [4, 3, 28, 28]
            data = fluid.layers.data(name='data', shape=[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') as prof:
                for i in range(epoc):
                    input = np.random.random(dshape).astype('float32')
                    exe.run(fluid.default_main_program(), feed={'data': input})
280
    """
X
Xin Pan 已提交
281
    start_profiler(state)
282
    yield
X
Xin Pan 已提交
283
    stop_profiler(sorted_key, profile_path)