How to run Stable Diffusion on Mac
Quick answer
Run
Stable Diffusion on Mac by installing Python 3.8+, setting up a virtual environment, and installing the diffusers library with torch. Use the StableDiffusionPipeline from diffusers to generate images locally on your Mac.PREREQUISITES
Python 3.8+pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpupip install diffusers transformers scipy ftfyBasic terminal and Python knowledge
Setup
Install Python 3.8+ if not already installed. Use pip to install torch (CPU version recommended for Mac), diffusers, and dependencies. Create a virtual environment to isolate packages.
python3 -m venv sd-env
source sd-env/bin/activate
pip install --upgrade pip
pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu
pip install diffusers transformers scipy ftfy Step by step
Use the StableDiffusionPipeline from diffusers to load the model and generate an image. This example uses the runwayml/stable-diffusion-v1-5 model.
from diffusers import StableDiffusionPipeline
import torch
# Load the pipeline with CPU device
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float32
)
pipe = pipe.to("cpu")
# Generate an image from prompt
prompt = "A fantasy landscape, vivid colors"
image = pipe(prompt).images[0]
# Save the image
image.save("output.png")
print("Image saved as output.png") output
Image saved as output.png
Common variations
- Use GPU acceleration on Mac with Apple Silicon by installing
torchwith MPS support and settingpipe.to("mps"). - Run asynchronously with
asyncioanddiffusersfor non-blocking calls. - Try different Stable Diffusion models by changing the model name in
from_pretrained.
import asyncio
from diffusers import StableDiffusionPipeline
import torch
async def generate_image_async(prompt: str):
pipe = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float32
)
pipe = pipe.to("cpu")
image = await pipe(prompt).images[0]
image.save("async_output.png")
print("Async image saved as async_output.png")
asyncio.run(generate_image_async("A futuristic cityscape at sunset")) output
Async image saved as async_output.png
Troubleshooting
- If you get
RuntimeError: CUDA not availableon Mac, switch to CPU or MPS device. - For slow performance, ensure you use Apple Silicon optimized
torchand MPS device if available. - If
diffusersinstallation fails, upgradepipand install dependencies manually.
Key Takeaways
- Use
diffusersandtorchCPU or MPS builds to run Stable Diffusion on Mac. - Create a Python virtual environment to manage dependencies cleanly.
- Switch device to
mpsfor Apple Silicon Macs to improve performance. - Troubleshoot CUDA errors by using CPU or MPS devices on Mac.
- Experiment with different models by changing the
from_pretrainedargument.