-
Notifications
You must be signed in to change notification settings - Fork 21.4k
/
record_function.cpp
523 lines (452 loc) · 14.7 KB
/
record_function.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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
408
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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
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
491
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
#include <ATen/record_function.h>
#include <ATen/core/dispatch/Dispatcher.h>
#include <c10/macros/Macros.h>
#include <algorithm>
#include <cstdlib>
#include <random>
namespace at {
namespace {
// Used to generate unique callback handles
CallbackHandle next_unique_callback_handle() {
static std::atomic<uint64_t> unique_cb_id {1};
return CallbackHandle(unique_cb_id++);
}
RecordFunctionHandle next_unique_record_function_handle() {
static std::atomic<uint64_t> unique_rf_id {1};
return RecordFunctionHandle(unique_rf_id++);
}
thread_local RecordFunctionTLS rf_tls_;
std::atomic<int64_t> defaultNodeId(-1);
// Enumerates thread ids logically;
// note: std::this_thread::get_id may return potentially
// reused thread id
std::atomic<uint64_t> next_thread_id_ {0};
thread_local uint64_t current_thread_id_ = 0;
// Low probability constant
static const double kLowProb = 0.001;
struct CoinflipTLS {
int tries_left_;
std::mt19937 genGeo_;
std::mt19937 genZeroOne_;
std::geometric_distribution<int> distGeo_;
std::uniform_real_distribution<double> distZeroOne_;
CoinflipTLS();
};
CoinflipTLS::CoinflipTLS()
: tries_left_(0), genGeo_(std::random_device()()), genZeroOne_(std::random_device()()), distGeo_(kLowProb), distZeroOne_(0.0, 1.0) {}
thread_local CoinflipTLS coinflip_tls_;
int sample_geometric() {
return coinflip_tls_.distGeo_(coinflip_tls_.genGeo_);
}
double sample_zero_one() {
return coinflip_tls_.distZeroOne_(coinflip_tls_.genZeroOne_);
}
} // namespace
const RecordFunctionTLS& get_record_function_tls_() {
return rf_tls_;
}
void set_record_function_tls_(const RecordFunctionTLS& tls) {
rf_tls_ = tls;
}
class CallbackManager {
public:
CallbackHandle addThreadLocalCallback(RecordFunctionCallback cb) {
if (cb.samplingProb() > kLowProb) {
// pre-sampling of RecordFunction with prob. kLowProb cannot be used
at::bumpRecordAllFunctions();
}
// note: monotonically increasing callbacks_unique_id keeps
// sorted_tls_callbacks_ sorted
auto handle = next_unique_callback_handle();
rf_tls_.sorted_tls_callbacks_.emplace_back(std::move(cb), handle);
return handle;
}
CallbackHandle addGlobalCallback(RecordFunctionCallback cb) {
if (cb.samplingProb() > kLowProb) {
// pre-sampling of RecordFunction with prob. kLowProb cannot be used
at::bumpRecordAllFunctions();
}
auto handle = next_unique_callback_handle();
sorted_global_callbacks_.emplace_back(std::move(cb), handle);
return handle;
}
void removeCallback(CallbackHandle handle) {
auto find_and_remove = [handle](RecordFunctionCallbacks& cbs) {
auto it = std::find_if(
cbs.begin(), cbs.end(),
[handle](
const std::pair<
RecordFunctionCallback,
CallbackHandle>& el) {
return el.second == handle;
});
if (it != cbs.end()) {
if (it->first.samplingProb() > kLowProb) {
// try to restore pre-sampling of RecordFunction
at::releaseRecordAllFunctions();
}
// keeps it sorted
cbs.erase(it);
return true;
}
return false;
};
auto found = find_and_remove(rf_tls_.sorted_tls_callbacks_);
if (!found) {
found = find_and_remove(sorted_global_callbacks_);
}
if (!found) {
LOG(WARNING) << "Requested callback is not found";
}
}
void clearGlobalCallbacks() {
sorted_global_callbacks_.clear();
}
void clearThreadLocalCallbacks() {
rf_tls_.sorted_tls_callbacks_.clear();
}
inline bool hasGlobalCallbacks() const {
return !sorted_global_callbacks_.empty();
}
inline bool hasThreadLocalCallbacks() const {
return !rf_tls_.sorted_tls_callbacks_.empty();
}
// We need this function to be inlined: init() is a hot path and
// callbackShouldRun is even hotter because it's called multiple
// times per init(). Profiling shows that the function prologue is
// taking up a significant fraction of the time.
static bool C10_ALWAYS_INLINE callbackShouldRun(
const RecordFunctionCallback& cb, RecordScope scope, bool pre_sampled) {
TORCH_INTERNAL_ASSERT(
!pre_sampled || (cb.sampling_prob_ <= kLowProb),
"Incorrect usage of a pre-sampled RecordFunction with a high-frequency "
" or non-sampled callback");
// first check whether this callback is interested in
// the given scope type
if (!cb.checkScope(scope)) {
return false;
}
// if we have registered should_run_ function, use it
if (cb.should_run_) {
return cb.should_run_(cb);
}
// otherwise potentially do the sampling
double sampling_prob = cb.sampling_prob_;
if (pre_sampled) {
// adjust the sampling rate to account for kLowProb pre-sampling of
// the RecordFunction
sampling_prob /= kLowProb;
}
if (sampling_prob < 1.0) {
// model the low probability events as events happening
// with probability kLowProb followed by another sampling with
// probability (sampling_prob / kLowProb), then replace the coin
// flip for kLowProb with a thread local number of tries tries_left_
// sampled from the geometric distribution.
if (sampling_prob < kLowProb) {
if (coinflip_tls_.tries_left_ == 0) {
coinflip_tls_.tries_left_ = sample_geometric();
return (sample_zero_one() < sampling_prob / kLowProb);
} else {
--coinflip_tls_.tries_left_;
return false;
}
} else {
return (sample_zero_one() < sampling_prob);
}
}
return true;
}
// init is called by RecordFunction in constructor to
// determine which thread local and global callbacks are going
// to be executed and whether any of them need inputs
inline void init(RecordFunction& rec_fn, RecordScope scope, bool pre_sampled) {
bool found_needs_inputs = false;
bool found_needs_ids = false;
for (const auto& cb: rf_tls_.sorted_tls_callbacks_) {
if (callbackShouldRun(cb.first, scope, pre_sampled)) {
if (cb.first.needsInputs()) {
found_needs_inputs = true;
}
if (cb.first.needsIds()) {
found_needs_ids = true;
}
if (!rec_fn.state_) {
rec_fn.state_ = std::make_unique<RecordFunction::State>(scope);
}
rec_fn.state_->sorted_active_tls_handles_.push_back(cb.second);
}
}
for (const auto& cb: sorted_global_callbacks_) {
if (callbackShouldRun(cb.first, scope, pre_sampled)) {
if (cb.first.needsInputs()) {
found_needs_inputs = true;
}
if (cb.first.needsIds()) {
found_needs_ids = true;
}
if (!rec_fn.state_) {
rec_fn.state_ = std::make_unique<RecordFunction::State>(scope);
}
rec_fn.state_->sorted_active_global_handles_.push_back(cb.second);
}
}
if (!rec_fn.state_) {
return;
}
// Pre-allocate observer context list with nullptr.
rec_fn.state_->tls_ctx_.resize(rec_fn.state_->sorted_active_tls_handles_.size());
rec_fn.state_->global_ctx_.resize(rec_fn.state_->sorted_active_global_handles_.size());
rec_fn.state_->needs_inputs = found_needs_inputs;
if (found_needs_ids) {
rec_fn.setHandle(next_unique_record_function_handle());
}
}
void runStartCallbacks(RecordFunction& rf) {
mergeRunCallbacks(
sorted_global_callbacks_,
rf.state_->sorted_active_global_handles_,
rf.state_->global_ctx_,
/* is_start */ true,
rf);
mergeRunCallbacks(
rf_tls_.sorted_tls_callbacks_,
rf.state_->sorted_active_tls_handles_,
rf.state_->tls_ctx_,
/* is_start */ true,
rf);
rf.state_->called_start_callbacks_ = true;
}
void runEndCallbacks(RecordFunction& rf) {
mergeRunCallbacks(
sorted_global_callbacks_,
rf.state_->sorted_active_global_handles_,
rf.state_->global_ctx_,
/* is_start */ false,
rf);
mergeRunCallbacks(
rf_tls_.sorted_tls_callbacks_,
rf.state_->sorted_active_tls_handles_,
rf.state_->tls_ctx_,
/* is_start */ false,
rf);
}
// Global callbacks; must be sorted in increasing handle order
RecordFunctionCallbacks sorted_global_callbacks_;
private:
bool tryRunCallback(
const RecordFunctionCallback& rfcb,
RecordFunction& rf,
std::unique_ptr<ObserverContext>& ctx,
bool is_start) {
try {
if (is_start) {
ctx = rfcb.start()(rf);
}
else {
rfcb.end()(rf, ctx.get());
}
return true;
} catch (const std::exception &e) {
LOG(WARNING) << "Exception in RecordFunction callback: "
<< e.what() << " , for the range " << rf.name();
return false;
} catch (...) {
LOG(WARNING) << "Exception in RecordFunction callback: unknown"
<< " , for the range " << rf.name();
return false;
}
}
void mergeRunCallbacks(
const RecordFunctionCallbacks& sorted_callbacks,
const CallbackHandles& sorted_handles,
ObserverContextList& ctx_list,
bool is_start,
RecordFunction& rf) {
size_t num_executed = 0;
size_t idx_c = 0;
for (size_t idx_h = 0; idx_h < sorted_handles.size() && idx_h < ctx_list.size(); ++idx_h) {
while (idx_c < sorted_callbacks.size() &&
sorted_callbacks[idx_c].second < sorted_handles[idx_h]) {
++idx_c;
}
if (idx_c >= sorted_callbacks.size()) {
break;
}
if (sorted_callbacks[idx_c].second == sorted_handles[idx_h]) {
tryRunCallback(sorted_callbacks[idx_c].first, rf, ctx_list[idx_h], is_start);
++num_executed;
}
}
if (num_executed != sorted_handles.size()) {
C10_LOG_EVERY_MS(WARNING, 1000)
<< "Could not match some of the start callbacks with the corresponding end callbacks, "
<< "callbacks changed during RecordFunction lifetime; you might be trying to profile "
<< "the code after profiler is finished";
}
}
};
namespace {
// Keeping this static manager local.
CallbackManager& manager() {
static CallbackManager _manager;
return _manager;
}
} // namespace
RecordFunctionCallbacks _getTLSCallbacks() {
return rf_tls_.sorted_tls_callbacks_;
}
void _setTLSCallbacks(const RecordFunctionCallbacks& callbacks) {
// keep the original handles
rf_tls_.sorted_tls_callbacks_ = callbacks;
std::sort(
rf_tls_.sorted_tls_callbacks_.begin(),
rf_tls_.sorted_tls_callbacks_.end(),
[](const std::pair<RecordFunctionCallback, CallbackHandle>& l,
const std::pair<RecordFunctionCallback, CallbackHandle>& r) {
return l.second < r.second;
});
}
bool hasCallbacks() {
auto& m = manager();
return m.hasGlobalCallbacks() || m.hasThreadLocalCallbacks();
}
bool hasGlobalCallbacks() {
return manager().hasGlobalCallbacks();
}
bool hasThreadLocalCallbacks() {
return manager().hasThreadLocalCallbacks();
}
CallbackHandle addThreadLocalCallback(
RecordFunctionCallback cb) {
return manager().addThreadLocalCallback(std::move(cb));
}
CallbackHandle addGlobalCallback(
RecordFunctionCallback cb) {
return manager().addGlobalCallback(std::move(cb));
}
void removeCallback(CallbackHandle handle) {
manager().removeCallback(handle);
}
void clearGlobalCallbacks() {
manager().clearGlobalCallbacks();
}
void clearThreadLocalCallbacks() {
manager().clearThreadLocalCallbacks();
}
void clearCallbacks() {
auto& m = manager();
m.clearGlobalCallbacks();
m.clearThreadLocalCallbacks();
}
bool isRecordFunctionEnabled() {
return rf_tls_.tls_record_function_enabled_;
}
void enableRecordFunction(bool enable) {
rf_tls_.tls_record_function_enabled_ = enable;
}
RecordFunction::RecordFunction(RecordScope scope, bool pre_sampled) {
auto* rf_tls_ptr = &rf_tls_;
if (rf_tls_ptr->tls_record_function_enabled_) {
auto& m = manager();
if (!m.sorted_global_callbacks_.empty() || !rf_tls_ptr->sorted_tls_callbacks_.empty()) {
m.init(*this, scope, pre_sampled);
}
}
}
/* static */
uint64_t RecordFunction::currentThreadId() {
if (!current_thread_id_) {
// happens only once per thread
current_thread_id_ = ++next_thread_id_;
}
return current_thread_id_;
}
void RecordFunction::before(const char* name, int64_t sequence_nr) {
if (!isActive()) {
return;
}
state_->name_ = StringView(name);
state_->sequence_nr_ = sequence_nr;
state_->thread_id_ = currentThreadId();
state_->operator_name_.reset();
manager().runStartCallbacks(*this);
}
void RecordFunction::before(std::string name, int64_t sequence_nr) {
if (!isActive()) {
return;
}
state_->name_ = StringView(std::move(name));
state_->sequence_nr_ = sequence_nr;
state_->thread_id_ = currentThreadId();
state_->operator_name_.reset();
manager().runStartCallbacks(*this);
}
void RecordFunction::before(
c10::OperatorHandle const& op,
int64_t sequence_nr) {
if (!isActive()) {
return;
}
state_->sequence_nr_ = sequence_nr;
state_->thread_id_ = currentThreadId();
state_->operator_name_ = op.operator_name();
state_->name_ = StringView(op.schema().name());
manager().runStartCallbacks(*this);
}
/* static */ void RecordFunction::setDefaultNodeId(int64_t newDefaultNodeId) {
TORCH_CHECK(newDefaultNodeId >= 0, "setDefaultNodeId expects an id >= 0.");
defaultNodeId = newDefaultNodeId;
}
/* static */ int64_t RecordFunction::getDefaultNodeId() {
return defaultNodeId;
}
RecordFunction::~RecordFunction() {
end();
}
void RecordFunction::end() {
if (isActive() && state_->called_start_callbacks_) {
manager().runEndCallbacks(*this);
state_.reset();
}
}
// RecordFunction pre-sampling
namespace {
// Whether to try to create RecordFunction on each call (>0) or
// use pre-sampling (=0)
std::atomic<int> global_record_all_functions_ {0};
}
void bumpRecordAllFunctions() {
global_record_all_functions_.fetch_add(1, std::memory_order_relaxed);
}
void releaseRecordAllFunctions() {
TORCH_CHECK(global_record_all_functions_.fetch_sub(1, std::memory_order_relaxed) >= 0);
}
bool checkRecordAllFunctions() {
return (global_record_all_functions_.load(std::memory_order_relaxed) > 0);
}
bool shouldRunRecordFunction(bool* pre_sampled) {
auto* rf_tls_ptr = &rf_tls_;
if (rf_tls_ptr->sorted_tls_callbacks_.empty() && !manager().hasGlobalCallbacks()) {
*pre_sampled = false;
return false;
}
if (global_record_all_functions_.load(std::memory_order_relaxed) > 0) {
*pre_sampled = false;
return true;
}
if (!rf_tls_ptr->tls_record_function_enabled_) {
*pre_sampled = false;
return false;
}
*pre_sampled = true;
auto* coinflip_tls_ptr = &coinflip_tls_;
if (coinflip_tls_ptr->tries_left_ == 0) {
coinflip_tls_ptr->tries_left_ = sample_geometric();
return true;
} else {
--coinflip_tls_ptr->tries_left_;
return false;
}
}
} // namespace at