What is the proper way to install TensorFlow on Apple M1 in 2022
Asked Answered
L

15

76

I am facing 4 problems when I tried to install TensorFlow on Apple M1:

  1. Conda has supported M1 since 2022.05.06 but most of articles I googled talk about using Miniforge, e.g. So I feel they are all kind of outdated.

    1. How To Install TensorFlow on M1 Mac (The Easy Way)
    2. AI - Apple Silicon Mac M1 natively supports TensorFlow 2.8 GPU acceleration
    3. How to Setup TensorFlow on Apple M1 Pro and M1 Max (works for M1 too)
    4. How To Install TensorFlow 2.7 on MacBook Pro M1 Pro With Ease
  2. I used the latest conda 4.13 to setup my python environment(3.8, 3.9 and 3.10) successfully but when I tried to install tensorflow I got the error "No matching distribution found for tensorflow" (all failed).

    ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none)
    ERROR: No matching distribution found for tensorflow 
    

The answers in Could not find a version that satisfies the requirement tensorflow didn't help. I can't find useful information on https://www.tensorflow.org/ too, actually https://www.tensorflow.org/install just said pip install tensorflow.

  1. I tried to run pip install tensorflow-macos and it succeeded. I read from the above "works for M1 too" article mentioned "Apple's fork of TensorFlow is called tensorflow-macos" although I can't find much information about that. For example, https://www.tensorflow.org/ does not mention that. I also found from https://developer.apple.com/forums/thread/686926 that someone hit that "ERROR: No matching distribution found for tensorflow-macos" (but I didn't).

  2. All the articles I googled, including above 4 articles and this Tensorflow on macOS Apple M1, all say I also need to run the following 2 commands

    conda install -c apple tensorflow-deps

    pip install tensorflow-metal

But do I really need to that? I can't find this information from https://www.tensorflow.org/. What are these 2 packages tensorflow-deps and tensorflow-metal ?

Leroy answered 13/7, 2022 at 10:32 Comment(4)
Conda has supported osx-arm64 for much longer via Conda Forge. Anaconda only recently added support, which is what OP links. The official Apple installation directions show using Miniforge (which is from Conda Forge), not Anaconda.Lusty
This worked for me milindsoorya.com/blog/…Latreese
@TomJ if you read merv's answer, Lescurel's answer and my own answer you will see our answers are way better than the article you mentioned, because we explain why as how is now a very simple answer.Leroy
@Leroy I would suggest to use Docker for running ML applications in Apple M1. You can find template for that here: cryptiot.de/machine-learning/docker-for-ml-on-macActino
L
37

Distilling the official directions from Apple (as of 13 July 2022), one would create an environment using the following YAML:

tf-metal-arm64.yaml

name: tf-metal
channels:
  - apple
  - conda-forge
dependencies:
  - python=3.9  ## specify desired version
  - pip
  - tensorflow-deps

  ## uncomment for use with Jupyter
  ## - ipykernel

  ## PyPI packages
  - pip:
    - tensorflow-macos
    - tensorflow-metal  ## optional, but recommended

Edit to include additional packages.

Creating environment

Before creating the environment we need to know what the base architecture is. Check this with conda config --show subdir.

Native (osx-arm64) base

If you have installed a native osx-arm64 Miniforge variant (I recommend Mambaforge), then you can create with:

mamba env create -n my_tf_env -f tf-metal-arm64.yaml

Note: If you don't have Mamba, then substitute conda for mamba; or install it for much faster solving: conda install -n base mamba.

Emulated (osx-64) base

If you do not have a native base, then you will need to override the subdir setting:

## create env
CONDA_SUBDIR=osx-arm64 mamba env create -n my_tf_env -f tf-metal-arm64.yaml

## activate
mamba activate my_tf_env

## permanently set the subdir
conda config --env --set subdir osx-arm64

Be sure to always activate the environment before installing or updating packages.

Lusty answered 13/7, 2022 at 18:10 Comment(2)
Thanks for answering my question but why mamba ? I was quite confused with all these installers and that is one of reasons I asked my question.Leroy
It’s a compiled (fast) version of Conda.Lusty
M
31

I battled with this for hours. The current instructions at https://developer.apple.com/metal/tensorflow-plugin/ specify using Miniconda and can be summarized as:

conda create -y --name cv python
conda activate cv
conda install -y -c apple tensorflow-deps
python -m pip install tensorflow-macos tensorflow-metal

As of Jan 2023, these instructions are riddled with issues:

  • Symptom: you ran conda install -c apple tensorflow-deps expecting to get the current version (2.10.0) , but conda list tensorflow-deps shows tensorflow-deps 2.9.0

Reason: Apple's tensorflow-deps package v2.10.0 depends on numpy >=1.23.2,<1.23.3. There is no such version of numpy in Anaconda (only conda-forge). Anaconda's dependency resolution silently falls back to an older version of tensorflow-deps. This will cause more problems as you continue with the instructions.

  • Symptom: you ran conda install -c apple tensorflow-deps==2.10.0 and got UnsatisfiableError: The following specifications were found to be incompatible with each other

Reason: Same as above, but at least Anaconda has told you about it. It doesn't mention what the incompatibility is, because that would be helpful.

  • Symptom: "RuntimeError: module compiled against API version 0x10 but this version of numpy is 0xf"

Reason: If you install tensorflow-deps 2.9.0 (or Anaconda installs it for you due to the above) you will get numpy 1.22.3. When you pip install tensorflow-macos tensorflow-metal, you will get tensorflow-macos 2.11.0 and tensorflow-metal 0.7.0, one or both of which is binary-incompatible with numpy 1.22.3.

  • Symptom: 2023-01-22 15:16:23.209301: W tensorflow/core/framework/op_kernel.cc:1830] OP_REQUIRES failed at xla_ops.cc:418 : NOT_FOUND: could not find registered platform with id

Problem: TensorFlow 2.11 has introduced an incompatibility between optimizers and pluggable architectures. You can have TF 2.11, but you'll need to use a legacy optimizer.

Solutions

I have found 3 options for a working GPU-accelerated TF install on Apple Silicon using Anaconda.

It will help your debugging to get a minimal test script like the one from https://developer.apple.com/metal/tensorflow-plugin/ which is:

import tensorflow as tf

cifar = tf.keras.datasets.cifar100
(x_train, y_train), (x_test, y_test) = cifar.load_data()
model = tf.keras.applications.ResNet50(
    include_top=True,
    weights=None,
    input_shape=(32, 32, 3),
    classes=100,)

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
model.fit(x_train, y_train, epochs=5, batch_size=64)

This way you can check GPU usage by running TF_MLC_LOGGING=1 python tf_arch_test.py and watching Activity Monitor. While feeling which side of the laptop is burning your legs can be a helpful indicator of GPU usage, it's not always reliable.

Fix #1: Add conda-forge as a channel, use the legacy optimizer in your code.

conda config --add channels conda-forge
conda config --set channel_priority strict 
 
conda create -y --name cv
conda activate cv
conda install -y -c apple tensorflow-deps
python -m pip install tensorflow-macos
python -m pip install tensorflow-metal

python --version
conda list|grep -E '(tensorflow|numpy)'

TF_MLC_LOGGING=1 python tf_arch_test.py

You will get:

Python 3.10.8
numpy                     1.23.2          py310h127c7cf_0    conda-forge
tensorflow-deps           2.10.0                        0    apple
tensorflow-estimator      2.11.0                   pypi_0    pypi
tensorflow-macos          2.11.0                   pypi_0    pypi
tensorflow-metal          0.7.0                    pypi_0    pypi

You will need to modify your code to use one of the legacy optimizers. e.g.:

model.compile(
    optimizer=tf.keras.optimizers.legacy.Adam(learning_rate=1e-3),
    loss=loss_fn,
    metrics=["accuracy"],
)

Fix #2: Add conda-forge as a channel, pin the version numbers to avoid the pluggable architecture issue.

conda config --add channels conda-forge
conda config --set channel_priority strict 
 
conda create -y --name cv
conda activate cv
conda install -y -c apple tensorflow-deps==2.10.0
python -m pip install tensorflow-macos==2.10.0
python -m pip install tensorflow-metal==0.6.0

python --version
conda list|grep -E '(tensorflow|numpy)'

You will get:

Python 3.10.8
numpy                     1.23.2          py310h127c7cf_0    conda-forge
tensorflow-deps           2.10.0                        0    apple
tensorflow-estimator      2.10.0                   pypi_0    pypi
tensorflow-macos          2.10.0                   pypi_0    pypi
tensorflow-metal          0.6.0                    pypi_0    pypi

Fix #3: Don't add conda-forge, pin the version numbers way back to the last ones that actually worked:

conda create -y --name cv python
conda activate cv
conda install -y -c apple tensorflow-deps==2.9.0
python -m pip install tensorflow-macos==2.9.2
python -m pip install tensorflow-metal==0.5.1

python --version
conda list|grep -E '(tensorflow|numpy)'

You will get:

Python 3.10.9
numpy                     1.22.3          py310hdb36b11_0
numpy-base                1.22.3          py310h5e3e9f0_0
tensorflow-deps           2.9.0                         0    apple
tensorflow-estimator      2.9.0                    pypi_0    pypi
tensorflow-macos          2.9.2                    pypi_0    pypi
tensorflow-metal          0.5.1                    pypi_0    pypi
Michalemichalski answered 22/1, 2023 at 5:31 Comment(7)
Thanks! I've been struggling with this myself for a day or two. 1) How did you diagnose this? I don't know conda that well, but I couldn't figure out how to get it to tell me what the dependencies for a particular package/version were. 2) What's your thoughts for the most viable path forward here? What needs to be fixed, what's brittle if we just follow this recipe?Esmaria
It would be super nice and useful if Apple updated the docs... 😢Axum
@Johann-Hibschman I think the choice depends on which version of TensorFlow you need to get your work done. In particular if you're using TF via huggingface or fastai, which version of the high-level library has the features and fixes you need, but doesn't rely on one of the many GPU operations implemented in CUDA but not MPS. It's all brittle, pick whatever hacks work for you this month. Look forward to deleting it if/when Apple eventually catches up, and downstream tools just auto-discover which GPU they can move processing to. Then it's goodbye conda!Michalemichalski
Saved me tons of time! Thanks!Storax
Thank you very much. Looks like with 2.12.0 using the legacy optimizer is not neededColorable
This is the answer for upgrading to the latest Metal!!! In my case I had to update conda first. It will prompt you.Rahel
I would discourage the "not adding conda-forge" option since the about.json in the tensorflow-deps builds show they were built against conda-forge channel (not defaults). If anything should be updated in the Apple docs, it should be recommending a Miniforge variant (preferably Mambaforge) for base install rather than Miniconda.Lusty
I
8

First of all, TensorFlow does not support officially the Mac M1. They don't distribute packages precompiled for the Mac M1 (and its specific arm64 arch), hence the tensorflow-macos package, which is maintained by Apple. TensorFlow distributes, as far as I know, official wheels only for x86 (Linux, Windows, Mac), and the Raspberry PI (arm64).

Apple is using a specific plugin in Tensorflow to make the framework compatible with Metal, the graphic stack of MacOS. To put it in a other way, they are leveraging the PluggableDevice API of Tensorflow to write code that translates the TensorFlow operations to code that the GPU of the M1 understands.

Those two packages contain respectively:

  • tensorflow-deps the dependencies to run Tensorflow on arm64, i.e python, numpy, grpcio and h5py. This is more of a convenience package, I believe.
  • tensorflow-metal: a plugin to make tensorflow able to run on metal, the shader API of MacOS (comparable to the low level APIs of Vulkan or DirectX12 on other platforms). You can think of it as a replacement of CUDA, if you are used to run TensorFlow on Nvidia GPUs.

Without the tensorflow-metal package, TensorFlow won't be able to leverage the GPU of the M1, but will still be able to run code on the CPU.

Iselaisenberg answered 13/7, 2022 at 13:21 Comment(4)
Thanks! But what about tensorflow-macos ? Is it "the" package for M1 ? I wonder why tensorflow.org does not mention it.Leroy
TensorFlow does not support officially the Mac M1. They don't distribute packages precompiled for the Mac M1 (specific arm64 arch), hence the tensorflow-macos package, which is maintained by Apple. TensorFlow distributes, as far as I know, official wheels only for x86 (Linux, Windows, Mac), and the Raspberry PI (arm64).Iselaisenberg
Thanks again. Before I asked my question I also searched developer.apple.com forum and found developer.apple.com/forums/thread/686926, so someone hit that ""ERROR: Could not find a version: error with tensorflow-macos too. So it is kind of confusing about this package.Leroy
I added an answer too, so I did need tensorflow-depsLeroy
D
8
  1. Download and install Conda env:

https://github.com/conda-forge/miniforge/releases/latest/download/Miniforge3-MacOSX-arm64.sh

chmod +x ~/Downloads/Miniforge3-MacOSX-arm64.sh
sh ~/Downloads/Miniforge3-MacOSX-arm64.sh
source ~/miniforge3/bin/activate
  1. Install the TensorFlow dependencies:

    conda install -c apple tensorflow-deps

  2. Install base TensorFlow:

python -m pip install tensorflow-macos
  1. Install base TensorFlow-metal:

    python -m pip install tensorflow-metal

  2. Create Conda Environment:

conda create -n tensorflow-env tensorflow
  1. conda activate tensorflow-env
Discussion answered 7/9, 2022 at 9:47 Comment(4)
I think I said it clearly I don't want miniforgeLeroy
You can skip it if u don't want it but make sure u have condaDiscussion
@NikhilJaitak Is there no way to avoid the absolute programming STD that is anything conda/anaconda/miniconda/miniforge related?Woodyard
@PeterR looks like atleast one tool to install the libraries are requiredDiscussion
L
4

The two answers I got have helped better understand how to install TensorFlow on m1. But I would like share my experience too.

  1. About tensorflow-deps. I do need it, without it pip failed to installed grpcio, and thus actually failed to install tensorflow-macos. When I first asked the question I didn't pay enough attention to output of pip install tensorflow-macos.

  2. About tensorflow-macos package, actually https://blog.tensorflow.org/2020/11/accelerating-tensorflow-performance-on-mac.html has the full information. BTW that article, published 2020-11-18, said "In the near future, we’ll be making updates like this even easier for users to get these performance numbers by integrating the forked version into the TensorFlow master branch." But according to Lescurel's answer it seems they have not.

  3. I didn't know the concept of PluggableDevice (as in Lescurel's), so even when I visited https://github.com/apple/tensorflow_macos I was still confused. Take a look at that article if you do not know that either, basically it will let TensorFlow support new devices.

  4. For 4 articles I listed, "works for M1 too" is the most helpful. It actually explained why I need tensorflow-deps & tensorflow-metal. But part of reasons I did not pay enough attention beforehand were: a) I want to use conda, not miniforge, all these package manager tools scare me a little bit (come from nodejs background, npm, yarn, yarn2, pnmp). The answer from merv also suggested another one mamba, but I think I will pass. b) I don't use homebrew, basically all the articles talking about installing ts on m1 mentioned installing homebrew first. But I use macport, for the reason I mentioned here (again I am bit scared of these these package manager tools)

  5. Using environment.yaml like the one in merv's answer is a reliable way to install tensorflow!

BTW, once I have figured out the whole process of installing tensorflow, install pytorch is a lot easier as pytorch also supports M1 now, check here https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/

Leroy answered 14/7, 2022 at 4:8 Comment(0)
P
4

Official instructions from Apple are available here.

At the time of writing:

conda create python=3.10.6 --name <NAME>
conda activate <NAME>
conda install -c apple tensorflow-deps
python -m pip install tensorflow-macos
python -m pip install tensorflow-metal
Pamela answered 4/10, 2022 at 14:43 Comment(4)
Have you or someone actually tried this approach and if yes then how did it went?Dorsy
I'm still getting "The kernel appears to have died. It will restart automatically." from nvlabs.github.io/sionna/examples/Discover_Sionna.ipynb with miniforge3 env set as in the official instructions.Dorsy
It works fine on my M1. I find that executing on CPU with tensorflow-macos is a bit faster for smaller neural nets, and then tensorflow-metal on GPU is faster for larger stuff.Pamela
OK, I noticed that those official instructions changed this week maybe, maybe I'll give it a new try.Dorsy
L
3

I installed a working version of tensorflow 2.9.2 on my M1 Mac with pip. First, install pyenv and python 3.10.6. Next, pip install tensorflow-metal and finally pip install tensorflow-macos. That's it, no need for tensorflow-deps.

If your model complains about the unavailability of cuDNN and runs slowly, try adjusting your script to enable cuDNN as per tensorflow docs

Lunn answered 3/8, 2022 at 19:44 Comment(3)
Without tensorflow-deps I am really not sure if you actually installed tensorflow-macos successfullyLeroy
If you mean grpcio, it installs on the fly (v1.47.0) as dependence.Lunn
this looks like the most reasonable approach to me, unfortunately on mac m1 + python 3.10 it fails during import of tf with symbol not found in flat namespace '__ZNK6google8protobuf10TextFormat21FastFieldValuePrinter19PrintMessageContentERKNS0_7MessageEiibPNS1_17BaseTextGeneratorE'Divorce
F
3

Write 2023-09

tensorflow-deps: Just as it's name, it is a collection of dependencies needed by tensorflow when install on m1.

tensorflow-metal: It is just like cuda, a set of api that make tensorflow can make use of m1, accelarate training. So it is generally recommeded.

Actually, now is no need to install tensorflow-deps. Just follow the official tutorial: Get started with tensorflow-metal

By the way, now wheather to use conda(anaconda, miniforge or others) is also not neccesary. So you can use conda to create environment or just use venv of python itself.

Key installation steps:

If install v2.13 or later: pip install tensorflow

else if install v2.12 or before: pip install tensorflow-macos==<version>

Then install tensorflow-metal: pip install tensorflow-metal==<version>

NOTICE: There is version match between tensorflow(tensorflow-macos) and tensorflow-metal, you can check version on tensorflow-metal pypi https://pypi.org/project/tensorflow-metal/

Now the installation is completed, check it:

import tensorflow as tf

cifar = tf.keras.datasets.cifar100
(x_train, y_train), (x_test, y_test) = cifar.load_data()
model = tf.keras.applications.ResNet50(
    include_top=True,
    weights=None,
    input_shape=(32, 32, 3),
    classes=100,)

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
model.fit(x_train, y_train, epochs=5, batch_size=64)
Facelift answered 7/9, 2023 at 13:17 Comment(0)
M
2

Worked for me using Python 3.10.8 via Homebrew and following the instructions from Apple but using the instructions for "x86: AMD" instead.

Check Python version:

% which python3.10
/opt/homebrew/bin/python3.10

Create venv, activate it (prompt will change), and update pip:

% python3.10 -m venv ~/py310-tf-metal
% source ~/py310-tf-metal/bin/activate
(py310-tf-metal) % which python
~/py310-tf-metal/bin/python
(py310-tf-metal) % python -m pip install -U pip
...
Successfully installed pip-22.3.1

Install tensorflow-macos:

(py310-tf-metal) % python -m pip install tensorflow-macos
...
Successfully installed MarkupSafe-2.1.1 absl-py-1.3.0 astunparse-1.6.3 cachetools-5.2.0 certifi-2022.9.24 charset-normalizer-2.1.1 flatbuffers-22.11.23 gast-0.4.0 google-auth-2.14.1 google-auth-oauthlib-0.4.6 google-pasta-0.2.0 grpcio-1.50.0 h5py-3.7.0 idna-3.4 keras-2.10.0 keras-preprocessing-1.1.2 libclang-14.0.6 markdown-3.4.1 numpy-1.23.5 oauthlib-3.2.2 opt-einsum-3.3.0 packaging-21.3 protobuf-3.19.6 pyasn1-0.4.8 pyasn1-modules-0.2.8 pyparsing-3.0.9 requests-2.28.1 requests-oauthlib-1.3.1 rsa-4.9 six-1.16.0 tensorboard-2.10.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-estimator-2.10.0 tensorflow-macos-2.10.0 termcolor-2.1.1 typing-extensions-4.4.0 urllib3-1.26.13 werkzeug-2.2.2 wheel-0.38.4 wrapt-1.14.1

Install tensorflow-metal:

(py310-tf-metal) % python -m pip install tensorflow-metal
Collecting tensorflow-metal
  Downloading tensorflow_metal-0.6.0-cp310-cp310-macosx_12_0_arm64.whl (1.4 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 1.4/1.4 MB 25.5 MB/s eta 0:00:00
Requirement already satisfied: six>=1.15.0 in ./Venvs/py310-tf-metal/lib/python3.10/site-packages (from tensorflow-metal) (1.16.0)
Requirement already satisfied: wheel~=0.35 in ./Venvs/py310-tf-metal/lib/python3.10/site-packages (from tensorflow-metal) (0.38.4)
Installing collected packages: tensorflow-metal
Successfully installed tensorflow-metal-0.6.0

Test using the CIFAR training script at the Apple page:

import tensorflow as tf

cifar = tf.keras.datasets.cifar100
(x_train, y_train), (x_test, y_test) = cifar.load_data()
model = tf.keras.applications.ResNet50(
    include_top=True,
    weights=None,
    input_shape=(32, 32, 3),
    classes=100,)

loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
model.compile(optimizer="adam", loss=loss_fn, metrics=["accuracy"])
model.fit(x_train, y_train, epochs=5, batch_size=64)

Save above as testcifar.py and run it:

(py310-tf-metal) % python testcifar.py
Downloading data from https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz
169001437/169001437 [==============================] - 3s 0us/step
Metal device set to: Apple M1

systemMemory: 16.00 GB
maxCacheSize: 5.33 GB

2022-11-28 07:58:10.715660: 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.
2022-11-28 07:58:10.715837: 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>)
2022-11-28 07:58:14.736843: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
Epoch 1/5
...
2022-11-28 07:58:21.975675: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
...
Epoch 5/5
782/782 [==============================] - 206s 264ms/step - loss: 4.0877 - accuracy: 0.1292

Mcghee answered 28/11, 2022 at 13:16 Comment(3)
So you didn't install tensorflow-deps ?Leroy
No, did not install tensorflow-deps.Mcghee
It looks like tensorflow or tensorflow macos fixed it so you no longer need to install the deps via miniforge. If I could vote for this answer 10 times I would. But alas, I am the first vote. Thanks!!! Confirmed working on M1 Max (Ventura 13.2)Gangway
M
1

I had to downgrade tensorflow to get it to work on Macbook Pro M2:

pip install tensorflow-macos==2.9 

pip install tensorflow-metal==0.5.0
Martsen answered 18/2, 2023 at 11:17 Comment(1)
It is good to know that because I don't have M2Leroy
H
1

A pure pyenv/poetry based solution (no conda/mamba/brew).

Environment: Mac Mini M1 - Ventura 13.2.1

pyenv managing python versions - using 3.10.9

poetry new m1tfgpu
cd m1tfgpu
poetry add tensorflow-macos==2.9.2
poetry add tensorflow-metal==0.5.0
poetry shell

From this shell you can launch python for example on the CIFAR test at Apple's page and it will happily run using your M1 GPU.

Humidify answered 9/3, 2023 at 17:5 Comment(3)
Unable to find installation candidates for tensorflow-io-gcs-filesystem (0.31.0)Coati
Not sure why, just reran those 5 lines today (28 March 2022) and they work well without any errors. What python are you using? M1, right ?Humidify
ML packages are a joke... update May 24th, 2023: now I also get the Unable to find installation candidates for tensorflow-io-gcs-filesystem (0.32.0) error :( - different version from what @Coati got ...Humidify
U
0

As of 2023, The only option that worked for me was to downgrade the TensorFlow-macos to 2.8 with TensorFlow-metal 0.4.0 Downalod The old tensorflow from pip(history)

This version uses the GPU, which was verified using "Activity Monitor".

pip uninstall tensorflow-metal
conda deactivate <current env>
conda create --name tensorflow_m1 python==3.9
conda activate tensorflow_m1
conda install -c apple tensorflow-deps==2.8
pip install tensorflow-macos==2.8
pip install tensorflow-macos==2.8 --no-dependencies
pip install tensorflow-metal==0.4.0
conda install ipykernel
ipython kernel install --name tensorflow_m1 --user

If you use Jupyter lab/notebook, switch your kernel using the menu on the top right with the one you created ().

enter image description here

if you get an error while importing TensorFlow, you might need to downgrade protobuf using:

pip install protobuf==3.20.*

After all this, you will be able to use M1 GPU for training your models. Happy training. ** Tested on M1 Pro, Feb 2023 **

Ullyot answered 22/2, 2023 at 20:7 Comment(0)
R
0

in 2023 https://developer.apple.com/metal/tensorflow-plugin/ helped me on a mac mini m2. i used anaconda for x86 and thus ran into problems with the channel. for me the following did the job:

[download Miniconda3-latest-MacOSX-arm64.sh from https://developer.apple.com/metal/tensorflow-plugin/ and copy it to ~/]
bash ~/Miniconda3-latest-MacOSX-arm64.sh -b -p $HOME/miniconda

source ~/miniconda/bin/activate
conda install -c apple tensorflow-deps

python -m pip install tensorflow-macos

python -m pip install tensorflow-metal
Robison answered 17/4, 2023 at 16:10 Comment(1)
Any base architecture is capable of installing other architectures. You are free to choose whichever one makes more sense. Moreover, you can even redefine the architecture in the .condarc with the subdir config option. Reinstalling a different version is unnecessary.Lusty
F
0

The Apple M1 error I got stuck on was:

>>> import tensorflow as tf

2023-06-25 13:36:32.780749: F tensorflow/c/experimental/stream_executor/stream_executor.cc:808] Non-OK-status: stream_executor::MultiPlatformManager::RegisterPlatform( std::move(cplatform)) status: INTERNAL: platform is already registered with name: "METAL"

I tried conda / pip / poetry and every combination of pinned packages above, but to no avail.

ChatGPT + Bing explained [https://mcmap.net/q/270243/-tensorflow-metal-plugin-already-registered-error/70966904#70966904] as

TensorFlow metal plugin appears to be registering itself twice when installed under /opt/homebrew.

I manually verified the following fix:

If you install tensorflow-metal using pip in the system locations for brewed pythons, you might get the error about the METAL plugin having been already registered. To avoid this, install tensorflow-metal in your user directory library instead:

This solution suggests that the bug with TensorFlow plugin initialization is avoided when the plugin is installed in the local user directory rather than the system directory​​.

conda deactivate
pip uninstall      tensorflow-macos tensorflow-metal tensorflow 
pip install --user tensorflow-macos tensorflow-metal

Tensorflow Test Script

#!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'  # or any number from 0-3

import sys
import tensorflow as tf
import tensorflow.keras
import platform

if __name__ == '__main__':
    print(f"Python               {sys.version}")
    print(f"Python Platform:     {platform.platform()}")
    print(f"Tensor Flow Version: {tf.__version__}")
    print(f"Keras Version:       {tensorflow.keras.__version__}")
    print("len(tf.config.list_physical_devices('GPU')) ", len(tf.config.list_physical_devices('GPU')))
    print("tf.config.list_physical_devices('GPU')      ", tf.config.list_physical_devices('GPU'))

    # Create some tensors
    print("\nExample:")
    tf.debugging.set_log_device_placement(True)
    a = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
    b = tf.constant([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]])
    c = tf.matmul(a, b)
    print(f"{a} * {b} == {c}")
Python               3.11.4 (main, Jun 15 2023, 07:55:38) [Clang 14.0.3 (clang-1403.0.22.14.1)]
Python Platform:     macOS-13.4.1-arm64-arm-64bit
Tensor Flow Version: 2.12.0
Keras Version:       2.12.0
len(tf.config.list_physical_devices('GPU'))  1
tf.config.list_physical_devices('GPU')       [PhysicalDevice(name='/physical_device:GPU:0', device_type='GPU')]

Example:
input: (_Arg): /job:localhost/replica:0/task:0/device:GPU:0
_EagerConst: (_EagerConst): /job:localhost/replica:0/task:0/device:GPU:0
output_RetVal: (_Retval): /job:localhost/replica:0/task:0/device:GPU:0
a: (_Arg): /job:localhost/replica:0/task:0/device:GPU:0
b: (_Arg): /job:localhost/replica:0/task:0/device:GPU:0
MatMul: (MatMul): /job:localhost/replica:0/task:0/device:GPU:0
product_RetVal: (_Retval): /job:localhost/replica:0/task:0/device:GPU:0
[[1. 2. 3.]
 [4. 5. 6.]] * [[1. 2.]
 [3. 4.]
 [5. 6.]] == [[22. 28.]
 [49. 64.]]
Fraya answered 25/6, 2023 at 13:7 Comment(0)
L
0

XCode's version of Python installs tensorflow-macos without any issues. This is 2023.

% python
Python 3.9.6 (default, May  7 2023, 23:32:44)
[Clang 14.0.3 (clang-1403.0.22.14.1)] 
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
>>>

And below versions work for my code:

 % /Applications/Xcode.app/Contents/Developer/usr/bin/python3 pip list
tensorflow                     2.15.0
tensorflow-estimator           2.15.0
tensorflow-io-gcs-filesystem   0.34.0
tensorflow-macos               2.15.0

Mine was found here:

/Applications/Xcode.app/Contents/Developer/usr/bin/python3 

I added the below line to set python to point to this version in my .zshrc:

 alias python=/Applications/Xcode.app/Contents/Developer/usr/bin/python3
Linc answered 9/12, 2023 at 7:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.