ML Frameworks/TensorFlow

맥북 m1 프로에서 ML 세팅하기 (아나콘다 anaconda 없이, 텐서플로우 tensorflow)

makeitworth 2022. 9. 6. 08:36

처음 파이썬을 배우게 되면 보통 파이썬 다운로드와 환경 세팅을 위해서 아나콘다를 다운받아서 사용하라고 한다. 특히 주피터 노트북 사용이나 가상환경 사용을위해서 이를 더 강조하는데, 내 생각엔 대부분의 작업이 콘다 없이 가능한데 굳이 무거운데다 가상환경 경로까지 관리하기 귀찮은 콘다를 굳이 사용할 필요가 없다는 생각이다.
이번에 이직을 하게 되면서 새 노트북을 받아 세팅하게 되었는데, 대부분의 참고 포스팅이 콘다를 활용하도록 가이드하고 있어, 콘다 없이 세팅한 과정을 공유하고자 한다.

 

환경

맥북 프로 18, 1 (애플 M1 Pro 칩, 메모리 16GB)

맥 OS (Monterey 12.5.1)

  • 10-core CPU with 8 performance cores and 2 efficiency cores
  • 16-core GPU

prerequisites

파이썬3.8 이상 (나의 경우는 공식 홈페이지에서 인텔과 M칩을 모두 지원하는 3.9.12 버전을 다운로드 받아서 설치했다)

가상환경 만들기 (많은 분들이 conda 가상환경을 선호하지만 나는 여러 이유로 virtualenv를 선호. 작업을 할 워킹 디렉토리를 만들어 들거 간 다음, 새롭게 tf_test 가상환경을 만들고 켜준다.

mkdir tf
cd tf

virtualenv tf_test
source tf_test/bin/activate

 

텐서플로우 설치하기

1. dependencies 설치

pip install -c apple tensorflow-deps

2. 텐서플로우 설치하기

python -m pip install tensorflow-macos

3. gpu framework 설치하기

python -m pip install tensorflow-metal

 

특별히 에러 없이 쭉쭉 설치된다.

 

작동 테스트 

잘 설치되었는지, 연산에서 GPU를 잘 사용하는지 테스트 해보자.

새 주피터 노트북을 열고 가상환경을 연결한 다음 (참고 : https://rollingsnowball.tistory.com/248) 일단 gpu를 잘 잡는지 확인해본다.

import tensorflow as tf

# Check for TensorFlow GPU access
print(f"TensorFlow has access to the following devices:\n{tf.config.list_physical_devices()}")

# See TensorFlow version
print(f"TensorFlow version: {tf.__version__}")

[output]

TensorFlow has access to the following devices: [PhysicalDevice(name='/physical_device:CPU:0', device_type='CPU'), PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

TensorFlow version: 2.9.2

 

요렇게 잘 잡고 있다.

연산할 때도 GPU를 잘 사용하는지 테스트 해보자.

mnist = tf.keras.datasets.mnist

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = tf.keras.models.Sequential([
  tf.keras.layers.Flatten(input_shape=(28, 28)),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(10, activation='softmax')
])

model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=5)

model.evaluate(x_test,  y_test, verbose=2)

맥의 활성 상태 보기 앱을 열어보면,

맥 활성 상태 보기 앱

GPU를 잘 사용하고 있음을 알 수 있다.

 

학습 로그를 보면 초기에 

 

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.

 

요런 로그 메시지가 떠서 쫄았는데, 여기에 따르면 애플 실리콘은 NUMA(non-unified memory architecture) 가 아닌 UMA(unified memory architectur) 이기 때문에 그런 것이고 크게 신경 쓸 필요없다고. 

 

참고 : https://velog.io/@seonghyun/M1-setting-for-MachineLearning

https://datascience.stackexchange.com/questions/102435/could-not-identify-numa-node-of-platform-gpu-id-0-on-m1-macbook