Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rordi/9970c8840614644e01a53d68e51f37fd to your computer and use it in GitHub Desktop.
Save rordi/9970c8840614644e01a53d68e51f37fd to your computer and use it in GitHub Desktop.

Tensorflow & Keras in RStudio on Apple M1 or M2 (arm64) Chips

The problem is not M1 or M2 (arm64) chipset. The problem is keras installation that installs tensorflow-metal, which makes Keras to choose GPU over CPU, even if Sys.setenv("CUDA_VISIBLE_DEVICES" = -1) is set. However, Apple's GPUs are not supported yet by tensorflow-metal. Thus, we have to get rid of tensorflow-metal! Combined with R / RStudio, the trick is to use a dedicated r-reticulate environment to run python and to manually uninstall tensorflow-metal again, which is installed automatically whenever we install and load the keras package in R.

Install Anaconda for arm64 first: https://docs.anaconda.com/anaconda/install/mac-os/

Open the terminal (iterm) and use whereis python on the command line to find your current path to python. You will need to copy the path in below's R scnippet where it says python = "/Users/my_user/opt/anaconda3/bin/python".

Then add this snippet to your R scripts:

# Disable GPU                                                                   
Sys.setenv("CUDA_VISIBLE_DEVICES" = -1)   

install.packages("tensorflow")
library(reticulate)

# replace the file path to your Anaconda python installation accordingly
virtualenv_create("r-reticulate", python = "/Users/my_user/opt/anaconda3/bin/python")
install_tensorflow(envname = "r-reticulate")
install.packages("keras")
library(keras)
install_keras(envname = "r-reticulate")

Then switch over to the terminal (iterm). Because the r-reticulate Keras installation always installs tensorflow-metal again, we have to switch to that conda environment and uninstall the tensorflow-metal again (beacuse Apple's GPU chips are not supported).

  1. Open terminal (iterm)
  2. check the python / conda envs availalbe - find the path to r-miniconda-arm64: conda info --envs
  3. activate the conda env for r-reticulate, for me this was: source /Users/my_user/Library/r-miniconda-arm64/bin/activate
  4. then -- still in iterm -- uninstall the tensorflow-metal again (be sure to use the same coda env python distro): /Users/my_user/Library/r-miniconda-arm64/envs/r-reticulate/bin/python -m pip uninstall tensorflow-metal

Back in your R script, confirm that Tensorflow works:

# confirm installation 
library(tensorflow)
tf$constant("Hello Tensorflow!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment