TensorFlow 1.6-rc1 on Mac with GPU Acceleration and optional eGPU Support

How to compile TensorFlow 1.6-rc1 on macOS High Sierra 10.13.3 with GPU acceleration and optionally eGPU support.

Recently the internal dedicated Nvidia GPU of my MacBook Pro (mid-2012) died and I was forced to search for alternatives, to attach my WQHD monitor. In the end, I got the chance to buy a used eGPU housing with am NVIDIA GeForce GTX-1060 graphics card.

As of version 1.2, TensorFlow no longer provides GPU support on macOS.

Since GPU acceleration was dropped from the official binaries, I have been satisfied with the CPU-only version but by buying the eGPU enclosure the cards are being reshuffled.

To get GPU-acceleration running on macOS, we want to compile TensorFlow from source. Why will we take this pain? Just, because it’s fun ;-)

Without further ado, let’s start with the requirements.


Caution: you have to disable SIP (System Integrity Protection)

  • NVIDIA Web-Drivers
  • CUDA-Drivers
  • CUDA 9.1 Toolkit
  • cuDNN 7
  • Python 3.6
  • Apple Command-Line-Tools 8.3.2
  • bazel 0.8.1

eGPU Support (optional)


NVIDIA Web-Drivers

First, check your macOS build version. You can inspect the build version within the shell $ system_profiler SPSoftwareDataType
or by open the System-Profiler and clicking on the macOS version string.

With the build version in hand, grab the appropriate driver from NVIDIA and install it.

macOS High Sierra Version 10.13.3 (17D102) https://images.nvidia.com/mac/pkg/387/WebDriver-387.

macOS High Sierra Version 10.13.3 (17D47) https://images.nvidia.com/mac/pkg/387/WebDriver-387.

Add eGPU Support

At this point a big thank to the egpu.io community. If you encounter any issues depending on the eGPU installation or if you need a recommendation for an enclosure or graphics card, I highly recommend you to visit the egpu.io website.

Disable SIP (System Integrity Protection)

  • restart your mac and boot into Recovery Mode by holding cmd + r
  • open terminal and disable SIP by executing $ csrutil disable
  • restart

Caution: In case of incompatibility there is a chance, that you will not be able to boot after installing the eGPU Support file. Here you can boot into recovery mode and delete the following file /Library/Extensions/NVDAEGPUSupport.kext

So again, depending on your macOS build version, you will need to pick the correct file and install it.

macOS High Sierra Version 10.13.3 (17D102)

macOS High Sierra Version 10.13.3 (17D47)

Did the Mac boot gracefully? Great! Now it is time to shut down your Mac and attach your eGPU enclosure. Boot again an check if the GPU is available within the System-Profiler.

Further Dependencies


If not also available, this installation process will also install the latest Apple Command-Line-Tools
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Python 3.6

I recommend using pyenv for installing Python. On top of that, I will use pyenv-virtualenv to create a virtual environment for the custom build.

$ brew update
$ brew install pyenv pyenv-virtualenv
# add the next block to bottom of `.bash_profile`
if command -v pyenv 1>/dev/null 2>&1; then
eval “$(pyenv init -)”
eval “$(pyenv virtualenv-init -)”
$ source .bash_profile# install Python
$ pyenv install 3.6.0
# create virtualenv
$ pyenv virtualenv 3.6.0 tensorflow-gpu
$ pyenv activate tensorflow-gpu

Python dependencies

$ pip install six numpy wheel


$ brew install coreutils

bazel 0.8.1

Do not install bazel with Homebrew

$ mkdir ~/temp && cd ~/temp
$ curl -L https://github.com/bazelbuild/bazel/releases/download/0.8.1/bazel-0.8.1-installer-darwin-x86_64.sh -o bazel-0.8.1-installer-darwin-x86_64.sh
$ chmod +x bazel-0.8.1-installer-darwin-x86_64.sh
$ ./bazel-0.8.1-installer-darwin-x86_64.sh

Downgrading Command-Line-Tools to Version 8.3.2

Because we need an older version of clang, unfortunately, we have to downgrade to an older version of the Apple Command-Line-Tools.

You can download the older version 8.3.2 directly from the Apple Developer Portal or from Xcode itself Xcode -> Support -> Apple Developer.

$ sudo mv /Library/Developer/CommandLineTools /Library/Developer/CommandLineTools_backup
$ sudo xcode-select — switch /Library/Developer/CommandLineTools

Install CUDA Toolkit 9.1 with Cuda Drivers

Download CUDA-9.1

$ vim ~/.bash_profile# add the two exports to .bash_profileexport PATH=/usr/local/cuda/bin:/Developer/NVIDIA/CUDA-9.1/bin${PATH:+:${PATH}}
export DYLD_LIBRARY_PATH=/usr/local/cuda/lib:/Developer/NVIDIA/CUDA-9.1/lib
$ source ~/.bash_profile

Let`s quick check if the driver is loaded.

$ kextstat | grep -i cuda
164 0 0xffffff7f83c65000 0x2000 0x2000 com.nvidia.CUDA (1.1.0) 4329B052–6C8A-3900–8E83–744487AEDEF1 <4 1>

Compile Samples

We want to compile some CUDA sample to check if the GPU is correctly recognized and supported.

$ cp -R /Developer/NVIDIA/CUDA-9.1/samples ~/temp/cuda_samples
$ cd ~/temp/cuda_samples/
$ make -C 1_Utilities/deviceQuery
# execute sample
$ ~/temp/cuda_samples/bin/x86_64/darwin/release/deviceQuery
Detected 1 CUDA Capable device(s)Device 0: “GeForce GTX 1060 6GB”
CUDA Driver Version / Runtime Version 9.1 / 9.1
CUDA Capability Major/Minor version number: 6.1
Total amount of global memory: 6144 MBytes (6442254336 bytes)
(10) Multiprocessors, (128) CUDA Cores/MP: 1280 CUDA Cores
GPU Max Clock rate: 1709 MHz (1.71 GHz)
Memory Clock rate: 4004 Mhz
Memory Bus Width: 192-bit
L2 Cache Size: 1572864 bytes
Maximum Texture Dimension Size (x,y,z) 1D=(131072), 2D=(131072, 65536), 3D=(16384, 16384, 16384)
Maximum Layered 1D Texture Size, (num) layers 1D=(32768), 2048 layers
Maximum Layered 2D Texture Size, (num) layers 2D=(32768, 32768), 2048 layers
Total amount of constant memory: 65536 bytes
Total amount of shared memory per block: 49152 bytes
Total number of registers available per block: 65536
Warp size: 32
Maximum number of threads per multiprocessor: 2048
Maximum number of threads per block: 1024
Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
Max dimension size of a grid size (x,y,z): (2147483647, 65535, 65535)
Maximum memory pitch: 2147483647 bytes
Texture alignment: 512 bytes
Concurrent copy and kernel execution: Yes with 2 copy engine(s)
Run time limit on kernels: Yes
Integrated GPU sharing Host Memory: No
Support host page-locked memory mapping: Yes
Alignment requirement for Surfaces: Yes
Device has ECC support: Disabled
Device supports Unified Addressing (UVA): Yes
Supports Cooperative Kernel Launch: Yes
Supports MultiDevice Co-op Kernel Launch: No
Device PCI Domain ID / Bus ID / location ID: 0 / 195 / 0
Compute Mode:
< Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

NVIDIA cuDNN — Deep Learning Primitives

If not already done, register at https://developer.nvidia.com/cudnn

Download cuDNN 7.0.5

Change into your download directory and follow the post installation steps.

$ tar -xzvf cudnn-9.1-osx-x64-v7-ga.tgz
$ sudo cp cuda/include/cudnn.h /usr/local/cuda/include
$ sudo cp cuda/lib/libcudnn* /usr/local/cuda/lib
$ sudo chmod a+r /usr/local/cuda/include/cudnn.h /usr/local/cuda/lib/libcudnn*

Detailed installation instructions are available at: http://developer.download.nvidia.com/compute/machine-learning/cudnn/secure/v7.0.5/prod/Doc/cuDNN-Installation-Guide.pdf

Clone TensorFlow from Repository

$ cd ~/temp
$ git clone https://github.com/tensorflow/tensorflow
$ cd tensorflow
$ git checkout v1.6.0-rc1

Apply Patch

Sadly, with the repo untouched, it will fail to build.

I created a patch to occur this. Grab it from Github and apply it.
$ git apply tensorflow_v1.6.0-rc1_osx.patch

Prepare Build

Except CUDA support, CUDA SDK version and Cuda compute capabilities, I left the other settings untouched.

$ ./configureYou have bazel 0.8.1 installed.
Please specify the location of python. [Default is /Users/user/.pyenv/versions/tensorflow-gpu/bin/python]:
Found possible Python library paths:
Please input the desired Python library path to use. Default is [/Users/user/.pyenv/versions/tensorflow-gpu/lib/python3.6/site-packages]
Do you wish to build TensorFlow with Google Cloud Platform support? [Y/n]: n
No Google Cloud Platform support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Hadoop File System support? [Y/n]: n
No Hadoop File System support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Amazon S3 File System support? [Y/n]: n
No Amazon S3 File System support will be enabled for TensorFlow.
Do you wish to build TensorFlow with Apache Kafka Platform support? [y/N]: n
No Apache Kafka Platform support will be enabled for TensorFlow.
Do you wish to build TensorFlow with XLA JIT support? [y/N]: n
No XLA JIT support will be enabled for TensorFlow.
Do you wish to build TensorFlow with GDR support? [y/N]: n
No GDR support will be enabled for TensorFlow.
Do you wish to build TensorFlow with VERBS support? [y/N]: n
No VERBS support will be enabled for TensorFlow.
Do you wish to build TensorFlow with OpenCL SYCL support? [y/N]: n
No OpenCL SYCL support will be enabled for TensorFlow.
Do you wish to build TensorFlow with CUDA support? [y/N]: y
CUDA support will be enabled for TensorFlow.
Please specify the CUDA SDK version you want to use, e.g. 7.0. [Leave empty to default to CUDA 9.0]: 9.1Please specify the location where CUDA 9.1 toolkit is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:Please specify the cuDNN version you want to use. [Leave empty to default to cuDNN 7.0]:Please specify the location where cuDNN 7 library is installed. Refer to README.md for more details. [Default is /usr/local/cuda]:Please specify a list of comma-separated Cuda compute capabilities you want to build with.
You can find the compute capability of your device at: https://developer.nvidia.com/cuda-gpus.
Please note that each additional compute capability significantly increases your build time and binary size. [Default is: 3.5,5.2]6.1
Do you want to use clang as CUDA compiler? [y/N]: n
nvcc will be used as CUDA compiler.
Please specify which gcc should be used by nvcc as the host compiler. [Default is /usr/bin/gcc]:Do you wish to build TensorFlow with MPI support? [y/N]:
No MPI support will be enabled for TensorFlow.
Please specify optimization flags to use during compilation when bazel option “ — config=opt” is specified [Default is -march=native]:Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]:
Not configuring the WORKSPACE for Android builds.
Preconfigured Bazel build configs. You can use any of the below by adding “ — config=<>” to your build command. See tools/bazel.rc for more details.
— config=mkl # Build with MKL support.
— config=monolithic # Config for mostly static monolithic build.
Configuration finished

Set Environment Variables

$ export CUDA_HOME=/usr/local/cuda# (of course USERNAME is your Mac Username)
$ export DYLD_LIBRARY_PATH=/Users/USERNAME/lib:/usr/local/cuda/lib:/usr/local/cuda/extras/CUPTI/lib

Build Process

Feel free to download my wheel file. But hey, no build no fun ;-)
Build duration on my machine was about one hour.

$ bazel build — config=cuda — config=opt — action_env PATH — action_env LD_LIBRARY_PATH — action_env DYLD_LIBRARY_PATH //tensorflow/tools/pip_package:build_pip_packageCreate wheel file and install it

Create wheel file and install it

$ bazel-bin/tensorflow/tools/pip_package/build_pip_package /tmp/tensorflow_pkg
$ cd ~
$ pip install /tmp/tensorflow_pkg/tensorflow-1.6.0rc0-cp36-cp36m-macosx_10_13_x86_64.whl

Test Installation

Get it a shoot an open the python interpreter…

>>> import tensorflow as tf
>>> tf.__version__
>>> if.Session()

tensorflow/core/common_runtime/gpu/gpu_device.cc:1331] Found device 0 with properties:
name: GeForce GTX 1060 6GB major: 6 minor: 1 memoryClockRate(GHz): 1.7085
pciBusID: 0000:c3:00.0
totalMemory: 6.00GiB freeMemory: 5.91GiB

tensorflow/core/common_runtime/gpu/gpu_device.cc:1021] Creating TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 5699 MB memory) -> physical GPU (device: 0, name: GeForce GTX 1060 6GB, pci bus id: 0000:c3:00.0, compute capability: 6.1)

Test GPU Acceleration

Finally, we will use Theano, Keras and TensorFlow to test the GPU acceleration.

$ pip install git+git://github.com/Theano/Theano.git
$ pip install keras
$ cd ~/temp
$ git clone https://github.com/fchollet/keras.git
$ cd keras/examples
# Run in CPU mode
$ THEANO_FLAGS=mode=FAST_RUN python imdb_cnn.py
# Run in GPU mode
$ THEANO_FLAGS=mode=FAST_RUN,device=gpu,floatX=float32 python imdb_cnn.py
25000/25000 [==============================] — 15s 595us/step — loss: 0.4028 — acc: 0.8008 — val_loss: 0.3038 — val_acc: 0.8690
Epoch 2/2
25000/25000 [==============================] — 10s 387us/step — loss: 0.2298 — acc: 0.9072 — val_loss: 0.2858 — val_acc: 0.8817

Originally published at byai.io on March 10, 2018.

Software Developer and AI Enthusiast