forked from tensorflow/tensorflow
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfast_module_type.cc
More file actions
343 lines (314 loc) · 12.3 KB
/
Copy pathfast_module_type.cc
File metadata and controls
343 lines (314 loc) · 12.3 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
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
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.
==============================================================================*/
#include <Python.h>
#include <array>
// clang-format off
// These headers must be at the top, before including Python.h header
// Otherwise, we get C2039 on MSVC due to 'copysign'
#include "absl/log/check.h"
#include "pybind11/complex.h" // from @pybind11
#include "pybind11/pybind11.h" // from @pybind11
// clang-format on
#include "absl/container/flat_hash_map.h"
#include "tensorflow/core/platform/logging.h"
namespace py = pybind11;
#ifdef Py_GIL_DISABLED
constexpr int PY_MODULE_TYPE_TP_BASIC_SIZE = 80; // Under Python 3.13t
#else // Py_GIL_DISABLED
constexpr int PY_MODULE_TYPE_TP_BASIC_SIZE = 56;
#endif // Py_GIL_DISABLED
struct FastModuleObject {
// A dummy array that ensures enough size is reserved for FastModuleObject,
// because it's inherited from PyModuleObject.
const std::array<char, PY_MODULE_TYPE_TP_BASIC_SIZE> opaque_base_fields;
// A cache that helps reduce attribute lookup overhead.
absl::flat_hash_map<PyObject *, PyObject *> attr_map;
// pointer to the external getattribute function
PyObject *cb_getattribute;
// pointer to the external getattr function
PyObject *cb_getattr;
// static PyTypeObject type;
FastModuleObject() = delete;
~FastModuleObject() = delete;
static FastModuleObject *UncheckedCast(PyObject *obj);
};
static PyObject *FastModule_new(PyTypeObject *subtype, PyObject *args,
PyObject *kwds) {
DCHECK_EQ(PY_MODULE_TYPE_TP_BASIC_SIZE, PyModule_Type.tp_basicsize);
PyObject *obj = PyModule_Type.tp_new(subtype, args, kwds);
FastModuleObject *self = reinterpret_cast<FastModuleObject *>(obj);
new (&(self->attr_map)) absl::flat_hash_map<PyObject *, PyObject *>();
self->cb_getattribute = nullptr;
self->cb_getattr = nullptr;
return obj;
}
static int FastModule_traverse(PyObject *self, visitproc visit, void *arg) {
if (int super_result = PyModule_Type.tp_traverse(self, visit, arg) != 0) {
return super_result;
}
auto &attr_map = FastModuleObject::UncheckedCast(self)->attr_map;
for (auto &it : attr_map) {
Py_VISIT(it.first);
Py_VISIT(it.second);
}
return 0;
}
// Parses the input as a callable and checks the result.
static PyObject *ParseFunc(PyObject *args) {
PyObject *func;
if (!PyArg_ParseTuple(args, "O:set_callback", &func)) return nullptr;
if (!PyCallable_Check(func)) {
PyErr_SetString(PyExc_TypeError, "input args must be callable");
return nullptr;
}
Py_INCREF(func); // Add a reference to new callback
return func;
}
// Sets the pointer 'cb_getattribute' in the FastModuleObject object
// corresponding to 'self'.
static PyObject *SetGetattributeCallback(PyObject *self, PyObject *args) {
PyObject *func = ParseFunc(args);
// Dispose of previous callback
Py_XDECREF(FastModuleObject::UncheckedCast(self)->cb_getattribute);
// Remember new callback
FastModuleObject::UncheckedCast(self)->cb_getattribute = func;
Py_RETURN_NONE;
}
// Sets the pointer 'cb_getattr' in the FastModuleObject object
// corresponding to 'self'.
static PyObject *SetGetattrCallback(PyObject *self, PyObject *args) {
PyObject *func = ParseFunc(args);
// Dispose of previous callback
Py_XDECREF(FastModuleObject::UncheckedCast(self)->cb_getattr);
// Remember new callback
FastModuleObject::UncheckedCast(self)->cb_getattr = func;
Py_RETURN_NONE;
}
// Inserts or updates a key-value pair in the cache 'attr_map'
// of the FastModuleObject object corresponding to 'self'.
static PyObject *FastDictInsert(FastModuleObject *self, PyObject *args) {
PyObject *name, *value;
if (!PyArg_ParseTuple(args, "OO", &name, &value)) {
PyErr_SetString(PyExc_TypeError, "_fastdict_insert: incorrect inputs");
return nullptr;
}
auto &attr_map = self->attr_map;
Py_INCREF(value);
if (auto [it, inserted] = attr_map.emplace(name, value); inserted) {
Py_INCREF(name);
} else {
Py_DECREF(it->second);
it->second = value;
}
// Properly handle returning Py_None
Py_RETURN_NONE;
}
// Gets a value from a key in the cache 'attr_map'
// of the FastModuleObject object corresponding to 'self'.
static PyObject *FastDictGet(FastModuleObject *self, PyObject *args) {
PyObject *name;
if (!PyArg_ParseTuple(args, "O", &name)) {
PyErr_SetString(PyExc_TypeError, "_fastdict_get: incorrect inputs");
return nullptr;
}
auto &attr_map = self->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
Py_INCREF(it->second);
return it->second;
}
// Copied from CPython's moduleobject.c
PyErr_Format(PyExc_KeyError, "module has no attribute '%U'", name);
return nullptr;
}
// Gets a value from a key in the cache 'attr_map'
// of the FastModuleObject object corresponding to 'self'.
static PyObject *FastDictPop(FastModuleObject *self, PyObject *args) {
PyObject *name;
if (!PyArg_ParseTuple(args, "O", &name)) {
PyErr_SetString(PyExc_TypeError, "_fastdict_pop: incorrect inputs");
return nullptr;
}
auto &attr_map = self->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
Py_DECREF(it->first);
PyObject *value = it->second;
attr_map.erase(it);
return value;
}
// Copied from CPython's moduleobject.c
PyErr_Format(PyExc_KeyError, "module has no attribute '%U'", name);
return nullptr;
}
// Returns true if a key exists in the cache 'attr_map'
// of the FastModuleObject object corresponding to 'self',
// otherwise returns false.
static PyObject *FastDictContains(FastModuleObject *self, PyObject *args) {
PyObject *name;
if (!PyArg_ParseTuple(args, "O", &name)) {
PyErr_SetString(PyExc_TypeError, "_fastdict_key_in: incorrect inputs");
return nullptr;
}
const auto &attr_map = self->attr_map;
const auto result = attr_map.contains(name);
if (result) {
// Properly handle returning Py_True
Py_RETURN_TRUE;
}
// Properly handle returning Py_False
Py_RETURN_FALSE;
}
// Calls a function 'func' with inputs 'self' and 'args'.
static PyObject *CallFunc(FastModuleObject *self, PyObject *args,
PyObject *func) {
if (func == nullptr) {
PyErr_SetString(PyExc_NameError,
"Attempting to call a callback that was not defined");
return nullptr;
}
PyObject *name;
if (!PyArg_ParseTuple(args, "O", &name)) {
PyErr_SetString(PyExc_TypeError, "CallFunc: incorrect inputs");
return nullptr;
}
PyObject *arglist = Py_BuildValue("(OO)", self, name);
auto result = PyObject_CallObject(func, arglist);
Py_DECREF(arglist);
return result;
}
static PyMethodDef FastModule_methods[] = {
{"_fastdict_insert", reinterpret_cast<PyCFunction>(FastDictInsert),
METH_VARARGS, "Registers a method to the fast lookup table."},
{"_fastdict_get", reinterpret_cast<PyCFunction>(FastDictGet), METH_VARARGS,
"Gets a method from the fast lookup table."},
{"_fastdict_pop", reinterpret_cast<PyCFunction>(FastDictPop), METH_VARARGS,
"Removes a method in the fast lookup table."},
{"_fastdict_key_in", reinterpret_cast<PyCFunction>(FastDictContains),
METH_VARARGS, "Checks if a method exists in the fast lookup table."},
{"set_getattribute_callback", SetGetattributeCallback, METH_VARARGS,
"Defines the callback function to replace __getattribute__"},
{"set_getattr_callback", SetGetattrCallback, METH_VARARGS,
"Defines the callback function to replace __getattr__"},
{nullptr, nullptr, 0, nullptr},
};
// Attempts to get the attribute based on 'name' as the key in cache 'attr_map'
// of the FastModuleObject object corresponding to 'module'.
// If the lookup fails in the cache, either uses
// a user-defined callback 'cb_getattribute'
// or the default 'tp_getattro' function to look for the attribute.
static PyObject *FastTpGetattro(PyObject *module, PyObject *name) {
FastModuleObject *fast_module = FastModuleObject::UncheckedCast(module);
auto &attr_map = fast_module->attr_map;
// If the attribute lookup is successful in the cache, directly return it.
if (auto it = attr_map.find(name); it != attr_map.end()) {
PyObject *value = it->second;
Py_INCREF(value);
return value;
}
PyObject *arglist = Py_BuildValue("(O)", name);
PyObject *result;
// Prefer the customized callback function over the default function.
if (fast_module->cb_getattribute != nullptr) {
result = CallFunc(fast_module, arglist, fast_module->cb_getattribute);
} else {
result = PyModule_Type.tp_getattro(module, name);
}
// Return result if it's found
if (result != nullptr) {
Py_DECREF(arglist);
return result;
}
// If the default lookup fails and an AttributeError is raised,
// clear the error status before using the __getattr__ callback function.
auto is_error = PyErr_Occurred();
if (is_error && PyErr_ExceptionMatches(PyExc_AttributeError) &&
fast_module->cb_getattr != nullptr) {
PyErr_Clear();
result = CallFunc(fast_module, arglist, fast_module->cb_getattr);
}
// If all options were used up
Py_DECREF(arglist);
return result;
}
// Customized destructor for FastModuleType.tp_dealloc
// In addition to default behavior it also clears up the contents in attr_map.
static void FastModuleObjectDealloc(PyObject *module) {
FastModuleObject *fast_module = FastModuleObject::UncheckedCast(module);
for (auto [key, value] : fast_module->attr_map) {
Py_DECREF(key);
Py_DECREF(value);
}
fast_module->attr_map.~flat_hash_map<PyObject *, PyObject *>();
Py_XDECREF(fast_module->cb_getattribute);
Py_XDECREF(fast_module->cb_getattr);
Py_TYPE(module)->tp_free(module);
}
static PyTypeObject FastModuleType = []() {
PyTypeObject obj = {PyVarObject_HEAD_INIT(&PyType_Type, 0)};
obj.tp_name = "fast_module_type.FastModuleType";
obj.tp_basicsize = sizeof(FastModuleObject);
obj.tp_itemsize = 0;
obj.tp_dealloc = FastModuleObjectDealloc;
obj.tp_getattro = FastTpGetattro;
obj.tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC;
obj.tp_doc = "FastModuleType objects";
obj.tp_methods = FastModule_methods;
obj.tp_traverse = reinterpret_cast<traverseproc>(FastModule_traverse);
obj.tp_new = reinterpret_cast<newfunc>(FastModule_new);
return obj;
}();
// Returns true if the type of 'obj' or any of its parent class
// is equal to 'target'. Otherwise returns false.
bool IsAnyBaseSameType(const PyObject *obj, const PyTypeObject *target) {
auto *tp = Py_TYPE(obj);
while (true) {
if (tp == target) return true;
// If the default type is found, there is no need to search further
if (tp == &PyBaseObject_Type) break;
tp = tp->tp_base;
}
return false;
}
// Casts 'obj' to 'FastModuleObject *'.
// Conducts a check only in non-optimized builds.
FastModuleObject *FastModuleObject::UncheckedCast(PyObject *obj) {
DCHECK(IsAnyBaseSameType(obj, &FastModuleType));
return reinterpret_cast<FastModuleObject *>(obj);
}
PYBIND11_MODULE(fast_module_type, m) {
FastModuleType.tp_base = &PyModule_Type;
FastModuleType.tp_setattro = [](PyObject *module, PyObject *name,
PyObject *value) -> int {
auto &attr_map = FastModuleObject::UncheckedCast(module)->attr_map;
Py_INCREF(value);
if (auto [it, inserted] = attr_map.emplace(name, value); inserted) {
Py_INCREF(name);
} else {
Py_DECREF(it->second);
it->second = value;
}
PyObject_GenericSetAttr(module, name, value);
return 0;
};
m.doc() = R"pbdoc(
fast_module_type
-----
)pbdoc";
// Use getter function to hold attributes rather than pybind11's m.attr due to
// b/145559202.
m.def(
"get_fast_module_type_class",
[]() {
return py::cast<py::object>(
reinterpret_cast<PyObject *>(&FastModuleType));
},
py::return_value_policy::reference);
}