pytorch/torch/csrc/jit/python/python_tracer.cpp
tangleintel 7980ed95bd Support unpacking python dictionary in torch.jit.trace() (#81623)
# Support unpacking python dictionary in **torch.jit.trace()**

## Problem statement & Motivation
### Problem 1(usability):
Say, if you have a model and its forward method defined as follows:
**`def forward(self, key1=value1, key2=value2, key3=value3)`**
And you have a dataset and each data point in the dataset is a python dict as follows:
**`data = {key1:value1, key3:value3, key2:value2}`**

The problem is that if you want to trace the model using the dict data by the giving dataset, you need unpack the dictionary and reorder its value manually and make up a tuple as **`data_tuple = (value1, value2, value3)`** as the **`example_inputs`** parameter of **`torch.jit.trace()`**. This marshalling process is not user friendly.

### Problem 2 (feasibility):
Say, if you have a model and its forward method defined as follows:
**`def forward(self, key1=None, key2=None, key3=None)`** -> The default value is **None**
And you have a dataset and each data point in the dataset is a python dict as follows:
**`data = {key1:value1, key3:value3}`** -> Only **part of** the required value by forward was given, the rest use the default value.

The problem is that if you want to trace the model using the dict data by the giving dataset, it's not feasible at all. Cause neither you can pass a tuple like **`T1 = (value1, value3)`**  nor **`T2 = (value1, None, value3)`**. T1 will mismatch value3 with key2 and T2 include **None** type which will be blocked by tracer's type checking. (Of course you can pass **`T3 = (value1,)`**  to make the trace function finish without exception, but the traced model you get probably is not what you expect cause the different input may result in different traced result.).

These problems come from the HuggingFace's PT model, especially in text-classification tasks with datasets such as [MRPC,](https://paperswithcode.com/dataset/mrpc)  [MNLI](https://paperswithcode.com/dataset/multinli) etc.

## Solution
To address these two issues, we propose to support a new type, that is, python dict as example_inputs parameter for torch.jit.trace(). We can base on the runtime type information of the example_inputs object to determine if we fall back to the original tuple path or go into the new dictionary path. Both problem 1 and  problem 2 can be solved by utilizing the "**`**`**"
operator.

## Limitation & Mitigation

1. If we use dict as example_inputs to trace the model, then we have to pass a dictionary to the traced model too. (Cause probably we will change the order of debug name of the input parameter in torchscript IR, thus we can't assume the traced model's input parameters order are the same with the original model.). We need highlight this too in the document to mitigate this problem.

    For example:
```
# fetch a data from dataloader, and the data is a dictionary
# and the example_inputs_dict is like: {key1:value1, key3:value3, key2:value2}
# the forward() is like: def forward(self, key1=value1, key2=value2, key3=value3)
example_inputs_dict = next(iter(dataloader))
jit_model = model.eval()
# use the dictionary to trace the model
jit_model = torch.jit.trace(jit_model, example_inputs_dict, strict=False)  # Now the IR will be graph(%self : __torch__.module.___torch_mangle_n.Mymodule, %key1 : type1, %key3 : type3, %key2 : type2)
jit_model = torch.jit.freeze(jit_model)

# It's OK to use dict as the parameter for traced model
jit_model(**example_inputs_dict)

example_inputs_tuple = (value1, value3, value2)
# It's wrong to rely on the original args order.
jit_model(*example_inputs_tuple)

```
## Note
1. This PR will make some UT introduced in [39601](https://github.com/pytorch/pytorch/pull/39601) fail, which I think should be classified as unpacking a tuple containing a single dictionary element in our solution.
4. I think there is ambiguity since currently we only specify passing a tuple or a single Tensor as our example_inputs parameter in **torch.jit.trace()**'s documentation, but it seems we can still passing a dictionary.

Pull Request resolved: https://github.com/pytorch/pytorch/pull/81623
Approved by: https://github.com/davidberard98
2022-10-15 05:33:09 +00:00

294 lines
9.3 KiB
C++

#include <torch/csrc/python_headers.h>
#include <torch/csrc/jit/frontend/tracer.h>
#include <torch/csrc/jit/passes/dead_code_elimination.h>
#include <torch/csrc/jit/passes/inliner.h>
#include <torch/csrc/jit/passes/lower_tuples.h>
#include <torch/csrc/jit/python/pybind.h>
#include <torch/csrc/jit/python/python_tracer.h>
#include <torch/csrc/jit/serialization/export.h>
#include <torch/csrc/utils/python_strings.h>
#include <c10/util/Exception.h>
#include <c10/util/irange.h>
#include <sstream>
using namespace torch::autograd;
using namespace torch::jit;
using namespace torch::jit::tracer;
namespace torch {
namespace jit {
namespace tracer {
// Python interpreter retrieval routine adapted from
// https://stackoverflow.com/a/8706144
std::vector<StackEntry> _pythonCallstack() {
pybind11::gil_scoped_acquire gil;
PyFrameObject* frame = PyEval_GetFrame();
Py_INCREF(frame);
std::vector<StackEntry> entries;
while (nullptr != frame) {
auto code = THPCodeObjectPtr(PyFrame_GetCode(frame));
size_t line = PyCode_Addr2Line(code.get(), PyFrame_GetLasti(frame));
std::string filename = THPUtils_unpackString(code->co_filename);
std::string funcname = THPUtils_unpackString(code->co_name);
auto source = std::make_shared<Source>(funcname, filename, line);
entries.emplace_back(
StackEntry{funcname, SourceRange(source, 0, funcname.size())});
auto new_frame = PyFrame_GetBack(frame);
Py_DECREF(frame);
frame = new_frame;
}
return entries;
}
SourceRange getPythonInterpreterSourceRange() {
auto cs = pythonCallstack();
c10::optional<std::string> source_filename;
size_t source_line = 0;
std::stringstream stack_trace;
for (const auto& entry : cs) {
auto& range = entry.range;
if (range.source()) {
auto& src = range.source();
if (src && src->filename()) {
auto line =
src->starting_line_no() + src->lineno_for_offset(range.start());
stack_trace << *(src->filename()) << "(" << line
<< "): " << entry.filename << "\n";
if (!source_filename) {
source_filename = *(src->filename());
source_line = line;
}
}
}
}
auto stack_trace_text = stack_trace.str();
auto source =
std::make_shared<Source>(stack_trace_text, source_filename, source_line);
return SourceRange(source, 0, stack_trace_text.size());
}
std::pair<std::shared_ptr<Graph>, Stack> createGraphByTracingWithDict(
const py::function& func,
const py::dict& inputs_dict,
Stack trace_inputs,
const py::function& var_name_lookup_fn,
bool strict,
bool force_outplace,
Module* self,
const std::vector<std::string>& argument_names) {
C10_LOG_API_USAGE_ONCE("torch.tracer");
auto lookup_fn_adapter =
[var_name_lookup_fn](const Variable& var) -> std::string {
pybind11::gil_scoped_acquire ag;
return py::cast<std::string>(var_name_lookup_fn(var));
};
// The argument_names parameter is parsed in python and its order
// is the same as the arguments' decalaration order in forward() method.
// These name shall be added to the graph as debug name and the order
// should align with the traceable stack we generated by the python dict.
std::vector<std::string> compact_argument_names;
Stack compact_trace_inputs;
for (std::vector<std::string>::size_type i = 0; i < argument_names.size();
i++) {
if (inputs_dict.contains(argument_names[i])) {
compact_argument_names.push_back(argument_names[i]);
}
}
for (std::vector<std::string>::size_type i = 0;
i < compact_argument_names.size();
i++) {
for (auto it = inputs_dict.begin(); it != inputs_dict.end(); it++) {
if (py::cast<std::string>(it->first) == compact_argument_names[i]) {
if (THPVariable_Check(it->second.ptr())) {
compact_trace_inputs.push_back(
toIValue(it->second, tryToInferType(it->second).type()));
}
}
}
}
auto outs = tracer::trace(
std::move(compact_trace_inputs),
[&](Stack inputs) -> Stack {
// We just leave the inputs_dict as it was and pass it to forward
// method.
auto out = func(**inputs_dict);
if (out.ptr() == Py_None) {
AT_ERROR(
"The traced function didn't return any values! Side-effects are not "
"captured in traces, so it would be a no-op.");
}
return {toTypeInferredIValue(out)};
},
lookup_fn_adapter,
strict,
force_outplace,
self,
compact_argument_names);
return std::make_pair(std::get<0>(outs)->graph, std::get<1>(outs));
}
std::pair<std::shared_ptr<Graph>, Stack> createGraphByTracing(
const py::function& func,
Stack trace_inputs,
const py::function& var_name_lookup_fn,
bool strict,
bool force_outplace,
Module* self,
const std::vector<std::string>& argument_names) {
C10_LOG_API_USAGE_ONCE("torch.tracer");
auto lookup_fn_adapter =
[var_name_lookup_fn](const Variable& var) -> std::string {
pybind11::gil_scoped_acquire ag;
return py::cast<std::string>(var_name_lookup_fn(var));
};
auto outs = tracer::trace(
std::move(trace_inputs),
[&func](Stack inputs) -> Stack {
size_t num_func_inputs = inputs.size();
py::tuple py_inputs(num_func_inputs);
for (const auto i : c10::irange(num_func_inputs)) {
py_inputs[i] = py::cast(inputs[i]);
}
auto out = func(*py_inputs);
if (out.ptr() == Py_None) {
AT_ERROR(
"The traced function didn't return any values! Side-effects are not "
"captured in traces, so it would be a no-op.");
}
return {toTypeInferredIValue(out)};
},
lookup_fn_adapter,
strict,
force_outplace,
self,
argument_names);
return std::make_pair(std::get<0>(outs)->graph, std::get<1>(outs));
}
Node* preRecordPythonTrace(
THPObjectPtr pyobj,
const std::string& arg_types,
at::ArrayRef<Variable> inputs,
pyobj_list scalar_args) {
THPObjectPtr apply(PyObject_GetAttrString(pyobj.get(), "apply"));
if (!apply) {
throw python_error();
}
auto& graph = getTracingState()->graph;
Node* n = graph->createPythonOp(
std::move(apply), arg_types, std::move(scalar_args));
recordSourceLocation(n);
for (const Variable& input : inputs) {
n->addInput(getValueTrace(input));
}
graph->insertNode(n);
return n;
}
void pythonRecordSourceLocation(Node* n) {
n->setSourceRange(getPythonInterpreterSourceRange());
}
void pythonWarn(const std::string& reason) {
pybind11::gil_scoped_acquire gil;
auto warn_class = py::module::import("torch.jit").attr("TracerWarning");
PyErr_WarnEx(warn_class.ptr(), reason.c_str(), 1);
}
void initPythonTracerBindings(PyObject* module) {
setPythonCallstack(_pythonCallstack);
setRecordSourceLocation(pythonRecordSourceLocation);
auto m = py::handle(module).cast<py::module>();
py::class_<TracingState, std::shared_ptr<TracingState>>(
m, "TracingState", py::dynamic_attr())
// NB: no constructor; you have to get it from C++ code
.def(
"__repr__",
[](const TracingState& s) {
std::ostringstream ss;
ss << "<TracingState " << (const void*)&s << ">";
return ss.str();
})
.def(
"__str__",
[](const TracingState& s) -> std::string {
std::ostringstream ss;
ss << *s.graph;
return ss.str();
})
.def(
"push_scope",
[](TracingState& s, const std::string& scope_name) {
s.graph->push_scope(scope_name);
})
.def("pop_scope", [](TracingState& s) { s.graph->pop_scope(); })
.def(
"current_scope",
[](TracingState& s) {
return s.graph->current_scope()->name().toUnqualString();
})
.def(
"set_graph",
[](TracingState& s, std::shared_ptr<Graph> g) {
s.graph = std::move(g);
})
.def("graph", [](TracingState& s) { return s.graph; });
m.def("_tracer_warn_use_python", []() { tracer::setWarn(pythonWarn); });
m.def(
"_create_graph_by_tracing",
createGraphByTracing,
py::arg("func"),
py::arg("inputs"),
py::arg("var_name_lookup_fn"),
py::arg("strict"),
py::arg("force_outplace"),
py::arg("self") = nullptr,
py::arg("argument_names") = std::vector<std::string>());
m.def("_get_tracing_state", []() { return getTracingState(); });
m.def("_set_tracing_state", [](std::shared_ptr<TracingState> state) {
return setTracingState(std::move(state));
});
m.def("_get_value_trace", [](const Variable& var) {
return getValueTrace(var);
});
m.def("_set_value_trace", [](const Variable& var, Value* value) {
return setValueTrace(var, value);
});
m.def("_tracer_set_get_unique_name_fn", [](const py::function& func) {
const auto& tracing_state = getTracingState();
AT_ASSERT(tracing_state);
tracing_state->lookup_var_name_fn =
[func](const Variable& var) -> std::string {
pybind11::gil_scoped_acquire ag;
return py::cast<std::string>(func(var));
};
});
m.def("_tracer_set_force_outplace", [](bool force_outplace) {
const auto& tracing_state = getTracingState();
AT_ASSERT(tracing_state);
tracing_state->force_outplace = force_outplace;
});
}
} // namespace tracer
} // namespace jit
} // namespace torch