Skip to content

Commit 11f5f65

Browse files
swolchokpytorchmergebot
authored andcommitted
Use PyObject_GetOptionalAttrString in PyObject_FastGetAttrString when available (#164624)
Python 3.13 added PyObject_GetOptionalAttrString. I'm not 100% certain that it is strictly better than the old approach in all cases, but based on documentation/comments it seems to be meant for this type of use, and it's faster when I profile torchtitan training (which gets to the "check for the `__torch_function__` attr on some object" part of maybe_has_torch_function frequently enough to notice, but wastes a bunch of time generating exceptions that we then suppressed here). Pull Request resolved: #164624 Approved by: https://github.com/Skylion007
1 parent af32d16 commit 11f5f65

File tree

1 file changed

+10
-0
lines changed

1 file changed

+10
-0
lines changed

torch/csrc/utils/python_strings.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
#include <torch/csrc/python_headers.h>
44
#include <torch/csrc/utils/object_ptr.h>
55
#include <torch/csrc/utils/pybind.h>
6+
#include <torch/csrc/utils/python_compat.h>
67
#include <stdexcept>
78
#include <string>
89

@@ -98,6 +99,14 @@ inline void THPUtils_internStringInPlace(PyObject** obj) {
9899
*/
99100

100101
inline py::object PyObject_FastGetAttrString(PyObject* obj, const char* name) {
102+
#if IS_PYTHON_3_13_PLUS
103+
PyObject* res = (PyObject*)nullptr;
104+
int result_code = PyObject_GetOptionalAttrString(obj, name, &res);
105+
if (result_code == -1) {
106+
PyErr_Clear();
107+
}
108+
return py::reinterpret_steal<py::object>(res);
109+
#else
101110
PyTypeObject* tp = Py_TYPE(obj);
102111
PyObject* res = (PyObject*)nullptr;
103112

@@ -122,4 +131,5 @@ inline py::object PyObject_FastGetAttrString(PyObject* obj, const char* name) {
122131
}
123132
}
124133
return py::reinterpret_steal<py::object>(res);
134+
#endif
125135
}

0 commit comments

Comments
 (0)