forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSavedTensorHooks.cpp
82 lines (65 loc) · 2.39 KB
/
SavedTensorHooks.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
#include <ATen/SavedTensorHooks.h>
#include <c10/util/Exception.h>
#include <stack>
namespace at {
namespace {
thread_local impl::SavedTensorDefaultHooksTLS tls;
// This flag is set to true the first time default hooks are registered
// and left at true for the rest of the execution.
// It's an optimization so that users who never use default hooks don't need to
// read the thread_local variables pack_hook_ and unpack_hook_.
static bool is_initialized(false);
}
static void assertSavedTensorHooksNotDisabled() {
TORCH_CHECK(SavedTensorDefaultHooks::is_enabled(), tls.disabled_error_message.value());
}
bool SavedTensorDefaultHooks::is_enabled() {
// See NOTE: [disabled_error_message invariant]
return !tls.disabled_error_message.has_value();
}
void SavedTensorDefaultHooks::disable(const std::string& message) {
tls.disabled_error_message = message;
if (tls.stack.size() > 0) {
assertSavedTensorHooksNotDisabled();
}
}
void SavedTensorDefaultHooks::enable() {
tls.disabled_error_message = c10::nullopt;
}
const c10::optional<std::string>& SavedTensorDefaultHooks::get_disabled_error_message() {
return tls.disabled_error_message;
}
const impl::SavedTensorDefaultHooksTLS& SavedTensorDefaultHooks::get_tls_state() {
return tls;
}
void SavedTensorDefaultHooks::set_tls_state(const impl::SavedTensorDefaultHooksTLS& state) {
tls = state;
}
void SavedTensorDefaultHooks::lazy_initialize() {
is_initialized = true;
}
void SavedTensorDefaultHooks::push_hooks(PyObject* pack_hook, PyObject* unpack_hook) {
// Reference counting is handled by the caller of `push_hooks`
TORCH_INTERNAL_ASSERT(is_initialized);
TORCH_INTERNAL_ASSERT(pack_hook != nullptr && unpack_hook != nullptr);
assertSavedTensorHooksNotDisabled();
tls.stack.push(std::make_pair(pack_hook, unpack_hook));
}
void SavedTensorDefaultHooks::pop_hooks() {
// Reference counting is handled by the caller of `pop_hooks`
TORCH_INTERNAL_ASSERT(is_initialized && !tls.stack.empty());
tls.stack.pop();
}
std::pair<PyObject*, PyObject*> SavedTensorDefaultHooks::get_hooks() {
if (!is_initialized || tls.stack.empty()) {
return std::make_pair(nullptr, nullptr);
}
return tls.stack.top();
}
std::stack<std::pair<PyObject*, PyObject*>> SavedTensorDefaultHooks::get_stack() {
return tls.stack;
}
void SavedTensorDefaultHooks::set_stack(std::stack<std::pair<PyObject*, PyObject*>> stack_) {
tls.stack = stack_;
}
}