profiler.cc 44.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 16
#include "paddle/fluid/platform/profiler.h"

17
#include <mutex>  // NOLINT
18
#include <random>
L
liutiexing 已提交
19
#include <sstream>
20
#include <string>
L
liutiexing 已提交
21
#include <type_traits>
Y
Yancey1989 已提交
22

23
#include "paddle/fluid/platform/device_tracer.h"
W
wangchaochaohu 已提交
24
#include "paddle/fluid/platform/enforce.h"
25
#include "paddle/fluid/platform/profiler/common_event.h"
L
liutiexing 已提交
26
#include "paddle/fluid/platform/profiler/host_event_recorder.h"
27
#include "paddle/fluid/platform/profiler/host_tracer.h"
C
chenjian 已提交
28
#include "paddle/fluid/platform/profiler/profiler.h"
W
wangchaochaohu 已提交
29
#include "paddle/fluid/platform/profiler_helper.h"
30 31 32
#ifdef PADDLE_WITH_CUDA
#include "paddle/fluid/platform/dynload/nvtx.h"
#endif
33 34
#include "paddle/fluid/framework/op_proto_maker.h"
#include "paddle/fluid/framework/operator.h"
35
#include "paddle/fluid/platform/os_info.h"
D
dangqingqing 已提交
36

37 38
PADDLE_DEFINE_EXPORTED_bool(enable_rpc_profiler,
                            false,
Z
Zeng Jinle 已提交
39
                            "Enable rpc profiler or not.");
G
gongweibao 已提交
40

41 42
DEFINE_bool(enable_host_event_recorder_hook,
            false,
43 44
            "enable HostEventRecorder, hook Profiler");

45 46 47 48
DEFINE_bool(enable_record_input_shape, false, "enable input shape recorder");

DEFINE_bool(enable_record_memory, false, "enable memory recorder");

D
dangqingqing 已提交
49 50 51
namespace paddle {
namespace platform {

W
wangchaochaohu 已提交
52
MemEvenRecorder MemEvenRecorder::recorder;
D
dangqingqing 已提交
53

54 55 56 57 58
Event::Event(EventType type,
             std::string name,
             uint32_t thread_id,
             EventRole role,
             std::string attr)
Y
Yuang Liu 已提交
59 60 61 62 63
    : type_(type),
      name_(name),
      thread_id_(thread_id),
      role_(role),
      attr_(attr) {
D
dangqingqing 已提交
64 65 66
  cpu_ns_ = GetTimeInNsec();
}

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

C
chengduo 已提交
69
double Event::CpuElapsedMs(const Event &e) const {
70
  return (e.cpu_ns_ - cpu_ns_) / (1000000.0);
D
dangqingqing 已提交
71 72
}

C
chengduo 已提交
73
double Event::CudaElapsedMs(const Event &e) const {
74 75
#ifdef PADDLE_WITH_CUPTI
  return gpu_ns_ / 1000000.0;
D
Dun Liang 已提交
76
#else
D
Dun Liang 已提交
77 78
  LOG_FIRST_N(WARNING, 1) << "CUDA CUPTI is not enabled";
  return 0;
D
dangqingqing 已提交
79 80 81
#endif
}

82 83 84 85
RecordEvent::RecordEvent(const char *name,
                         const TracerEventType type,
                         uint32_t level,
                         const EventRole role) {
L
liutiexing 已提交
86 87 88 89 90 91 92 93
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name);
    is_pushed_ = true;
  }
#endif
#endif
C
chenjian 已提交
94 95 96 97
  if (UNLIKELY(HostTraceLevel::GetInstance().NeedTrace(level) == false)) {
    return;
  }

98
  if (FLAGS_enable_host_event_recorder_hook == false) {
L
liutiexing 已提交
99
    if (g_state != ProfilerState::kDisabled) {  // avoid temp string
C
chenjian 已提交
100 101 102 103 104
      if (type == TracerEventType::Operator ||
          type == TracerEventType::OperatorInner ||
          type == TracerEventType::UserDefined) {
        OriginalConstruct(name, role, "none");
      }
L
liutiexing 已提交
105
    }
L
liutiexing 已提交
106 107
    return;
  }
C
chenjian 已提交
108

109
  is_enabled_ = true;
L
liutiexing 已提交
110 111
  shallow_copy_name_ = name;
  role_ = role;
C
chenjian 已提交
112
  type_ = type;
L
liutiexing 已提交
113 114 115
  start_ns_ = PosixInNsec();
}

116 117 118 119
RecordEvent::RecordEvent(const std::string &name,
                         const TracerEventType type,
                         uint32_t level,
                         const EventRole role) {
L
liutiexing 已提交
120 121 122 123 124 125 126 127
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name.c_str());
    is_pushed_ = true;
  }
#endif
#endif
C
chenjian 已提交
128
  if (UNLIKELY(HostTraceLevel::GetInstance().NeedTrace(level) == false)) {
L
liutiexing 已提交
129 130
    return;
  }
C
chenjian 已提交
131 132 133 134 135 136 137

  if (FLAGS_enable_host_event_recorder_hook == false) {
    if (type == TracerEventType::Operator ||
        type == TracerEventType::OperatorInner ||
        type == TracerEventType::UserDefined) {
      OriginalConstruct(name, role, "none");
    }
138 139
    return;
  }
C
chenjian 已提交
140

141
  is_enabled_ = true;
L
liutiexing 已提交
142 143
  name_ = new std::string(name);
  role_ = role;
C
chenjian 已提交
144
  type_ = type;
L
liutiexing 已提交
145 146 147
  start_ns_ = PosixInNsec();
}

148 149 150 151
RecordEvent::RecordEvent(const std::string &name,
                         const std::string &attr,
                         const TracerEventType type,
                         uint32_t level,
C
chenjian 已提交
152
                         const EventRole role) {
153 154 155 156 157 158 159 160
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name.c_str());
    is_pushed_ = true;
  }
#endif
#endif
C
chenjian 已提交
161 162

  if (UNLIKELY(HostTraceLevel::GetInstance().NeedTrace(level) == false)) {
L
liutiexing 已提交
163 164
    return;
  }
C
chenjian 已提交
165 166 167 168 169 170 171

  if (FLAGS_enable_host_event_recorder_hook == false) {
    if (type == TracerEventType::Operator ||
        type == TracerEventType::OperatorInner ||
        type == TracerEventType::UserDefined) {
      OriginalConstruct(name, role, attr);
    }
172 173
    return;
  }
C
chenjian 已提交
174

175
  is_enabled_ = true;
C
chenjian 已提交
176
  type_ = type;
L
liutiexing 已提交
177 178 179 180
  name_ = new std::string(name);
  start_ns_ = PosixInNsec();
  attr_ = new std::string(attr);
}
L
liutiexing 已提交
181

L
liutiexing 已提交
182 183 184
void RecordEvent::OriginalConstruct(const std::string &name,
                                    const EventRole role,
                                    const std::string &attr) {
185
  if (g_state == ProfilerState::kDisabled || name.empty()) return;
186 187

  // do some initialization
L
liutiexing 已提交
188
  name_ = new std::string(name);
189 190
  start_ns_ = PosixInNsec();
  role_ = role;
L
liutiexing 已提交
191
  attr_ = new std::string(attr);
X
Xin Pan 已提交
192
  is_enabled_ = true;
193
  // lock is not needed, the code below is thread-safe
194
  // Maybe need the same push/pop behavior.
Y
Yuang Liu 已提交
195
  Event *e = PushEvent(name, role, attr);
196
  SetCurAnnotation(e);
L
liutiexing 已提交
197
  *name_ = e->name();
D
dangqingqing 已提交
198 199
}

L
liutiexing 已提交
200
void RecordEvent::End() {
201 202
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
203
  if (g_enable_nvprof_hook && is_pushed_) {
204
    dynload::nvtxRangePop();
205
    is_pushed_ = false;
206 207 208
  }
#endif
#endif
209
  if (LIKELY(FLAGS_enable_host_event_recorder_hook && is_enabled_)) {
L
liutiexing 已提交
210
    uint64_t end_ns = PosixInNsec();
L
liutiexing 已提交
211
    if (LIKELY(shallow_copy_name_ != nullptr)) {
L
liutiexing 已提交
212
      HostEventRecorder<CommonEvent>::GetInstance().RecordEvent(
C
chenjian 已提交
213
          shallow_copy_name_, start_ns_, end_ns, role_, type_);
L
liutiexing 已提交
214 215
    } else if (name_ != nullptr) {
      if (attr_ == nullptr) {
L
liutiexing 已提交
216 217
        HostEventRecorder<CommonEvent>::GetInstance().RecordEvent(
            *name_, start_ns_, end_ns, role_, type_);
L
liutiexing 已提交
218
      } else {
L
liutiexing 已提交
219 220
        HostEventRecorder<CommonEvent>::GetInstance().RecordEvent(
            *name_, start_ns_, end_ns, role_, type_, *attr_);
L
liutiexing 已提交
221
        delete attr_;
L
liutiexing 已提交
222
      }
L
liutiexing 已提交
223
      delete name_;
L
liutiexing 已提交
224
    }
225 226
    // use this flag to avoid double End();
    is_enabled_ = false;
L
liutiexing 已提交
227 228 229
    return;
  }

X
Xin Pan 已提交
230
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
231
  // lock is not needed, the code below is thread-safe
C
chengduo 已提交
232
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
233
  if (tracer) {
L
liutiexing 已提交
234
    uint64_t end_ns = PosixInNsec();
235 236
    tracer->AddCPURecords(
        CurAnnotationName(), start_ns_, end_ns, BlockDepth(), g_thread_id);
X
Xin Pan 已提交
237
  }
Y
Yibing Liu 已提交
238
  ClearCurAnnotation();
L
liutiexing 已提交
239 240 241
  PopEvent(*name_, role_);
  delete name_;
  delete attr_;
242 243
  // use this flag to avoid double End();
  is_enabled_ = false;
D
dangqingqing 已提交
244
}
D
dangqingqing 已提交
245

246 247
RecordInstantEvent::RecordInstantEvent(const char *name,
                                       TracerEventType type,
248 249
                                       uint32_t level) {
  if (UNLIKELY(HostTraceLevel::GetInstance().NeedTrace(level) == false)) {
L
liutiexing 已提交
250 251 252
    return;
  }
  auto start_end_ns = PosixInNsec();
L
liutiexing 已提交
253 254
  HostEventRecorder<CommonEvent>::GetInstance().RecordEvent(
      name, start_end_ns, start_end_ns, EventRole::kOrdinary, type);
L
liutiexing 已提交
255 256
}

257 258 259 260 261 262 263 264
RecordOpInfoSupplement::RecordOpInfoSupplement(
    const std::string &type,
    const framework::AttributeMap &attrs,
    const framework::InferShapeContext &shape_ctx,
    const framework::RuntimeContext &ctx) {
  if (FLAGS_enable_host_event_recorder_hook == false) {
    return;
  }
265 266 267
  if (IsEnabled() == false) {
    return;
  }
268 269 270 271 272 273 274 275 276 277 278 279
  std::map<std::string, std::vector<framework::DDim>> input_shapes;
  std::map<std::string, std::vector<framework::proto::VarType::Type>> dtypes;
  for (auto it = ctx.inputs.begin(); it != ctx.inputs.end(); it++) {
    input_shapes[it->first] = shape_ctx.GetInputsDim(it->first);
    dtypes[it->first] = shape_ctx.GetInputsVarType(it->first);
  }

  const std::vector<std::string> *callstack_ptr = nullptr;
  std::vector<std::string> callstack;
  auto iter = attrs.find(
      framework::OpProtoAndCheckerMaker::OpCreationCallstackAttrName());
  if (iter != attrs.end()) {
R
Ruibiao Chen 已提交
280
    callstack_ptr = &PADDLE_GET_CONST(std::vector<std::string>, iter->second);
281 282 283 284 285 286
    callstack = *callstack_ptr;
  }
  HostEventRecorder<OperatorSupplementOriginEvent>::GetInstance().RecordEvent(
      PosixInNsec(), type, input_shapes, dtypes, callstack);
}

C
chenjian 已提交
287 288 289 290 291 292 293 294
RecordOpInfoSupplement::RecordOpInfoSupplement(
    const std::string &type,
    const framework::AttributeMap &attrs,
    const framework::InferShapeContext &shape_ctx,
    const phi::KernelSignature &kernel_signature) {
  if (FLAGS_enable_host_event_recorder_hook == false) {
    return;
  }
295 296 297
  if (IsEnabled() == false) {
    return;
  }
C
chenjian 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
  std::map<std::string, std::vector<framework::DDim>> input_shapes;
  std::map<std::string, std::vector<framework::proto::VarType::Type>> dtypes;
  for (auto it = kernel_signature.input_names.begin();
       it != kernel_signature.input_names.end();
       it++) {
    std::string input_name(*it);
    if (shape_ctx.HasInputs(input_name)) {
      input_shapes[input_name] = shape_ctx.GetInputsDim(input_name);
      dtypes[input_name] = shape_ctx.GetInputsVarType(input_name);
    }
  }
  const std::vector<std::string> *callstack_ptr = nullptr;
  std::vector<std::string> callstack;
  auto iter = attrs.find(
      framework::OpProtoAndCheckerMaker::OpCreationCallstackAttrName());
  if (iter != attrs.end()) {
R
Ruibiao Chen 已提交
314
    callstack_ptr = &PADDLE_GET_CONST(std::vector<std::string>, iter->second);
C
chenjian 已提交
315 316 317 318 319 320
    callstack = *callstack_ptr;
  }
  HostEventRecorder<OperatorSupplementOriginEvent>::GetInstance().RecordEvent(
      PosixInNsec(), type, input_shapes, dtypes, callstack);
}

321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
RecordOpInfoSupplement::RecordOpInfoSupplement(
    const std::string &type,
    const std::vector<std::pair<const char *, std::vector<framework::DDim>>>
        &input_shapes) {
  if (FLAGS_enable_host_event_recorder_hook == false) {
    return;
  }
  if (IsEnabled() == false) {
    return;
  }
  std::map<std::string, std::vector<framework::proto::VarType::Type>> dtypes;
  std::vector<std::string> callstack;
  HostEventRecorder<OperatorSupplementOriginEvent>::GetInstance().RecordEvent(
      PosixInNsec(), type, input_shapes, dtypes, callstack);
}

bool RecordEvent::IsEnabled() {
  return FLAGS_enable_host_event_recorder_hook || g_enable_nvprof_hook ||
         g_state != ProfilerState::kDisabled;
}

bool RecordOpInfoSupplement::IsEnabled() {
  return FLAGS_enable_record_input_shape;
}

bool RecordMemEvent::IsEnabled() { return FLAGS_enable_record_memory; }

348 349
std::map<const char *, std::map<uint64_t, std::vector<uint64_t>>>
    RecordMemEvent::size_cache;
L
Leo Chen 已提交
350

351 352
std::map<const char *, std::map<uint64_t, bool>>
    RecordMemEvent::has_initialized;
L
Leo Chen 已提交
353

354 355 356 357 358 359 360 361
RecordMemEvent::RecordMemEvent(const void *ptr,
                               const phi::Place &place,
                               size_t size,
                               const TracerMemEventType type) {
  if (g_state == ProfilerState::kDisabled &&
      FLAGS_enable_host_event_recorder_hook == false) {
    return;
  }
362 363 364 365 366

  if (IsEnabled() == false) {
    return;
  }

367 368 369 370 371 372 373
  if (type == TracerMemEventType::Allocate) {
    uint64_t current_allocated;
    uint64_t peak_allocated;
    uint64_t current_reserved = 0;  // 0 means keep the same as before
    uint64_t peak_reserved = 0;     // 0 means keep the same as before
    if (platform::is_cpu_place(place) ||
        platform::is_cuda_pinned_place(place)) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
      if (RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] = true;
      } else {
        current_allocated =
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId());
        peak_allocated =
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId());
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0] =
            current_allocated;
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2] =
            peak_allocated;
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
      }

408
    } else {
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
      if (RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] = true;
      } else {
        current_allocated =
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId());
        peak_allocated =
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId());
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0] =
            current_allocated;
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2] =
            peak_allocated;
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
      }
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    }
    platform::MemEvenRecorder::Instance().PushMemRecord(ptr,
                                                        place,
                                                        size,
                                                        type,
                                                        current_allocated,
                                                        current_reserved,
                                                        peak_allocated,
                                                        peak_reserved);
  } else if (type == TracerMemEventType::ReservedAllocate) {
    uint64_t current_reserved;
    uint64_t peak_reserved;
    uint64_t current_allocated = 0;  // 0 means keep the same as before
    uint64_t peak_allocated = 0;     // 0 means keep the same as before
    if (platform::is_cpu_place(place) ||
        platform::is_cuda_pinned_place(place)) {
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
      if (RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] = true;
      } else {
        current_reserved =
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId());
        peak_reserved =
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId());
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1] =
            current_reserved;
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3] =
            peak_reserved;
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
      }
491
    } else {
492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
      if (RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] = true;
      } else {
        current_reserved =
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId());
        peak_reserved =
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId());
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1] =
            current_reserved;
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3] =
            peak_reserved;
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
      }
525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540
    }
    platform::MemEvenRecorder::Instance().PushMemRecord(ptr,
                                                        place,
                                                        size,
                                                        type,
                                                        current_allocated,
                                                        current_reserved,
                                                        peak_allocated,
                                                        peak_reserved);
  } else if (type == TracerMemEventType::Free) {
    uint64_t current_allocated;
    uint64_t peak_allocated;
    uint64_t current_reserved = 0;  // 0 means keep the same as before
    uint64_t peak_reserved = 0;     // 0 means keep the same as before
    if (platform::is_cpu_place(place) ||
        platform::is_cuda_pinned_place(place)) {
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
      if (RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] = true;
      } else {
        current_allocated =
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId());
        peak_allocated =
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId());
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0] =
            current_allocated;
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2] =
            peak_allocated;
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
      }
574
    } else {
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607
      if (RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] = true;
      } else {
        current_allocated =
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId());
        peak_allocated =
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId());
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0] =
            current_allocated;
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2] =
            peak_allocated;
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
      }
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    }
    platform::MemEvenRecorder::Instance().PopMemRecord(ptr,
                                                       place,
                                                       size,
                                                       type,
                                                       current_allocated,
                                                       current_reserved,
                                                       peak_allocated,
                                                       peak_reserved);
  } else if (type == TracerMemEventType::ReservedFree) {
    uint64_t current_reserved;
    uint64_t peak_reserved;
    uint64_t current_allocated = 0;  // 0 means keep the same as before
    uint64_t peak_allocated = 0;     // 0 means keep the same as before
    if (platform::is_cpu_place(place) ||
        platform::is_cuda_pinned_place(place)) {
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
      if (RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()].push_back(
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["cpu"][place.GetDeviceId()] = true;
      } else {
        current_reserved =
            HOST_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId());
        peak_reserved =
            HOST_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId());
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][1] =
            current_reserved;
        RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][3] =
            peak_reserved;
        current_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][0];
        peak_allocated =
            RecordMemEvent::size_cache["cpu"][place.GetDeviceId()][2];
      }
657
    } else {
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
      if (RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] ==
          false) {
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Allocated, place.GetDeviceId()));
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()].push_back(
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId()));
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        current_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
        peak_reserved =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3];
        RecordMemEvent::has_initialized["gpu"][place.GetDeviceId()] = true;
      } else {
        current_reserved =
            DEVICE_MEMORY_STAT_CURRENT_VALUE(Reserved, place.GetDeviceId());
        peak_reserved =
            DEVICE_MEMORY_STAT_PEAK_VALUE(Reserved, place.GetDeviceId());
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][1] =
            current_reserved;
        RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][3] =
            peak_reserved;
        current_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][0];
        peak_allocated =
            RecordMemEvent::size_cache["gpu"][place.GetDeviceId()][2];
      }
691 692 693 694 695 696 697 698 699 700 701 702 703 704
    }
    platform::MemEvenRecorder::Instance().PopMemRecord(ptr,
                                                       place,
                                                       size,
                                                       type,
                                                       current_allocated,
                                                       current_reserved,
                                                       peak_allocated,
                                                       peak_reserved);
  }
}

void MemEvenRecorder::PushMemRecord(const void *ptr,
                                    const Place &place,
C
chengduo 已提交
705
                                    size_t size) {
706 707 708
  if (g_state == ProfilerState::kDisabled) {
    return;
  }
C
chengduo 已提交
709 710
  std::lock_guard<std::mutex> guard(mtx_);
  auto &events = address_memevent_[place];
711 712
  PADDLE_ENFORCE_EQ(events.count(ptr),
                    0,
G
GaoWei8 已提交
713 714
                    platform::errors::InvalidArgument(
                        "The Place can't exist in the stage of PushMemRecord"));
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
  events.emplace(ptr,
                 std::unique_ptr<RecordMemEvent>(
                     new MemEvenRecorder::RecordMemEvent(place, size)));
}

void MemEvenRecorder::PushMemRecord(const void *ptr,
                                    const Place &place,
                                    size_t size,
                                    TracerMemEventType type,
                                    uint64_t current_allocated,
                                    uint64_t current_reserved,
                                    uint64_t peak_allocated,
                                    uint64_t peak_reserved) {
  std::lock_guard<std::mutex> guard(mtx_);
  if (FLAGS_enable_host_event_recorder_hook) {  // new MemRecord
    HostEventRecorder<CommonMemEvent>::GetInstance().RecordEvent(
        PosixInNsec(),
        reinterpret_cast<uint64_t>(ptr),
        type,
        size,
        place,
        current_allocated,
        current_reserved,
        peak_allocated,
        peak_reserved);
    return;
  }
  if (type == TracerMemEventType::ReservedAllocate) {
    // old profiler only analyse memory managed by paddle.
    return;
  }
  if (g_state == ProfilerState::kDisabled) return;
  auto &events = address_memevent_[place];
  PADDLE_ENFORCE_EQ(events.count(ptr),
                    0,
                    platform::errors::InvalidArgument(
                        "The Place can't exist in the stage of PushMemRecord"));
  events.emplace(ptr,
                 std::unique_ptr<RecordMemEvent>(
                     new MemEvenRecorder::RecordMemEvent(place, size)));
C
chengduo 已提交
755 756 757
}

void MemEvenRecorder::PopMemRecord(const void *ptr, const Place &place) {
758 759 760
  if (g_state == ProfilerState::kDisabled) {
    return;
  }
C
chengduo 已提交
761 762 763 764 765 766 767 768 769
  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);
  }
}

770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804
void MemEvenRecorder::PopMemRecord(const void *ptr,
                                   const Place &place,
                                   size_t size,
                                   TracerMemEventType type,
                                   uint64_t current_allocated,
                                   uint64_t current_reserved,
                                   uint64_t peak_allocated,
                                   uint64_t peak_reserved) {
  std::lock_guard<std::mutex> guard(mtx_);
  if (FLAGS_enable_host_event_recorder_hook) {  // new MemRecord
    HostEventRecorder<CommonMemEvent>::GetInstance().RecordEvent(
        PosixInNsec(),
        reinterpret_cast<uint64_t>(ptr),
        type,
        -size,
        place,
        current_allocated,
        current_reserved,
        peak_allocated,
        peak_reserved);
    return;
  }
  if (type == TracerMemEventType::ReservedFree) {
    // old profiler only analyse memory managed by paddle.
    return;
  }
  if (g_state == ProfilerState::kDisabled) return;
  auto &events = address_memevent_[place];
  auto iter = events.find(ptr);
  // The ptr maybe not in address_memevent
  if (iter != events.end()) {
    events.erase(iter);
  }
}

C
chengduo 已提交
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
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) {
825 826 827 828 829 830 831
    tracer->AddMemInfoRecord(start_ns_,
                             end_ns_,
                             bytes_,
                             place_,
                             alloc_in_,
                             annotation_free,
                             g_mem_thread_id);
C
chengduo 已提交
832 833 834 835
  }
  PopMemEvent(start_ns_, end_ns_, bytes_, place_, annotation_free);
}

L
liutiexing 已提交
836
/*RecordRPCEvent::RecordRPCEvent(const std::string &name) {
G
gongweibao 已提交
837
  if (FLAGS_enable_rpc_profiler) {
838
    event_.reset(new platform::RecordEvent(name));
G
gongweibao 已提交
839
  }
L
liutiexing 已提交
840
}*/
G
gongweibao 已提交
841

X
Xin Pan 已提交
842 843
RecordBlock::RecordBlock(int block_id)
    : is_enabled_(false), start_ns_(PosixInNsec()) {
844
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
845
  if (g_state == ProfilerState::kDisabled) return;
X
Xin Pan 已提交
846
  is_enabled_ = true;
X
Xin Pan 已提交
847 848 849 850 851
  SetCurBlock(block_id);
  name_ = string::Sprintf("block_%d", block_id);
}

RecordBlock::~RecordBlock() {
852
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
853
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
C
chengduo 已提交
854
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
855 856 857
  if (tracer) {
    // We try to put all blocks at the same nested depth in the
    // same timeline lane. and distinguish the using thread_id.
858 859
    tracer->AddCPURecords(
        name_, start_ns_, PosixInNsec(), BlockDepth(), g_thread_id);
X
Xin Pan 已提交
860 861 862 863
  }
  ClearCurBlock();
}

864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889
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);
W
wangchaochaohu 已提交
890 891 892
}

void Mark(const std::string &name) {
893
  if (FLAGS_enable_host_event_recorder_hook) {
L
liutiexing 已提交
894
    HostEventRecorder<CommonEvent>::GetInstance().RecordEvent(
C
chenjian 已提交
895
        name, 0, 0, EventRole::kOrdinary, TracerEventType::UserDefined);
896 897
    return;
  }
W
wangchaochaohu 已提交
898 899 900
  GetEventList().Record(EventType::kMark, name, g_thread_id);
}

901 902
Event *PushEvent(const std::string &name,
                 const EventRole role,
Y
Yuang Liu 已提交
903
                 std::string attr) {
904 905
  return GetEventList().Record(
      EventType::kPushRange, name, g_thread_id, role, attr);
906 907
}

Y
Yuang Liu 已提交
908 909
void PopEvent(const std::string &name, const EventRole role, std::string attr) {
  GetEventList().Record(EventType::kPopRange, name, g_thread_id, role, attr);
W
wangchaochaohu 已提交
910
}
D
dangqingqing 已提交
911
void EnableProfiler(ProfilerState state) {
912 913
  PADDLE_ENFORCE_NE(state,
                    ProfilerState::kDisabled,
W
wangchaochaohu 已提交
914 915 916
                    platform::errors::InvalidArgument(
                        "Can't enable profiling, since the input state is"
                        "ProfilerState::kDisabled"));
917
  SynchronizeAllDevice();
X
Xin Pan 已提交
918
  std::lock_guard<std::mutex> l(profiler_mu);
919 920
  if (state == g_state) {
    return;
921
  }
922
  g_state = state;
C
chenjian 已提交
923 924
  ProfilerOptions option;
  HostTraceLevel::GetInstance().SetLevel(option.trace_level);
X
Xin Pan 已提交
925
  should_send_profile_state = true;
926
  GetDeviceTracer()->Enable();
927
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
928 929
  if (g_state == ProfilerState::kCUDA || g_state == ProfilerState::kAll ||
      g_state == ProfilerState::kCPU) {
930
    // Generate some dummy events first to reduce the startup overhead.
931 932
    DummyKernelAndEvent();
    GetDeviceTracer()->Reset();
D
dangqingqing 已提交
933 934 935
  }
#endif
  // Mark the profiling start.
936
  Mark("_start_profiler_");
D
dangqingqing 已提交
937 938
}

939
void ResetProfiler() {
940 941
  SynchronizeAllDevice();
  GetDeviceTracer()->Reset();
C
chengduo 已提交
942
  MemEvenRecorder::Instance().Flush();
D
dangqingqing 已提交
943
  std::lock_guard<std::mutex> guard(g_all_event_lists_mutex);
944 945 946 947
  for (auto it = g_all_event_lists.begin(); it != g_all_event_lists.end();
       ++it) {
    (*it)->Clear();
  }
C
chengduo 已提交
948
  for (auto it = g_all_mem_event_lists.begin();
949 950
       it != g_all_mem_event_lists.end();
       ++it) {
C
chengduo 已提交
951 952
    (*it)->Clear();
  }
953 954
}

955 956 957 958
static std::map<uint64_t, ThreadEvents> DockHostEventRecorderHostPart();
static void DockHostEventRecorderDevicePart(
    const std::map<uint64_t, ThreadEvents> &thr_events);

959
void DisableProfiler(EventSortingKey sorted_key,
C
chengduo 已提交
960
                     const std::string &profile_path) {
961
  SynchronizeAllDevice();
962
  auto thr_events = DockHostEventRecorderHostPart();
C
chengduo 已提交
963 964
  MemEvenRecorder::Instance().Flush();

X
Xin Pan 已提交
965
  std::lock_guard<std::mutex> l(profiler_mu);
966
  if (g_state == ProfilerState::kDisabled) return;
967
  // Mark the profiling stop.
968
  Mark("_stop_profiler_");
969
  DealWithShowName();
970

C
chengduo 已提交
971
  DeviceTracer *tracer = GetDeviceTracer();
972
  if (tracer->IsEnabled()) {
973
    tracer->Disable();
974
    DockHostEventRecorderDevicePart(thr_events);
975
    tracer->GenEventKernelCudaElapsedTime();
976
    tracer->GenProfile(profile_path);
977
  }
978 979

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

981 982
  ParseEvents(all_events, true, sorted_key);
  ParseEvents(all_events, false, sorted_key);
H
Huihuang Zheng 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996

  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();
997
  auto thr_events = DockHostEventRecorderHostPart();
H
Huihuang Zheng 已提交
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  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();
1009
    DockHostEventRecorderDevicePart(thr_events);
H
Huihuang Zheng 已提交
1010 1011 1012 1013 1014 1015 1016 1017 1018
    tracer->GenEventKernelCudaElapsedTime();
    *tracer_profile = tracer->GetProfile();
  }

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

1021
  ResetProfiler();
1022
  g_state = ProfilerState::kDisabled;
1023
  g_tracer_option = TracerOption::kDefault;
X
Xin Pan 已提交
1024
  should_send_profile_state = true;
1025 1026
}

W
wangchaochaohu 已提交
1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
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;
}

1037 1038
bool IsProfileEnabled() { return g_state != ProfilerState::kDisabled; }

W
wangchaochaohu 已提交
1039
bool ShouldSendProfileState() { return should_send_profile_state; }
1040

1041 1042
std::string OpName(const framework::VariableNameMap &name_map,
                   const std::string &type_name) {
1043 1044
  if (platform::GetTracerOption() != platform::TracerOption::kAllOpDetail ||
      !IsProfileEnabled())
1045 1046 1047 1048 1049
    return "";

  std::string ret = type_name + "%";
  for (auto it = name_map.begin(); it != name_map.end(); it++) {
    auto name_outputs = it->second;
1050
    if (!name_outputs.empty()) {
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
      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 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076

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

1077 1078 1079 1080 1081 1082 1083
void NvprofEnableRecordEvent() {
  SynchronizeAllDevice();
  g_enable_nvprof_hook = true;
}

void NvprofDisableRecordEvent() { g_enable_nvprof_hook = false; }

1084
void EnableHostEventRecorder() { FLAGS_enable_host_event_recorder_hook = true; }
L
liutiexing 已提交
1085

C
chenjian 已提交
1086 1087 1088 1089
void DisableHostEventRecorder() {
  FLAGS_enable_host_event_recorder_hook = false;
}

1090 1091 1092 1093 1094 1095 1096 1097
void EnableInputShapeRecorder() { FLAGS_enable_record_input_shape = true; }

void DisableInputShapeRecorder() { FLAGS_enable_record_input_shape = false; }

void EnableMemoryRecorder() { FLAGS_enable_record_memory = true; }

void DisableMemoryRecorder() { FLAGS_enable_record_memory = false; }

L
liutiexing 已提交
1098 1099
std::string PrintHostEvents() {
  std::ostringstream oss;
L
liutiexing 已提交
1100 1101
  auto host_evt_sec =
      HostEventRecorder<CommonEvent>::GetInstance().GatherEvents();
L
liutiexing 已提交
1102 1103 1104
  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) {
L
liutiexing 已提交
1105 1106 1107
      oss << "{ " << evt.name << " | " << evt.start_ns << "ns | " << evt.end_ns
          << "ns | " << (evt.end_ns - evt.start_ns) / 1000.000 << "us }"
          << std::endl;
L
liutiexing 已提交
1108 1109 1110 1111 1112
    }
  }
  return oss.str();
}

L
liutiexing 已提交
1113 1114 1115
static void EmulateEventPushAndPop(
    const HostEventSection<CommonEvent> &host_sec,
    std::map<uint64_t, ThreadEvents> *out) {
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153
  for (const auto &thr_sec : host_sec.thr_sections) {
    uint64_t tid = thr_sec.thread_id;
    auto cur_thr_list = std::make_shared<EventList<Event>>();
    g_all_event_lists.emplace_front(cur_thr_list);
    // for nesting events
    std::stack<size_t> evt_stk;
    std::stack<std::string> prefix_stk;
    std::map<uint64_t, size_t> start2evt;
    for (size_t i = 0; i < thr_sec.events.size(); ++i) {
      const auto &evt = thr_sec.events[i];
      start2evt[evt.start_ns] = i;
    }
    auto iter = start2evt.begin();
    // loop events
    for (size_t i = 0; i < thr_sec.events.size(); ++i) {
      const auto &thr_evts = thr_sec.events;
      const auto &evt = thr_evts[i];
      // For nesting events
      while (!evt_stk.empty() && thr_evts[evt_stk.top()].end_ns <= evt.end_ns) {
        evt_stk.pop();
        prefix_stk.pop();
      }
      while (iter != start2evt.end() &&
             thr_evts[iter->second].start_ns < evt.start_ns) {
        if (thr_evts[iter->second].end_ns > evt.start_ns) {
          evt_stk.push(iter->second);
          std::string prefix = thr_evts[iter->second].name;
          if (!prefix_stk.empty()) {
            prefix = prefix_stk.top() + "/" + prefix;
          }
          prefix_stk.push(prefix);
        }
        ++iter;
      }
      // Record orig event pair
      std::string name =
          prefix_stk.empty() ? evt.name : prefix_stk.top() + "/" + evt.name;
      const char *attr = (evt.attr == nullptr ? "none" : evt.attr);
1154 1155
      Event *orig_evt = cur_thr_list->Record(
          EventType::kPushRange, name, tid, evt.role, attr);
1156 1157 1158 1159 1160 1161
      (*out)[tid][evt.end_ns] = std::make_pair(orig_evt, evt.start_ns);
      cur_thr_list->Record(EventType::kPopRange, name, tid, evt.role, attr);
    }
  }
}

L
liutiexing 已提交
1162 1163
static void EmulateCPURecordsAdd(
    const HostEventSection<CommonEvent> &host_sec) {
1164 1165 1166 1167 1168 1169 1170
  DeviceTracer *tracer = GetDeviceTracer();
  if (tracer == nullptr) {
    return;
  }
  for (const auto &thr_sec : host_sec.thr_sections) {
    uint64_t tid = thr_sec.thread_id;
    for (const auto &evt : thr_sec.events) {
1171 1172
      tracer->AddCPURecords(
          evt.name, evt.start_ns, evt.end_ns, BlockDepth(), tid);
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190
    }
  }
}

static void EmulateCorrelation(
    const std::map<uint64_t, ThreadEvents> &thr_events) {
  DeviceTracer *tracer = GetDeviceTracer();
  if (tracer == nullptr) {
    return;
  }
  tracer->AddAnnotations(thr_events);
}

static std::map<uint64_t, ThreadEvents> DockHostEventRecorderHostPart() {
  std::map<uint64_t, ThreadEvents> thr_events;
  if (FLAGS_enable_host_event_recorder_hook == false) {
    return thr_events;
  }
L
liutiexing 已提交
1191 1192
  auto host_evt_sec =
      HostEventRecorder<CommonEvent>::GetInstance().GatherEvents();
1193 1194
  EmulateEventPushAndPop(host_evt_sec, &thr_events);
  EmulateCPURecordsAdd(host_evt_sec);
1195
  return thr_events;
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
}

static void DockHostEventRecorderDevicePart(
    const std::map<uint64_t, ThreadEvents> &thr_events) {
  if (FLAGS_enable_host_event_recorder_hook == false) {
    return;
  }
  EmulateCorrelation(thr_events);
}

D
dangqingqing 已提交
1206 1207
}  // namespace platform
}  // namespace paddle