Tensorflow 2 : Build on macOS

2021년, macOS에서 최신 tensorflow 를 사용해 보려고 빌드과정을 거쳐 보았다.

macOS: build tesorflow

준비

  1. python
  • brew 등으로 최신 파이썬 설치

  • 여기서는 가상환경에서 설치한다 가정

    • pyenv, venv, conda …
  • 가상환경이 아닌 시스템 환경이면 --user 이용.

  1. 유틸 설치

numpy, wheel, keras_preprocessing 설치

  • 가상환경이 아닌 시스템 환경이면 --user 이용.

tensorflow 2.4.1 requires numpy~=1.19.2, but you have numpy 1.18.0 which is incompatible.

1
2
pip install -U pip numpy wheel
pip install -U keras_preprocessing --no-deps

설치된 패키지를 확인

1
2
3
$ pip freeze
Keras-Preprocessing==1.1.2
numpy==1.20.0

Xcode

xcode-select –install

Xcode installed on your macOS,Then execute the command:

1
sudo xcodebuild -license accept

What flags are supported by my CPU?

To check the instruction sets supported by your CPU, check the output of the following commands:

macOS

1
$ sysctl -a | grep "machdep.cpu.*features:"

Linux

1
$ cat /proc/cpuinfo | grep flags

Bazel 설치

tensorflow/configure.py 파일에서 BAZEL 버전을 찾는다. 이중 MAX 로 지시한 Bazel 버전을 사용한다.

1
2
3
_TF_CURRENT_BAZEL_VERSION = None
_TF_MIN_BAZEL_VERSION = '3.1.0'
_TF_MAX_BAZEL_VERSION = '3.99.0'

https://docs.bazel.build/versions/4.0.0/install-os-x.html 를 참고해서

https://github.com/bazelbuild/bazel/releases 에서 MIN, MaX 사이의 적합한 installer 버전을 설치한다.

다운로드

다운로드한다. 예를 들어 3.7.2 버전의 sh 설치 파일은 bazel-3.7.2-installer-darwin-x86_64.sh 이다.

1
2
$ export BAZEL_VERSION=3.7.2
$ curl -fLO "https://github.com/bazelbuild/bazel/releases/download/${BAZEL_VERSION}/bazel-${BAZEL_VERSION}-installer-darwin-x86_64.sh"

Run the installer

Run the Bazel installer as follows:

1
2
chmod +x "bazel-${BAZEL_VERSION}-installer-darwin-x86_64.sh"
./bazel-${BAZEL_VERSION}-installer-darwin-x86_64.sh --user

--user 플래그로 설치시 환경변수에 지정

1
export PATH="$PATH:$HOME/bin"
1
2
~$ bazel --version
bazel 3.7.2

bazel 설치: brew

~$ brew install bazel

빌드

텐서플로우 소스를 준비해서 bazel 을 사용해 빌드한다.

소스 준비

1
2
3
4
5
6
7
$ git clone https://github.com/tensorflow/tensorflow.git
'tensorflow_src'에 복제합니다...
remote: Enumerating objects: 1081830, done.
remote: Total 1081830 (delta 0), reused 0 (delta 0), pack-reused 1081830
오브젝트를 받는 중: 100% (1081830/1081830), 648.00 MiB | 5.20 MiB/s, 완료.
델타를 알아내는 중: 100% (881614/881614), 완료.
Updating files: 100% (24312/24312), 완료.

v2.3.2 빌드

git 체크아웃

1
2
3
4
5
6
7
8
9
$ git tag
0.12.0-rc0
...
v2.3.0
v2.3.1
v2.3.2


$ git checkout v2.3.2

필요한 유틸리티 패키지 설치

1
2
3
4
5
6
7
8
$ python -V
Python 3.8.7


$ pip install -U pip wheel
$ conda install "numpy>=1.8,<1.19"

$ pip install -U keras_preprocessing --no-deps

configure

configure 쉘 스크립이 LFCR 로 되어 ㅇㅣㅆ어서 CR로 변경해야 한다.

1
2
$ mv configure configure.orig
$ sed $'s/\r$//' configure.orig > configure

configure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
$ ./configure
You have bazel 3.7.2 installed.
Please specify the location of python. [Default is /Users/qkboo/.pyenv/versions/tf2_build/bin/python3]:


Found possible Python library paths:
/Users/qkboo/.pyenv/versions/tf2_build/lib/python3.8/site-packages
Please input the desired Python library path to use. Default is [/Users/qkboo/.pyenv/versions/tf2_build/lib/python3.8/site-packages]

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 ROCm support? [y/N]: n
No ROCm support will be enabled for TensorFlow.

Do you wish to build TensorFlow with CUDA support? [y/N]: n
No CUDA support will be enabled for TensorFlow.

Do you wish to download a fresh release of clang? (Experimental) [y/N]: n
Clang will not be downloaded.

Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -march=native -Wno-sign-compare]:


Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: n
Not configuring the WORKSPACE for Android builds.

Do you wish to build TensorFlow with iOS support? [y/N]: y
iOS support will be enabled for TensorFlow.

Preconfigured Bazel build configs. You can use any of the below by adding "--config=<>" to your build command. See .bazelrc for more details.
--config=mkl # Build with MKL support.
--config=monolithic # Config for mostly static monolithic build.
--config=ngraph # Build with Intel nGraph support.
--config=numa # Build with NUMA support.
--config=dynamic_kernels # (Experimental) Build kernels into separate shared objects.
--config=v2 # Build TensorFlow 2.x instead of 1.x.
Preconfigured Bazel build configs to DISABLE default on features:
--config=noaws # Disable AWS S3 filesystem support.
--config=nogcp # Disable GCP support.
--config=nohdfs # Disable HDFS support.
--config=nonccl # Disable NVIDIA NCCL support.
Configuration finished

빌드 시작

Intel 기반의 macOS에서 기본 배포되는 tensorflow@2.0 을 설치하고 tensorflow 를 실행하면,

1
2
3
4
5
6
7
8
9
10
11
(tf2_p37)~$ python
Python 3.7.9 (default, Aug 31 2020, 07:22:35)
[Clang 10.0.0 ] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow as tf
>>>
>>> tf.add(1,2).numpy()
2021-02-01 14:11:37.000601: I tensorflow/core/platform/cpu_feature_guard.cc:145] This TensorFlow binary is optimized with Intel(R) MKL-DNN to use the following CPU instructions in performance critical operations: SSE4.1 SSE4.2 AVX AVX2 FMA
To enable them in non-MKL-DNN operations, rebuild TensorFlow with the appropriate compiler flags.
2021-02-01 14:11:37.001166: I tensorflow/core/common_runtime/process_util.cc:115] Creating new thread pool with default inter op setting: 8. Tune using inter_op_parallelism_threads for best performance.
3

특화 명령 을 –copt 부분에 명시해서 빌드한다.

bazel build: Intel CPU 특화 명령 세트

빌드할 때 아래와 같이 cpu option을 추가로주면 해당 cpu에 대해 최적화된 빌드로 진행됩니다. 아래의 copt 들은 머신마다 다르며, tensorflow warning을 보고 적절히 추가해주면 됩니다.

1
$ bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-msse4.2 //tensorflow/tools/pip_package:build_pip_package

pip에 배포된 패키지와 동일하게 진행할 것이라면…

1
bazel build –config=opt //tensorflow/tools/pip_package:build_pip_package

GPU로 Tensorflow를 사용하고 싶다면… (위에 반드시 CUDA 옵션 선택 메시지에서 Y를 눌러야합니다. 그리고 아래와 같은 명령어를 입력하세요.)

1
$ bazel build –config=opt –config=cuda //tensorflow/tools/pip_package:build_pip_package

GPU cuda 를 포함한 빌드와 CpU 특화 를 함께

1
$ bazel build -c opt --copt=-mavx --copt=-mavx2 --copt=-mfma --copt=-mfpmath=both --copt=-msse4.2 --config=cuda //tensorflow/tools/pip_package:build_pip_package

패키지 빌드

pip 패키지를 생성하기 .whl 설치 패키지를 생성한다.
패키지 추출

1
./bazel-bin/tensorflow/tools/pip_package/build_pip_package ../tensorflow_pkg

v2.4.1 빌드

1
2
3
4
5
6
7
8
9
10
$ git tag
0.12.0-rc0
...
v2.4.0
v2.4.0-rc0
v2.4.0-rc1
v2.4.0-rc2
v2.4.0-rc3
v2.4.0-rc4
v2.4.1
1
git checkout v2.4.1

configure 로 CPU 기반 지원을 구성한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$ ./configure
You have bazel 3.7.2 installed.
Please specify the location of python. [Default is /Users/qkboo/.pyenv/versions/miniconda3-latest/bin/python3]: /Users/qkboo/.pyenv/versions/tf2_p38/bin/python


Found possible Python library paths:
/Users/qkboo/.pyenv/versions/tf2_p38/lib/python3.8/site-packages
Please input the desired Python library path to use. Default is [/Users/qkboo/.pyenv/versions/tf2_p38/lib/python3.8/site-packages]

Do you wish to build TensorFlow with ROCm support? [y/N]: n
No ROCm support will be enabled for TensorFlow.

Do you wish to build TensorFlow with CUDA support? [y/N]: n
No CUDA support will be enabled for TensorFlow.

Do you wish to download a fresh release of clang? (Experimental) [y/N]: n
Clang will not be downloaded.

Please specify optimization flags to use during compilation when bazel option "--config=opt" is specified [Default is -Wno-sign-compare]:


Would you like to interactively configure ./WORKSPACE for Android builds? [y/N]: n
Not configuring the WORKSPACE for Android builds.

Do you wish to build TensorFlow with iOS support? [y/N]: y
iOS support will be enabled for TensorFlow.

Preconfigured Bazel build configs. You can use any of the below by adding "--config=<>" to your build command. See .bazelrc for more details.
--config=mkl # Build with MKL support.
--config=mkl_aarch64 # Build with oneDNN support for Aarch64.
--config=monolithic # Config for mostly static monolithic build.
--config=ngraph # Build with Intel nGraph support.
--config=numa # Build with NUMA support.
--config=dynamic_kernels # (Experimental) Build kernels into separate shared objects.
--config=v2 # Build TensorFlow 2.x instead of 1.x.
Preconfigured Bazel build configs to DISABLE default on features:
--config=noaws # Disable AWS S3 filesystem support.
--config=nogcp # Disable GCP support.
--config=nohdfs # Disable HDFS support.
--config=nonccl # Disable NVIDIA NCCL support.
Configuration finished

파이썬 실행 가능을 확인하고 configure 후 빌드한다.

1
2
3
4
5
6
7
8
9
10
11
12
$ bazel build --config=opt //tensorflow/tools/pip_package:build_pip_package
...
...

INFO: Build options --action_env and --python_path have changed, discarding analysis cache.
INFO: Analyzed target //tensorflow/tools/pip_package:build_pip_package (406 packages loaded, 31116 targets configured).
INFO: Found 1 target...
Target //tensorflow/tools/pip_package:build_pip_package up-to-date:
bazel-bin/tensorflow/tools/pip_package/build_pip_package
INFO: Elapsed time: 16525.185s, Critical Path: 542.13s
INFO: 18390 processes: 150 internal, 18240 local.
INFO: Build completed successfully, 18390 total actions
  • macbook pro 15(2015), 8GB 에서 약 5시간 소요.

패키지 빌드

pip 패키지를 생성하기 .whl 설치 패키지를 생성한다.

1
2
3
4
./bazel-bin/tensorflow/tools/pip_package/build_pip_package ../tensorflow_pkg

$ $ ls -l ../tensorflow_pkg/
-rw-r--r-- 1 qkboo admin 167M 2 1 13:54 tensorflow-2.4.1-cp38-cp38-macosx_11_0_x86_64.whl

패키지 설치

그리고 현재 파이썬 환경에 텐서 플로우를 설치한다

1
2
3
4
5
$ pip install ../tensorflow_pkg/tensorflow-2.4.1-cp38-cp38-macosx_11_0_x86_64.whl

...

Successfully installed absl-py-0.11.0 astunparse-1.6.3 cachetools-4.2.1 certifi-2020.12.5 chardet-4.0.0 flatbuffers-1.12 gast-0.3.3 google-auth-1.24.0 google-auth-oauthlib-0.4.2 google-pasta-0.2.0 grpcio-1.32.0 h5py-2.10.0 idna-2.10 markdown-3.3.3 numpy-1.19.5 oauthlib-3.1.0 opt-einsum-3.3.0 protobuf-3.14.0 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-2.25.1 requests-oauthlib-1.3.0 rsa-4.7 six-1.15.0 tensorboard-2.4.1 tensorboard-plugin-wit-1.8.0 tensorflow-2.4.1 tensorflow-estimator-2.4.0 termcolor-1.1.0 typing-extensions-3.7.4.3 urllib3-1.26.3 werkzeug-1.0.1 wrapt-1.12.1

빌드 후에 소스 트리 디렉토리에서 벗어나 설치된 텐서 플로우를 확인해 보자.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ cd ~
$ python

>>> import tensorflow as tf



>>> import tensorflow as tf
>>> tf.add(1, 2).numpy()
3
>>> hello = tf.constant('Hello, TensorFlow!')
>>> hello.numpy()
b'Hello, TensorFlow!'



>>> t = tf.constant('logcg')
2020-01-18 20:04:43.088104: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fefdc983db0 initialized for platform Host (this does not guarantee that XLA will be used). Devices:
2020-01-18 20:04:43.088134: I tensorflow/compiler/xla/service/service.cc:176] StreamExecutor device (0): Host, Default Version