From 0351e2042b62f828f5adb3d553cfa9a92e8616c5 Mon Sep 17 00:00:00 2001 From: "Edward Z. Yang" Date: Wed, 20 Sep 2023 20:29:54 -0400 Subject: [PATCH] Avoid throwing exception in ClosingTHPObjectPtr (#109758) Previously, if ClosingTHPObjectPtr was destructed because we were unwinding the stack from an exception, we would attempt to call close() which just isn't going to work. Two fixes: 1. Detect if we're unwinding due to a Python error, and don't try to do more Python stuff if so. 2. If close() fails somehow, write an unraisable exception, don't try to throw because that will terminate if you're in an exception. Signed-off-by: Edward Z. Yang Pull Request resolved: https://github.com/pytorch/pytorch/pull/109758 Approved by: https://github.com/jansel --- torch/csrc/dynamo/python_compiled_autograd.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/torch/csrc/dynamo/python_compiled_autograd.cpp b/torch/csrc/dynamo/python_compiled_autograd.cpp index 76ec16dc534f90..190caeefd5af65 100644 --- a/torch/csrc/dynamo/python_compiled_autograd.cpp +++ b/torch/csrc/dynamo/python_compiled_autograd.cpp @@ -290,8 +290,15 @@ static PyObject* call_end_capture(PyObject* self, const variable_list& inputs) { struct ClosingTHPObjectPtr : public THPObjectPtr { ClosingTHPObjectPtr(PyObject* o) : THPObjectPtr(o) {} ~ClosingTHPObjectPtr() { + if (PyErr_Occurred()) { + // do nothing, do not attempt to close + return; + } static PyObject* method_name = PyUnicode_InternFromString("close"); - check(PyObject_CallMethodNoArgs(get(), method_name)); + if (PyObject_CallMethodNoArgs(get(), method_name) == nullptr) { + PyErr_WriteUnraisable(get()); + PyErr_Clear(); + } } };