forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprofiler_python.cpp
More file actions
1601 lines (1434 loc) · 52.6 KB
/
profiler_python.cpp
File metadata and controls
1601 lines (1434 loc) · 52.6 KB
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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
574
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
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
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
657
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
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
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
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <torch/csrc/autograd/profiler_python.h>
#include <atomic>
#include <cstdint>
#include <deque>
#include <limits>
#include <memory>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include <Python.h>
#include <frameobject.h>
#include <ATen/core/TensorBase.h>
#include <c10/macros/Macros.h>
#include <c10/util/ApproximateClock.h>
#include <c10/util/Exception.h>
#include <c10/util/Logging.h>
#include <c10/util/flat_hash_map.h>
#include <c10/util/irange.h>
#include <torch/csrc/autograd/python_variable.h>
#include <torch/csrc/profiler/collection.h>
#include <torch/csrc/profiler/containers.h>
#include <torch/csrc/profiler/orchestration/python_tracer.h>
#include <torch/csrc/profiler/util.h>
#include <torch/csrc/utils/pybind.h>
#include <torch/csrc/utils/python_compat.h>
#include <torch/csrc/utils/python_numbers.h>
#include <torch/csrc/utils/python_strings.h>
#include <optional>
namespace py = pybind11;
namespace torch::profiler::impl {
namespace {
enum CallType { PyCall = 0, PyModuleCall, PyCCall, PyOptimizerCall };
static constexpr size_t CallTypeSize = 4;
using no_ephemeral_t = std::tuple<>;
static constexpr uint64_t NoTID = std::numeric_limits<uint64_t>::max();
// ============================================================================
// == Miscellaneous structs and utils =========================================
// ============================================================================
struct CodeLocation {
CodeLocation() = default;
explicit CodeLocation(PyFrameObject* frame)
: line_number_{PyFrame_GetLineNumber(frame)} {
auto code = THPCodeObjectPtr(PyFrame_GetCode(frame));
filename_ = THPUtils_unpackStringView(code->co_filename).data();
name_ = THPUtils_unpackStringView(code->co_name).data();
}
bool operator==(const CodeLocation& other) const {
return filename_ == other.filename_ && name_ == other.name_ &&
line_number_ == other.line_number_;
}
const char* filename_{nullptr};
const char* name_{nullptr};
int line_number_{0};
};
template <CallType C>
PyCodeObject* getCode();
template <>
PyCodeObject* getCode<CallType::PyModuleCall>() {
static auto module_call_code = []() {
pybind11::gil_scoped_acquire gil;
auto res = py::module::import("torch.nn")
.attr("Module")
.attr("__call__")
.attr("__code__")
.ptr();
TORCH_INTERNAL_ASSERT(PyCode_Check(res));
return (PyCodeObject*)res;
}();
return module_call_code;
}
template <>
PyCodeObject* getCode<CallType::PyOptimizerCall>() {
static auto optimizer_step_code = []() {
pybind11::gil_scoped_acquire gil;
auto res = py::module::import("torch.optim")
.attr("Optimizer")
.attr("_optimizer_step_code")
.attr("__code__")
.ptr();
TORCH_INTERNAL_ASSERT(PyCode_Check(res));
return (PyCodeObject*)res;
}();
return optimizer_step_code;
}
} // namespace
} // namespace torch::profiler::impl
template <>
struct std::hash<torch::profiler::impl::CodeLocation> {
size_t operator()(const torch::profiler::impl::CodeLocation& x) {
return c10::get_hash(x.filename_, x.name_, x.line_number_);
}
};
namespace torch::profiler::impl {
namespace {
// ============================================================================
// == CallTypeHelper: Tools for generic programming on specializations. =======
// ============================================================================
template <template <CallType> class ClassT>
class CallTypeHelper final {
private:
static_assert(
CallType::PyCall == 0,
"CallTypeHelper uses integer math which depends on a zero start.");
static constexpr size_t End = CallTypeSize;
template <size_t... I>
static constexpr std::tuple<ClassT<(CallType)I>...> make_tuple_impl(
std::index_sequence<I...>);
template <size_t C, typename T, typename FunctorT, typename... Args>
static void map(T& t, FunctorT& f, Args&&... args) {
f(std::get<C>(t), args...);
if constexpr (C + 1 < End) {
map<C + 1>(t, f, std::forward<Args>(args)...);
}
}
public:
using tuple_type = decltype(make_tuple_impl(std::make_index_sequence<End>{}));
template <typename FunctorT, typename... Args>
static void map(tuple_type& t, FunctorT& f, Args&&... args) {
map<0>(t, f, std::forward<Args>(args)...);
}
};
// ============================================================================
// == Event type definitions. =================================================
// ============================================================================
// When we are tracing a Python program, the general procedure is to record
// every time we enter or exit a function and later replay these events during
// post processing. Thus, during the profiling phase we want to do the MINIMAL
// amount of work to capture all of the information that we need; otherwise we
// will distort the profile. (While we don't wish to be terribly inefficient
// during post processing, we are willing to do extra fixup work in post if it
// reduces overhead in the profiling phase.)
//
// When the tracer first enters a frame, it constructs a CallKey for that
// location. The contents of the key vary by context. For a python function
// the key is the (PyCodeObject*, int) pair that defines the bytecode of the
// function. For an `nn.Module` the key is a (non-owning) pointer to `self`.
// For a bound C function it is a (non-owning) pointer to the bound function.
// A CallKey should be small, inexpensive, and POD.
//
// We then collect a CallKey<CallType::PyCall> for the calling frame for better
// source tracking. This pair is a `Callsite`, and serves as a first level key
// during tracing. We lookup the Callsite in a thread local cache which maps
// Callsite to a unique integer `TraceKey`. On a cache hit, we simply store the
// TraceKey and return. On a cache miss, we use a global value cache to store
// whatever fields we need from the two CallKeys, generate a new TraceKey, and
// update the local cache.
//
// During post processing we:
// 1) Determine the type represented by a TraceKey by checking which
// sub-cache it appears in the thread local cache.
// 2) Look up the pair of CallKeys from the thread local cache.
// 3) Look up the expanded values of each CallKey from the global value cache.
//
// To add a new event type to the cache:
// 1) Add an entry to the `CallType` enum.
// 2) Add a specialization of Config which defined key_t, ephemeral_t and
// cache_t.
// 3) Add a specialization of ValueCache::store and ValueCache::load.
//
// -------------------------
// -- Ephemeral arguments --
// -------------------------
// The value cache mechanism assumes that `key_t` is enough to specify the
// correct value. However it may not be possible to materialize a value using
// only an instance of `key_t`. As a result, the cache also accepts "ephemeral"
// inputs which can be used to populate the value cache. Ephemeral inputs come
// with two caveats:
// 1) They are NOT safe to save, and cannot be used after `ValueCache::store`.
// 2) They should be used to access data that is not expect to change from
// call to call, such as the name of a function.
template <CallType>
struct Config;
template <>
struct Config<CallType::PyCall> {
using key_t = CodeLocation;
using ephemeral_t = no_ephemeral_t;
using cache_t = ska::flat_hash_map<key_t, PyFrameState>;
static constexpr EventType event_type = EventType::PyCall;
};
template <typename Key, typename Cls, typename ParameterInfo>
struct ExtendedPyCallConfig {
using key_t = Key;
using cls_t = Cls;
using ephemeral_t = PyFrameObject*;
struct ClsAndParameters {
cls_t cls_;
std::vector<ParameterInfo> parameters_;
};
struct Cache {
// `nn.Module.forward` or `optim.Optimizer._optimizer_step_code`
std::optional<CodeLocation> location_;
ska::flat_hash_map<key_t, ClsAndParameters> cls_and_parameters_;
ska::flat_hash_map<cls_t, at::StringView> cls_names_;
};
using cache_t = Cache;
static constexpr EventType event_type = EventType::PyCall;
};
template <>
struct Config<CallType::PyModuleCall> : ExtendedPyCallConfig<
PyModuleSelf,
PyModuleCls,
NNModuleInfo::ParameterInfo> {};
template <>
struct Config<CallType::PyOptimizerCall> : ExtendedPyCallConfig<
PyOptimizerSelf,
PyOptimizerCls,
OptimizerInfo::ParameterInfo> {};
template <>
struct Config<CallType::PyCCall> {
using key_t = PyMethod;
using ephemeral_t = PyObject*;
using cache_t = ska::flat_hash_map<key_t, at::StringView>;
static constexpr EventType event_type = EventType::PyCCall;
};
// ============================================================================
// == Callsite & ValueCache: Storage during profiling =========================
// ============================================================================
template <CallType C>
class Callsite {
public:
static constexpr CallType call_type = C;
using key_t = typename Config<C>::key_t;
static_assert(
std::is_trivially_copyable_v<key_t>,
"Key should be trivial, as it is passed by value.");
template <typename U>
Callsite(U value, PyFrameObject* f_back) : value_(value), caller_(f_back) {}
bool operator==(const Callsite<C>& other) const {
return value_ == other.value_ && caller_ == other.caller_;
}
key_t value_;
Config<CallType::PyCall>::key_t caller_;
};
// ============================================================================
// == Type specific store and load implementations. ===========================
// ============================================================================
using PyCallKey = Config<CallType::PyCall>::key_t;
using PyModuleCallKey = Config<CallType::PyModuleCall>::key_t;
using PyCCallKey = Config<CallType::PyCCall>::key_t;
using PyOptimizerCallKey = Config<CallType::PyOptimizerCall>::key_t;
class ValueCache {
public:
ValueCache() = default;
ValueCache(const ValueCache&) = delete;
ValueCache& operator==(const ValueCache&) = delete;
ValueCache(ValueCache&&) = default;
ValueCache& operator==(ValueCache&&) = delete;
~ValueCache() = default;
template <CallType C>
void store(const typename Config<C>::key_t&, typename Config<C>::ephemeral_t);
template <CallType C>
auto load(const Callsite<C>& callsite, size_t python_tid) const {
auto caller = load<CallType::PyCall>(callsite.caller_);
TORCH_INTERNAL_ASSERT(!caller.module_info_.has_value());
return ExtraFields<Config<C>::event_type>{
/*end_time_ns=*/std::numeric_limits<c10::time_t>::min(),
python_tid,
caller.frame_state_,
load<C>(callsite.value_)};
}
std::optional<TensorMetadata> recordIfTensor(py::handle p);
std::vector<std::pair<std::string, TensorMetadata>> unpackTensorMap(
const py::dict& tensor_map);
void trimPrefixes();
private:
template <CallType C>
typename ExtraFields<Config<C>::event_type>::args_t load(
const typename Config<C>::key_t&) const;
template <CallType C>
using State = typename Config<C>::cache_t;
CallTypeHelper<State>::tuple_type state_;
};
template <CallType C>
typename Config<C>::cls_t set_class(
ValueCache* value_cache,
typename Config<C>::cache_t& cache,
const typename Config<C>::key_t& key,
const typename Config<C>::ephemeral_t& frame) {
if (C10_UNLIKELY(!cache.location_.has_value())) {
auto code = THPCodeObjectPtr(PyFrame_GetCode(frame));
TORCH_INTERNAL_ASSERT(code.get() == getCode<C>());
cache.location_ = PyCallKey(frame);
value_cache->store<CallType::PyCall>(*cache.location_, no_ephemeral_t());
}
auto cls_handle = py::handle((PyObject*)key).attr("__class__");
auto cls = typename Config<C>::cls_t(cls_handle.ptr());
if (cache.cls_names_.find(cls) == cache.cls_names_.end()) {
cache.cls_names_[cls] =
at::StringView(py::str(cls_handle.attr("__name__")));
}
return cls;
}
TensorMetadata toTensorMetadata(PyObject* self) {
TORCH_INTERNAL_ASSERT(THPVariable_CheckExact(self));
const auto& t = THPVariable_Unpack(self);
RawTensorMetadata m{t};
return TensorMetadata{
m,
t.sizes().vec(),
m.layout_ == at::kStrided ? t.strides().vec() : std::vector<int64_t>()};
}
std::optional<TensorMetadata> ValueCache::recordIfTensor(py::handle p) {
return THPVariable_CheckExact(p.ptr())
? std::optional<TensorMetadata>{toTensorMetadata(p.ptr())}
: std::nullopt;
}
std::vector<std::pair<std::string, TensorMetadata>> ValueCache::unpackTensorMap(
const py::dict& tensor_map) {
std::vector<std::pair<std::string, TensorMetadata>> out;
for (auto& it : tensor_map) {
auto* value = it.second.ptr();
if (py::isinstance<py::str>(it.first) && THPVariable_CheckExact(value)) {
out.emplace_back(
py::cast<std::string>(it.first), toTensorMetadata(value));
}
}
return out;
}
template <>
void ValueCache::store<CallType::PyCall>(
const PyCallKey& key,
no_ephemeral_t /*unused*/) {
auto& locations = std::get<CallType::PyCall>(state_);
if (C10_UNLIKELY(locations.find(key) == locations.end())) {
locations[key] = {
key.line_number_,
at::StringView(key.filename_),
at::StringView(key.name_)};
}
}
template <>
ExtraFields<EventType::PyCall>::args_t ValueCache::load<CallType::PyCall>(
const PyCallKey& key) const {
return {std::get<CallType::PyCall>(state_).at(key), std::nullopt};
}
template <>
void ValueCache::store<CallType::PyModuleCall>(
const PyModuleCallKey& key,
Config<CallType::PyModuleCall>::ephemeral_t frame) {
auto& cache = std::get<CallType::PyModuleCall>(state_);
if (C10_UNLIKELY(
cache.cls_and_parameters_.find(key) ==
cache.cls_and_parameters_.end())) {
auto cls = set_class<CallType::PyModuleCall>(this, cache, key, frame);
py::dict params = py::handle((PyObject*)key).attr("_parameters");
std::vector<NNModuleInfo::ParameterInfo> params_;
for (auto& it : params) {
auto* p = it.second.ptr();
if (py::isinstance<py::str>(it.first) && THPVariable_CheckExact(p)) {
params_.push_back(
{it.first.cast<std::string>(),
toTensorMetadata(p),
recordIfTensor(py::getattr(it.second, "grad", py::none()))});
}
}
cache.cls_and_parameters_[key] = {cls, std::move(params_)};
}
}
template <>
ExtraFields<EventType::PyCall>::args_t ValueCache::load<CallType::PyModuleCall>(
const PyModuleCallKey& key) const {
auto& cache = std::get<CallType::PyModuleCall>(state_);
TORCH_INTERNAL_ASSERT(cache.location_.has_value());
const auto& cls_and_parameters = cache.cls_and_parameters_.at(key);
const auto& cls = cls_and_parameters.cls_;
NNModuleInfo info{
key, cls, cache.cls_names_.at(cls), cls_and_parameters.parameters_};
return {
/*frame_state_=*/std::get<CallType::PyCall>(state_).at(*cache.location_),
/*module_info_=*/std::move(info),
/*optimizer_info_=*/std::nullopt};
}
template <>
void ValueCache::store<CallType::PyOptimizerCall>(
const PyOptimizerCallKey& key,
Config<CallType::PyOptimizerCall>::ephemeral_t frame) {
auto& cache = std::get<CallType::PyOptimizerCall>(state_);
if (C10_UNLIKELY(
cache.cls_and_parameters_.find(key) ==
cache.cls_and_parameters_.end())) {
auto cls = set_class<CallType::PyOptimizerCall>(this, cache, key, frame);
const py::handle self{(PyObject*)key};
std::vector<OptimizerInfo::ParameterInfo> params;
for (const auto& i : (py::list)self.attr("param_groups")) {
for (auto& param : py::cast<py::dict>(i).attr("get")("params")) {
if (THPVariable_CheckExact(param.ptr())) {
// While `self.state` is permitted to store data in an arbitrary way,
// all generic optimizers (SGD, Adam, etc) use param as the key since
// the state in question is tied to particular parameters. We can
// relax this assumption if the need arises.
params.push_back(
{toTensorMetadata(param.ptr()),
recordIfTensor(py::getattr(param, "grad", py::none())),
unpackTensorMap(py::cast<py::dict>(self.attr("state"))
.attr("get")(param, py::dict()))});
}
}
}
cache.cls_and_parameters_[key] = {cls, std::move(params)};
}
}
template <>
ExtraFields<EventType::PyCall>::args_t ValueCache::load<
CallType::PyOptimizerCall>(const PyOptimizerCallKey& key) const {
auto& cache = std::get<CallType::PyOptimizerCall>(state_);
const auto& cls_and_parameters = cache.cls_and_parameters_.at(key);
auto cls = cls_and_parameters.cls_;
OptimizerInfo info{
key, cls, cache.cls_names_.at(cls), cls_and_parameters.parameters_};
return {
/*frame_state_=*/std::get<CallType::PyCall>(state_).at(
// NOLINTNEXTLINE(bugprone-unchecked-optional-access)
cache.location_.value()),
/*module_info_=*/std::nullopt,
/*optimizer_info_=*/std::move(info)};
}
template <>
void ValueCache::store<CallType::PyCCall>(
const PyCCallKey& key,
Config<CallType::PyCCall>::ephemeral_t arg) {
auto& names = std::get<CallType::PyCCall>(state_);
if (C10_UNLIKELY(names.find(key) == names.end())) {
names[key] = at::StringView(py::repr(arg));
}
}
template <>
ExtraFields<EventType::PyCCall>::args_t ValueCache::load<CallType::PyCCall>(
const PyCCallKey& key) const {
return std::get<CallType::PyCCall>(state_).at(key);
}
// TODO: Use re2.
void ValueCache::trimPrefixes() {
static const auto prefixes = []() {
pybind11::gil_scoped_acquire gil;
return py::module::import("torch.profiler.python_tracer")
.attr("_prefix_regex")()
.cast<std::vector<std::string>>();
}();
for (auto& it : std::get<CallType::PyCall>(state_)) {
std::string filename = it.second.filename_.str();
for (const auto& p : prefixes) {
if (filename.compare(0, p.size(), p) == 0) {
filename.erase(0, p.size());
it.second.filename_ = at::StringView(filename);
break;
}
}
}
}
// ============================================================================
// == TraceKey cache ==========================================================
// ============================================================================
using python_tracer::TraceKey;
TraceKey nextKey() {
static std::atomic<uint64_t> key{0};
return TraceKey{++key};
}
template <CallType C>
struct TraceKeyCacheState {
struct Hash {
size_t operator()(const Callsite<C>& key) {
return c10::get_hash(key.value_, key.caller_);
}
};
TraceKey intern(
Callsite<C> callsite,
typename Config<C>::ephemeral_t ephemeral,
ValueCache& value_cache) {
auto it = state_.find(callsite);
if (C10_UNLIKELY(it == state_.end())) {
value_cache.store<C>(callsite.value_, ephemeral);
value_cache.store<CallType::PyCall>(callsite.caller_, no_ephemeral_t());
it = state_.insert({callsite, nextKey()}).first;
}
return it->second;
}
auto lookup(Callsite<C>& callsite, ValueCache& value_cache) const {
return std::make_pair(
value_cache.load<C>(callsite.value_),
value_cache.load<CallType::PyCall>(callsite.caller_));
}
ska::flat_hash_map<Callsite<C>, TraceKey, Hash> state_;
};
// ============================================================================
// == Core CPython data types =================================================
// ============================================================================
// PyObject that allows different threads to record events without colliding.
// It is passed as the second argument when enabling tracing via
// `PyEval_SetProfile`.
struct ThreadLocalResults;
struct TraceContext {
PyObject_HEAD
ThreadLocalResults* thread_local_results_;
};
// CPython boilerplate to define `TraceContext` as a proper python object.
static PyTypeObject TraceContextType = {
PyVarObject_HEAD_INIT(nullptr, 0)
"TraceContext", /* tp_name */
sizeof(TraceContext), /* tp_basicsize */
0, /* tp_itemsize */
nullptr, /* tp_dealloc */
0,
/* tp_vectorcall_offset */
nullptr, /* tp_getattr */
nullptr, /* tp_setattr */
nullptr, /* tp_reserved */
nullptr, /* tp_repr */
nullptr, /* tp_as_number */
nullptr, /* tp_as_sequence */
nullptr, /* tp_as_mapping */
nullptr, /* tp_hash */
nullptr, /* tp_call */
nullptr, /* tp_str */
nullptr, /* tp_getattro */
nullptr, /* tp_setattro */
nullptr, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT, /* tp_flags */
"Python tracer TLS", /* tp_doc */
nullptr, /* tp_traverse */
nullptr, /* tp_clear */
nullptr, /* tp_richcompare */
0, /* tp_weaklistoffset */
nullptr, /* tp_iter */
nullptr, /* tp_iternext */
nullptr, /* tp_methods */
nullptr, /* tp_members */
nullptr, /* tp_getset */
nullptr, /* tp_base */
nullptr, /* tp_dict */
nullptr, /* tp_descr_get */
nullptr, /* tp_descr_set */
0, /* tp_dictoffset */
nullptr, /* tp_init */
nullptr, /* tp_alloc */
PyType_GenericNew, /* tp_new */
nullptr /* tp_free */
};
class gil_and_restore_thread {
public:
gil_and_restore_thread() : initial_thread_state_{PyThreadState_Get()} {}
~gil_and_restore_thread() {
PyThreadState_Swap(initial_thread_state_);
// `gil_scoped_acquire` is a bit fragile in on-demand mode:
// https://github.com/pytorch/pytorch/pull/91684#issuecomment-1413154458
if (!Py_IsInitialized()) {
gil_.disarm();
}
}
PyThreadState* initial_thread_state() const {
return initial_thread_state_;
}
private:
pybind11::gil_scoped_acquire gil_;
PyThreadState* initial_thread_state_;
};
// ============================================================================
// == Thread local cache ======================================================
// ============================================================================
class PythonTracer;
struct ThreadLocalResults {
ThreadLocalResults(
PyThreadState* thread_state,
ValueCache* value_cache,
PythonTracer* active_tracer)
: thread_state_{thread_state},
ctx_{(TraceContext*)TraceContextType.tp_alloc(&TraceContextType, 0)},
value_cache_{value_cache},
active_tracer_{active_tracer} {
ctx_->thread_local_results_ = this;
}
ThreadLocalResults() = delete;
ThreadLocalResults(const ThreadLocalResults&) = delete;
ThreadLocalResults(ThreadLocalResults&&) = delete;
ThreadLocalResults& operator=(const ThreadLocalResults&) = delete;
ThreadLocalResults& operator=(const ThreadLocalResults&&) = delete;
~ThreadLocalResults() {
// Currently, there is a bug in Profiler when using Python 3.12 that causes
// a segfault when decrementing the refcount of a TraceContext during
// on-demand. We are purposefully allowing for a small leak in this
// situation to avoid the segfault. This should be fixed in the future.
#if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 12)
Py_DECREF((PyObject*)ctx_);
#endif
}
template <CallType C, EventType E, typename Ephemeral, typename... Args>
TraceKey intern(Ephemeral ephemeral, Args... args) {
static_assert(
Config<C>::event_type == E,
"ThreadLocalResults.intern called from the wrong typed context.");
auto callsite = Callsite<C>(std::forward<Args>(args)...);
return std::get<C>(trace_keys_).intern(callsite, ephemeral, *value_cache_);
}
static constexpr size_t BLOCK_SIZE = 1024;
PyThreadState* thread_state_;
TraceContext* ctx_;
ValueCache* value_cache_;
PythonTracer* active_tracer_;
CallTypeHelper<TraceKeyCacheState>::tuple_type trace_keys_;
AppendOnlyList<c10::approx_time_t, BLOCK_SIZE> exit_times_;
AppendOnlyList<c10::approx_time_t, BLOCK_SIZE> c_exit_times_;
int active_frames_{0};
int remaining_start_frames_{0};
};
// ============================================================================
// == Tracing implementation ==================================================
// ============================================================================
#define IS_PYTHON_3_12 (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 12)
#if IS_PYTHON_3_12
// forward declarations
struct _PyEventHandler;
static PyObject* c_call_callback(
_PyEventHandler* self,
PyObject* const* args,
size_t nargsf,
PyObject* kwnames);
#endif
class PythonTracer final : public python_tracer::PythonTracerBase {
public:
PythonTracer(torch::profiler::impl::RecordQueue* queue);
// NOLINTNEXTLINE(bugprone-exception-escape)
~PythonTracer() override;
static int pyProfileFn(
PyObject* obj,
PyFrameObject* frame,
int what,
PyObject* arg);
void register_gc_callback() override;
void stop() override;
void restart() override;
std::vector<std::shared_ptr<Result>> getEvents(
std::function<c10::time_t(c10::approx_time_t)> time_converter,
std::vector<python_tracer::CompressedEvent>& enters,
c10::time_t end_time_ns) override;
struct StartFrame {
TraceKey trace_key_;
c10::approx_time_t start_time{};
};
private:
void recordPyCall(
ThreadLocalResults& tls,
PyFrameObject* frame,
bool is_startup_frame);
static PyObject* gc_event_callback(PyObject* self, PyObject* args);
void recordCCall(
ThreadLocalResults& tls,
PyFrameObject* frame,
PyObject* arg,
bool start_frame = false);
const std::vector<PyThreadState*> interpreterThreads() const;
std::atomic<bool> active_lock_{false};
bool active_{false};
bool gc_callback_registered_{false};
torch::profiler::impl::RecordQueue* queue_;
PyInterpreterState* interpreter_{nullptr};
PyCodeObject* module_call_code_;
PyCodeObject* optimizer_hook_;
std::vector<StartFrame> start_frames_;
std::deque<ThreadLocalResults> thread_local_results_;
ValueCache value_cache_;
#if IS_PYTHON_3_12
friend PyObject* c_call_callback(
_PyEventHandler* self,
PyObject* const* args,
size_t nargsf,
PyObject* kwnames);
#endif
};
#if IS_PYTHON_3_12
#define PROFILER_ID 2
#define PY_MONITORING_EVENT_CALL 4
static bool should_compensate_c_call_events() {
static const bool result = []() {
const char* version = Py_GetVersion();
const char micro = version[5];
return micro == '0' || (micro <= '4' && version[6] == ' ');
}();
return result;
}
struct _PyEventHandler {
PyObject_HEAD
vectorcallfunc vectorcall;
};
static PyTypeObject _PyEventHandler_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0) /* ob_base */
"torch.profiler.python_tracer_event_handler", /* tp_name */
sizeof(_PyEventHandler), /* tp_basicsize */
0, /* tp_itemsize */
(destructor)PyObject_Free, /* tp_dealloc */
offsetof(_PyEventHandler, vectorcall), /* tp_vectorcall_offset */
nullptr, /* tp_getattr */
nullptr, /* tp_setattr */
nullptr, /* tp_reserved */
nullptr, /* tp_repr */
nullptr, /* tp_as_number */
nullptr, /* tp_as_sequence */
nullptr, /* tp_as_mapping */
nullptr, /* tp_hash */
PyVectorcall_Call, /* tp_call */
nullptr, /* tp_str */
nullptr, /* tp_getattro */
nullptr, /* tp_setattro */
nullptr, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_VECTORCALL |
Py_TPFLAGS_DISALLOW_INSTANTIATION, /* tp_flags */
};
static PyObject* c_call_callback(
_PyEventHandler* self,
PyObject* const* args,
size_t nargsf,
PyObject* kwnames) {
// The logic of this function is based on sys_defile_call_or_return defined
// in https://github.com/python/cpython/blob/v3.12.5/Python/legacy_tracing.c
PyThreadState* tstate = PyThreadState_GET();
if (tstate->c_profilefunc != PythonTracer::pyProfileFn) {
// We don't care this case if tstate->c_profilefunc is not pyProfileFn,
// just return normally.
Py_RETURN_NONE;
}
PyObject* callable = args[2];
if (Py_TYPE(callable) == &PyMethod_Type) {
// The call event of a method with c function is missing on 3.12.0-3.12.4.
// See
// https://github.com/python/cpython/commit/257c413cd16ddabcedde413288d0bb93bf872da7
// Other cases have already be handled by the legacy_tracing, so we only
// need to handle this case.
// The exception branches keep the same behavior as CPython.
PyObject* func = PyMethod_GET_FUNCTION(callable);
if (!func) {
return NULL;
}
if (PyCFunction_Check(func)) {
PyFrameObject* frame = PyEval_GetFrame();
if (!frame) {
PyErr_SetString(
PyExc_SystemError, "Missing frame when calling profile function.");
return NULL;
}
Py_INCREF(frame);
auto& local_results =
*reinterpret_cast<TraceContext*>(tstate->c_profileobj)
->thread_local_results_;
local_results.active_tracer_->recordCCall(local_results, frame, func);
Py_DECREF(frame);
}
}
Py_RETURN_NONE;
}
static void registerMonitoringCallback() {
if (!should_compensate_c_call_events()) {
return;
}
auto sys_module = THPObjectPtr(PyImport_ImportModule("sys"));
if (!sys_module) {
TORCH_WARN("Failed to import sys module.");
PyErr_Clear();
return;
}
auto monitoring =
THPObjectPtr(PyObject_GetAttrString(sys_module, "monitoring"));
if (!monitoring) {
TORCH_WARN("Failed to get monitoring from sys module.");
PyErr_Clear();
return;
}
auto result = THPObjectPtr(PyObject_CallMethod(
monitoring, "use_tool_id", "is", PROFILER_ID, "PyTorch Profiler"));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.use_tool_id");
PyErr_Clear();
return;
}
auto handler = THPObjectPtr(PyObject_NEW(PyObject, &_PyEventHandler_Type));
if (!handler) {
TORCH_WARN("Failed to create _PyEventHandler object.");
PyErr_Clear();
return;
}
reinterpret_cast<_PyEventHandler*>(handler.get())->vectorcall =
(vectorcallfunc)c_call_callback;
result = THPObjectPtr(PyObject_CallMethod(
monitoring,
"register_callback",
"iiO",
PROFILER_ID,
1 << PY_MONITORING_EVENT_CALL,
handler.get()));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.register_callback.");
PyErr_Clear();
return;
}
result = THPObjectPtr(PyObject_CallMethod(
monitoring,
"set_events",
"ii",
PROFILER_ID,
1 << PY_MONITORING_EVENT_CALL));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.set_events.");
PyErr_Clear();
return;
}
}
static void unregisterMonitoringCallback() {
if (!should_compensate_c_call_events()) {
return;
}
auto sys_module = THPObjectPtr(PyImport_ImportModule("sys"));
if (!sys_module) {
TORCH_WARN("Failed to import sys module.");
PyErr_Clear();
return;
}
auto monitoring =
THPObjectPtr(PyObject_GetAttrString(sys_module, "monitoring"));
if (!monitoring) {
TORCH_WARN("Failed to get monitoring from sys module.");
PyErr_Clear();
return;
}
auto tool_name = THPObjectPtr(
PyObject_CallMethod(monitoring, "get_tool", "i", PROFILER_ID));
if (!tool_name) {
TORCH_WARN("Failed to call sys.monitoring.use_tool_id");
PyErr_Clear();
return;
}
if (!THPUtils_checkString(tool_name)) {
return;
}
const char* str = THPUtils_unpackStringView(tool_name).data();
if (strcmp(str, "PyTorch Profiler") != 0) {
return;
}
auto none = THPObjectPtr(Py_None);
Py_INCREF(Py_None);
auto result = THPObjectPtr(PyObject_CallMethod(
monitoring,
"register_callback",
"iiO",
PROFILER_ID,
1 << PY_MONITORING_EVENT_CALL,
none.get()));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.register_callback.");
PyErr_Clear();
return;
}
result = THPObjectPtr(
PyObject_CallMethod(monitoring, "set_events", "ii", PROFILER_ID, 0));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.set_events.");
PyErr_Clear();
return;
}
result = THPObjectPtr(
PyObject_CallMethod(monitoring, "free_tool_id", "i", PROFILER_ID));
if (!result) {
TORCH_WARN("Failed to call sys.monitoring.free_tool_id.");
PyErr_Clear();
return;
}
}
#endif
const std::vector<PyThreadState*> PythonTracer::interpreterThreads() const {
pybind11::gil_scoped_acquire gil;
std::vector<PyThreadState*> out;
if (SOFT_ASSERT(interpreter_)) {
auto* thread_state = PyInterpreterState_ThreadHead(interpreter_);
while (thread_state != nullptr) {
out.push_back(thread_state);
thread_state = PyThreadState_Next(thread_state);
}
}
return out;
}
// we are only registering on main thread while holding GIL so this should be
// safe
static PyObject* py_gc_callback = nullptr;
// The C function to be called by Python's GC
PyObject* PythonTracer::gc_event_callback(PyObject* self, PyObject* args) {
const char* phase;
PyObject* info;
if (!PyArg_ParseTuple(args, "sO", &phase, &info)) {
return nullptr;
}
PythonTracer* instance =
reinterpret_cast<PythonTracer*>(PyCapsule_GetPointer(self, nullptr));
if (!instance) {
PyErr_SetString(PyExc_RuntimeError, "Invalid tracer instance");
return nullptr;
}
instance->queue_->getSubqueue()->emplace_gc_call(
phase, c10::getApproximateTime());
Py_RETURN_NONE;
}