LibTorch for Min-DevKit
A while ago I wrote a post showing how to embed PyTorch (via LibTorch) in a Max object using the standard Max SDK. Now, 2 years later (!), I’m finally getting around to building the rolypoly~ Max object, and I’ve decided to start using the shiny new Min system, which provides a much smoother C++ experience for writing Max externals.
And since the Max 8.2 SDK update, the process is fairly streamlined, as this video also shows.1 Here’s how you do it:
First, make sure you have cmake, ruby, and a recent version of vs (Build Tools will suffice) installed. Now, follow the instructions to install Min. Then proceed to the guide for creating a new package. Note: I got the error documented in this issue - the solution is to simply run ruby script/create_package.rb ../yourProject
.
Then follow the instructions for creating a new object, which involves copying one of the existing examples. But before you run CMake to generate the project files, you need to edit CMakeLists.txt to add the LibTorch includes and libraries:2
include_directories(
"${C74_INCLUDES}"
${CMAKE_CURRENT_SOURCE_DIR}/../../../libtorch/include
${CMAKE_CURRENT_SOURCE_DIR}/../../../libtorch/include/torch/csrc/api/include
)
link_directories(
${CMAKE_CURRENT_SOURCE_DIR}/../../../libtorch/lib
)
link_libraries(
torch.lib
torch_cpu.lib
c10.lib
)
Of course, you should also download and extract LibTorch to your Max package folder. This would result in something like Max 8/Packages/yourProject/libtorch
. Only then should you run CMake and then build your project.3
A big advantage of starting with a Max Package right off the bat like this, is that you don’t need to copy dll files to your Max application folder. Just copy every dll file from yourProject/libtorch/lib
to a yourProject/support
folder which you create and Max knows to look for.
Now, to test that it works properly, edit source/projects/yourProject/yourProject.cpp
and add:
#include "torch\torch.h"
...
// constructor
yourProject() {
torch::Tensor tensor = torch::rand({ 2, 3 });
cout << "random tensor: "
<< tensor[0][0].item<float>() << " " << tensor[0][1].item<float>() << " " << tensor[0][2].item<float>()
<< " | "
<< tensor[1][0].item<float>() << " " << tensor[1][1].item<float>() << " " << tensor[1][2].item<float>()
<< endl;
}
Then open Max and, when you create an yourProject
object you should see a random tensor in the console. Now you’re ready to move forth into Min+LibTorch greatness!
(update May 2023) I recorded a video guide:
-
As with my initial Max SDK guide, these instructions are Windows-specific. A similar process should work for Mac, but I haven’t tried it yet. ↩
-
Depending on your version of LibTorch, the exact names of the libraries may change. Check your
libtorch/lib
folder contents. ↩ -
I use VS Code, whose CMake integration is very clever: make any change in CMakeLists, save it, and VS Code automatically regenerates your project files, so you just need to hit ‘Build’. ↩