Install Tensorflow On Apple Silicon With Pipenv

There is an Apple's tensorflow-metal page describing how to install Tensorflow using Conda, but I prefer to use my pyenv+pipenv setup. To do it my way I had to solve few issues. I thought I will share what I've leaned to save you some time on googling.

Base setup:

  • Chip Apple M1 Pro
  • macOS Monterey, version 12.1
  • Python versions and virtual environments managed with pyenv and pipenv

Verify if you have Xcode Command Line Tools installed: xcode-select -p If you're using Homebrew you should already have it, otherwise install it with command: xcode-select --install

Initialise project directory

mkdir <project-dir>
cd <project-dir>
pipenv --python 3.9

I tried to install Tensorflow dependencies tensorflow-deps but it throws the following error:

ERROR: Could not find a version that satisfies the requirement tensorflow-deps (from versions: none)
ERROR: No matching distribution found for tensorflow-deps

I've skipped it and installed later only required packages.

Next I tried to install Tensorflow library, but it failed when installing h5py dependency

pipenv install tensorflow-macos
[...]
Building wheels for collected packages: h5py
  Building wheel for h5py (pyproject.toml): started
  Building wheel for h5py (pyproject.toml): finished with status 'error'
Failed to build h5py
[...]
  Loading library to get build settings and version: libhdf5.dylib
  error: Unable to load dependency HDF5, make sure HDF5 is installed properly
  error: dlopen(libhdf5.dylib, 0x0006): tried: 'libhdf5.dylib' (no such file), '/usr/local/lib/libhdf5.dylib' (no such file), '/usr/lib/libhdf5.dylib' (no such file), '/private/var/folders/_x/b7_mhj413dqgf7d6s9hs5g9h0000gn/T/pip-install-re87cabd/h5py_81a2f64881e942029f1687c6753d7eae/libhdf5.dylib' (no such file), '/usr/local/lib/libhdf5.dylib' (no such file), '/usr/lib/libhdf5.dylib' (no such file)
  ----------------------------------------
  ERROR: Failed building wheel for h5py
ERROR: Could not build wheels for h5py, which is required to install pyproject.toml-based projects

✘ Installation Failed

To solve this issue I had to install HDF5 library with Homebrew and then h5py without binaries:

brew install hdf5
export HDF5_DIR="$(brew --prefix hdf5)"
export PIP_NO_BINARY=h5py && pipenv install h5py

Equivalent for the last command when using PIP is pip install --no-binary=h5py h5py

After that I was able to install Tensorflow

pipenv install tensorflow-macos
pipenv install tensorflow-metal

Now you can start training your models, just remember that TF will complain about missing packages and you have to install them manually.