I needed to bind C++ torch modules to python, but could not find any detailed documentation anywhere.
So I turned to docstring in code, specifically in torch/python.h, and followed minimal example provided in the comments for simple identity module.
Minimal example below
CMakeLists.txt
cmake_minimum_required(VERSION 3.8 FATAL_ERROR)
project(example VERSION 1.0.0 LANGUAGES C CXX CUDA)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(Python COMPONENTS Interpreter Development REQUIRED)
find_package(pybind11 CONFIG REQUIRED)
find_package(Torch REQUIRED)
pybind11_add_module(pybind_example tmp.cpp)
target_link_libraries(pybind_example PRIVATE ${TORCH_LIBRARIES})
tmp.cpp
#include <torch/extension.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
struct Net : torch::nn::Module {
Net(int in, int out) { }
torch::Tensor forward(torch::Tensor x) { return x; }
};
PYBIND11_MODULE(my_module, m)
{
torch::python::bind_module<Net>(m, "Net")
.def(py::init<int, int>())
.def("forward", &Net::forward);
}
Code compiles and creates shared library pybind_example.cpython-39-x86_64-linux-gnu.so
Problem occurs on import of created module with error
${TORCH_LIBRARIES} doesn’t include header files (such as Python.h) and dynamic link libraries (such as torch_python) required for Python. You must manually add them. If you want to compile it with cmake, you can imitate following CMakeLists.txt template:
Of course, you can also compile using g++ or torch.utils.cpp_extension module. You must add -lc10, -ltorch and -ltorch_python to ldflags, and add -I<path_to_python>/include/python3.x, -I<path_to_torch>/include/torch/csrc/api/include and -I<path_to_torch>/include to cxxflags.