profiler.py 9.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# 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
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# 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.
# pylint: disable=doc-string-missing
D
dongdaxiang 已提交
15

16 17
import os
import sys
B
barrierye 已提交
18
import logging
19 20 21 22 23 24
if sys.version_info.major == 2:
    import Queue
elif sys.version_info.major == 3:
    import queue as Queue
else:
    raise Exception("Error Python version")
B
barriery 已提交
25
from time import time as _time
B
barriery 已提交
26
import time
B
barrierye 已提交
27
import threading
B
barriery 已提交
28
import multiprocessing
W
wangjiawei04 已提交
29
import copy
30 31
_LOGGER = logging.getLogger(__name__)
_LOGGER.propagate = False
B
barrierye 已提交
32

W
wangjiawei04 已提交
33
_is_profile = int(os.environ.get('FLAGS_profile_pipeline', 0))
D
dongdaxiang 已提交
34

B
barriery 已提交
35
class PerformanceTracer(object):
B
barriery 已提交
36 37 38 39 40 41 42 43 44 45
    def __init__(self, is_thread_mode, interval_s, server_worker_num):
        self._is_thread_mode = is_thread_mode
        if is_thread_mode:
            # Because the Channel in the thread mode cannot be
            # accessed across processes, when using thread mode,
            # the PerformanceTracer is also the thread mode.
            # However, performance may be affected by GIL.
            self._data_buffer = Queue.Queue()
        else:
            self._data_buffer = multiprocessing.Manager().Queue()
B
barriery 已提交
46
        self._interval_s = interval_s
B
barriery 已提交
47
        self._thrd = None
B
barriery 已提交
48 49
        self._proc = None
        self._channels = []
B
barriery 已提交
50 51
        # The size of data in Channel will not exceed server_worker_num
        self._server_worker_num = server_worker_num
B
bjjwwang 已提交
52
        self.profile_dict = {}
S
ShiningZhang 已提交
53
        self._enable_dict = False
B
barriery 已提交
54 55 56 57 58

    def data_buffer(self):
        return self._data_buffer

    def start(self):
B
bjjwwang 已提交
59 60 61 62 63
        self._thrd = threading.Thread(
            target=self._trace_func, args=(self._channels, ))
        self._thrd.daemon = True
        self._thrd.start()
        """
B
barriery 已提交
64 65 66 67 68 69 70 71 72 73
        if self._is_thread_mode:
            self._thrd = threading.Thread(
                target=self._trace_func, args=(self._channels, ))
            self._thrd.daemon = True
            self._thrd.start()
        else:
            self._proc = multiprocessing.Process(
                target=self._trace_func, args=(self._channels, ))
            self._proc.daemon = True
            self._proc.start()
B
bjjwwang 已提交
74
        """
B
barriery 已提交
75 76 77 78

    def set_channels(self, channels):
        self._channels = channels

S
ShiningZhang 已提交
79 80 81
    def set_enable_dict(self, enable):
        self._enable_dict = enable

B
barriery 已提交
82
    def _trace_func(self, channels):
B
barrierye 已提交
83
        all_actions = ["in", "prep", "midp", "postp", "out"]
B
barriery 已提交
84
        calcu_actions = ["prep", "midp", "postp"]
B
barriery 已提交
85 86
        while True:
            op_cost = {}
B
barrierye 已提交
87
            err_request = []
B
barriery 已提交
88
            err_count = 0
B
barriery 已提交
89

90
            _LOGGER.info("==================== TRACER ======================")
B
barriery 已提交
91
            # op
B
barriery 已提交
92 93
            while True:
                try:
B
barrierye 已提交
94 95 96
                    item = self._data_buffer.get_nowait()
                    name = item["name"]
                    actions = item["actions"]
W
wangjiawei04 已提交
97
                    
B
barrierye 已提交
98 99 100 101 102 103
                    if name == "DAG":
                        succ = item["succ"]
                        req_id = item["id"]
                        if not succ:
                            err_count += 1
                            err_request.append(req_id)
B
barriery 已提交
104

B
barriery 已提交
105 106
                    if name not in op_cost:
                        op_cost[name] = {}
B
barrierye 已提交
107 108 109 110 111

                    for action, cost in actions.items():
                        if action not in op_cost[name]:
                            op_cost[name][action] = []
                        op_cost[name][action].append(cost)
B
barriery 已提交
112 113 114 115 116 117
                except Queue.Empty:
                    break

            if len(op_cost) != 0:
                for name in op_cost:
                    tot_cost, calcu_cost = 0.0, 0.0
S
ShiningZhang 已提交
118
                    count = 0
B
barriery 已提交
119 120 121
                    for action, costs in op_cost[name].items():
                        op_cost[name][action] = sum(costs) / (1e3 * len(costs))
                        tot_cost += op_cost[name][action]
S
ShiningZhang 已提交
122 123 124 125
                        if action == "midp":
                            count = len(costs)
                    if "midp" in op_cost[name].keys():
                        op_cost[name]['count'] = count
B
barriery 已提交
126
                    if name != "DAG":
127
                        _LOGGER.info("Op({}):".format(name))
W
wangjiawei04 已提交
128
                        
B
barrierye 已提交
129
                        for action in all_actions:
B
barriery 已提交
130
                            if action in op_cost[name]:
131
                                _LOGGER.info("\t{}[{} ms]".format(
B
barriery 已提交
132 133 134 135
                                    action, op_cost[name][action]))
                        for action in calcu_actions:
                            if action in op_cost[name]:
                                calcu_cost += op_cost[name][action]
136
                        _LOGGER.info("\tidle[{}]".format(1 - 1.0 * calcu_cost /
B
barriery 已提交
137
                                                         tot_cost))
B
bjjwwang 已提交
138
            self.profile_dict = copy.deepcopy(op_cost)
W
wangjiawei04 已提交
139
                
B
barriery 已提交
140
            if "DAG" in op_cost:
T
TeslaZhao 已提交
141
                calls = list(op_cost["DAG"].values())
B
barriery 已提交
142 143 144 145 146
                calls.sort()
                tot = len(calls)
                qps = 1.0 * tot / self._interval_s
                ave_cost = sum(calls) / tot
                latencys = [50, 60, 70, 80, 90, 95, 99]
147
                _LOGGER.info("DAGExecutor:")
B
barrierye 已提交
148 149 150
                _LOGGER.info("\tQuery count[{}]".format(tot))
                _LOGGER.info("\tQPS[{} q/s]".format(qps))
                _LOGGER.info("\tSucc[{}]".format(1 - 1.0 * err_count / tot))
B
barriery 已提交
151 152
                _LOGGER.info("\tError req[{}]".format(", ".join(
                    [str(x) for x in err_request])))
B
barrierye 已提交
153
                _LOGGER.info("\tLatency:")
154
                _LOGGER.info("\t\tave[{} ms]".format(ave_cost))
B
barriery 已提交
155
                for latency in latencys:
156
                    _LOGGER.info("\t\t.{}[{} ms]".format(latency, calls[int(
B
barriery 已提交
157
                        tot * latency / 100.0)]))
S
ShiningZhang 已提交
158
                if _is_profile or self._enable_dict:
W
wangjiawei04 已提交
159 160 161 162 163 164 165 166 167 168
                    self.profile_dict["DAG"]["query_count"] = tot
                    self.profile_dict["DAG"]["qps"] = qps
                    self.profile_dict["DAG"]["succ"] = 1 - 1.0 * err_count / tot
                    self.profile_dict["DAG"]["avg"] = ave_cost
                    for latency in latencys:
                        self.profile_dict["DAG"][str(latency)] = calls[int(tot * latency / 100.0)]
            if _is_profile:
                import yaml
                with open("benchmark.log", "w") as fout:
                    yaml.dump(self.profile_dict, fout, default_flow_style=False)
B
barriery 已提交
169
            # channel
170
            _LOGGER.info("Channel (server worker num[{}]):".format(
B
barriery 已提交
171
                self._server_worker_num))
B
barriery 已提交
172
            for channel in channels:
173
                _LOGGER.info("\t{}(In: {}, Out: {}) size[{}/{}]".format(
B
barriery 已提交
174 175 176 177
                    channel.name,
                    channel.get_producers(),
                    channel.get_consumers(),
                    channel.size(), channel.get_maxsize()))
B
barriery 已提交
178 179 180
            time.sleep(self._interval_s)


B
barriery 已提交
181
class UnsafeTimeProfiler(object):
182 183
    """ thread unsafe profiler """

B
barriery 已提交
184 185 186 187 188 189 190 191 192 193 194 195
    def __init__(self):
        self.pid = os.getpid()
        self.print_head = 'PROFILE\tpid:{}\t'.format(self.pid)
        self.time_record = [self.print_head]
        self._enable = False

    def enable(self, enable):
        self._enable = enable

    def record(self, name):
        if self._enable is False:
            return
B
barriery 已提交
196 197 198
        timestamp = int(round(_time() * 1000000))
        self.time_record.append('{}:{} '.format(name, timestamp))
        return timestamp
B
barriery 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213

    def print_profile(self):
        if self._enable is False:
            return
        sys.stderr.write(self.gen_profile_str())

    def gen_profile_str(self):
        if self._enable is False:
            return
        self.time_record.append('\n')
        profile_str = ''.join(self.time_record)
        self.time_record = [self.print_head]
        return profile_str


D
dongdaxiang 已提交
214 215 216 217 218 219
class TimeProfiler(object):
    def __init__(self):
        self._pid = os.getpid()
        self._print_head = 'PROFILE\tpid:{}\t'.format(self._pid)
        self._time_record = Queue.Queue()
        self._enable = False
B
barrierye 已提交
220
        self._lock = threading.Lock()
D
dongdaxiang 已提交
221 222 223 224 225 226 227

    def enable(self, enable):
        self._enable = enable

    def record(self, name_with_tag):
        if self._enable is False:
            return
B
barriery 已提交
228
        timestamp = int(round(_time() * 1000000))
D
dongdaxiang 已提交
229 230 231
        name_with_tag = name_with_tag.split("_")
        tag = name_with_tag[-1]
        name = '_'.join(name_with_tag[:-1])
B
barrierye 已提交
232 233
        with self._lock:
            self._time_record.put((name, tag, timestamp))
B
barriery 已提交
234
        return timestamp
D
dongdaxiang 已提交
235 236

    def print_profile(self):
237 238
        if self._enable is False:
            return
B
barrierye 已提交
239 240 241
        sys.stderr.write(self.gen_profile_str())

    def gen_profile_str(self):
D
dongdaxiang 已提交
242 243 244 245
        if self._enable is False:
            return
        print_str = self._print_head
        tmp = {}
B
barrierye 已提交
246 247 248 249 250 251 252 253 254 255 256 257 258
        with self._lock:
            while not self._time_record.empty():
                name, tag, timestamp = self._time_record.get()
                if name in tmp:
                    ptag, ptimestamp = tmp.pop(name)
                    print_str += "{}_{}:{} ".format(name, ptag, ptimestamp)
                    print_str += "{}_{}:{} ".format(name, tag, timestamp)
                else:
                    tmp[name] = (tag, timestamp)
            print_str = "\n{}\n".format(print_str)
            for name, item in tmp.items():
                tag, timestamp = item
                self._time_record.put((name, tag, timestamp))
B
barrierye 已提交
259
            return print_str