Skip to content

Instructions for setup and running on Mac Silicon chips #25

Open

Description

@crsrusl

Hi,

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

Activity

  1. thelamedia commented on Aug 16, 2022

    @thelamedia

    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?

  2. mja commented on Aug 20, 2022

    @mja

    With Homebrew

    brew install [email protected]
    pip3 install torch torchvision
    pip3 install setuptools_rust
    pip3 install -U git+https://github.com/huggingface/diffusers.git
    pip3 install transformers scipy ftfy

    Then start python3 and 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.

  3. frenchie1980 commented on Aug 20, 2022

    @frenchie1980

    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 )

          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

  4. filipux commented on Aug 20, 2022

    @filipux

    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🤩

  5. thelamedia commented on Aug 20, 2022

    @thelamedia

    Incredible! Would you mind sharing your exact setup so I can duplicate on my end?

  6. filipux commented on Aug 20, 2022

    @filipux

    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.

  7. thelamedia commented on Aug 21, 2022

    @thelamedia

    Thanks. What are you currently using for checkpoints? Are you using research weights or are you using another model for now?

  8. magnusviri commented on Aug 21, 2022

    @magnusviri

    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.

  9. einanao commented on Aug 21, 2022

    @einanao

    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

  10. Raymonf commented on Aug 21, 2022

    @Raymonf

    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_out that appears to work from what I can tell: https://github.com/Raymonf/pytorch/tree/mps_master

    If 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:

    # clone the modified mps_master branch
    git clone --recursive -b mps_master https://github.com/Raymonf/pytorch.git pytorch_mps && cd pytorch_mps
    
    # dependencies to build (including for distributed)
    # slightly modified from the docs
    conda install astunparse numpy ninja pyyaml setuptools cmake cffi typing_extensions future six requests dataclasses pkg-config libuv
    
    # build pytorch with explicit USE_DISTRIBUTED=1
    USE_DISTRIBUTED=1 MACOSX_DEPLOYMENT_TARGET=12.4 CC=clang CXX=clang++ python setup.py install

    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 😃

  11. magnusviri commented on Aug 21, 2022

    @magnusviri

    @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.

  12. einanao commented on Aug 21, 2022

    @einanao
  13. Raymonf commented on Aug 21, 2022

    @Raymonf

    @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.

  14. einanao commented on Aug 21, 2022

    @einanao

    It takes me 1.5 minutes to generate 1 sample on a 13 inch M2 2022

  15. 346 remaining items

  16. Birch-san commented on Sep 25, 2022

    @Birch-san

    @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.

  17. Birch-san commented on Sep 25, 2022

    @Birch-san

    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.

  18. AkiKagura commented on Oct 8, 2022

    @AkiKagura

    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.

  19. Vargol commented on Oct 8, 2022

    @Vargol

    @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.

  20. AkiKagura commented on Oct 8, 2022

    @AkiKagura

    @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.

  21. Vargol commented on Oct 8, 2022

    @Vargol

    @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.

  22. Any-Winter-4079 commented on Oct 8, 2022

    @Any-Winter-4079

    @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 -n3

    50/50 [00:26<00:00,  1.87it/s]
    50/50 [00:26<00:00,  1.91it/s]
    50/50 [00:26<00:00,  1.88it/s]
    

    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.

    Also I suggest you check out @Birch-san 's repo.

  23. added a commit that references this issue on Dec 5, 2022
  24. BeginAnAdventure commented on Feb 3, 2023

    @BeginAnAdventure

    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

  25. Raymonf commented on Feb 4, 2023

    @Raymonf

    @BeginAnAdventure In txt2img, --W and --H:

    parser.add_argument(
    "--H",
    type=int,
    default=512,
    help="image height, in pixel space",
    )
    parser.add_argument(
    "--W",
    type=int,
    default=512,
    help="image width, in pixel space",
    )

    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".

  26. BeginAnAdventure commented on Feb 4, 2023

    @BeginAnAdventure

    But do consider using InvokeAI or some other UI - the scripts in this repository aren't exactly "feature complete".

    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!

  27. joaquinariasco-lab commented on Apr 17, 2026

    @joaquinariasco-lab

    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?

  28. Birch-san commented on Apr 17, 2026

    @Birch-san

    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.

    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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions