profiler.cc 11.1 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>
17
#include <string>
Y
Yancey1989 已提交
18

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

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

D
dangqingqing 已提交
30 31 32
namespace paddle {
namespace platform {

W
wangchaochaohu 已提交
33
MemEvenRecorder MemEvenRecorder::recorder;
D
dangqingqing 已提交
34

35
Event::Event(EventType type, std::string name, uint32_t thread_id,
Y
Yuang Liu 已提交
36 37 38 39 40 41
             EventRole role, std::string attr)
    : type_(type),
      name_(name),
      thread_id_(thread_id),
      role_(role),
      attr_(attr) {
D
dangqingqing 已提交
42 43 44
  cpu_ns_ = GetTimeInNsec();
}

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

C
chengduo 已提交
47
double Event::CpuElapsedMs(const Event &e) const {
48
  return (e.cpu_ns_ - cpu_ns_) / (1000000.0);
D
dangqingqing 已提交
49 50
}

C
chengduo 已提交
51
double Event::CudaElapsedMs(const Event &e) const {
52 53
#ifdef PADDLE_WITH_CUPTI
  return gpu_ns_ / 1000000.0;
D
Dun Liang 已提交
54
#else
D
Dun Liang 已提交
55 56
  LOG_FIRST_N(WARNING, 1) << "CUDA CUPTI is not enabled";
  return 0;
D
dangqingqing 已提交
57 58 59
#endif
}

Y
Yuang Liu 已提交
60 61
RecordEvent::RecordEvent(const std::string &name, const EventRole role,
                         const std::string attr) {
62 63 64 65 66 67 68 69
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook) {
    dynload::nvtxRangePushA(name.c_str());
    is_pushed_ = true;
  }
#endif
#endif
70
  if (g_state == ProfilerState::kDisabled || name.empty()) return;
71 72 73 74

  // do some initialization
  start_ns_ = PosixInNsec();
  role_ = role;
X
Xin Pan 已提交
75
  is_enabled_ = true;
76
  // lock is not needed, the code below is thread-safe
77
  // Maybe need the same push/pop behavior.
Y
Yuang Liu 已提交
78
  Event *e = PushEvent(name, role, attr);
79 80
  SetCurAnnotation(e);
  name_ = e->name();
D
dangqingqing 已提交
81 82 83
}

RecordEvent::~RecordEvent() {
84 85 86 87 88 89 90
#ifndef _WIN32
#ifdef PADDLE_WITH_CUDA
  if (g_enable_nvprof_hook && is_pushed_) {
    dynload::nvtxRangePop();
  }
#endif
#endif
X
Xin Pan 已提交
91
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
92
  // lock is not needed, the code below is thread-safe
C
chengduo 已提交
93
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
94
  if (tracer) {
95
    tracer->AddCPURecords(CurAnnotationName(), start_ns_, PosixInNsec(),
96
                          BlockDepth(), g_thread_id);
X
Xin Pan 已提交
97
  }
Y
Yibing Liu 已提交
98
  ClearCurAnnotation();
W
wangchaochaohu 已提交
99
  PopEvent(name_, role_);
D
dangqingqing 已提交
100
}
D
dangqingqing 已提交
101

C
chengduo 已提交
102 103 104 105 106
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 已提交
107 108 109
  PADDLE_ENFORCE_EQ(events.count(ptr), 0,
                    platform::errors::InvalidArgument(
                        "The Place can't exist in the stage of PushMemRecord"));
C
chengduo 已提交
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
  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 已提交
152
  if (FLAGS_enable_rpc_profiler) {
153
    event_.reset(new platform::RecordEvent(name));
G
gongweibao 已提交
154 155 156
  }
}

X
Xin Pan 已提交
157 158
RecordBlock::RecordBlock(int block_id)
    : is_enabled_(false), start_ns_(PosixInNsec()) {
159
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
160
  if (g_state == ProfilerState::kDisabled) return;
X
Xin Pan 已提交
161
  is_enabled_ = true;
X
Xin Pan 已提交
162 163 164 165 166
  SetCurBlock(block_id);
  name_ = string::Sprintf("block_%d", block_id);
}

RecordBlock::~RecordBlock() {
167
  // lock is not needed, the code below is thread-safe
X
Xin Pan 已提交
168
  if (g_state == ProfilerState::kDisabled || !is_enabled_) return;
C
chengduo 已提交
169
  DeviceTracer *tracer = GetDeviceTracer();
X
Xin Pan 已提交
170 171 172 173
  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(),
174
                          g_thread_id);
X
Xin Pan 已提交
175 176 177 178
  }
  ClearCurBlock();
}

W
wangchaochaohu 已提交
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
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 已提交
195 196 197 198
Event *PushEvent(const std::string &name, const EventRole role,
                 std::string attr) {
  return GetEventList().Record(EventType::kPushRange, name, g_thread_id, role,
                               attr);
199 200
}

Y
Yuang Liu 已提交
201 202
void PopEvent(const std::string &name, const EventRole role, std::string attr) {
  GetEventList().Record(EventType::kPopRange, name, g_thread_id, role, attr);
W
wangchaochaohu 已提交
203
}
D
dangqingqing 已提交
204
void EnableProfiler(ProfilerState state) {
W
wangchaochaohu 已提交
205 206 207 208
  PADDLE_ENFORCE_NE(state, ProfilerState::kDisabled,
                    platform::errors::InvalidArgument(
                        "Can't enable profiling, since the input state is"
                        "ProfilerState::kDisabled"));
209
  SynchronizeAllDevice();
X
Xin Pan 已提交
210
  std::lock_guard<std::mutex> l(profiler_mu);
211 212
  if (state == g_state) {
    return;
213
  }
214
  g_state = state;
X
Xin Pan 已提交
215
  should_send_profile_state = true;
216
  GetDeviceTracer()->Enable();
217
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
218 219
  if (g_state == ProfilerState::kCUDA || g_state == ProfilerState::kAll ||
      g_state == ProfilerState::kCPU) {
220
    // Generate some dummy events first to reduce the startup overhead.
221 222
    DummyKernelAndEvent();
    GetDeviceTracer()->Reset();
D
dangqingqing 已提交
223 224 225
  }
#endif
  // Mark the profiling start.
226
  Mark("_start_profiler_");
D
dangqingqing 已提交
227 228
}

229
void ResetProfiler() {
230 231
  SynchronizeAllDevice();
  GetDeviceTracer()->Reset();
C
chengduo 已提交
232
  MemEvenRecorder::Instance().Flush();
D
dangqingqing 已提交
233
  std::lock_guard<std::mutex> guard(g_all_event_lists_mutex);
234 235 236 237
  for (auto it = g_all_event_lists.begin(); it != g_all_event_lists.end();
       ++it) {
    (*it)->Clear();
  }
C
chengduo 已提交
238 239 240 241
  for (auto it = g_all_mem_event_lists.begin();
       it != g_all_mem_event_lists.end(); ++it) {
    (*it)->Clear();
  }
242 243
}

244
void DisableProfiler(EventSortingKey sorted_key,
C
chengduo 已提交
245
                     const std::string &profile_path) {
246
  SynchronizeAllDevice();
C
chengduo 已提交
247 248
  MemEvenRecorder::Instance().Flush();

X
Xin Pan 已提交
249
  std::lock_guard<std::mutex> l(profiler_mu);
250
  if (g_state == ProfilerState::kDisabled) return;
251
  // Mark the profiling stop.
252
  Mark("_stop_profiler_");
253
  DealWithShowName();
254

C
chengduo 已提交
255
  DeviceTracer *tracer = GetDeviceTracer();
256
  if (tracer->IsEnabled()) {
257
    tracer->Disable();
258
    tracer->GenEventKernelCudaElapsedTime();
259
    tracer->GenProfile(profile_path);
260
  }
261 262

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

264 265
  ParseEvents(all_events, true, sorted_key);
  ParseEvents(all_events, false, sorted_key);
H
Huihuang Zheng 已提交
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

  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 已提交
300 301
  }

302
  ResetProfiler();
303
  g_state = ProfilerState::kDisabled;
304
  g_tracer_option = TracerOption::kDefault;
X
Xin Pan 已提交
305
  should_send_profile_state = true;
306 307
}

W
wangchaochaohu 已提交
308 309 310 311 312 313 314 315 316 317
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;
}

318 319
bool IsProfileEnabled() { return g_state != ProfilerState::kDisabled; }

W
wangchaochaohu 已提交
320
bool ShouldSendProfileState() { return should_send_profile_state; }
321

322 323
std::string OpName(const framework::VariableNameMap &name_map,
                   const std::string &type_name) {
324 325
  if (platform::GetTracerOption() != platform::TracerOption::kAllOpDetail ||
      !IsProfileEnabled())
326 327 328 329 330
    return "";

  std::string ret = type_name + "%";
  for (auto it = name_map.begin(); it != name_map.end(); it++) {
    auto name_outputs = it->second;
331
    if (!name_outputs.empty()) {
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
      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 已提交
347 348 349 350 351 352 353 354 355 356 357

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

358 359 360 361 362 363 364
void NvprofEnableRecordEvent() {
  SynchronizeAllDevice();
  g_enable_nvprof_hook = true;
}

void NvprofDisableRecordEvent() { g_enable_nvprof_hook = false; }

D
dangqingqing 已提交
365 366
}  // namespace platform
}  // namespace paddle