profiler.py 6.5 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.

Y
Yang Yu 已提交
15
import core
D
dangqingqing 已提交
16
from contextlib import contextmanager
17
import os
D
dangqingqing 已提交
18

X
Xin Pan 已提交
19 20 21 22
__all__ = [
    'cuda_profiler', 'reset_profiler', 'profiler', 'start_profiler',
    'stop_profiler'
]
D
dangqingqing 已提交
23

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


D
dangqingqing 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
@contextmanager
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
    is ['gpustarttimestamp', 'gpustarttimestamp', 'gridsize3d',
    'threadblocksize', 'streamid', 'enableonstart 0', 'conckerneltrace'].

    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'.
51 52
        config (list of string) : The profiler options and counters can refer
            to "Compute Command Line Profiler User Guide".
D
dangqingqing 已提交
53 54 55
    """
    if output_mode is None:
        output_mode = 'csv'
D
dangqingqing 已提交
56 57 58
    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
59 60 61 62
    config_file = 'nvprof_config_file'
    with open(config_file, 'wb') as fp:
        fp.writelines(["%s\n" % item for item in config])
    core.nvprof_init(output_file, output_mode, config_file)
D
dangqingqing 已提交
63
    # Enables profiler collection by the active CUDA profiling tool.
D
dangqingqing 已提交
64
    core.nvprof_start()
D
dangqingqing 已提交
65 66
    yield
    # Disables profiler collection.
D
dangqingqing 已提交
67
    core.nvprof_stop()
68
    os.remove(config_file)
69 70 71


def reset_profiler():
72 73 74
    """The profiler clear interface.
    reset_profiler will clear the previous time record.
    """
75 76 77
    core.reset_profiler()


X
Xin Pan 已提交
78
def start_profiler(state):
X
Xin Pan 已提交
79 80 81 82 83 84 85 86 87
    """Enable the profiler.

    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.
    """
    if core.is_profiler_enabled():
        return
X
Xin Pan 已提交
88 89 90 91 92 93 94 95 96 97 98 99
    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'):
X
Xin Pan 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
    """Stop the profiler.

    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.
    """
    if not core.is_profiler_enabled():
        return
X
Xin Pan 已提交
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    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)


134
@contextmanager
X
Xin Pan 已提交
135
def profiler(state, sorted_key=None, profile_path='/tmp/profile'):
136
    """The profiler interface.
137 138 139 140
    Different from cuda_profiler, this profiler can be used to profile both CPU
    and GPU program. By defalut, it records the CPU and GPU operator kernels,
    if you want to profile other program, you can refer the profiling tutorial
    to add more records.
141 142

    Args:
D
dangqingqing 已提交
143 144 145 146 147
        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
            (CPUPlace/CUDAPlace) in the begining, for flexibility the profiler
            would not inherit this place.
148 149 150 151 152
        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.
153 154 155 156
            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 已提交
157 158
        profile_path (string) : If state == 'All', it will write a profile
            proto output file.
159
    """
X
Xin Pan 已提交
160
    start_profiler(state)
161
    yield
X
Xin Pan 已提交
162
    stop_profiler(sorted_key, profile_path)