R Tensorflow and Keras on Mac M1 (Max)

A method for using tensorflow and keras in R on Mac M1

I was so excited to update from my MacBook Air to the new Pro, especially since I added more memory and RAM.

However, I should have done more research as I didn’t realize that not all software is running natively yet. I planned to use Rstudio, Tensorflow and Keras, for a new project so after I loaded the libraries as normal and ran the RStudio keras demo. And was met with a fatal error, then massive confusion and frustration. Most posts I found about this issue reference OS 11, but my computer was preloaded with OS 12. After many days of trial and error, I finally found success. Hopefully, this helps someone else, too.

Details:
MacBook Pro with M1 Max Chip
macOS Monterey 12.0.1

First, follow the directions here to get tensorflow set up:

Download and install Conda env. In terminal, run:

chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh
sh ~/Downloads/Miniforge3-MacOSX-arm64.sh
source ~/miniforge3/bin/activate

Go through the process to review, then accept license then initialize:

Do you wish the installer to initialize Miniforge3
by running conda init? [yes|no]
[no] >>> yes

Install the TensorFlow dependencies:

conda install -c apple tensorflow-deps

Install base TensorFlow:

python -m pip install tensorflow-macos

Install tensorflow-metal plugin:

python -m pip install tensorflow-metal

Then, use the info at Jarrett Byrnes’s blog to download an ARM-compatible version of R and RStudio

Skip step 1. I had tried different iterations of using the environment created in this step. I may have done something wrong along the way; all I know is that this part did not work for me. (Always got stuck at the .whl file step)

So, starting at step 2:

  1. Install one of the arm64 nightly builds at https://mac.r-project.org/

  2. Install a daily build of Rstudio for OSX from https://dailies.rstudio.com/ so it can handle the new version of R.

Then, modify steps 5 and 8 to account for not having that environment set up. I’m not sure if the conda activate is required, but the Sys.setenv seemed like the key!

conda activate

open -na rstudio

I had already run install.packages(“tensorflow”) install.packages(“keras”); not sure if required to do so in R.

Finally, (in R) load the libraries, set environment to the location of the miniforge download, and specify python location

library(tensorflow)
library(keras)

Sys.setenv(RETICULATE_PYTHON="/Users/kaitlin/miniforge3/bin/python")

use_python("/Users/kaitlin/miniforge3/bin/python")

Now when trying the code from the RStudio tutorial …

mnist <- dataset_mnist()

It works!!