3

I want to receive a dictionary includes PyTorch Tensor in C++ module using pybind11, and return the result dictionary with some modification that includes C++ torch::Tensor back. As far as I was looking for, there seems no clear way to convert PyTorch Tensor to C++ Tensor, and C++ Tensor to PyTorch Tensor. For a last trial, I tried to convert PyObject to torch::Tensor but seems not working as well. (https://discuss.pytorch.org/t/is-it-possible-to-get-pyobject-from-a-torch-tensor/85980/2) I want to know if it is correct and there are there any workarounds. I share my code snippet on the below.

py::dict quantize(py::dict target) {
    ...
    for (auto item: target) {
        py::str key(item.first);
        torch::Tensor test = item.second.ptr(); // it fails to compile
    }
    ...
    return py::dict("name"_a="test", "tensor"_a=torch::rand({3, 3, 3})); // it fails on runtime
}
Jisung Kim
  • 133
  • 1
  • 9

1 Answers1

2
PyObject * THPVariable_Wrap(at::Tensor t);

at::Tensor& THPVariable_Unpack(PyObject* obj);

Those two are what you are looking for i guess.

Josef
  • 2,869
  • 2
  • 22
  • 23
Jangwoong Kim
  • 121
  • 10
  • That's the correct answer. Note that `THPVariable_Wrap` creates a new object, so the reference needs to be stolen, e.g. `py::object tensorToPy(th::Tensor& tensor) { return py::reinterpret_steal(THPVariable_Wrap(tensor)); }` – heiner Mar 31 '23 at 23:42