building a pybind11 module with cpp and cuda sources using cmake
Asked Answered
R

2

6

I'm trying to generate python bindings for a dummy class which needs to be compiled with a cuda enabled compiler. I'm using cmake 3.12.0, pybind11 v2.2.3 and nvcc 7.5.17. Compilation fails because options like -flto and -fno-fat-lto-objects are passed directly to nvcc, which doesn't recognize them.

Here is a (minimal) example:
Cuda Code:

//Adder.hpp
#include <thrust/host_vector.h>
struct Adder {
    thrust::host_vector<float> a_h;
    thrust::host_vector<float> b_h;
    thrust::host_vector<float> r_h;
    int N;

    Adder(int N);
    void set_a(float const * const in);
    void set_b(float const * const in);
    void calc();
    void calc_gpu();
};

//Adder.cu
#include "Adder.hpp"
#include <thrust/device_vector.h>

Adder::Adder(int N): N(N),a_h(N),b_h(N),r_h(N) {}
void Adder::set_a(float const * const in) {
    for (int i=0; i<N; ++i) {
        a_h[i] = in[i];
    }
}
void Adder::set_b(float const * const in) {
    for (int i=0; i<N; ++i) {
        b_h[i] = in[i];
    }
}
void Adder::calc() {
    for (int i=0; i<N; ++i) {
        r_h[i] = a_h[i]+b_h[i];
    }
}
void Adder::calc_gpu() {
    thrust::device_vector<float> a_d(a_h);
    thrust::device_vector<float> b_d(b_h);
    thrust::device_vector<float> r_d(r_h);

    thrust::transform(a_d.begin(), a_d.end(), b_d.begin(), r_d.begin(),thrust::plus<float>());
    r_h = r_d;
}

Binding Code:

#include "Adder.hpp"
#include "lib/include/pybind11/pybind11.h"
#include "lib/include/pybind11/numpy.h"
#include <stdexcept>

namespace py = pybind11;

void bind_Adder(py::module& m) {
    py::class_<Adder>(m,"Adder","Module docstring")
        .def(py::init<int>(), py::arg("N"), "Init Adder")
        .def(
            "set_a"
            , [](Adder& self, py::array_t<float, py::array::c_style | py::array::forcecast> in) {
                py::buffer_info ai = in.request();
                if (ai.ndim!=1 || ai.shape[0]!=self.N || ai.strides[0]!=sizeof(float)) {
                    throw std::runtime_error("Shape of given numpy array must be (N,)! Type must be float.");
                }
                self.set_a(static_cast<float const * const>(ai.ptr));
            }
            , py::arg("in")
            , "Set a."
        )
        .def(
            "set_b"
            , [](Adder& self, py::array_t<float, py::array::c_style | py::array::forcecast> in) {
                py::buffer_info ai = in.request();
                if (ai.ndim!=1 || ai.shape[0]!=self.N || ai.strides[0]!=sizeof(float))
                    throw std::runtime_error("Shape of given numpy array must be (N,)! Type must be float.");
                self.set_b(static_cast<float const * const>(ai.ptr));
            }
            , py::arg("in")
            , "Set b."
        )
        .def(
            "get_r"
            , [](Adder& self, py::array_t<float> x) {
                auto r = x.mutable_unchecked<1>(); 
                for (ssize_t i = 0; i < r.shape(0); i++) {
                    r(i) = self.r_h[i];
                }
            }
            , py::arg("x").noconvert())
        .def("calc", &Adder::calc, "Calculate on CPU.")
        .def("calc_gpu", &Adder::calc_gpu, "Calculate on GPU.");
}

PYBIND11_MODULE(dummy, m) {
    bind_Adder(m);
}

CMakeLists.txt:

CMAKE_MINIMUM_REQUIRED(VERSION 3.11)
project(dummy LANGUAGES CXX CUDA)

set(PYBIND11_CPP_STANDARD -std=c++11)
add_subdirectory(lib/pybind11)

pybind11_add_module(dummy 
    Adder.pybind.cpp
    Adder.cu
)

Building with e.g. cmake ../src && make -VERBOSE=1 fails. While the object file for Adder.pybind.cpp is generated succesfully. The compilation of Adder.cu fails with:

/usr/bin/nvcc  -Ddummy_EXPORTS -I/home/user/projects/pybind11_cuda_cmake/lib/pybind11/include -I/home/user/.anaconda3/include/python3.6m  -Xcompiler=-fPIC   -std=c++11 -flto -fno-fat-lto-objects -x cu -c /home/user/projects/pybind11_cuda_cmake/Adder.cu -o CMakeFiles/dummy.dir/Adder.cu.o
nvcc fatal   : Unknown option 'flto'

I tried to disable automatic propagation to nvcc, but with no luck.

set(CUDA_PROPAGATE_HOST_FLAGS FALSE)
set(CUDAFLAGS "-Xcompiler -fPIC -Xcompiler -flto -Xcompiler=-fvisibility=hidden")

Does anybody know how to make this work?

Remaremain answered 18/8, 2018 at 10:46 Comment(2)
You do not need to use pybind11_add_module. Just find_package(PythonLibs...) and target_link_libraries(your_target ${PYTHON_LIBRARIES} is sufficient. This way you can easily use cuda_add_library without any issues.Chromo
@Chromo thanks this works also by enabling cuda as language and using add_library (the cuda package seem deprecated). But it seems to be difficult to add the additional compile/linker flags for link time optimization suggested by pybind11.Remaremain
R
6

UPDATE: A (maybe) cleaner version using target_set_properties and thus letting cmake sort out the actual compiler/linker flags.

cmake_minimum_required(VERSION 3.12)
project(dummy LANGUAGES CXX CUDA)

set(PYBIND11_CPP_STANDARD -std=c++11)
add_subdirectory(lib/pybind11)

add_library(dummycu STATIC
    Adder.cu
)

set_target_properties(dummycu PROPERTIES 
    POSITION_INDEPENDENT_CODE ON
    CUDA_VISIBILITY_PRESET "hidden"
    # CUDA_SEPARABLE_COMPILATION ON
)


add_library(dummy MODULE
    Adder.pybind.cpp
)

set_target_properties(dummy PROPERTIES 
    CXX_VISIBILITY_PRESET "hidden"
    INTERPROCEDURAL_OPTIMIZATION TRUE
    PREFIX "${PYTHON_MODULE_PREFIX}"
    SUFFIX "${PYTHON_MODULE_EXTENSION}"
)

target_link_libraries(dummy PRIVATE dummycu)
target_link_libraries(dummy PRIVATE pybind11::module)

We can also compile and link everything within one target. This can probably also be used to modify pybind11_add_module in pybind11Tools.cmake.
Since pybind11 sets the visibility flag for its module target unconditionally, which is therefore used with nvcc without -Xcompiler, a small hack is required if one doesn't want to change the pybind11 CMakeLists.txt or pybind11Tools.cmake. Probably it would be better to write custom versions for the module target and/or pybind11_add_module function.

cmake_minimum_required(VERSION 3.12)
project(dummy LANGUAGES CXX CUDA)

set(PYBIND11_CPP_STANDARD -std=c++11)
add_subdirectory(lib/pybind11)

##pybind11 sets -fvisibility=hidden in INTERFACE_COMPILE_OPTIONS on it's module target
get_target_property(modifacecopts module INTERFACE_COMPILE_OPTIONS)
list(REMOVE_ITEM modifacecopts "-fvisibility=hidden")
set_target_properties(module PROPERTIES INTERFACE_COMPILE_OPTIONS "${modifacecopts}")

add_library(dummy MODULE
    Adder.pybind.cpp
    Adder.cu
)

set_target_properties(dummy PROPERTIES 
    POSITION_INDEPENDENT_CODE ON
    CUDA_VISIBILITY_PRESET "hidden"
    CXX_VISIBILITY_PRESET "hidden"
    INTERPROCEDURAL_OPTIMIZATION TRUE
    PREFIX "${PYTHON_MODULE_PREFIX}"
    SUFFIX "${PYTHON_MODULE_EXTENSION}"
)

target_link_libraries(dummy PRIVATE pybind11::module)
Remaremain answered 20/8, 2018 at 14:41 Comment(0)
B
0

You can pass nvcc unknown flags to host compiler using -forward-unknown-to-host-compiler flag.

Usage from https://docs.nvidia.com/cuda/cuda-compiler-driver-nvcc/index.html#options-for-guiding-compiler-driver-forward-host-compiler

'nvcc -forward-unknown-to-host-compiler -foo=bar a.cu' will forward '-foo=bar' to host compiler.
'nvcc -forward-unknown-to-host-compiler -foo bar a.cu' will report an error for 'bar' argument.
'nvcc -forward-unknown-to-host-compiler -foo -bar a.cu' will forward '-foo' and '-bar' to host compiler.
Bahner answered 1/3, 2022 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.