You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Instructions for setup and running on Mac Silicon chips #25
I’ve heard it is possible to run Stable-Diffusion on Mac Silicon (albeit slowly), would be good to include basic setup and instructions to do this.
Thanks,
Chris
Reacted by Taco Ekkel, Jens Descamps, Augustin Luna, recurrence, Vicent Stéphane, Patrick I. Oliveras, Ryo "Genbuchan" Shigematsu, Andi Andreas, Kevin Hu, Kosei Akaboshi and 30 more
I heard that pytorch updated to include apple MDS in the latest nightly release as well. Will this improve performance on M1 devices by utilizing Metal?
Reacted by j_jones, Vicent Stéphane, Self, Patrick Berard, Art Netsvetaev, Danila Poyarkov, Max Liu, Thushan Fernando, Jan Vermeulen, Alex Merose and 11 more
thanks for these steps. I can get as far as the last one but then installing transformers fails with this error. (the install of setuptools_rust was successful )
running build_ext
running build_rust
error: can't find Rust compiler
If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.
To update pip, run:
pip install --upgrade pip
and then retry package installation.
If you did intend to build this package from source, try installing a Rust compiler from your system package manager and ensure it is on the PATH during installation. Alternatively, rustup (available at https://rustup.rs) is the recommended way to download and update the Rust compiler toolchain.
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for tokenizers
Failed to build tokenizers
ERROR: Could not build wheels for tokenizers, which is required to install pyproject.toml-based projects
for context the first step failed to install python3.10 with brew so I did it with Conda instead. Not sure if having a full anaconda env installed is the problem
Unfortunately I got it working by many hours of trial and error, and in the end I don't know what worked. I'm not even a programmer, I'm just really good at googling stuff.
Basically my process was:
install pytorch nightly
update osx (12.3 required, mine was at 12.1)
use a conda environment, I could not get it to work without it
install missing packages using either pip or conda (one of them usually works)
go through every file and changetorch.device("cpu"/"cuda")to torch.device("mps")
in register_buffer() in ddim.py, change to attr = attr.to(torch.device("mps"), torch.float32)
in layer_norm() in functional.py (part of pytorch I guess), change to return torch.layer_norm(input.contiguous(), ...
in terminal write export PYTORCH_ENABLE_MPS_FALLBACK=1
+ dozens of other things I have forgotten about...
I'm sorry that I can't be more helpful than this.
Reacted by Farley Lai, Yannick, Remixer Dec, neon-sunset, parunach, Alex Merose, Omar Solano, Carter Cole, Klaus Kobald, 337240552 and 10 more
Reacted by Nanao Ei, John D. Pope, Vicent Stéphane, Jeff Easter, Jakub Piotr Cłapa, epi-morphism, Keegan Stothert, Agusti F., Remixer Dec, 0xevm1 and 14 more
Reacted by Nish, lukas balabonas, Sourav Mandal and Dionessa
I don't have access to the model so I haven't tested it, but based off of what @filipux said, I created this pull request to add mps support. If you can't wait for them to merge it you can clone my fork and switch to the apple-silicon-mps-support branch and try it out. Just follow the normal instructions but instead of running conda env create -f environment.yaml, run conda env create -f environment-mac.yaml. I think the only other requirement is that you have to have macOS 12.3 or greater.
Reacted by John D. Pope, thelamedia, Vicent Stéphane, Yuichi Yogo, Keegan Stothert, Sergio, Diego Oliveira, Sam, leavesster, Andrew J Hughes and 1 more
Edit: If you're looking at this comment now, you probably shouldn't follow this. Apparently a lot can change in 2 weeks!
Old comment
I got it to work fully natively without the CPU fallback, sort of. The way I did things is ugly since I prioritized making it work. I can't comment on speeds but my assumption is that using only the native MPS backend is faster?
Just your typical pip install -e . should work for this, there's nothing too special going on here, it's just not what I'd call upstream-quality code by any means. I have only tested txt2img, but I did try to modify knn2img and img2img too.
Edit: It definitely takes more than 20 seconds per image at the default settings with either sampler, not sure if I did something wrong. Might be hitting pytorch/pytorch#77799 :(
@magnusviri: You are free to take anything from my branch for yourself if it's helpful at all, thanks for the PR 😃
Reacted by Nanao Ei, Filip, Vicent Stéphane, Birch-san, Cognitive Catalyst, Agusti F. and Danila Poyarkov
@Raymonf: I merged your changes with mine and so they are in the pull request now. It caught everything that I missed and it almost identical to the changes that @einanao made as well. The only difference I could see was in ldm/models/diffusion/plms.py
einanao:
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device("cuda"):
attr = attr.type(torch.float32).to(torch.device("mps")).contiguous()
Raymonf:
def register_buffer(self, name, attr):
if type(attr) == torch.Tensor:
if attr.device != torch.device(self.device_available):
attr = attr.to(torch.float32).to(torch.device(self.device_available))
I don't know what the code differences are, except that I read that adding .contiguous() fixes bugs when falling back to the cpu.
@einanao Maybe not! How long does yours take to run the default seed and prompt with full precision? GNU time reports 4.52.5 minutes with the fans at 100% on a 16 inch M1 Max, which is way longer than 20 seconds. I'm curious if you using the CPU fallback for some parts makes it faster at all.
@HenkPoley oh wow! I'll have a look into it, but I think the point of Flash attention is using the hardware better. as such, I think there's only a CUDA version of it at the moment. I know there's one merged into PyTorch, but by default isn't even built. perhaps this required building PyTorch from source, enabling that build flag, and relies on having CUDA? will investigate.
okay yeah, it uses HazyResearch's implementation, which is definitely CUDA-specific.
maybe that Triton implementation will be more platform-agnostic. but their readme says they don't support M1.
Hello everyone! I've got both x86_64(Anaconda) and arm64(Miniforge3) Conda environment, but the arm64 one runs much slower than the X86 one. I have no idea how to speed up in the arm64 structure cause it's slow as cpu.I am using the same code, and I'm using M1 silicon chip.
Also don't use the pytorch nightlies they've totally tanked torch.einsum performance recently, stick with the current stable
as that supports MPS enough for good performance from SD.
@Vargol In fact, I am using a version of SD that has been modified to adapt mps support, and it could generate a picture in about 3-4 minutes on the x86 framework(but on arm64 it’s much slower).
But the pytorch I am using is a nightly version. Thanks for reminding me of using the stable version of pytorch, and I would try the fork you provide.
For comparison I'm on a 8Gb Mac Mini and despite it still causing a little swap usage now and again I get 4 it/s so
~ 3.5 minutes for a 50 sample 512x512 image plus around 40-60 seconds for all the model loading (it really does vary a lot for some reason, probably due to the swap usage.).
I understand its significantly faster with 16Gb+. M1 Max @ 64Gb should take ~ 30 seconds per image for the 50 sample 512x512 image plus the model loading time according to the benchmarks I've seen.
I suggest you use that repo in you are on M1 because a lot of people are there, collaborating, and it has many features, such as inpainting, outpainting, textual inversion, as well as allowing to generate large images (e.g. 1024x1024 and beyond) without out-of-memory problems, etc.
Does anyone know what commands will increase the resolution to photographic quality, like you get from the Stable Diffusion website, and if you can get more than one image at a time. This is the only command I have right now to define the output:
--n_samples 1 --n_iter 1 --plms
But I keep getting errors despite no issues with doing all in Terminal. Will check out InvokeAI, just wondering if I'll need to create a whole new setup for their UI. Thanks!
I’m trying to understand how Stable Diffusion works on Apple Silicon (M1/M2/Mac Studio), and I’m a bit confused about the real state of setup and performance.
First, is it actually possible today to run Stable Diffusion properly on Mac Silicon using PyTorch MPS, or is it still mostly CPU-bound in practice unless you use specific forks like InvokeAI or heavily modified repos?
Second, why do some setups (like nightly PyTorch builds with MPS support) show massive speed improvements (e.g., 20–30 seconds per image), while other users report that even on M1 Max the generation time can be 4–9 minutes per image? What exactly determines whether MPS is actually being used correctly?
Third, is there a “recommended stable setup” right now for Apple Silicon users (Python version, PyTorch version, Conda vs pip, and specific SD forks), or is the ecosystem still too fragmented to have a standard installation path?
Finally, why do some repositories or configurations require so many manual patches (like changing .to("mps"), .contiguous(), or modifying layer_norm), and is this still necessary in modern versions or has it been mostly fixed in current releases?
if I recall correctly, there's a lot of overhead (e.g. MPS kernel launch overhead) that the design of pytorch isn't well-suited to fixing.
though, nowadays pytorch supports torch.compile for Mac, so maybe that's worth a try.
Pytorch does have ways to export to CoreML (I think via ONNX), which is probably the only way to access the Neural Processing Unit, but I believe it's slower than the GPU; NPU is for power-saving rather than for performance.
I'm not sure whether MLX supports accessing the NPU, but I would say that even if it doesn't support NPU, MLX is still probably the best way to run it.
I'm also not sure which solutions support flash attention. I think pytorch MPS supports some kind of flash attention nowadays, but my guess would be that CoreML doesn't.
why do some repositories or configurations require so many manual patches (like changing .to("mps"), .contiguous(), or modifying layer_norm), and is this still necessary in modern versions or has it been mostly fixed in current releases?
I would be surprised if pytorch hadn't caught up by now on every operation stable-diffusion required. even a few years ago, it was already very close to working without modifications. I expect the only patches needed today are "remove anything that explicitly mentions CUDA".
my guess is that HF diffusers probably supports it without any compatibility workarounds by now.
Third, is there a “recommended stable setup” right now for Apple Silicon users (Python version, PyTorch version, Conda vs pip, and specific SD forks), or is the ecosystem still too fragmented to have a standard installation path?
I would start with latest stable pytorch (2.11.0), Python 3.14 (if you have any problems with 3.14 due to its substantial changes, I guess try 3.13). I would not use conda. I would use pip, and set up a virtualenv for the project. uv would probably be fine too if you prefer.
the default implementation I would try (in pytorch) would be diffusers.
but MLX is likely faster and the more futureproofed route if you're not married to pytorch.
Activity
thelamedia commentedon Aug 16, 2022
I heard that pytorch updated to include apple MDS in the latest nightly release as well. Will this improve performance on M1 devices by utilizing Metal?
mja commentedon Aug 20, 2022
With Homebrew
Then start
python3and follow the instructions for using diffusers.StableDiffusion is CPU-only on M1 Macs because not all the pytorch ops are implemented for Metal. Generating one image with 50 steps takes 4-5 minutes.
frenchie1980 commentedon Aug 20, 2022
Hi @mja,
thanks for these steps. I can get as far as the last one but then installing transformers fails with this error. (the install of setuptools_rust was successful )
for context the first step failed to install python3.10 with brew so I did it with Conda instead. Not sure if having a full anaconda env installed is the problem
filipux commentedon Aug 20, 2022
Just tried the pytorch nighly build with mps support and have some good news.
On my cpu (M1 Max) it runs very slow, almost 9 minutes per image, but with mps enabled it's ~18x faster: less than 30 seconds per image🤩
thelamedia commentedon Aug 20, 2022
Incredible! Would you mind sharing your exact setup so I can duplicate on my end?
filipux commentedon Aug 20, 2022
Unfortunately I got it working by many hours of trial and error, and in the end I don't know what worked. I'm not even a programmer, I'm just really good at googling stuff.
Basically my process was:
torch.device("cpu"/"cuda")totorch.device("mps")attr = attr.to(torch.device("mps"), torch.float32)return torch.layer_norm(input.contiguous(), ...export PYTORCH_ENABLE_MPS_FALLBACK=1I'm sorry that I can't be more helpful than this.
thelamedia commentedon Aug 21, 2022
Thanks. What are you currently using for checkpoints? Are you using research weights or are you using another model for now?
magnusviri commentedon Aug 21, 2022
I don't have access to the model so I haven't tested it, but based off of what @filipux said, I created this pull request to add mps support. If you can't wait for them to merge it you can clone my fork and switch to the apple-silicon-mps-support branch and try it out. Just follow the normal instructions but instead of running
conda env create -f environment.yaml, runconda env create -f environment-mac.yaml. I think the only other requirement is that you have to have macOS 12.3 or greater.Make input contiguous for torch.layer_norm call
einanao commentedon Aug 21, 2022
I couldn't quite get your fork to work @magnusviri, but based on most of @filipux's suggestions, I was able to install and generate samples on my M2 machine using https://github.com/einanao/stable-diffusion/tree/apple-silicon
Raymonf commentedon Aug 21, 2022
Edit: If you're looking at this comment now, you probably shouldn't follow this. Apparently a lot can change in 2 weeks!
Old comment
I got it to work fully natively without the CPU fallback, sort of. The way I did things is ugly since I prioritized making it work. I can't comment on speeds but my assumption is that using only the native MPS backend is faster?
I used the mps_master branch from kulinseth/pytorch as a base, since it contains an implementation for
aten::index.Tensor_outthat appears to work from what I can tell: https://github.com/Raymonf/pytorch/tree/mps_masterIf you want to use my ugly changes, you'll have to compile PyTorch from scratch as I couldn't get the CPU fallback to work:
I based my version of the Stable Diffusion code on the code from PR #47's branch, you can find my fork here: https://github.com/Raymonf/stable-diffusion/tree/apple-silicon-mps-support
Just your typical
pip install -e .should work for this, there's nothing too special going on here, it's just not what I'd call upstream-quality code by any means. I have only tested txt2img, but I did try to modify knn2img and img2img too.Edit: It definitely takes more than 20 seconds per image at the default settings with either sampler, not sure if I did something wrong. Might be hitting pytorch/pytorch#77799 :(
@magnusviri: You are free to take anything from my branch for yourself if it's helpful at all, thanks for the PR 😃
magnusviri commentedon Aug 21, 2022
@Raymonf: I merged your changes with mine and so they are in the pull request now. It caught everything that I missed and it almost identical to the changes that @einanao made as well. The only difference I could see was in ldm/models/diffusion/plms.py
einanao:
Raymonf:
I don't know what the code differences are, except that I read that adding .contiguous() fixes bugs when falling back to the cpu.
einanao commentedon Aug 21, 2022
Raymonf commentedon Aug 21, 2022
@einanao Maybe not! How long does yours take to run the default seed and prompt with full precision? GNU time reports
4.52.5 minutes with the fans at 100% on a 16 inch M1 Max, which is way longer than 20 seconds. I'm curious if you using the CPU fallback for some parts makes it faster at all.einanao commentedon Aug 21, 2022
It takes me 1.5 minutes to generate 1 sample on a 13 inch M2 2022
346 remaining items
HenkPoley commentedon Sep 25, 2022
@Birch-san 👀 "Speed up stable diffusion by ~50% using flash attention"
https://twitter.com/labmlai/status/1573634095732490240
..might just be a CUDA thing, the way it (doesn't) have access to large caches.
https://github.com/labmlai/annotated_deep_learning_paper_implementations/blob/master/labml_nn/diffusion/stable_diffusion/model/unet_attention.py#L192-L235
Birch-san commentedon Sep 25, 2022
@HenkPoley oh wow! I'll have a look into it, but I think the point of Flash attention is using the hardware better. as such, I think there's only a CUDA version of it at the moment. I know there's one merged into PyTorch, but by default isn't even built. perhaps this required building PyTorch from source, enabling that build flag, and relies on having CUDA? will investigate.
Birch-san commentedon Sep 25, 2022
okay yeah, it uses HazyResearch's implementation, which is definitely CUDA-specific.
maybe that Triton implementation will be more platform-agnostic. but their readme says they don't support M1.
AkiKagura commentedon Oct 8, 2022
Hello everyone! I've got both x86_64(Anaconda) and arm64(Miniforge3) Conda environment, but the arm64 one runs much slower than the X86 one. I have no idea how to speed up in the arm64 structure cause it's slow as cpu.I am using the same code, and I'm using M1 silicon chip.
Vargol commentedon Oct 8, 2022
@AkiKagura This repository has never been changed to enable MPS so it is running on the CPU on Apple Silicon.
Try another fork, I use this one
https://github.com/invoke-ai/InvokeAI
as it makes an effort to keep performance high on M1/M2
Also don't use the pytorch nightlies they've totally tanked torch.einsum performance recently, stick with the current stable
as that supports MPS enough for good performance from SD.
AkiKagura commentedon Oct 8, 2022
@Vargol In fact, I am using a version of SD that has been modified to adapt mps support, and it could generate a picture in about 3-4 minutes on the x86 framework(but on arm64 it’s much slower).
But the pytorch I am using is a nightly version. Thanks for reminding me of using the stable version of pytorch, and I would try the fork you provide.
Vargol commentedon Oct 8, 2022
@AkiKagura
For comparison I'm on a 8Gb Mac Mini and despite it still causing a little swap usage now and again I get 4 it/s so
~ 3.5 minutes for a 50 sample 512x512 image plus around 40-60 seconds for all the model loading (it really does vary a lot for some reason, probably due to the swap usage.).
I understand its significantly faster with 16Gb+. M1 Max @ 64Gb should take ~ 30 seconds per image for the 50 sample 512x512 image plus the model loading time according to the benchmarks I've seen.
Any-Winter-4079 commentedon Oct 8, 2022
@AkiKagura M1 Max with 64GB RAM. The time is 26-27s for 50 steps. It was 30s, but an extra optimization was added a while ago in https://github.com/invoke-ai/InvokeAI
"banana pie" -s50 -W512 -H512 -C7.5 -Ak_lms -n3I suggest you use that repo in you are on M1 because a lot of people are there, collaborating, and it has many features, such as inpainting, outpainting, textual inversion, as well as allowing to generate large images (e.g. 1024x1024 and beyond) without out-of-memory problems, etc.
Also I suggest you check out @Birch-san 's repo.
support apple silicon MPS
Move environment-mac.yaml to Python 3.9 and patch dream.py for Macs.
BeginAnAdventure commentedon Feb 3, 2023
Does anyone know what commands will increase the resolution to photographic quality, like you get from the Stable Diffusion website, and if you can get more than one image at a time. This is the only command I have right now to define the output:
--n_samples 1 --n_iter 1 --plms
Raymonf commentedon Feb 4, 2023
@BeginAnAdventure In txt2img,
--Wand--H:stable-diffusion/scripts/txt2img.py
Lines 163 to 174 in 21f890f
For more than one image at a time, you might have a bad time, but the option is actually
--n_samples.But do consider using InvokeAI or some other UI - the scripts in this repository aren't exactly "feature complete".
BeginAnAdventure commentedon Feb 4, 2023
That's what I thought. I did try using this one:
https://replicate.com/cjwbw/stable-diffusion-high-resolution
But I keep getting errors despite no issues with doing all in Terminal. Will check out InvokeAI, just wondering if I'll need to create a whole new setup for their UI. Thanks!
joaquinariasco-lab commentedon Apr 17, 2026
Hi,
I’m trying to understand how Stable Diffusion works on Apple Silicon (M1/M2/Mac Studio), and I’m a bit confused about the real state of setup and performance.
First, is it actually possible today to run Stable Diffusion properly on Mac Silicon using PyTorch MPS, or is it still mostly CPU-bound in practice unless you use specific forks like InvokeAI or heavily modified repos?
Second, why do some setups (like nightly PyTorch builds with MPS support) show massive speed improvements (e.g., 20–30 seconds per image), while other users report that even on M1 Max the generation time can be 4–9 minutes per image? What exactly determines whether MPS is actually being used correctly?
Third, is there a “recommended stable setup” right now for Apple Silicon users (Python version, PyTorch version, Conda vs pip, and specific SD forks), or is the ecosystem still too fragmented to have a standard installation path?
Finally, why do some repositories or configurations require so many manual patches (like changing .to("mps"), .contiguous(), or modifying layer_norm), and is this still necessary in modern versions or has it been mostly fixed in current releases?
Birch-san commentedon Apr 17, 2026
if I recall correctly, there's a lot of overhead (e.g. MPS kernel launch overhead) that the design of pytorch isn't well-suited to fixing.
though, nowadays pytorch supports torch.compile for Mac, so maybe that's worth a try.
I suspect that the best way to run stable-diffusion would be via MLX, because that's where Apple's development effort is going:
https://github.com/ml-explore/mlx-examples/tree/main/stable_diffusion
Pytorch does have ways to export to CoreML (I think via ONNX), which is probably the only way to access the Neural Processing Unit, but I believe it's slower than the GPU; NPU is for power-saving rather than for performance.
I'm not sure whether MLX supports accessing the NPU, but I would say that even if it doesn't support NPU, MLX is still probably the best way to run it.
I'm not sure why generation time would be as slow as 4–9 mins per image on M1 Max. Apple's benchmarks (pytorch export to CoreML) are more like 30 secs:
https://github.com/apple/ml-stable-diffusion?tab=readme-ov-file#-performance-benchmarks
but bear in mind that CoreML is likely faster than pytorch MPS because it can probably eliminate some overheads.
I'm also not sure which solutions support flash attention. I think pytorch MPS supports some kind of flash attention nowadays, but my guess would be that CoreML doesn't.
I would be surprised if pytorch hadn't caught up by now on every operation stable-diffusion required. even a few years ago, it was already very close to working without modifications. I expect the only patches needed today are "remove anything that explicitly mentions CUDA".
my guess is that HF diffusers probably supports it without any compatibility workarounds by now.
I would start with latest stable pytorch (2.11.0), Python 3.14 (if you have any problems with 3.14 due to its substantial changes, I guess try 3.13). I would not use conda. I would use pip, and set up a virtualenv for the project. uv would probably be fine too if you prefer.
the default implementation I would try (in pytorch) would be diffusers.
but MLX is likely faster and the more futureproofed route if you're not married to pytorch.