Building the TensorFlow C++ library for macOS, especially on the newer M2 chips, requires careful setup due to the architecture differences and dependencies. Here's how to successfully compile TensorFlow v2.15.0 and run a C++ example on macOS with an M2 chip.
Ensure you have Python, Bazel, and other necessary tools installed. If not, follow these steps:
-
Install Homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" -
Install Python and Bazel:
brew install python bazel
-
Install Additional Dependencies:
brew install coreutils automake libtool wget
Follow these steps to build the TensorFlow library:
-
Create a Virtual Environment (optional but recommended):
python3 -m venv ~/tensorflow_venv source ~/tensorflow_venv/bin/activate pip install --upgrade pip numpy six
-
Clone TensorFlow Repository:
git clone https://github.com/tensorflow/tensorflow.git cd tensorflow git checkout v2.15.0 -
Configure TensorFlow Build: Configure TensorFlow by running
./configure. When asked, opt out of CUDA support unless you're specifically targeting GPU acceleration with external GPUs compatible with macOS. -
Build TensorFlow C++ Library: Now, compile the TensorFlow C++ library targeting the ARM architecture of the M2 chip.
bazel build --config=macos_arm64 //tensorflow:libtensorflow_cc.dylib
After building TensorFlow, extract the necessary libraries and headers:
-
Extract TensorFlow C++ Library: Locate and copy the built TensorFlow libraries (
libtensorflow_cc.soandlibtensorflow_framework.so) to your desired directory, e.g.,~/tensorflow_lib. -
Copy Header Files: TensorFlow's header files need to be collected from the source tree and copied to your include directory, e.g.,
~/tensorflow_include.
Compile a simple TensorFlow C++ example to verify the installation:
-
Example C++ Code: Write or use an existing TensorFlow C++ example, such as
example_trainer.cc, and save it to a file. -
Compile Your C++ Example: Use
clang++org++with the appropriate flags to include the TensorFlow headers and link against the TensorFlow libraries.clang++ -std=c++14 -I${HOME}/tensorflow_include -L${HOME}/tensorflow_lib -ltensorflow_cc -ltensorflow_framework -o example_trainer example_trainer.cc
-
Run Your Example: Ensure that the dynamic libraries are found by setting the
DYLD_LIBRARY_PATHenvironment variable before running your executable.export DYLD_LIBRARY_PATH=${HOME}/tensorflow_lib:$DYLD_LIBRARY_PATH ./example_trainer
Note: The above steps are tailored for macOS environments, specifically targeting ARM64 architecture found in M2 chips. Adjust paths and library names as necessary based on where you chose to extract TensorFlow libraries and headers.
This tutorial simplifies the process of building and using the TensorFlow C++ library on macOS with M2 chips, covering everything from setting up the environment to compiling and running a simple TensorFlow C++ example.