profiler.cc 9.7 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
D
dangqingqing 已提交
2 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
6

D
dangqingqing 已提交
7 8 9 10 11 12 13 14
    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. */

15
#include <algorithm>
16
#include <iomanip>
17
#include <limits>
18
#include <map>
19
#include <mutex>  // NOLINT
20
#include <random>
21
#include <stack>
22
#include <string>
C
chengduo 已提交
23
#include <vector>
24 25 26
#ifdef PADDLE_WITH_CUDA
#include <cuda.h>
#endif  // PADDLE_WITH_CUDA
Y
Yancey1989 已提交
27

28
#include "glog/logging.h"
29 30
#include "paddle/fluid/framework/block_desc.h"
#include "paddle/fluid/platform/device_tracer.h"
W
wangchaochaohu 已提交
31 32
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/errors.h"
Y
Yancey1989 已提交
33
#include "paddle/fluid/platform/port.h"
W
wangchaochaohu 已提交
34 35
#include "paddle/fluid/platform/profiler.h"
#include "paddle/fluid/platform/profiler_helper.h"
36
#include "paddle/fluid/string/printf.h"
D
dangqingqing 已提交
37

G
gongweibao 已提交
38 39
DEFINE_bool(enable_rpc_profiler, false, "Enable rpc profiler or not.");

D
dangqingqing 已提交
40 41 42
namespace paddle {
namespace platform {

W
wangchaochaohu 已提交
43
MemEvenRecorder MemEvenRecorder::recorder;
D
dangqingqing 已提交
44

45 46 47
Event::Event(EventType type, std::string name, uint32_t thread_id,
             EventRole role)
    : type_(type), name_(name), thread_id_(thread_id), role_(role) {
D
dangqingqing 已提交
48 49 50
  cpu_ns_ = GetTimeInNsec();
}

C
chengduo 已提交
51
const EventType &Event::type() const { return type_; }
D
dangqingqing 已提交
52

C
chengduo 已提交
53
double Event::CpuElapsedMs(const Event &e) const {
54
  return (e.cpu_ns_ - cpu_ns_) / (1000000.0);
D
dangqingqing 已提交
55 56
}

C
chengduo 已提交
57
double Event::CudaElapsedMs(const Event &e) const {
58 59
#ifdef PADDLE_WITH_CUPTI
  return gpu_ns_ / 1000000.0;
D
Dun Liang 已提交
60
#else
D
Dun Liang 已提交
61 62
  LOG_FIRST_N(WARNING, 1) << "CUDA CUPTI is not enabled";
  return 0;
D
dangqingqing 已提交
63 64 65
#endif
}

66
RecordEvent::RecordEvent(const std::string &name, const EventRole role)
67
    : is_enabled_(false), start_ns_(PosixInNsec()), role_(role) {
68
  if (g_state == ProfilerState::kDisabled || name.empty()) return;
69
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
70
  is_enabled_ = true;
71
  Event *e = PushEvent(name, role);
72
  // Maybe need the same push/pop behavior.
73
  SetCurAnnotation(e);
74
  name_ = e->name();
D
dangqingqing 已提交
75 76 77
}

RecordEvent::~RecordEvent() {
X
Xin Pan 已提交
78
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
79
  // lock is not needed, the code below is thread-safe
C
chengduo 已提交
80
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
81
  if (tracer) {
82
    tracer->AddCPURecords(CurAnnotationName(), start_ns_, PosixInNsec(),
83
                          BlockDepth(), g_thread_id);
X
Xin Pan 已提交
84
  }
Y
Yibing Liu 已提交
85
  ClearCurAnnotation();
86
  PopEvent(name_);
D
dangqingqing 已提交
87
}
D
dangqingqing 已提交
88

C
chengduo 已提交
89 90 91 92 93
void MemEvenRecorder::PushMemRecord(const void *ptr, const Place &place,
                                    size_t size) {
  if (g_state == ProfilerState::kDisabled) return;
  std::lock_guard<std::mutex> guard(mtx_);
  auto &events = address_memevent_[place];
W
wangchaochaohu 已提交
94 95 96 97
  PADDLE_ENFORCE_EQ(
      events.count(ptr), 0,
      platform::errors::InvalidArgument(
          "The Place can't  exist in the stage of PushMemRecord"));
C
chengduo 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
  events.emplace(ptr, std::unique_ptr<RecordMemEvent>(
                          new MemEvenRecorder::RecordMemEvent(place, size)));
}

void MemEvenRecorder::PopMemRecord(const void *ptr, const Place &place) {
  if (g_state == ProfilerState::kDisabled) return;
  std::lock_guard<std::mutex> guard(mtx_);
  auto &events = address_memevent_[place];
  auto iter = events.find(ptr);
  // The ptr maybe not in address_memevent
  if (iter != events.end()) {
    events.erase(iter);
  }
}

void MemEvenRecorder::Flush() {
  std::lock_guard<std::mutex> guard(mtx_);
  address_memevent_.clear();
}

MemEvenRecorder::RecordMemEvent::RecordMemEvent(const Place &place,
                                                size_t bytes)
    : place_(place),
      bytes_(bytes),
      start_ns_(PosixInNsec()),
      alloc_in_(CurAnnotationName()) {
  PushMemEvent(start_ns_, end_ns_, bytes_, place_, alloc_in_);
}

MemEvenRecorder::RecordMemEvent::~RecordMemEvent() {
  DeviceTracer *tracer = GetDeviceTracer();
  end_ns_ = PosixInNsec();

  auto annotation_free = CurAnnotationName();
  if (tracer) {
    tracer->AddMemInfoRecord(start_ns_, end_ns_, bytes_, place_, alloc_in_,
                             annotation_free, g_mem_thread_id);
  }
  PopMemEvent(start_ns_, end_ns_, bytes_, place_, annotation_free);
}

RecordRPCEvent::RecordRPCEvent(const std::string &name) {
G
gongweibao 已提交
140
  if (FLAGS_enable_rpc_profiler) {
141
    event_.reset(new platform::RecordEvent(name));
G
gongweibao 已提交
142 143 144
  }
}

X
Xin Pan 已提交
145 146
RecordBlock::RecordBlock(int block_id)
    : is_enabled_(false), start_ns_(PosixInNsec()) {
147
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
148
  if (g_state == ProfilerState::kDisabled) return;
X
Xin Pan 已提交
149
  is_enabled_ = true;
X
Xin Pan 已提交
150 151 152 153 154
  SetCurBlock(block_id);
  name_ = string::Sprintf("block_%d", block_id);
}

RecordBlock::~RecordBlock() {
155
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
156
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
C
chengduo 已提交
157
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
158 159 160 161
  if (tracer) {
    // We try to put all blocks at the same nested depth in the
    // same timeline lane. and distinguish the using thread_id.
    tracer->AddCPURecords(name_, start_ns_, PosixInNsec(), BlockDepth(),
162
                          g_thread_id);
X
Xin Pan 已提交
163 164 165 166
  }
  ClearCurBlock();
}

W
wangchaochaohu 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
void PushMemEvent(uint64_t start_ns, uint64_t end_ns, size_t bytes,
                  const Place &place, const std::string &annotation) {
  GetMemEventList().Record(EventType::kPushRange, start_ns, end_ns, bytes,
                           place, g_mem_thread_id, annotation);
}

void PopMemEvent(uint64_t start_ns, uint64_t end_ns, size_t bytes,
                 const Place &place, const std::string &annotation) {
  GetMemEventList().Record(EventType::kPopRange, start_ns, end_ns, bytes, place,
                           g_mem_thread_id, annotation);
}

void Mark(const std::string &name) {
  GetEventList().Record(EventType::kMark, name, g_thread_id);
}

183 184
Event *PushEvent(const std::string &name, const EventRole role) {
  return GetEventList().Record(EventType::kPushRange, name, g_thread_id, role);
185 186
}

W
wangchaochaohu 已提交
187 188 189
void PopEvent(const std::string &name) {
  GetEventList().Record(EventType::kPopRange, name, g_thread_id);
}
D
dangqingqing 已提交
190
void EnableProfiler(ProfilerState state) {
W
wangchaochaohu 已提交
191 192 193 194
  PADDLE_ENFORCE_NE(state, ProfilerState::kDisabled,
                    platform::errors::InvalidArgument(
                        "Can't enable profiling, since the input state is"
                        "ProfilerState::kDisabled"));
195
  SynchronizeAllDevice();
X
Xin Pan 已提交
196
  std::lock_guard<std::mutex> l(profiler_mu);
197 198
  if (state == g_state) {
    return;
199
  }
200
  g_state = state;
X
Xin Pan 已提交
201
  should_send_profile_state = true;
202
  GetDeviceTracer()->Enable();
D
dangqingqing 已提交
203
#ifdef PADDLE_WITH_CUDA
204 205
  if (g_state == ProfilerState::kCUDA || g_state == ProfilerState::kAll ||
      g_state == ProfilerState::kCPU) {
206
    // Generate some dummy events first to reduce the startup overhead.
207 208
    DummyKernelAndEvent();
    GetDeviceTracer()->Reset();
D
dangqingqing 已提交
209 210 211
  }
#endif
  // Mark the profiling start.
212
  Mark("_start_profiler_");
D
dangqingqing 已提交
213 214
}

215
void ResetProfiler() {
216 217
  SynchronizeAllDevice();
  GetDeviceTracer()->Reset();
C
chengduo 已提交
218
  MemEvenRecorder::Instance().Flush();
D
dangqingqing 已提交
219
  std::lock_guard<std::mutex> guard(g_all_event_lists_mutex);
220 221 222 223
  for (auto it = g_all_event_lists.begin(); it != g_all_event_lists.end();
       ++it) {
    (*it)->Clear();
  }
C
chengduo 已提交
224 225 226 227
  for (auto it = g_all_mem_event_lists.begin();
       it != g_all_mem_event_lists.end(); ++it) {
    (*it)->Clear();
  }
228 229
}

230
void DisableProfiler(EventSortingKey sorted_key,
C
chengduo 已提交
231
                     const std::string &profile_path) {
232
  SynchronizeAllDevice();
C
chengduo 已提交
233 234
  MemEvenRecorder::Instance().Flush();

X
Xin Pan 已提交
235
  std::lock_guard<std::mutex> l(profiler_mu);
236
  if (g_state == ProfilerState::kDisabled) return;
237
  // Mark the profiling stop.
238
  Mark("_stop_profiler_");
239
  DealWithShowName();
240

C
chengduo 已提交
241
  DeviceTracer *tracer = GetDeviceTracer();
242
  if (tracer->IsEnabled()) {
243
    tracer->Disable();
244
    tracer->GenEventKernelCudaElapsedTime();
245
    tracer->GenProfile(profile_path);
246
  }
247 248

  std::vector<std::vector<Event>> all_events = GetAllEvents();
249

250 251
  ParseEvents(all_events, true, sorted_key);
  ParseEvents(all_events, false, sorted_key);
C
chengduo 已提交
252 253 254 255 256
  if (VLOG_IS_ON(5)) {
    std::vector<std::vector<MemEvent>> all_mem_events = GetMemEvents();
    ParseMemEvents(all_mem_events);
  }

257
  ResetProfiler();
258
  g_state = ProfilerState::kDisabled;
X
Xin Pan 已提交
259
  should_send_profile_state = true;
260 261
}

W
wangchaochaohu 已提交
262 263 264 265 266 267 268 269 270 271
std::vector<std::vector<Event>> GetAllEvents() {
  std::lock_guard<std::mutex> guard(g_all_event_lists_mutex);
  std::vector<std::vector<Event>> result;
  for (auto it = g_all_event_lists.begin(); it != g_all_event_lists.end();
       ++it) {
    result.emplace_back((*it)->Reduce());
  }
  return result;
}

272 273
bool IsProfileEnabled() { return g_state != ProfilerState::kDisabled; }

W
wangchaochaohu 已提交
274
bool ShouldSendProfileState() { return should_send_profile_state; }
275

276 277 278 279 280 281 282 283
std::string OpName(const framework::VariableNameMap &name_map,
                   const std::string &type_name) {
  if (platform::GetTracerOption() != platform::TracerOption::kAllOpDetail)
    return "";

  std::string ret = type_name + "%";
  for (auto it = name_map.begin(); it != name_map.end(); it++) {
    auto name_outputs = it->second;
284
    if (!name_outputs.empty()) {
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
      ret = ret + name_outputs[0];
      break;
    }
  }
  ret = ret + "%";

  return ret;
}

void SetTracerOption(TracerOption option) {
  std::lock_guard<std::mutex> l(profiler_mu);
  g_tracer_option = option;
}

platform::TracerOption GetTracerOption() { return g_tracer_option; }
W
wangchaochaohu 已提交
300 301 302 303 304 305 306 307 308 309 310

void SetProfileListener() {
  std::mt19937 rng;
  rng.seed(std::random_device()());
  std::uniform_int_distribution<std::mt19937::result_type> dist6(
      1, std::numeric_limits<int>::max());
  profiler_lister_id = dist6(rng);
}

int64_t ListenerId() { return profiler_lister_id; }

D
dangqingqing 已提交
311 312
}  // namespace platform
}  // namespace paddle