profiler.cc 22.4 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 <mutex>  // NOLINT
16
#include <random>
L
liutiexing 已提交
17
#include <sstream>
18
#include <string>
L
liutiexing 已提交
19
#include <type_traits>
Y
Yancey1989 已提交
20

21
#include "paddle/fluid/platform/device_tracer.h"
W
wangchaochaohu 已提交
22 23 24
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/profiler.h"
#include "paddle/fluid/platform/profiler_helper.h"
25 26 27
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/dynload/nvtx.h"
#endif
D
dangqingqing 已提交
28

Z
Zeng Jinle 已提交
29 30
PADDLE_DEFINE_EXPORTED_bool(enable_rpc_profiler, false,
                            "Enable rpc profiler or not.");
G
gongweibao 已提交
31

D
dangqingqing 已提交
32 33 34
namespace paddle {
namespace platform {

L
liutiexing 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
struct DurationEvent {
 public:
  DurationEvent(const char *name, uint64_t start_ns, uint64_t end_ns,
                EventRole role)
      : name(name), start_ns(start_ns), end_ns(end_ns), role(role) {}

  DurationEvent(std::function<void *(size_t)> &arena_allocator,
                const std::string &name_str, uint64_t start_ns, uint64_t end_ns,
                EventRole role, const std::string &attr_str)
      : start_ns(start_ns), end_ns(end_ns), role(role) {
    auto buf = static_cast<char *>(arena_allocator(name_str.length() + 1));
    strncpy(buf, name_str.c_str(), name_str.length() + 1);
    name = buf;
    buf = static_cast<char *>(arena_allocator(attr_str.length() + 1));
    strncpy(buf, attr_str.c_str(), attr_str.length() + 1);
    attr = buf;
  }

  DurationEvent(const std::function<void *(size_t)> &arena_allocator,
                const std::string &name_str, uint64_t start_ns, uint64_t end_ns,
                EventRole role)
      : start_ns(start_ns), end_ns(end_ns), role(role) {
    auto buf = static_cast<char *>(arena_allocator(name_str.length() + 1));
    strncpy(buf, name_str.c_str(), name_str.length() + 1);
    name = buf;
  }

  const char *name = nullptr;  // not owned, designed for performance
  uint64_t start_ns = 0;
  uint64_t end_ns = 0;
  EventRole role = EventRole::kOrdinary;
  const char *attr = nullptr;  // not owned, designed for performance
};

template <typename HeadType, typename... RestTypes>
struct ContainsStdString
    : std::conditional_t<
          std::is_same<std::string, std::remove_cv_t<std::remove_reference_t<
                                        HeadType>>>::value,
          std::true_type, ContainsStdString<RestTypes...>> {};

template <typename TailType>
struct ContainsStdString<TailType>
    : std::is_same<std::string,
                   std::remove_cv_t<std::remove_reference_t<TailType>>> {};

template <typename EventType>
class EventContainer {
 public:
  EventContainer() {
    event_blocks_ = cur_event_block_ = new EventBlock;
    str_blocks_ = cur_str_block_ = new StringBlock;
  }
  ~EventContainer() {
    Reduce();
    delete event_blocks_;
    for (auto cur = str_blocks_; cur != nullptr;) {
      auto next = cur->next;
      delete cur;
      cur = next;
    }
  }
  DISABLE_COPY_AND_ASSIGN(EventContainer);

 public:
  // Record an event
  template <typename... Args>
  void Record(Args &&... args) {
    DoRecord(ContainsStdString<Args...>(), std::forward<Args>(args)...);
  }

  // Get all events and clear the container
  std::vector<EventType> Reduce();

  // Return a buffer to store the string attribute of Event.
  // HostEventRecorder locates in the static data section.
  // So it's safe to use arena to avoid fragmented allocations.
  char *GetStrBufFromArena(size_t size) { return GetStringStorage(size); }

 private:
  struct EventBlock {
    union InitDeferedEvent {
      InitDeferedEvent() {}
      ~InitDeferedEvent() {}

      EventType event;
    };

    static constexpr size_t kBlockSize = 1 << 24;  // 16 MB
    static constexpr size_t kAvailSize =
        kBlockSize - sizeof(size_t) - sizeof(nullptr);
    static constexpr size_t kNumEvents = kAvailSize / sizeof(InitDeferedEvent);
    static constexpr size_t kPadSize =
        kAvailSize - kNumEvents * sizeof(InitDeferedEvent);
    static constexpr size_t kMinimumEventsPerBlock = 1024;
    static_assert(
        kNumEvents >= kMinimumEventsPerBlock,
        "EventType is too large for kBlockSize, make kBlockSize larger");

    size_t offset = 0;
    EventBlock *next = nullptr;
    InitDeferedEvent events[kNumEvents];
    char padding[kPadSize];
  };
  static_assert(sizeof(EventBlock) == EventBlock::kBlockSize,
                "sizeof EventBlock must equal to kBlockSize");

  struct StringBlock {
    static constexpr size_t kBlockSize = 1 << 22;  // 4 MB
    static constexpr size_t kAvailSize =
        kBlockSize - sizeof(size_t) - sizeof(nullptr);

    size_t offset = 0;
    StringBlock *next = nullptr;
    char storage[kAvailSize];
  };
  static_assert(sizeof(StringBlock) == StringBlock::kBlockSize,
                "sizeof StringBlock must equal to kBlockSize");

  // Record an event with string arguments
  template <typename... Args>
  void DoRecord(std::true_type, Args &&... args) {
    auto *storage = GetEventStorage();
    std::function<void *(size_t)> allocator = [this](size_t size) {
      return GetStrBufFromArena(size);
    };
    new (storage) EventType(allocator, std::forward<Args>(args)...);
  }

  // Record an event without any string argument
  template <typename... Args>
  void DoRecord(std::false_type, Args &&... args) {
    auto *storage = GetEventStorage();
    new (storage) EventType(std::forward<Args>(args)...);
  }

  EventType *GetEventStorage();

  char *GetStringStorage(size_t sz);

  EventBlock *event_blocks_ = nullptr;
  EventBlock *cur_event_block_ = nullptr;
  StringBlock *str_blocks_ = nullptr;
  StringBlock *cur_str_block_ = nullptr;
};

template <typename EventType>
std::vector<EventType> EventContainer<EventType>::Reduce() {
  std::vector<EventType> all_events;
  size_t event_cnt = 0;
  for (auto cur = event_blocks_; cur != nullptr; cur = cur->next) {
    event_cnt += cur->offset;
  }
  all_events.reserve(event_cnt);
  for (auto cur = event_blocks_; cur != nullptr;) {
    for (size_t i = 0; i < cur->offset; ++i) {
      all_events.emplace_back(cur->events[i].event);
    }
    auto next = cur->next;
    delete cur;
    cur = next;
  }
  event_blocks_ = cur_event_block_ = new EventBlock;
  return std::move(all_events);
}

template <typename EventType>
EventType *EventContainer<EventType>::GetEventStorage() {
  if (UNLIKELY(cur_event_block_->offset >=
               EventBlock::kNumEvents)) {  // another block
    cur_event_block_->next = new EventBlock;
    cur_event_block_ = cur_event_block_->next;
  }
  auto &obj = cur_event_block_->events[cur_event_block_->offset].event;
  ++cur_event_block_->offset;
  return &obj;
}

template <typename EventType>
char *EventContainer<EventType>::GetStringStorage(size_t sz) {
  if (UNLIKELY(cur_str_block_->offset + sz >
               StringBlock::kAvailSize)) {  // another block
    cur_str_block_->next = new StringBlock;
    cur_str_block_ = cur_str_block_->next;
  }
  char *storage = cur_str_block_->storage + cur_str_block_->offset;
  cur_str_block_->offset += sz;
  return storage;
}

struct ThreadEventSection {
  std::string thread_name;
  uint64_t thread_id;
  std::vector<DurationEvent> events;
};

class ThreadEventRecorder {
 public:
  ThreadEventRecorder();
  DISABLE_COPY_AND_ASSIGN(ThreadEventRecorder);

 public:
  // Forward call to EventContainer::Record
  template <typename... Args>
  void RecordEvent(Args &&... args) {
    base_evt_cntr_.Record(std::forward<Args>(args)...);
  }

  ThreadEventSection GatherEvents() {
    ThreadEventSection thr_sec;
    thr_sec.thread_name = thread_name_;
    thr_sec.thread_id = thread_id_;
    thr_sec.events = std::move(base_evt_cntr_.Reduce());
    return std::move(thr_sec);
  }

 private:
  uint64_t thread_id_;
  std::string thread_name_;
  EventContainer<DurationEvent> base_evt_cntr_;
};

struct HostEventSection {
  std::string process_name;
  uint64_t process_id;
  std::vector<ThreadEventSection> thr_sections;
};

class HostEventRecorder {
 public:
  // singleton
  static HostEventRecorder &GetInstance() {
    static HostEventRecorder instance;
    return instance;
  }

  // If your string argument has a longer lifetime than the Event,
  // use 'const char*'. e.g.: string literal, op name, etc.
  // Do your best to avoid using 'std::string' as the argument type.
  // It will cause deep-copy to harm performance.
  template <typename... Args>
  void RecordEvent(Args &&... args) {
    GetThreadLocalRecorder().RecordEvent(std::forward<Args>(args)...);
  }

  // Poor performance, call it at the ending
  HostEventSection GatherEvents();

  void RegisterThreadRecorder(uint64_t tid, ThreadEventRecorder *recorder) {
    const std::lock_guard<std::mutex> guard(thread_recorders_lock_);
    thread_recorders_[tid] = recorder;
  }

 private:
  HostEventRecorder() = default;
  DISABLE_COPY_AND_ASSIGN(HostEventRecorder);

  ThreadEventRecorder &GetThreadLocalRecorder() {
    static thread_local ThreadEventRecorder tls_recorder;
    return tls_recorder;
  }

  std::mutex thread_recorders_lock_;
  std::unordered_map<uint64_t, ThreadEventRecorder *> thread_recorders_;
};

static uint64_t GetThreadId() {
  return std::hash<std::thread::id>{}(std::this_thread::get_id());
}

ThreadEventRecorder::ThreadEventRecorder() {
  thread_id_ = GetThreadId();
  HostEventRecorder::GetInstance().RegisterThreadRecorder(thread_id_, this);
}

HostEventSection HostEventRecorder::GatherEvents() {
  HostEventSection host_sec;
  host_sec.thr_sections.reserve(thread_recorders_.size());
  for (auto &kv : thread_recorders_) {
    host_sec.thr_sections.emplace_back(std::move(kv.second->GatherEvents()));
  }
  return std::move(host_sec);
}

W
wangchaochaohu 已提交
319
MemEvenRecorder MemEvenRecorder::recorder;
D
dangqingqing 已提交
320

321
Event::Event(EventType type, std::string name, uint32_t thread_id,
Y
Yuang Liu 已提交
322 323 324 325 326 327
             EventRole role, std::string attr)
    : type_(type),
      name_(name),
      thread_id_(thread_id),
      role_(role),
      attr_(attr) {
D
dangqingqing 已提交
328 329 330
  cpu_ns_ = GetTimeInNsec();
}

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

C
chengduo 已提交
333
double Event::CpuElapsedMs(const Event &e) const {
334
  return (e.cpu_ns_ - cpu_ns_) / (1000000.0);
D
dangqingqing 已提交
335 336
}

C
chengduo 已提交
337
double Event::CudaElapsedMs(const Event &e) const {
338 339
#ifdef PADDLE_WITH_CUPTI
  return gpu_ns_ / 1000000.0;
D
Dun Liang 已提交
340
#else
D
Dun Liang 已提交
341 342
  LOG_FIRST_N(WARNING, 1) << "CUDA CUPTI is not enabled";
  return 0;
D
dangqingqing 已提交
343 344 345
#endif
}

L
liutiexing 已提交
346 347 348 349 350 351 352 353 354 355
RecordEvent::RecordEvent(const char *name, const EventRole role) {
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name);
    is_pushed_ = true;
  }
#endif
#endif
  if (UNLIKELY(g_enable_host_event_recorder_hook == false)) {
L
liutiexing 已提交
356
    OriginalConstruct(name, role, "none");
L
liutiexing 已提交
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
    return;
  }
  shallow_copy_name_ = name;
  role_ = role;
  start_ns_ = PosixInNsec();
}

RecordEvent::RecordEvent(const std::string &name, const EventRole role) {
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name.c_str());
    is_pushed_ = true;
  }
#endif
#endif
  if (UNLIKELY(g_enable_host_event_recorder_hook == false)) {
L
liutiexing 已提交
374
    OriginalConstruct(name, role, "none");
L
liutiexing 已提交
375 376 377 378 379 380 381
    return;
  }
  name_ = new std::string(name);
  role_ = role;
  start_ns_ = PosixInNsec();
}

Y
Yuang Liu 已提交
382
RecordEvent::RecordEvent(const std::string &name, const EventRole role,
L
liutiexing 已提交
383
                         const std::string &attr) {
384 385 386 387 388 389 390 391
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name.c_str());
    is_pushed_ = true;
  }
#endif
#endif
L
liutiexing 已提交
392 393
  if (UNLIKELY(g_enable_host_event_recorder_hook == false)) {
    OriginalConstruct(name, role, attr);
L
liutiexing 已提交
394 395
    return;
  }
L
liutiexing 已提交
396 397 398 399
  name_ = new std::string(name);
  start_ns_ = PosixInNsec();
  attr_ = new std::string(attr);
}
L
liutiexing 已提交
400

L
liutiexing 已提交
401 402 403
void RecordEvent::OriginalConstruct(const std::string &name,
                                    const EventRole role,
                                    const std::string &attr) {
404
  if (g_state == ProfilerState::kDisabled || name.empty()) return;
405 406

  // do some initialization
L
liutiexing 已提交
407
  name_ = new std::string(name);
408 409
  start_ns_ = PosixInNsec();
  role_ = role;
L
liutiexing 已提交
410
  attr_ = new std::string(attr);
X
Xin Pan 已提交
411
  is_enabled_ = true;
412
  // lock is not needed, the code below is thread-safe
413
  // Maybe need the same push/pop behavior.
Y
Yuang Liu 已提交
414
  Event *e = PushEvent(name, role, attr);
415
  SetCurAnnotation(e);
L
liutiexing 已提交
416
  *name_ = e->name();
D
dangqingqing 已提交
417 418 419
}

RecordEvent::~RecordEvent() {
420 421 422 423 424 425 426
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook && is_pushed_) {
    dynload::nvtxRangePop();
  }
#endif
#endif
L
liutiexing 已提交
427 428 429 430 431 432 433 434 435 436 437 438
  uint64_t end_ns = PosixInNsec();
  if (LIKELY(g_enable_host_event_recorder_hook)) {
    if (LIKELY(shallow_copy_name_ != nullptr)) {
      HostEventRecorder::GetInstance().RecordEvent(shallow_copy_name_,
                                                   start_ns_, end_ns, role_);
    } else if (name_ != nullptr) {
      if (attr_ == nullptr) {
        HostEventRecorder::GetInstance().RecordEvent(*name_, start_ns_, end_ns,
                                                     role_);
      } else {
        HostEventRecorder::GetInstance().RecordEvent(*name_, start_ns_, end_ns,
                                                     role_, *attr_);
L
liutiexing 已提交
439
        delete attr_;
L
liutiexing 已提交
440
      }
L
liutiexing 已提交
441
      delete name_;
L
liutiexing 已提交
442 443 444 445
    }
    return;
  }

X
Xin Pan 已提交
446
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
447
  // lock is not needed, the code below is thread-safe
C
chengduo 已提交
448
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
449
  if (tracer) {
L
liutiexing 已提交
450 451
    tracer->AddCPURecords(CurAnnotationName(), start_ns_, end_ns, BlockDepth(),
                          g_thread_id);
X
Xin Pan 已提交
452
  }
Y
Yibing Liu 已提交
453
  ClearCurAnnotation();
L
liutiexing 已提交
454 455 456
  PopEvent(*name_, role_);
  delete name_;
  delete attr_;
D
dangqingqing 已提交
457
}
D
dangqingqing 已提交
458

C
chengduo 已提交
459 460 461 462 463
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];
G
GaoWei8 已提交
464 465 466
  PADDLE_ENFORCE_EQ(events.count(ptr), 0,
                    platform::errors::InvalidArgument(
                        "The Place can't exist in the stage of PushMemRecord"));
C
chengduo 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
  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);
}

L
liutiexing 已提交
508
/*RecordRPCEvent::RecordRPCEvent(const std::string &name) {
G
gongweibao 已提交
509
  if (FLAGS_enable_rpc_profiler) {
510
    event_.reset(new platform::RecordEvent(name));
G
gongweibao 已提交
511
  }
L
liutiexing 已提交
512
}*/
G
gongweibao 已提交
513

X
Xin Pan 已提交
514 515
RecordBlock::RecordBlock(int block_id)
    : is_enabled_(false), start_ns_(PosixInNsec()) {
516
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
517
  if (g_state == ProfilerState::kDisabled) return;
X
Xin Pan 已提交
518
  is_enabled_ = true;
X
Xin Pan 已提交
519 520 521 522 523
  SetCurBlock(block_id);
  name_ = string::Sprintf("block_%d", block_id);
}

RecordBlock::~RecordBlock() {
524
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
525
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
C
chengduo 已提交
526
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
527 528 529 530
  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(),
531
                          g_thread_id);
X
Xin Pan 已提交
532 533 534 535
  }
  ClearCurBlock();
}

W
wangchaochaohu 已提交
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
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);
}

Y
Yuang Liu 已提交
552 553 554 555
Event *PushEvent(const std::string &name, const EventRole role,
                 std::string attr) {
  return GetEventList().Record(EventType::kPushRange, name, g_thread_id, role,
                               attr);
556 557
}

Y
Yuang Liu 已提交
558 559
void PopEvent(const std::string &name, const EventRole role, std::string attr) {
  GetEventList().Record(EventType::kPopRange, name, g_thread_id, role, attr);
W
wangchaochaohu 已提交
560
}
D
dangqingqing 已提交
561
void EnableProfiler(ProfilerState state) {
W
wangchaochaohu 已提交
562 563 564 565
  PADDLE_ENFORCE_NE(state, ProfilerState::kDisabled,
                    platform::errors::InvalidArgument(
                        "Can't enable profiling, since the input state is"
                        "ProfilerState::kDisabled"));
566
  SynchronizeAllDevice();
X
Xin Pan 已提交
567
  std::lock_guard<std::mutex> l(profiler_mu);
568 569
  if (state == g_state) {
    return;
570
  }
571
  g_state = state;
X
Xin Pan 已提交
572
  should_send_profile_state = true;
573
  GetDeviceTracer()->Enable();
574
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
575 576
  if (g_state == ProfilerState::kCUDA || g_state == ProfilerState::kAll ||
      g_state == ProfilerState::kCPU) {
577
    // Generate some dummy events first to reduce the startup overhead.
578 579
    DummyKernelAndEvent();
    GetDeviceTracer()->Reset();
D
dangqingqing 已提交
580 581 582
  }
#endif
  // Mark the profiling start.
583
  Mark("_start_profiler_");
D
dangqingqing 已提交
584 585
}

586
void ResetProfiler() {
587 588
  SynchronizeAllDevice();
  GetDeviceTracer()->Reset();
C
chengduo 已提交
589
  MemEvenRecorder::Instance().Flush();
D
dangqingqing 已提交
590
  std::lock_guard<std::mutex> guard(g_all_event_lists_mutex);
591 592 593 594
  for (auto it = g_all_event_lists.begin(); it != g_all_event_lists.end();
       ++it) {
    (*it)->Clear();
  }
C
chengduo 已提交
595 596 597 598
  for (auto it = g_all_mem_event_lists.begin();
       it != g_all_mem_event_lists.end(); ++it) {
    (*it)->Clear();
  }
599 600
}

601
void DisableProfiler(EventSortingKey sorted_key,
C
chengduo 已提交
602
                     const std::string &profile_path) {
603
  SynchronizeAllDevice();
C
chengduo 已提交
604 605
  MemEvenRecorder::Instance().Flush();

X
Xin Pan 已提交
606
  std::lock_guard<std::mutex> l(profiler_mu);
607
  if (g_state == ProfilerState::kDisabled) return;
608
  // Mark the profiling stop.
609
  Mark("_stop_profiler_");
610
  DealWithShowName();
611

C
chengduo 已提交
612
  DeviceTracer *tracer = GetDeviceTracer();
613
  if (tracer->IsEnabled()) {
614
    tracer->Disable();
615
    tracer->GenEventKernelCudaElapsedTime();
616
    tracer->GenProfile(profile_path);
617
  }
618 619

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

621 622
  ParseEvents(all_events, true, sorted_key);
  ParseEvents(all_events, false, sorted_key);
H
Huihuang Zheng 已提交
623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656

  std::vector<std::vector<MemEvent>> all_mem_events = GetMemEvents();
  ParseMemEvents(all_mem_events);

  ResetProfiler();
  g_state = ProfilerState::kDisabled;
  g_tracer_option = TracerOption::kDefault;
  should_send_profile_state = true;
}

void CompleteProfilerEvents(proto::Profile *tracer_profile,
                            std::vector<std::vector<Event>> *time_events,
                            std::vector<std::vector<MemEvent>> *mem_events) {
  SynchronizeAllDevice();
  MemEvenRecorder::Instance().Flush();

  std::lock_guard<std::mutex> l(profiler_mu);
  if (g_state == ProfilerState::kDisabled) return;

  // Mark the profiling stop.
  Mark("_stop_profiler_");

  DeviceTracer *tracer = GetDeviceTracer();
  if (tracer->IsEnabled() && tracer_profile != nullptr) {
    tracer->Disable();
    tracer->GenEventKernelCudaElapsedTime();
    *tracer_profile = tracer->GetProfile();
  }

  if (time_events != nullptr) {
    *time_events = GetAllEvents();
  }
  if (mem_events != nullptr) {
    *mem_events = GetMemEvents();
C
chengduo 已提交
657 658
  }

659
  ResetProfiler();
660
  g_state = ProfilerState::kDisabled;
661
  g_tracer_option = TracerOption::kDefault;
X
Xin Pan 已提交
662
  should_send_profile_state = true;
663 664
}

W
wangchaochaohu 已提交
665 666 667 668 669 670 671 672 673 674
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;
}

675 676
bool IsProfileEnabled() { return g_state != ProfilerState::kDisabled; }

W
wangchaochaohu 已提交
677
bool ShouldSendProfileState() { return should_send_profile_state; }
678

679 680
std::string OpName(const framework::VariableNameMap &name_map,
                   const std::string &type_name) {
681 682
  if (platform::GetTracerOption() != platform::TracerOption::kAllOpDetail ||
      !IsProfileEnabled())
683 684 685 686 687
    return "";

  std::string ret = type_name + "%";
  for (auto it = name_map.begin(); it != name_map.end(); it++) {
    auto name_outputs = it->second;
688
    if (!name_outputs.empty()) {
689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
      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 已提交
704 705 706 707 708 709 710 711 712 713 714

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; }

715 716 717 718 719 720 721
void NvprofEnableRecordEvent() {
  SynchronizeAllDevice();
  g_enable_nvprof_hook = true;
}

void NvprofDisableRecordEvent() { g_enable_nvprof_hook = false; }

L
liutiexing 已提交
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
void EnableHostEventRecorder() { g_enable_host_event_recorder_hook = true; }

std::string PrintHostEvents() {
  std::ostringstream oss;
  auto host_evt_sec = HostEventRecorder::GetInstance().GatherEvents();
  for (const auto &thr_evt_sec : host_evt_sec.thr_sections) {
    oss << thr_evt_sec.thread_id << std::endl;
    for (const auto &evt : thr_evt_sec.events) {
      oss << "{ " << evt.name << " | " << evt.start_ns << " | " << evt.end_ns
          << " }" << std::endl;
    }
  }
  return oss.str();
}

D
dangqingqing 已提交
737 738
}  // namespace platform
}  // namespace paddle