forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
profiler.cpp
342 lines (309 loc) · 9.49 KB
/
profiler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
#include <torch/csrc/autograd/profiler.h>
#include <torch/csrc/jit/code_template.h>
#include <fstream>
#include <list>
#include <mutex>
#include <sstream>
#include <string>
#include <vector>
namespace torch { namespace autograd { namespace profiler {
CUDAStubs default_stubs;
constexpr CUDAStubs* default_stubs_addr = &default_stubs;
// constant initialization, so it is guaranteed to be initialized before
// static initialization calls which may invoke registerCUDAMethods
static CUDAStubs* cuda_stubs = default_stubs_addr;
void registerCUDAMethods(CUDAStubs* stubs) {
cuda_stubs = stubs;
}
ProfilerState state = ProfilerState::Disabled;
uint16_t next_thread_id = 0;
// Protects access to next_thread_id and all_event_lists_map.
std::mutex all_event_lists_map_mutex;
std::unordered_map<uint16_t, std::shared_ptr<RangeEventList>>
all_event_lists_map;
thread_local std::shared_ptr<RangeEventList> event_list;
thread_local uint16_t thread_id;
uint16_t getThreadId() {
return thread_id;
}
ProfilerConfig::~ProfilerConfig() = default;
RangeEventList& getEventList() {
if (!event_list) {
std::lock_guard<std::mutex> guard(all_event_lists_map_mutex);
event_list = std::make_shared<RangeEventList>();
thread_id = ++next_thread_id;
all_event_lists_map.emplace(thread_id, event_list);
}
return *event_list;
}
void mark(std::string name, bool include_cuda /* = true */) {
if (state == ProfilerState::Disabled) {
return;
}
if (state == ProfilerState::NVTX) {
cuda_stubs->nvtxMarkA(name.c_str());
} else {
getEventList().record(
EventKind::Mark,
StringView(std::move(name)),
thread_id,
include_cuda && state == ProfilerState::CUDA);
}
}
bool profilerEnabled() {
return state != ProfilerState::Disabled;
}
void pushRangeImpl(
const StringView& name,
const char* msg = "",
int64_t sequence_nr = -1,
std::vector<std::vector<int64_t>>&& shapes = {}) {
if (state == ProfilerState::Disabled) {
return;
}
if (state == ProfilerState::NVTX) {
if(sequence_nr >= 0 || shapes.size() > 0) {
std::stringstream s;
if(sequence_nr >= 0)
s << name.str() << msg << sequence_nr;
if(shapes.size() > 0) {
s << ", sizes = [";
for(int i = 0; i < shapes.size(); i++) {
if(shapes[i].size() > 0) {
s << "[";
for(int dim = 0; dim < shapes[i].size(); dim++) {
s << shapes[i][dim];
if(dim < shapes[i].size() - 1)
s << ", ";
}
s << "]";
}
else
s << "[]";
if(i < shapes.size() - 1)
s << ", ";
}
s << "]";
}
cuda_stubs->nvtxRangePushA(s.str().c_str());
} else {
cuda_stubs->nvtxRangePushA(name.str());
}
} else {
getEventList().record(
EventKind::PushRange,
name,
thread_id,
state == ProfilerState::CUDA,
std::move(shapes));
}
}
void pushRange(std::string name) {
pushRangeImpl(StringView(std::move(name)));
}
void popRange() {
if (state == ProfilerState::Disabled) {
return;
}
if (state == ProfilerState::NVTX) {
cuda_stubs->nvtxRangePop();
} else {
getEventList().record(
EventKind::PopRange,
StringView(""),
thread_id,
state == ProfilerState::CUDA);
}
}
void enableProfiler(ProfilerConfig config) {
ProfilerState new_state = config.state;
AT_ASSERT(new_state != ProfilerState::Disabled);
if (new_state == ProfilerState::NVTX && !cuda_stubs->enabled())
throw std::runtime_error("Can't use NVTX profiler - PyTorch was compiled without CUDA");
if (state != ProfilerState::Disabled && new_state != state) {
throw std::runtime_error("can't change kind of profiling (e.g. NVTX to CPU) while profiler is running");
}
pushCallback(
[config](const RecordFunction& fn) {
auto* msg = (fn.seqNr() >= 0) ? ", seq = " : "";
if (config.report_input_shapes) {
std::vector<std::vector<int64_t>> inputSizes;
inputSizes.reserve(fn.inputs().size());
for (const c10::IValue& input : fn.inputs()) {
if (!input.isTensor()) {
inputSizes.emplace_back();
continue;
}
const at::Tensor& tensor = input.toTensor();
if (tensor.defined()) {
inputSizes.push_back(input.toTensor().sizes().vec());
} else {
inputSizes.emplace_back();
}
}
pushRangeImpl(fn.name(), msg, fn.seqNr(), std::move(inputSizes));
} else {
pushRangeImpl(fn.name(), msg, fn.seqNr(), {});
}
},
[](const RecordFunction& fn) {
if (fn.getThreadId() != 0) {
// If we've overridden the thread_id on the RecordFunction, then find
// the eventList that was created for the original thread_id. Then,
// record the end event on this list so that the block is added to
// the correct list, instead of to a new list. This should only run
// when calling RecordFunction::end() in a different thread.
if (state == ProfilerState::Disabled) {
return;
} else {
std::lock_guard<std::mutex> guard(all_event_lists_map_mutex);
const auto& eventListIter =
all_event_lists_map.find(fn.getThreadId());
TORCH_INTERNAL_ASSERT(
eventListIter != all_event_lists_map.end(),
"Did not find thread_id matching ",
fn.getThreadId());
auto& eventList = eventListIter->second;
eventList->record(
EventKind::PopRange,
StringView(""),
fn.getThreadId(),
state == ProfilerState::CUDA);
}
} else {
popRange();
}
},
config.report_input_shapes);
state = new_state;
if(state == ProfilerState::CUDA) {
// event recording appears to have some startup overhead, so we need to
// to generate some dummy events first before recording synchronization events
for(int i = 0; i < 5; i++) {
cuda_stubs->onEachDevice([](int d) {
mark("__cuda_startup");
cuda_stubs->synchronize();
});
}
// cuda events must be on the same device, so we need a start event recorded
// for each gpu. we then use this event to synchronize time on the GPU
// with the CPU clock.
cuda_stubs->onEachDevice([](int d) {
mark("__cuda_start_event");
});
}
mark("__start_profile", false);
}
thread_event_lists disableProfiler() {
if (state == ProfilerState::Disabled) {
throw std::runtime_error("can't disable profiler when it's not running");
}
ProfilerState old_state = state;
mark("__stop_profile");
popCallback();
state = ProfilerState::Disabled;
if (old_state == ProfilerState::NVTX) {
return thread_event_lists();
} else {
thread_event_lists result;
std::lock_guard<std::mutex> guard(all_event_lists_map_mutex);
for (auto it = all_event_lists_map.begin(); it != all_event_lists_map.end();) {
auto & list = it->second;
result.emplace_back(list->consolidate());
// GC lists that are not held by any threads
if (list.use_count() == 1) {
auto current_it = it;
++it;
all_event_lists_map.erase(current_it);
} else {
++it;
}
}
return result;
}
}
void Event::record(bool record_cuda) {
if (record_cuda) {
cuda_stubs->record(&device_, &event, &cpu_ns_);
return;
}
cpu_ns_ = getTime();
}
double Event::cuda_elapsed_us(const Event & e) {
if(!e.has_cuda() || !has_cuda()) {
throw std::logic_error("Events were not recorded for CUDA");
}
if(e.device() != device()) {
throw std::logic_error("Events are not on the same device");
}
return cuda_stubs->elapsed(event, e.event);
}
CUDAStubs::~CUDAStubs() = default;
static jit::CodeTemplate event_template(R"(
{
"name": "${name}",
"ph": "X",
"ts": ${ts},
"dur": ${dur},
"tid": ${tid},
"pid": "CPU Functions",
"args": {}
})");
RecordProfile::RecordProfile(std::ostream& out)
: out_(out) {
init();
}
RecordProfile::RecordProfile(const std::string& filename)
: file_(new std::ofstream(filename)), out_(*file_) {
init();
}
void RecordProfile::init() {
enableProfiler(ProfilerConfig(ProfilerState::CPU, false /* report shapes */));
}
RecordProfile::~RecordProfile() {
thread_event_lists event_lists = disableProfiler();
std::vector<Event*> events;
for(auto& l : event_lists) {
for(auto& e : l) {
events.push_back(&e);
}
}
processEvents(events);
if (file_){
file_->close();
}
}
void RecordProfile::processEvents(const std::vector<Event*>& events) {
TORCH_CHECK(out_, "could not open file");
Event* start = nullptr;
for (Event* e : events) {
if(0 == strcmp(e->name(), "__start_profile")) {
start = e;
break;
}
}
TORCH_CHECK(start, "could not find start?");
std::vector<Event*> stack;
out_ << "[\n";
bool first = true;
for(Event* e : events) {
if(e->kind() == "push") {
stack.push_back(e);
} else if(e->kind() == "pop") {
if(!first) {
out_ << ",\n";
}
first = false;
Event* e_start = stack.back();
stack.pop_back();
jit::TemplateEnv env;
env.s("name", e_start->name());
env.d("ts", start->cpu_elapsed_us(*e_start));
env.d("dur", e_start->cpu_elapsed_us(*e));
env.d("tid", e_start->thread_id());
out_ << event_template.format(env);
}
}
out_ << "]\n";
}
}}}