简体   繁体   中英

How to convert PyTorch tensor to C++ torch::Tensor vice versa?

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
}
PyObject * THPVariable_Wrap(at::Tensor t);

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

Those two are what you are looking for i guess.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM