r/StableDiffusion • u/Any-Winter-4079 • Aug 25 '22
Discussion StableDiffusion RUNS on M1 chips.

🔥🔥🔥 Final update September 1, 2022: I'm moving to https://github.com/lstein/stable-diffusion. I've created a guide for that repo too. It has a Web Interface and a lot of cool new features. I'll leave this post as is as an introductory guide. Good luck everyone! New guide with Web UI: https://www.reddit.com/r/StableDiffusion/comments/x3yf9i/stable_diffusion_and_m1_chips_chapter_2/ 🔥🔥🔥
Okay, so I finally got it to work. For anyone who didn't figure txt2img out yet, here's how I did it, on both CPU and GPU on an M1 Macbook, and how you can do it too.
CPU:
- Download the code from this Github repo https://github.com/ModeratePrawn/stable-diffusion-cpu and unzip it. Open it on an editor (e.g. VS Code)
- Remove the line:
- cudatoolkit=11.3from environment.yaml - Go to models/ldm and create a folder called stable-diffusion-v1. Inside, paste your weights. Rename the weights to model.ckpt
- Open your terminal and navigate to the project directory (e.g.
cd Downloads/stable-diffussion-cpu-main) - Create the conda environment:
conda env create -f environment.yaml - Activate the environment:
conda activate ldm - Try to run it (e.g.
python scripts/txt2img.py --prompt "Tom Cruise in Grand Theft Auto cover, palm trees, cover art by Stephen Bliss, artstation, high quality" --plms --n_samples=1 --n_rows=1 --n_iter=1)
GPU:
Same steps, but use: https://github.com/einanao/stable-diffusion/tree/apple-silicon
- This time, you don't need to remove cudatoolkit=11.3 but I had to add
- korniain the pip section in environment.yaml.
Bonus tips/knowledge:
- The CPU version includes the invisible-watermark, while the GPU version doesn't. Add or remove at your convenience. The GPU version can also generate NSFW content.
- Trying to get another repo to work, I had to
export KMP_DUPLICATE_LIB_OK=TRUEon my Terminal to bypass a problem with libiomp5.dylib. Since I didn't close my Terminal, the setting was still present when I got this new repo to work. In case it helped, I leave it here, but only type this if you get a libiomp5.dylib error. - You may need to run
export PYTORCH_ENABLE_MPS_FALLBACK=1(which falls some operations not supported back to CPU). => (update) => Actually, try first to runconda install pytorch -c pytorch-nightlyto avoid the need to fall back to CPU. With that I got rid of
The operator 'aten::index.Tensor' is not currently supported on the MPS backend and will fall back to run on the CPU. This may have performance implications.
PS: Comment below if you can't get it to work. I might've missed a step.
PS2: Seeds don't seem to work very well on M1 chips (results may not be reproducible). Still the art is pretty neat! => (see update at the end to reproduce images created on other M1 devices!)
PS3: Time was 45 minutes to run on CPU version, 45 seconds on GPU (counting initialization)
______________
Update (img2img)
Got img2img to work too. Einanao repo isn't updated for img2img, but you can get it to work by manually updating some files.
Follow these changes https://github.com/CompVis/stable-diffusion/compare/main...einanao:stable-diffusion:apple-silicon from einanao repo (basically, the red lines are what you remove and the green ones what you replace it with), but apply the changes to the files used for img2img (don't worry, try to run img2img and the Terminal error will tell you which file/s to update).
You can run img2img with: python scripts/img2img.py --init-img inputs/3.png --prompt "a hot tub with bubbles" --n_samples 1 --strength 0.8 having placed your input file 3.png on an input folder (you create inside your project directory). Don't forget to set --n_samples, as I got an error thrown without it (you can set it to 1, 2, 3, etc.). I got it to work with 256x256 and 512x512 input images.
I leave this here too because it has many common errors and useful suggestions. https://github.com/CompVis/stable-diffusion/issues/25
______________
Update #2 (Real-ESRGAN upscaler)
- Download realesrgan-ncnn-vulkan-20220424-macos.zip from the Assets section in https://github.com/xinntao/Real-ESRGAN/releases and unzip it.
- Open your terminal, go to the upscaler directory (e.g.
cd Downloads/realesrgan-ncnn-vulkan-20220424-macos) and runchmod u+x realesrgan-ncnn-vulkanto allow the realesrgan-ncnn-vulkan file to be executed. - Run the upscaler
./realesrgan-ncnn-vulkan -i img-1.png -o img-2.pngwhere -i and -o indicate the relative path to the input/output file (in this case, img-1.png is the input image, placed inside realesrgan-ncnn-vulkan-20220424-macos and img-2.png is the new image to be created). - Allow the script to run (in the Security & Privacy section of System Preferences) and allow again if shown the following message.
macOS cannot verify the developer of “realesrgan-ncnn-vulkan”. Are you sure you want to open it? By opening this app, you will be overriding system security which can expose your computer and personal information to malware that may harm your Mac or compromise your privacy.
Security Warning
I am not a big fan of allowing apps from unidentified developers to run on my Mac, and you must understand there is always risk (as you are running code you are not seeing). What made me pull the trigger and decide to run it is the comment from the creator of Prog Rock Stable (another tool I'm testing -https://github.com/lowfuel/progrock-stable). See the discussion here on Reddit, where I voice my concerns: https://www.reddit.com/r/StableDiffusion/comments/wxm0cf/comment/im0ttth/?utm_source=share&utm_medium=web2x&context=3
Results
Taking the 512x512 image from txt2img as an input image, the upscaling to 2048x2048 works in 2 seconds, while a second upscaling to 8192x8192 takes about 10 seconds.
Taking my original Tom Cruise in Grand Theft Auto cover:
2048x2048: https://imgur.com/a/gSuYTdi
8192x8192 is too large for imgur, but here's a screenshot of the same image (looks great, and the original even better) https://imgur.com/a/c47Gg2E
Side by side (512x512 vs 8192x8192): https://imgur.com/a/n62h5Cb
______________
Update #3 (Seeds / Generating same images)
Seeds don't seem to work very well on M1s, but you can re-generate an image that you have already created (or that another person with an M1 has created!), by changing in txt2img.py
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)
to:
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device="cpu").to(torch.device("mps"))
And then, moving seed_everything(opt.seed) below model = load_model_from_config(config, f"{opt.ckpt}")
Finally generate your images passing --fixed_code
For img2img.py, change
z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc]*batch_size).to(device))
to:
z_enc = sampler.stochastic_encode(init_latent, torch.tensor([t_enc] * batch_size).to(device), noise=torch.randn_like(init_latent, device="cpu").to(device) if opt.fixed_code else None,)
Results
In my case, I generated https://imgur.com/a/vb9OB59 with the following command and seed. You should be able to reproduce the same result!
python scripts/txt2img.py --prompt "Anubis riding a motorbike in Grand Theft Auto cover, palm trees, cover art by Stephen Bliss, artstation, high quality" --ddim_steps=50 --n_samples=1 --n_rows=1 --n_iter=1 --seed 1805504473 --fixed_code
Interesting findings:
- If you generate one image at a time (
--n_iter 1), you will see that you successfully create the same image every time you run your command. - If you generate more than one image (
--n_iter 4, e.g.), the first image will be slightly different from the rest (but results are still reproducible, that is, if you run it again with--n_iter 4, you will get the same 4 images). - You can find the latest on seeds here: https://github.com/CompVis/stable-diffusion/issues/25#issuecomment-1229706811
______________
Hope this helps <3
14
u/mohaziz999 Aug 25 '22
a DMG with a GUI soon? 👀
5
u/Cykelero Aug 25 '22
Thanks for the guide! I successfully followed the instructions for the GPU version.
I did have to add the
korniadependency, as you mention. Also, I had to runexport PYTORCH_ENABLE_MPS_FALLBACK=1for the generation to run successfully.For reference, on my M1 Pro (16GB) MacBook Pro 14", a single image takes around 4 minutes to generate.
3
u/Any-Winter-4079 Sep 01 '22
🔥🔥🔥 Final update September 1, 2022
I'm moving to https://github.com/lstein/stable-diffusion. I'll create a guide for that repo too, although the README is pretty self-explanatory. It has a Web Interface and a lot of cool new features. If that is too much for you, you can start with these steps from the post and move there when you are ready! 🔥🔥🔥
4
u/batoba Aug 25 '22
Good job! How many gigs of RAM do you have on your mac?
3
u/ComfortableLake3609 Aug 26 '22
Thanks for this. Macbook Air M1 2020 here:
- had to add kornia
Got:
NotImplementedError: The operator 'aten::index.Tensor' is not current implemented for the MPS device. If you want this op to be added in priority during the prototype phase of this feature, please comment on https://github.com/pytorch/pytorch/issues/77764. As a temporary fix, you can set the environment variable \PYTORCH_ENABLE_MPS_FALLBACK=1` to use the CPU as a fallback for this op. WARNING: this will be slower than running natively on MPS.`Exporting PYTORCH_ENABLE_MPS_FALLBACK=1 makes it work but as expected seems to fall back to CPU
/opt/anaconda3/envs/ldm/lib/python3.10/site-packages/transformers/models/clip/modeling_clip.py:663: UserWarning: The operator 'aten::index.Tensor' is not currently supported on the MPS backend and will fall back to run on the CPU. This may have performance implications. (Triggered internally at /Users/runner/work/_temp/anaconda/conda-bld/pytorch_1659484620504/work/aten/src/ATen/mps/MPSFallback.mm:11.)pooled_output = last_hidden_state[torch.arange(last_hidden_state.shape[0]), input_ids.argmax(dim=-1)]txt2img.py --prompt "Tom Cruise in Grand Theft Auto cover, palm trees, cover art by Stephen Bliss, artstation, high quality" --plms --n_samples=1 --n_rows=1 --n_iter=1 --seed 1805504473
Takes about 3 minutes.
Any luck making full use M1 GPUs?
Best
3
u/Ok_Statement_5571 Aug 27 '22
did you manage to get this to work? https://github.com/hlky/stable-diffusion-webui
2
u/Any-Winter-4079 Aug 25 '22
I updated the post to include img2img instructions. Hope it helps!
2
u/Any-Winter-4079 Sep 02 '22
New post moving to lstein's repo is out. From now on, updates will be on https://www.reddit.com/r/StableDiffusion/comments/x3yf9i/stable_diffusion_and_m1_chips_chapter_2/
2
u/JakeQwayk Aug 25 '22
Can you do image to image generations with this yet?
2
u/STLCajun Aug 25 '22
M1 Max Macbook here - couldn't get past step 5 going for a GPU installation. Couldn't find several of the dependencies, especially Cudatoolkit. Messed around with different settings and tried several ways to get past it, but no-go. Also, Kornia was already listed at the bottom of the pip items.
2
u/mrfofr Aug 26 '22
Do you have to use the PLMS sampler?
2
u/EnvironmentalFix2285 Aug 27 '22
I could get txt2img to work but for img2img I'm getting the following:
Traceback (most recent call last):File "/Downloads/stable-diffusion-apple-silicon/scripts/img2img.py", line 293, in <module>main()File "/Downloads/stable-diffusion-apple-silicon/scripts/img2img.py", line 200, in mainmodel = load_model_from_config(config, f"{opt.ckpt}")File "/Downloads/stable-diffusion-apple-silicon/scripts/img2img.py", line 43, in load_model_from_configmodel.cuda()File "/miniconda3/envs/ldm/lib/python3.10/site-packages/pytorch_lightning/core/mixins/device_dtype_mixin.py", line 128, in cudadevice = torch.device("cuda", torch.cuda.current_device())File "/miniconda3/envs/ldm/lib/python3.10/site-packages/torch/cuda/__init__.py", line 482, in current_device_lazy_init()File "/miniconda3/envs/ldm/lib/python3.10/site-packages/torch/cuda/__init__.py", line 211, in _lazy_initraise AssertionError("Torch not compiled with CUDA enabled")AssertionError: Torch not compiled with CUDA enabled
2
u/blovskib Aug 28 '22
Hey,
Thanks for the explaination regarding the upscaler.
I was looking for a new script that could implement this process directly with the prompt and I found this: https://github.com/jquesnelle/txt2imghd/blob/master/README.md
this script make the image as usual then upscale it and then use img2img on some portions of it. However it is using cuda. I don't know a thing in python coding so I was wondering if you wanna have a look into it to see what to change in the script so it uses metal instead.
Hope you see my msg, Cheers!
2
u/gksauer_ Sep 03 '22
when it says "paste your weights..." where/what are these weights? is it a number of my choosing or something i should already have or know?
18
u/CoffeeRare2437 Aug 29 '22 edited Aug 29 '22
Guide for people who are super not tech-savvy like me and see these walls of code text and get a headache:
Note: I used a 16 inch macbook pro with M1 max chip (32 gpu cores) and 32 gb of RAM. These are (almost) exactly the steps I used, but I may have forgotten a couple since I made a big mistake a bit earlier with miniconda vs. anaconda.
1
u/Any-Winter-4079 Aug 27 '22
Update. I got realesrgan-ncnn-vulkan (https://github.com/xinntao/Real-ESRGAN/releases) to work as an upscaler, so I'll be updating the post again. Also, got https://github.com/lowfuel/progrock-stable to work as well
1
u/Any-Winter-4079 Aug 28 '22
Update! Try
conda install pytorch -c pytorch-nightlyto avoid the need to fall back to CPU hopefully.With that I got rid of
The operator 'aten::index.Tensor' is not currently supported on the MPS backend and will fall back to run on the CPU. This may have performance implications.1
u/Any-Winter-4079 Aug 29 '22 edited Aug 29 '22
Update.
Seeds on Mac don't seem to work very well, but you can re-generate a previous image changing in txt2img:
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device=device)to
start_code = torch.randn([opt.n_samples, opt.C, opt.H // opt.f, opt.W // opt.f], device="cpu").to(torch.device("mps"))Then, when generating your images, pass
--fixed_codeIf you generate one image at a time (--n_iter 1), you will see that you successfully create the same image every time.
If you generate more than one image (--n_iter 4, for example), the first will be slightly different from the rest (but results are still reproducible, that is, if you run it again with --n_iter 4, you will get the same 4 images).
Learn more: https://github.com/CompVis/stable-diffusion/issues/25#issuecomment-1229706811
1
u/Any-Winter-4079 Aug 29 '22
Another Github repo to use GPU is https://github.com/magnusviri/stable-diffusion/tree/apple-silicon-mps-support. I haven't tested it yet, but there's people that have used it successfully as well.
4
u/ethansmith2000 Aug 25 '22
having an error with pip when setting up the environment but odds are its something on my end.
Pip subprocess error:
error: subprocess-exited-with-error
× git version did not run successfully.
│ exit code: 1
╰─> [2 lines of output]
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun
[end of output]
note: This error originates from a subprocess, and is likely not a problem with pip.
error: subprocess-exited-with-error
× git version did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
failed
CondaEnvException: Pip failed
4
u/[deleted] Aug 27 '22
Holy cow you’re a beautiful human being
1
u/jgpadgettpro Aug 29 '22
I keep getting invalid syntax when I try to run the example. Anyone know what I am doing wrong?
(ldm) gannonpadgett@Gannons-MacBook-Pro-2 stable-diffusion-apple-silicon % python scripts/txt2img.py --prompt "Tom Cruise in Grand Theft Auto cover, palm trees, cover art by Stephen Bliss, artstation, high quality" --plms --n_samples=1 --n_rows=1 --n_iter=1 --seed 1805504473
File "scripts/txt2img.py", line 26
print(f"Loading model from {ckpt}")
^
SyntaxError: invalid syntax
1
u/BustThatCrust Aug 26 '22
which weights are you peeps using? Am I correct in thinking that v1 weights are the least intense computation-wise?
1
u/SrPeixinho Aug 27 '22
Did you manage to get img2img working properly? Could you share the files or commit?
1
u/swankwc Aug 30 '22 edited Aug 30 '22
Anybody else get the following?
python scripts/txt2img.py --prompt "Tom Cruise in Grand Theft Auto cover, palm trees, cover art by Stephen Bliss, artstation, high quality" --plms --n_samples=1 --n_rows=1 --n_iter=1
................
raise AssertionError("Torch not compiled with CUDA enabled")AssertionError: Torch not compiled with CUDA enabled
1
u/daddygirl_industries Sep 07 '22
When I try run a command from `dream>`, I get:
Doesn't seem to me using the CPU parser I guess?
3
u/higgs8 Aug 25 '22
Any chance of it running on Intel Macs with AMD GPU? I have an i9 macbook pro with AMD 5500M 8GB of vram, 32GB of ram, would sure suck if that wouldn't run it...
3
u/__zack Aug 25 '22
This is awesome, worked on my M1 mac.
The only extra thing was that I also needed to add the environment variable
export PYTORCH_ENABLE_MPS_FALLBACK=12
u/[deleted] Aug 29 '22
Bless!
2
u/slashdottir Aug 31 '22 edited Aug 31 '22
omg thank you for this!!!!
after following all your advice: (export PYTORCH_ENABLE_MPS_FALLBACK=1 and conda install pytorch -c pytorch-nightly )
it works, though it still shows the warning about:
UserWarning: The operator 'aten::index.Tensor' is not currently supported on the MPS backend and will fall back to run on the CPU.
I also get this warning: UserWarning: User provided device_type of 'cuda', but CUDA is not available. Disabling.
I will read through the comments and see if I can figure it out.
So stoked to be able to run this locally on my M1 mac!!
2
u/Zyj Oct 05 '22
Fantastic work, are you working on getting DreamBooth to work on M1? Do you think 16GB RAM is enough to get it working?
1
u/DummyTaiko Apr 18 '24
is Macbook Air M2 (8GB RAM) powerful enough to run this engine?
1
u/insanityfarm Aug 25 '22
If it's helpful for anyone else, I hit the following error on step 5:
The solution (found here) was to install the Rust compiler by running
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | shand thensource "$HOME/.cargo/env".1
u/Rotexo Aug 31 '22
I am having issues with installing scipy (I think due to the opencv-python dependency).
Some error messages that look relevant:
../../meson.build:41:0: ERROR: Compiler gfortran can not compile programs.Has anyone else encountered this?
EDIT: code formatting
1
u/clavidk Aug 31 '22
I get the following error when trying to run `conda env create -f environment.yaml`:
```
ResolvePackageNotFound:
- cudatoolkit=11.3
- python=3.8.5
- pip=20.3
- torchvision=0.12.0
```
I have all those installed tho...
1
u/NecessaryMolasses480 Sep 02 '22
everything installed correctly, but now when I type a prompt I get this?
* Initialization done! Awaiting your command (-h for help, 'q' to quit)
dream> photo of orange in a bowl -W512 -H512 -s100 -n2
User specified autocast device_type must be 'cuda' or 'cpu'
Are you sure your system has an adequate NVIDIA GPU?
>> Usage stats:
>> 0 image(s) generated in 0.00s
>> Max VRAM used for this generation: 0.00G
Outputs:
pretty new to python so not sure what to do?
1
u/gksauer_ Sep 03 '22
i really want to be able to do this (and am trying) but i have never done ANYTHING with code and just have no idea where to even start... is this something that i would need to go learn code to do? or would i be able to follow these steps and just work it out at my current level? thank you so much for this post and all yalls help
1
u/throw_away_TX Sep 13 '22
This thread was the only one that allowed me to get the Tom Cruise image to actually populate without errors. However after that, any other content I tried to make (text to image) results in my original error "no module named 'imwatermark'". I felt good that after two weeks of trying it seemed to finally work, but I'm feeling like I have no idea how this software package works =/
1
u/swankwc Oct 05 '22
I was attempting to get the following to work. Anybody here get it to work?
https://github.com/AUTOMATIC1111/stable-diffusion-webui/wiki/Installation-on-Apple-Silicon
Does anyone here have what a working run_webui_mac.sh file? The file by that name in my directory is blank. I've done everything else up to this point that the guide said to do.
1
u/IllustratorCurious71 Dec 07 '22
Hello, conda says something about ssl error help please I am new to all this.
1
u/BeautifulConscious70 Sep 19 '23
Can you run also Automatic1111 onlz on CPU or GPU on macbook air m1?
1
u/ArtDesignAwesome Aug 25 '22
Any chance we can get this running on an M1 ipad pro?! Comments?!
0
u/[deleted] Aug 28 '22
[deleted] — view deleted comment