Blog #getting-started #machine-learning #tensorflow
Install TensorFlow on Apple M1 (M1, Pro, Max) with GPU (Metal)
How to install native arm64 TensorFlow with the tensorflow-metal GPU plugin on Apple M1, M1 Pro, and M1 Max Macs using Miniforge.
- Published
- Updated
- Reading
- 2 min
- Author
- Sudhanva Narayana
Note: Remove any existing Intel/Rosetta Anaconda or Anaconda Navigator installations before starting, since Anaconda and arm64 Miniforge cannot coexist cleanly in the same shell profile.
Install Miniforge
- Install Miniforge via Homebrew:
brew install miniforge - Create a dedicated conda environment:
conda create -n tf - Activate the environment:
conda activate tf - Install native
arm64Python:conda install python
Install TensorFlow
- Install Apple’s base TensorFlow dependencies from the
applechannel:conda install -c apple tensorflow-deps - Install the Metal PluggableDevice GPU backend:
pip install tensorflow-metal - Install the native
arm64macOS TensorFlow runtime:pip install tensorflow-macos - Install datasets and notebook packages for the MNIST benchmark below:
pip install tensorflow-datasets pandas jupyterlab
Verify the Installation
- Launch JupyterLab with
jupyter-lab. - Verify that TensorFlow detects both the unified-memory CPU and the Metal GPU:
import tensorflow as tf
import tensorflow_datasets as tfds
print("TensorFlow version:", tf.__version__)
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
print("Num CPUs Available: ", len(tf.config.experimental.list_physical_devices('CPU')))
Here is how tensorflow-macos and the tensorflow-metal PluggableDevice bridge your Python code to Apple Silicon’s unified-memory GPU:
graph TD
subgraph TensorFlow App ["TensorFlow Code (Python)"]
tf["import tensorflow as tf"]
end
subgraph UserSpace ["macOS User Space"]
tf_macos["tensorflow-macos"]
tf_metal["tensorflow-metal plugin"]
end
subgraph AppleFrameworks ["macOS System Frameworks"]
Metal["Metal API"]
end
subgraph Hardware ["Apple Silicon Hardware"]
CPU["Unified Memory CPU"]
GPU["Unified Memory GPU"]
end
tf --> tf_macos
tf_macos --> tf_metal
tf_metal --> Metal
Metal --> GPU
tf_macos --> CPU
Run Sample Code (MNIST)
(ds_train, ds_test), ds_info = tfds.load(
'mnist',
split=['train', 'test'],
shuffle_files=True,
as_supervised=True,
with_info=True,
)
def normalize_img(image, label):
"""Normalizes images: `uint8` -> `float32`."""
return tf.cast(image, tf.float32) / 255., label
batch_size = 128
ds_train = ds_train.map(
normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)
ds_train = ds_train.cache()
ds_train = ds_train.shuffle(ds_info.splits['train'].num_examples)
ds_train = ds_train.batch(batch_size)
ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE)
ds_test = ds_test.map(
normalize_img, num_parallel_calls=tf.data.experimental.AUTOTUNE)
ds_test = ds_test.batch(batch_size)
ds_test = ds_test.cache()
ds_test = ds_test.prefetch(tf.data.experimental.AUTOTUNE)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv2D(32, kernel_size=(3, 3),
activation='relu'),
tf.keras.layers.Conv2D(64, kernel_size=(3, 3),
activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2)),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(128, activation='relu'),
tf.keras.layers.Dense(10, activation='softmax')
])
model.compile(
loss='sparse_categorical_crossentropy',
optimizer=tf.keras.optimizers.Adam(0.001),
metrics=['accuracy'],
)
model.fit(
ds_train,
epochs=12,
validation_data=ds_test,
)
Credits
Related work
Production ML context
See how this topic connects to production ML systems, infrastructure, and inference.