Last mod: 2025.02.19
Stable diffusion on CPU
Stable Diffusion allows users to generate AI images from text prompts. While it's often used with powerful GPUs, it can also run on a CPU, making AI-driven creativity accessible to more users. Whether for art, design, or experimentation, Stable Diffusion offers a flexible way to bring ideas to life with just a few lines of text.
Hardware and basic software
The example is run on:
- CPU i7-4770K
- 32GB RAM (8GB should be enough)
- Ubuntu 24.04 LTS Server
- Python 3.12 (After a default installation of Ubuntu)
Environment and required libraries
Install virtual environments venv:
sudo apt update
sudo apt install python3-venv -y
Create and run virtual environment:
python3 -m venv venv-sd
source venv-sd/bin/activate
Installation of required libraries
pip install diffusers torch transformers accelerate
Script
Writing a script to run stable-diffusion sd.py with code:
from diffusers import StableDiffusionPipeline
import torch
# Load model Stable Diffusion
pipe = StableDiffusionPipeline.from_pretrained("CompVis/stable-diffusion-v1-4")
pipe.to("cpu") # Forced CPU
# # Description and generate image
prompt = "A skyscraper on a starry night with the moon in the background"
image = pipe(prompt).images[0]
# Save image on disk
output_path = "generated_image.png"
image.save(output_path)
print(f"Image saved to file {output_path}")
Run:
python3 sd.py
Let's wait a few minutes and see the end result: