Caffe2 - C++ API
A deep learning, cross platform ML framework
python_anomaly_mode.cpp
1 #include <torch/csrc/autograd/python_anomaly_mode.h>
2 #include <torch/csrc/python_headers.h>
3 #include <torch/csrc/utils/auto_gil.h>
4 #include <torch/csrc/utils/python_strings.h>
5 #include <torch/csrc/utils/object_ptr.h>
6 #include <torch/csrc/Exceptions.h>
7 
8 #include <iostream>
9 
10 namespace torch { namespace autograd {
11 
12 void PyAnomalyMetadata::store_stack() {
13  AutoGIL gil;
14  THPObjectPtr mod(PyImport_ImportModule("traceback"));
15  if (!mod) {
16  throw python_error();
17  }
18 
19  THPObjectPtr list(PyObject_CallMethod(mod.get(), "format_stack", ""));
20  if (!list) {
21  throw python_error();
22  }
23 
24  if (PyDict_SetItemString(dict(), ANOMALY_TRACE_KEY, list.get())) {
25  throw python_error();
26  }
27 }
28 
29 void PyAnomalyMetadata::print_stack() {
30  AutoGIL gil;
31  if (!PyDict_Check(dict())) {
32  throw std::runtime_error("Anomaly metadata is not a python dictionary.");
33  }
34 
35  // PyDict_GetItemString returns a borrowed reference
36  PyObject* stack(PyDict_GetItemString(dict(), ANOMALY_TRACE_KEY));
37  if (!stack) {
38  AT_WARN("No forward pass information available. Enable detect anomaly "
39  "during forward pass for more information.");
40  return;
41  }
42 
43  THPObjectPtr empty_string(PyUnicode_FromString(""));
44  if (!empty_string) {
45  throw python_error();
46  }
47 
48  // stack is a list of Python strings ending with newlines. Use join to convert
49  // to a single string.
50  THPObjectPtr msg(PyUnicode_Join(empty_string, stack));
51  if (!msg) {
52  throw python_error();
53  }
54 
55  AT_WARN("Traceback of forward call that caused the error:\n",
56  THPUtils_unpackString(msg.get()));
57 }
58 
59 }}
Definition: jit_type.h:17