cmake for pytorch c++

I try to run project that is example of cmake usage for pytorch cuda extension link below [1]. The specified command is

cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_PREFIX_PATH=`python -c 'import torch;print(torch.utils.cmake_prefix_path)'` -GNinja ..

When I try to run it using this command it gives

PS C:\Users\jakub> cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_PREFIX_PATH=`python -c 'import torch;print(torch.utils.cmake_prefix_path)'` -GNinja C:\Users\jakub\source\repos\r-barnes\pytorch_cmake_example
CMake Error: Unknown argument -c

Generally when I compile cmake projects I add in visual studio configuration cmake command line arguments

-DCMAKE_PREFIX_PATH="D:\\projects\\libTorchC\\libtorch-win-shared-with-deps-1.10.2+cu113\\libtorch"

In order for cmake to find python. Hovewer I do not know how to combine those commands.

CMakeLists.txt

cmake_minimum_required (VERSION 3.9)

project(pytorch_cmake_example LANGUAGES CXX CUDA)

find_package(Python REQUIRED COMPONENTS Development)
find_package(Torch REQUIRED)

if(NOT DEFINED CMAKE_CUDA_ARCHITECTURES)
  set(CMAKE_CUDA_ARCHITECTURES 61)
endif()

add_library(pytorch_cmake_example SHARED
  main.cu
)
target_compile_features(pytorch_cmake_example PRIVATE cxx_std_11)
target_link_libraries(pytorch_cmake_example PRIVATE ${TORCH_LIBRARIES} Python::Python)

# Use if the default GCC version gives issues
target_compile_options(pytorch_cmake_example PRIVATE $<$<COMPILE_LANGUAGE:CUDA>:-ccbin g++-9>)

Configuration:
Windows 10
Python 3.7
torch==1.10.2+cu113 torchvision==0.11.3+cu113 torchaudio===0.10.2+cu113

[1] GitHub - r-barnes/pytorch_cmake_example

Thanks for help!

The example from GitHub - r-barnes/pytorch_cmake_example was made on Linux. It needs to be adapted for Windows. This is not a CMake issue.

Thanks for response ! I am not experienced in cmake but I thought that the whole idea of using cmake is to make project platform independent - could you hint me about what kind of modifications you are talking about?

As I wrote earlier, this is not a CMake issue. The command you are trying to execute contains backtick (`) characters, which are used to execute a subcommand in a Unix shell (see https://unix.stackexchange.com/a/27432 for a more detailed description), but in PowerShell they are used as the escape character.

In order to make that command work in PowerShell, you need to adapt it. See https://stackoverflow.com/a/434311 for how to.

1 Like

You can embed the command in backticks in cmake by using execute_process() and append the result to the same variable using list(APPEND …)

1 Like

Basically this is just trying to set the CMAKE_PREFIX_PATH to where pytorch is installed. You could do the same thing with two commands.

  1. run python -c ‘import torch;print(torch.utils.cmake_prefix_path)’
  2. take the output of that and use it when you run cmake -DCMAKE_PREFIX_PATH=path/from/1
2 Likes