M1 MacでTensorFlow

# 概要
M1 MacにTensorFlowをインストールして動かした。

https://developer.apple.com/metal/tensorflow-plugin/

以前にインストールしたときと手順が変わっていた。
tensorflow-depsを使わない。tensorflow-macosではなくtensorflowを使う。

# 環境
- MacBook Pro (M1): macOS 14.3.1 Build 23D60
- Python: 下記サイトから[Miniforge3-MacOSX-arm64.sh](https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh "Miniforge3-MacOSX-arm64")をダウンロードしてインストール

https://github.com/conda-forge/miniforge

# 準備
conda環境を作って、必要なパッケージをインストールする。
```shell-session:
$ conda create -n tf python=3.10
$ conda activate tf
```
```shell-session
$ python -m pip install tensorflow
Collecting tensorflow
   :
途中省略
   :
Successfully installed MarkupSafe-2.1.5 absl-py-2.1.0 astunparse-1.6.3
cachetools-5.3.2 certifi-2024.2.2 charset-normalizer-3.3.2
flatbuffers-23.5.26 gast-0.5.4 google-auth-2.27.0
google-auth-oauthlib-1.2.0 google-pasta-0.2.0 grpcio-1.60.1
h5py-3.10.0 idna-3.6 keras-2.15.0 libclang-16.0.6 markdown-3.5.2
ml-dtypes-0.2.0 numpy-1.26.4 oauthlib-3.2.2 opt-einsum-3.3.0
packaging-23.2 protobuf-4.25.2 pyasn1-0.5.1 pyasn1-modules-0.3.0
requests-2.31.0 requests-oauthlib-1.3.1 rsa-4.9 six-1.16.0
tensorboard-2.15.2 tensorboard-data-server-0.7.2 tensorflow-2.15.0
tensorflow-estimator-2.15.0 tensorflow-io-gcs-filesystem-0.36.0
tensorflow-macos-2.15.0 termcolor-2.4.0 typing-extensions-4.9.0
urllib3-2.2.0 werkzeug-3.0.1 wrapt-1.14.1
```
```shell-session
$ python -m pip install tensorflow-metal
Collecting tensorflow-metal
   :
途中省略
   :
Successfully installed tensorflow-metal-1.1.0
```
tensorflow-2.15.0とtensorflow-metal-1.1.0がインストールされた。

# 実行
## パッケージのインポート
```python:
>>> import tensorflow as tf
>>> tf.version.VERSION  # バージョンを確認
'2.15.0'
>>> tf.test.gpu_device_name()  # GPU有無を確認
2024-02-10 17:18:31.284525: I metal_plugin/src/device/metal_device.cc:1154] Metal device set to: Apple M1
2024-02-10 17:18:31.284546: I metal_plugin/src/device/metal_device.cc:296] systemMemory: 16.00 GB
2024-02-10 17:18:31.284554: I metal_plugin/src/device/metal_device.cc:313] maxCacheSize: 5.33 GB
2024-02-10 17:18:31.284629: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2024-02-10 17:18:31.284665: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] Created TensorFlow device (/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
'/device:GPU:0'
```
"Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support."というメッセージが気になるが、以降の動作確認から判断するとデバイスは動作していそう。

https://www.tensorflow.org/api_docs/python/tf/version

https://www.tensorflow.org/api_docs/python/tf/test/gpu_device_name

## データセットの取得
```python:
>>> cifar = tf.keras.datasets.cifar100
>>> (x_train, y_train), (x_test, y_test) = cifar.load_data()
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz
```

https://www.tensorflow.org/api_docs/python/tf/keras/datasets

## ResNet50でモデル構築
```python:
>>> model = tf.keras.applications.ResNet50(include_top=True, weights=None, input_shape=(32, 32, 3), classes=100,)
2024-02-10 17:19:55.334343: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2024-02-10 17:19:55.334368: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] 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>)
```
ここでも前述のメッセージが出る。
```python:
>>> loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
>>> model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
```

https://www.tensorflow.org/api_docs/python/tf/keras/applications/resnet50/ResNet50

https://www.tensorflow.org/api_docs/python/tf/keras/losses/SparseCategoricalCrossentropy

```python:
>>> model.fit(x_train, y_train, epochs=5, batch_size=64)
Epoch 1/5
2024-02-10 17:22:05.871572: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:117] Plugin optimizer for device_type GPU is enabled.
782/782 [==============================] - 128s 149ms/step - loss: 4.7573 - accuracy: 0.0691
Epoch 2/5
782/782 [==============================] - 111s 142ms/step - loss: 4.3355 - accuracy: 0.1049
Epoch 3/5
782/782 [==============================] - 115s 147ms/step - loss: 4.1427 - accuracy: 0.1232
Epoch 4/5
782/782 [==============================] - 122s 156ms/step - loss: 3.7634 - accuracy: 0.1630
Epoch 5/5
782/782 [==============================] - 116s 149ms/step - loss: 3.5003 - accuracy: 0.1960
<keras.src.callbacks.History object at 0x1589d5d50>
```

https://www.tensorflow.org/api_docs/python/tf/keras/Model

# 参考情報

https://pypi.org/project/tensorflow/

https://pypi.org/project/tensorflow-metal/

# 補足
類似の症状を経験されている人がいる模様

https://developer.apple.com/forums/thread/693292