profiler.h 7.6 KB
Newer Older
1
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved.
D
dangqingqing 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */

#pragma once
#include <forward_list>
#include <list>
C
chengduo 已提交
18 19 20
#include <map>
#include <memory>
#include <mutex>  // NOLINT
21
#include <string>
C
chengduo 已提交
22 23 24
#include <unordered_map>
#include <unordered_set>
#include <utility>
D
dangqingqing 已提交
25
#include <vector>
W
wanghuancoder 已提交
26

27
#include "paddle/fluid/framework/type_defs.h"
28 29
#include "paddle/fluid/platform/enforce.h"
#include "paddle/fluid/platform/event.h"
C
chengduo 已提交
30
#include "paddle/fluid/platform/place.h"
H
Huihuang Zheng 已提交
31
#include "paddle/fluid/platform/profiler.pb.h"
L
liutiexing 已提交
32
#include "paddle/fluid/platform/profiler/event_tracing.h"
33 34
#include "paddle/fluid/platform/profiler/mem_tracing.h"
#include "paddle/fluid/platform/profiler/supplement_tracing.h"
35
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
36
#include "paddle/fluid/platform/device/gpu/gpu_info.h"
D
dangqingqing 已提交
37
#endif
H
Huihuang Zheng 已提交
38

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

W
wangchaochaohu 已提交
42 43 44
const int kEnableProfiler = 1;
const int kDisableProfiler = 2;

45
enum class ProfilerState {
D
dangqingqing 已提交
46 47 48
  kDisabled,  // disabled state
  kCPU,       // CPU profiling state
  kCUDA,      // GPU profiling state
49
  kAll,       // Profile both CPU and GPU. (Currently experimental).
D
dangqingqing 已提交
50 51
};

52 53 54 55 56 57 58
// it is the flag to control to print the profiling result
enum class TracerOption {
  kDefault,      // print the different op type profiling result
  kOpDetail,     // print the detail profiling result of different op type
  kAllOpDetail,  // print the detail profiling result of different op name
};

W
wangchaochaohu 已提交
59 60 61 62 63 64 65 66 67 68 69
// Candidate keys to sort the profiling report
enum class EventSortingKey {
  kDefault,
  kCalls,
  kTotal,
  kMin,
  kMax,
  kAve,
  kCPUTime,
  kGPUTime
};
D
dangqingqing 已提交
70

W
wangchaochaohu 已提交
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
struct MemoryProfierReport {
  size_t alloc_times{0};
  size_t alloc_size{0};
  size_t free_times{0};
  size_t free_size{0};
};

// The information of each event given in the profiling report
struct EventItem {
  std::string name;
  int calls;
  double total_time;
  double max_time;
  double ave_time;
  double min_time;
  double cpu_time;
  double gpu_time;
  float ratio;
89
  EventRole role;
W
wangchaochaohu 已提交
90 91 92
};

struct OverHead {
93 94 95 96 97 98
  bool print_overhead = false;
  bool print_explanation = false;
  double elapsed_time = 0.;      // the elapsed time of all events
  double accumulated_time = 0.;  // the accumulated time of all events
  double compute_time = 0.0;
  double framework_time = 0.0;
W
wangchaochaohu 已提交
99 100 101
  EventItem memcpy_item;
  std::vector<EventItem> sub_memcpy_items;
};
C
chengduo 已提交
102 103 104 105 106

struct MemEvenRecorder {
 public:
  void PushMemRecord(const void* ptr, const Place& place, size_t size);
  void PopMemRecord(const void* ptr, const Place& place);
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
  void 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);
  void 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);
C
chengduo 已提交
123 124
  void Flush();
  static MemEvenRecorder& Instance() { return recorder; }
125

C
chengduo 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
 private:
  struct RecordMemEvent {
    RecordMemEvent(const Place& place, size_t bytes);
    ~RecordMemEvent();

    Place place_;
    size_t bytes_;
    uint64_t start_ns_;
    uint64_t end_ns_;
    std::string alloc_in_;
    std::string free_in_;
  };

  static MemEvenRecorder recorder;
  std::map<Place,
           std::unordered_map<const void*, std::unique_ptr<RecordMemEvent>>>
      address_memevent_;
  std::mutex mtx_;
  MemEvenRecorder() {}
  DISABLE_COPY_AND_ASSIGN(MemEvenRecorder);
};

X
Xin Pan 已提交
148 149 150 151 152
struct RecordBlock {
  explicit RecordBlock(int block_id);
  ~RecordBlock();

 private:
X
Xin Pan 已提交
153
  bool is_enabled_;
X
Xin Pan 已提交
154 155 156 157
  std::string name_;
  uint64_t start_ns_;
};

C
chengduo 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
template <typename T>
struct EventList {
  constexpr static size_t kMB = 1024 * 1024;
  constexpr static size_t kEventBlockSize = 16 * kMB;
  constexpr static size_t kEventSize = sizeof(T);
  constexpr static size_t kEventAlign = alignof(T);
  constexpr static size_t kNumBlock =
      kEventBlockSize /
      ((kEventSize + kEventAlign - 1) / kEventAlign * kEventAlign);

  template <typename... Args>
  T* Record(Args&&... args) {
    if (event_blocks.empty() || event_blocks.front().size() == kNumBlock) {
      event_blocks.emplace_front();
      event_blocks.front().reserve(kNumBlock);
    }
    event_blocks.front().emplace_back(std::forward<Args>(args)...);
    return &event_blocks.front().back();
  }

  std::vector<T> Reduce() {
    std::vector<T> result;
    for (auto& block : event_blocks) {
181 182
      result.insert(result.begin(),
                    std::make_move_iterator(block.begin()),
C
chengduo 已提交
183 184 185 186 187 188 189 190 191 192 193
                    std::make_move_iterator(block.end()));
    }
    event_blocks.clear();
    return result;
  }

  void Clear() { event_blocks.clear(); }

  std::forward_list<std::vector<T>> event_blocks;
};

W
wangchaochaohu 已提交
194
void Mark(const std::string& name);
195 196 197 198 199 200 201 202 203 204 205 206
void PushMemEvent(uint64_t start_ns,
                  uint64_t end_ns,
                  size_t bytes,
                  const Place& place,
                  const std::string& annotation);
void PopMemEvent(uint64_t start_ns,
                 uint64_t end_ns,
                 size_t bytes,
                 const Place& place,
                 const std::string& annotation);
Event* PushEvent(const std::string& name,
                 const EventRole role,
Y
Yuang Liu 已提交
207
                 const std::string attr = "none");
208 209
void PopEvent(const std::string& name,
              const EventRole role,
Y
Yuang Liu 已提交
210
              const std::string attr = "none");
W
wangchaochaohu 已提交
211 212 213 214
// Return the event list of all threads. Assumed the returned value calls
// event_lists, event_lists[i][j] represents the j-th Event of i-th thread.
std::vector<std::vector<Event>> GetAllEvents();

215 216 217 218
// Enable the profiling function.
void EnableProfiler(ProfilerState state);
// Clear the g_all_event_lists, which is total event lists of all threads.
void ResetProfiler();
X
Xin Pan 已提交
219 220
void DisableProfiler(EventSortingKey sorted_key,
                     const std::string& profile_path);
H
Huihuang Zheng 已提交
221 222 223 224 225
// Disable profiler but return events instead of print it.
void CompleteProfilerEvents(proto::Profile* tracer_profile,
                            std::vector<std::vector<Event>>* time_events,
                            std::vector<std::vector<MemEvent>>* mem_events);

226 227 228 229
// Test if the profiler is currently enabled.
bool IsProfileEnabled();
// Whether the trainer should send profiling state to PS.
bool ShouldSendProfileState();
230 231 232 233
std::string OpName(const framework::VariableNameMap& name_map,
                   const std::string& type_name);
void SetTracerOption(TracerOption option);
platform::TracerOption GetTracerOption();
234
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
235 236 237
void DummyKernelAndEvent();
#endif

W
wangchaochaohu 已提交
238 239 240 241
// Mark current process as PS by assigning a lister id.
void SetProfileListener();
int64_t ListenerId();

242 243 244
void NvprofEnableRecordEvent();
void NvprofDisableRecordEvent();

L
liutiexing 已提交
245
void EnableHostEventRecorder();
C
chenjian 已提交
246
void DisableHostEventRecorder();
L
liutiexing 已提交
247 248 249 250

// Defined for UT
std::string PrintHostEvents();

D
dangqingqing 已提交
251 252
}  // namespace platform
}  // namespace paddle