Slicer 5.9.0 with libtorch

hi, I am developing a c++ module on Slicer 5.9.0. I have a lot of confusion to use libtorch together with Slicer. I can compile the code but when I call a libtorch function, such as torch::jit::load(path), it crashes without given any error message.

In the past I used an older version Slicer (4.13.0) and it works well with libtorch.

Do you have any success experience to use libtorch with Slicer 5.9.0? I have tried many versions of libtorch but none of them works.

Thanks.

Is this on Linux, and what version of torch? Perhaps you are hitting the ABI issue with torch 2.7?

Thanks for your reply. I am using Ubuntu 20.04 + CUDA 12.8. My CMakeLists.txt sets C++ 17.

I downloaded libtorch from the following link (may need to change number)
https://download.pytorch.org/libtorch/cu126/

I have tried the following libtorch versions:
libtorch-cxx11-abi-shared-with-deps-2.7.0+cu128
libtorch-cxx11-abi-shared-with-deps-1.13.0+cu117
libtorch-cxx11-abi-shared-without-deps-1.13.0+cu117
[libtorch-win-shared-with-deps-2.6.0%2Bcu126

Is there another version I should give a try? Thanks.

I don’t think this works with Slicer, which uses an older glibc then 2.7 and cu128 requires.

I think this is for windows, not linux?

For the rest, someone with more C++ knowledge needs to chime in.

You usually can’t mix and match C++ compiled libraries so it’s not surprising that this crashes. It would be best if you could compile everything from source with the same compiler (i.e. look at compiling libtorch and your other code as a superbuild extension).

But also using Python is the suggested method of accessing torch features. Is there a reason you want to use C++?

Thank you Steve. Because there are a large amount of algorithms were implemented using C++, it is not possible for me to convert the code to Python.

I tried to compile libtorch from source but there are many version conflicts.

You could build a Python wheel that uses the same build environment as PyTorch, which would ensure ABI compatibility. I would recommend this if you want to distribute your solution as a Slicer extension.

For a custom application, it could be enough to build a standalone version of your software that runs in a separate process. Slicer can launch it using its original startup environment, so there would be no conflict with PyTorch or any other binaries. For non-interactive use cases you can simply pass all inputs as files and fetch output from files. For interactive use cases you can communicate with the started process via web requests (for 3D images or non-time-critical applications) or OpenIGTLink (for real-time processing of image streams). There are examples for all these in existing extensions.