Stable DiffusionをDockerで動かす on CPU

Stable DiffusionをDockerで動かす on CPU

Stable Diffusion

今何かと話題なStable Diffusionをローカルで動かしてみたい。

商用利用も可能とのことで、広告素材にも使えたら熱いと思い試してみる。

※GPUを使って動かそうとすると少し準備が大変そうだったので、また次回

GitHub - CompVis/stable-diffusion
Contribute to CompVis/stable-diffusion development by creating an account on GitHub.

作ったもの

GitHub - kooooohe/stable-diffusion
Contribute to kooooohe/stable-diffusion development by creating an account on GitHub.

環境

Ubuntu 20.04.5 LTS
AMD® Ryzen 7 pro 5850u with radeon graphics × 16 
AMD® Renoir
memory: 48GB

docker composeで動かす

services:
  stable-diffusion:
    build: .
    volumes:
      - ./app:/app
      - .cache/huggingface:/root/.cache/huggingface
    working_dir: /app
    tty: true
FROM pytorch/pytorch:latest

RUN pip3 install --upgrade diffusers transformers scipy

初回実行時に

git clone https://github.com/kooooohe/stable-diffusion app

として、volume先にcloneしておく。

docker compose up

docker compose stable-diffusion exec bash

でコンテナに入り、下記プログラムを実行する。

import torch
from diffusers import StableDiffusionPipeline
from torch import autocast
 
MODEL_ID = "CompVis/stable-diffusion-v1-4"
DEVICE = "cpu"
YOUR_TOKEN = "YOUR TOKEN"
 
pipe = StableDiffusionPipeline.from_pretrained(MODEL_ID,  use_auth_token=YOUR_TOKEN)
pipe.to(DEVICE)

prompt = "A digital Illustration of Cloud"
 
image = pipe(prompt, guidance_scale=7.5)["sample"][0]
image.save("test.png")

※公式のGitHubのsampleプログラムを実行するとGPUを使おうとしてエラーを吐いたので、とりあえず今の環境(CPU)でも動くように改変しています。

※tokenは予め公式の情報をみて取得しておいてください。

結果

実行時間: 約14分

ftfy or spacy is not installed using BERT BasicTokenizer instead of ftfy.
51it [10:59, 12.94s/it]
root@f3ef6ab788c6:/app# python3 sample.py 
ftfy or spacy is not installed using BERT BasicTokenizer instead of ftfy.
51it [11:12, 13.19s/it]
root@f3ef6ab788c6:/app# python3 sample.py 
ftfy or spacy is not installed using BERT BasicTokenizer instead of ftfy.
51it [14:05, 16.57s/it]
root@f3ef6ab788c6:/app# python3 sapmle.py 
ftfy or spacy is not installed using BERT BasicTokenizer instead of ftfy.
51it [12:13, 14.39s/it]

終わりに

機械でできた雲を出力しようとしましたが、なかなか難しかったです。

グーグル検索をして目的の情報を探すスキルのように、AIに期待する画像を出力させる文言選択のスキルが必要だなと感じました。