In the evolving world of deep learning, PyTorch has been a key player providing an array of tools to both researchers and developers alike. libtorch, the C++ frontend to PyTorch, provides an interface that is highly valuable for developers looking to integrate PyTorch into their native applications.
Apple's new M1 chip architecture presents new opportunities but also brings some new challenges. One of these challenges is compiling libtorch for M1 Macs, and specifically creating a static archive that can be run in the app sandbox.
In this blog post, I'll walk you through the steps to compile libtorch as a static archive on M1 Macs. This guide assumes that you have some experience with building C++ projects and are familiar with macOS development.
An M1 Mac running macOS Big Sur or later Xcode installed CMake 3.18 or newer Ninja build system (optional, but recommended) Step 1: Downloading the libtorch Source Code
Step 1: Downloading the libtorch Source Code
git clone --recursive https://github.com/pytorch/pytorch.git cd pytorch Step 2: Setting Up the Environment
brew install cmake ninja Step 3: Running the Build Script with Parameters
Set the parameters and then call the build script:
DEBUG=0 USEOPENMP=0 BUILDSHAREDLIBS=OFF BUILDPYTHON=0 USEMPS=0 USECUDA=0 USECUDNN=0 BLAS=OpenBLAS USELAPACK=0 USEKINET0=1 BUILDCUSTOMPROTOBUF=0 USENNPACK=0 USETBB=0 USESYSTEMTBB=0 USEOMP=0 USESYSTEMPROTOBUF=1 IOSPLATFORM=MACARM IOSARCH=arm64 ./scripts/build_macos.sh
./scripts/build_macos.sh is just a convenience script copied from scripts/build_local.sh
Now, you can link this static archive to your application, making sure to set the proper include paths for the headers. You may also need to link against other system libraries, such as Accelerate and Metal frameworks, depending on your app's needs.
Compiling libtorch as a static archive for M1 Macs is a slightly more intricate process, but with the steps laid out in this guide, you should be able to integrate PyTorch into your native macOS application. The advantage of a static archive is that it includes all dependencies in one file, potentially easing deployment and distribution.
Feel free to refer to the official PyTorch GitHub repository for additional information and to stay updated with the latest changes. If you encounter any issues, don't hesitate to report them on GitHub or consult the PyTorch community. Happy coding!