M1 Mac Tensorflow Installation in R

Page content

개요

  • M1 Mac에서 텐서플로를 설치 한다.
  • 필자의 현재 M1 환경은 아래와 같다.
sessionInfo()
R version 4.1.2 (2021-11-01)
Platform: aarch64-apple-darwin20 (64-bit)
Running under: macOS Big Sur 11.6

Matrix products: default
LAPACK: /Library/Frameworks/R.framework/Versions/4.1-arm64/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] ggplot2_3.3.5    dplyr_1.0.7      tfdatasets_2.7.0 keras_2.7.0     
[5] reticulate_1.22  tensorflow_2.7.0

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.7        compiler_4.1.2    pillar_1.6.4      prettyunits_1.1.1
 [5] base64enc_0.1-3   tools_4.1.2       progress_1.2.2    digest_0.6.28    
 [9] zeallot_0.1.0     nlme_3.1-153      gtable_0.3.0      jsonlite_1.7.2   
[13] lifecycle_1.0.1   tibble_3.1.6      lattice_0.20-45   mgcv_1.8-38      
[17] pkgconfig_2.0.3   png_0.1-7         rlang_0.4.12      Matrix_1.3-4     
[21] cli_3.1.0         rstudioapi_0.13   withr_2.4.2       generics_0.1.1   
[25] vctrs_0.3.8       hms_1.1.1         rprojroot_2.0.2   grid_4.1.2       
[29] tidyselect_1.1.1  glue_1.5.0        here_1.0.1        R6_2.5.1         
[33] fansi_0.5.0       farver_2.1.0      purrr_0.3.4       magrittr_2.0.1   
[37] whisker_0.4       splines_4.1.2     scales_1.1.1      tfruns_1.5.0     
[41] ellipsis_0.3.2    colorspace_2.0-2  labeling_0.4.2    utf8_1.2.2       
[45] munsell_0.5.0     crayon_1.4.2 

Miniforge3 설치

  • 다운로드된 파일을 확인해보자.
$ ls
Miniforge3-MacOSX-arm64.sh
  • 파일을 실행한다.
$ chmod +x Miniforge3-MacOSX-arm64.sh
$ sh Miniforge3-MacOSX-arm64.sh
  • Enter키를 여러번 눌러준다.
  • 설치가 끝난 후, conda를 실행해서 정상적으로 conda가 실행되는지 확인한다.
$ bash conda

Conda를 활용한 가상환경 설치

  • 가상환경 설치를 진행한다.
$ conda create --name tf_env python=3.8
Collecting package metadata (current_repodata.json): done
Solving environment: done

## Package Plan ##

  environment location: /Users/your_name/miniforge3/envs/tf_env

  added / updated specs:
    - python=3.8


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    setuptools-59.1.1          |   py38h10201cd_0         1.0 MB  conda-forge
    ------------------------------------------------------------
                                           Total:         1.0 MB

The following NEW packages will be INSTALLED:

  ca-certificates    conda-forge/osx-arm64::ca-certificates-2021.10.8-h4653dfc_0
  libcxx             conda-forge/osx-arm64::libcxx-12.0.1-h168391b_0
  libffi             conda-forge/osx-arm64::libffi-3.4.2-h3422bc3_5
  libzlib            conda-forge/osx-arm64::libzlib-1.2.11-hee7b306_1013
  ncurses            conda-forge/osx-arm64::ncurses-6.2-h9aa5885_4
  openssl            conda-forge/osx-arm64::openssl-3.0.0-h3422bc3_2
  pip                conda-forge/noarch::pip-21.3.1-pyhd8ed1ab_0
  python             conda-forge/osx-arm64::python-3.8.12-hd949e87_2_cpython
  python_abi         conda-forge/osx-arm64::python_abi-3.8-2_cp38
  readline           conda-forge/osx-arm64::readline-8.1-hedafd6a_0
  setuptools         conda-forge/osx-arm64::setuptools-59.1.1-py38h10201cd_0
  sqlite             conda-forge/osx-arm64::sqlite-3.36.0-h72a2b83_2
  tk                 conda-forge/osx-arm64::tk-8.6.11-he1e0b03_1
  wheel              conda-forge/noarch::wheel-0.37.0-pyhd8ed1ab_1
  xz                 conda-forge/osx-arm64::xz-5.2.5-h642e427_1
  zlib               conda-forge/osx-arm64::zlib-1.2.11-hee7b306_1013


Proceed ([y]/n)? y


Downloading and Extracting Packages
setuptools-59.1.1    | 1.0 MB    | ################################################################################## | 100% 
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
#
# To activate this environment, use
#
#     $ conda activate tf_env
#
# To deactivate an active environment, use
#
#     $ conda deactivate
  • 이제 가상환경을 활성화 한 후, 텐서플로를 설치한다.
  • 필자는 pip3으로 패키지를 관리하기 때문에 pip3으로 설정했다. 이는 각 컴퓨터마다 다르기 때문에 필수로 확인한다.
$ conda activate tf_env
(tf_env) your_name$ conda install -c apple tensorflow-deps
(tf_env) your_name$ conda install -c apple tensorflow-deps==2.5.0
(tf_env) your_name$ pip3 install tensorflow-macos
(tf_env) your_name$ pip3 install tensorflow-metal
  • 이제 파이썬을 실행한후 정상적으로 tensorflow가 설치되었는지 확인해본다.
(tf_env) your_name$ python3
Python 3.8.12 | packaged by conda-forge | (default, Oct 12 2021, 21:21:17) 
[Clang 11.1.0 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>> print(tf.__version__)
2.6.0
>>> print(tf.constant("Hello World"))
Metal device set to: Apple M1

systemMemory: 16.00 GB
maxCacheSize: 5.33 GB

2021-11-17 01:59:43.485670: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:305] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2021-11-17 01:59:43.486054: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:271] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
tf.Tensor(b'Hello World', shape=(), dtype=string)
>>> 

RStudio 연결

  • 이제 RStudio를 열어보도록 한다.
  • 그리고 다음과 같이 코드를 작성한다.
library(tensorflow)
library(reticulate) # R에서 파이썬 코드를 쓸 수 있도록 도와주는 패키지

# 아나콘다로 가상환경 설정 (tf_env)
# tf_env 환경안에서 텐서플로우 설치 진행

use_python("~/miniforge3/envs/tf_env/bin/python", require = T)
use_condaenv(condaenv = "tf_env", conda = "~/miniforge3/condabin/conda")

py_config() # crash 일어날 가능성이 큼
> py_config() # crash 일어날 가능성이 큼
python:         /Users/yourname/miniforge3/envs/tf_env/bin/python
libpython:      /Users/yourname/miniforge3/envs/tf_env/lib/libpython3.8.dylib
pythonhome:     /Users/yourname/miniforge3/envs/tf_env:/Users/yourname/miniforge3/envs/tf_env
version:        3.8.12 | packaged by conda-forge | (default, Oct 12 2021, 21:21:17)  [Clang 11.1.0 ]
numpy:          /Users/yourname/miniforge3/envs/tf_env/lib/python3.8/site-packages/numpy
numpy_version:  1.19.5
tensorflow:     /Users/yourname/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow

NOTE: Python version was forced by use_python function
  • 이제 텐서플로를 실행해본다.
> tf$constant("Hellow Tensorflow")
tf.Tensor(b'Hellow Tensorflow', shape=(), dtype=string)
  • 여기까지 잘 따라왔다면 성공한 것이다! 이제 M1 컴퓨터에서 Tensorflow 딥러닝 코드를 작성할 수 있다.

R 강의 소개

Python 강의 홍보