Repository navigation
Expand file tree
/
Copy pathfast_module_type.cc
More file actions
447 lines (416 loc) · 15.1 KB
/
Copy pathfast_module_type.cc
File metadata and controls
447 lines (416 loc) · 15.1 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
/* 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>
#include <vector>
// 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/base/thread_annotations.h"
#include "absl/container/flat_hash_map.h"
#include "absl/synchronization/mutex.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 ABSL_GUARDED_BY(mutex);
// pointer to the external getattribute function
PyObject *cb_getattribute;
// pointer to the external getattr function
PyObject *cb_getattr;
// mutex to protect attr_map
absl::Mutex mutex;
// 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 *>();
new (&(self->mutex)) absl::Mutex();
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;
}
FastModuleObject* fast_module = FastModuleObject::UncheckedCast(self);
{
absl::MutexLock lock(fast_module->mutex);
for (auto& it : fast_module->attr_map) {
Py_VISIT(it.first);
Py_VISIT(it.second);
}
// Visit the callbacks to ensure the GC tracks them and detects cycles.
Py_VISIT(fast_module->cb_getattribute);
Py_VISIT(fast_module->cb_getattr);
}
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);
if (func == nullptr) return nullptr;
FastModuleObject* fast_module = FastModuleObject::UncheckedCast(self);
PyObject* old_func = nullptr;
{
absl::MutexLock lock(fast_module->mutex);
old_func = fast_module->cb_getattribute;
fast_module->cb_getattribute = func;
}
Py_XDECREF(old_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);
if (func == nullptr) return nullptr;
FastModuleObject* fast_module = FastModuleObject::UncheckedCast(self);
PyObject* old_func = nullptr;
{
absl::MutexLock lock(fast_module->mutex);
old_func = fast_module->cb_getattr;
fast_module->cb_getattr = func;
}
Py_XDECREF(old_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;
}
Py_INCREF(value);
PyObject* to_decref = nullptr;
{
absl::MutexLock lock(self->mutex);
auto& attr_map = self->attr_map;
if (auto [it, inserted] = attr_map.emplace(name, value); inserted) {
Py_INCREF(name);
} else {
to_decref = it->second;
it->second = value;
}
}
Py_XDECREF(to_decref);
// 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;
}
{
absl::MutexLock lock(self->mutex);
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;
}
PyObject* key_to_decref = nullptr;
PyObject* value = nullptr;
{
absl::MutexLock lock(self->mutex);
auto& attr_map = self->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
key_to_decref = it->first;
value = it->second;
attr_map.erase(it);
}
}
if (value) {
Py_DECREF(key_to_decref);
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;
}
bool result;
{
absl::MutexLock lock(self->mutex);
const auto& attr_map = self->attr_map;
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);
{
absl::MutexLock lock(fast_module->mutex);
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;
PyObject* cb_getattribute = nullptr;
{
absl::MutexLock lock(fast_module->mutex);
cb_getattribute = fast_module->cb_getattribute;
Py_XINCREF(cb_getattribute);
}
// Prefer the customized callback function over the default function.
if (cb_getattribute != nullptr) {
result = CallFunc(fast_module, arglist, cb_getattribute);
Py_DECREF(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();
PyObject* cb_getattr = nullptr;
if (is_error && PyErr_ExceptionMatches(PyExc_AttributeError)) {
absl::MutexLock lock(fast_module->mutex);
cb_getattr = fast_module->cb_getattr;
Py_XINCREF(cb_getattr);
}
if (cb_getattr != nullptr) {
PyErr_Clear();
result = CallFunc(fast_module, arglist, cb_getattr);
Py_DECREF(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);
std::vector<std::pair<PyObject*, PyObject*>> items;
{
absl::MutexLock lock(fast_module->mutex);
items.reserve(fast_module->attr_map.size());
for (auto [key, value] : fast_module->attr_map) {
items.push_back({key, value});
}
fast_module->attr_map.~flat_hash_map<PyObject*, PyObject*>();
}
for (auto [key, value] : items) {
Py_DECREF(key);
Py_DECREF(value);
}
fast_module->mutex.~Mutex();
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* fast_module = FastModuleObject::UncheckedCast(module);
PyObject* to_decref = nullptr;
if (value == nullptr) {
PyObject* key_to_decref = nullptr;
{
absl::MutexLock lock(fast_module->mutex);
auto& attr_map = fast_module->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
key_to_decref = it->first;
to_decref = it->second;
attr_map.erase(it);
}
}
Py_XDECREF(key_to_decref);
Py_XDECREF(to_decref);
return PyObject_GenericSetAttr(module, name, value);
}
Py_INCREF(value);
{
absl::MutexLock lock(fast_module->mutex);
auto& attr_map = fast_module->attr_map;
if (auto [it, inserted] = attr_map.emplace(name, value); inserted) {
Py_INCREF(name);
} else {
to_decref = it->second;
it->second = value;
}
}
Py_XDECREF(to_decref);
int status = PyObject_GenericSetAttr(module, name, value);
if (status < 0) {
PyObject* key_to_decref = nullptr;
PyObject* val_to_decref = nullptr;
{
absl::MutexLock lock(fast_module->mutex);
auto& attr_map = fast_module->attr_map;
if (auto it = attr_map.find(name); it != attr_map.end()) {
key_to_decref = it->first;
val_to_decref = it->second;
attr_map.erase(it);
}
}
Py_XDECREF(key_to_decref);
Py_XDECREF(val_to_decref);
}
return status;
};
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);
}