diff --git a/torch/csrc/jit/passes/onnx/shape_type_inference.cpp b/torch/csrc/jit/passes/onnx/shape_type_inference.cpp index 8acdb3ea032e..d8fe34712e6f 100644 --- a/torch/csrc/jit/passes/onnx/shape_type_inference.cpp +++ b/torch/csrc/jit/passes/onnx/shape_type_inference.cpp @@ -2344,8 +2344,8 @@ size_t ONNXAssignOutputShape( // Support for dict data type is limited to fixed size dictionaries in // ONNX. // Dictionary values are unrolled and keys are not preserved. - auto unrolled_dict = - py::reinterpret_borrow(PyDict_Items(output_obj)); + auto* items = PyDict_Items(output_obj); + auto unrolled_dict = py::reinterpret_borrow(items); TORCH_INTERNAL_ASSERT(PyList_Check(unrolled_dict.ptr())); for (const auto i : c10::irange(unrolled_dict.size())) { outputs_index = ONNXAssignOutputShape( @@ -2356,6 +2356,7 @@ size_t ONNXAssignOutputShape( is_script, opset_version); } + Py_DECREF(items); } else if (THPUtils_checkString(output_obj)) { // Ignore string, since they are not supported as output in ONNX. } else if (PyNone_Check(output_obj)) { diff --git a/torch/csrc/jit/python/python_arg_flatten.cpp b/torch/csrc/jit/python/python_arg_flatten.cpp index 248e64c4d792..0856eb392fb3 100644 --- a/torch/csrc/jit/python/python_arg_flatten.cpp +++ b/torch/csrc/jit/python/python_arg_flatten.cpp @@ -55,12 +55,13 @@ void flatten_rec(PyObject* obj, ParsedArgs& args) { flatten_rec(item.ptr(), args); structure.push_back(D::ListClose); } else if (PyDict_Check(obj)) { - auto dict_items = PyDict_Items(obj); + auto* dict_items = PyDict_Items(obj); structure.push_back(D::DictOpen); for (auto item : py::reinterpret_borrow(dict_items)) { flatten_rec(item.ptr(), args); } structure.push_back(D::DictClose); + Py_DECREF(dict_items); } else if (THPUtils_checkString(obj)) { string str = THPUtils_unpackString(obj); args.desc.strings.emplace_back(str);