Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 876
Jisung Kim Avatar asked Oct 28 '25 13:10

Jisung Kim


1 Answers

PyObject * THPVariable_Wrap(at::Tensor t);

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

Those two are what you are looking for i guess.

like image 173
Jangwoong Kim Avatar answered Oct 31 '25 03:10

Jangwoong Kim