td2sk の日記

技術メモとかゲームとか

Stable Diffusion メモ

概要

画像生成 AI の Stable Diffusion について取り急ぎ需要のありそうな点をメモ

  • NSFW フィルタの無効化
  • VRAM 8GB の GPU での設定方法

NSFW フィルタの無効化

ローカルPCで設定する手順

Google Colaboratory 用手順

Google アカウントを BAN されても知らん*1。自己責任で

  1. !pip install diffusers で diffusers をインストールする
  2. ファイルから /usr/local/lib/python3.7/dist-packages/diffusers/pipelines/stable_diffusion/safety_checker.py を開く
  3. ローカルPCの手順と同様の修正を行い、Ctrl+S で保存する
  4. ランタイム > ランタイムを再起動 を実行

VRAM 8GB の GPU での設定方法

diffusers を通して利用する場合

基本的には 公式の利用手順に沿って設定すればよいが コメントにある通り autocast を用いないとエラーが発生する。

import torch
from torch import autocast
from diffusers import StableDiffusionPipeline

model_id = "CompVis/stable-diffusion-v1-4"
device = "cuda"

# torch_dtype=torch.float16 を追加する
# Windows環境での初回実行時のみ、Administrator権限で実行する必要がある (Symlinkを作るため)
pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16, use_auth_token=True)
pipe = pipe.to(device)

prompt = "sushi on dish"

# 公式ドキュメントに記載がないが、pipe(prompt) の前に with autocast("cuda"): を入れておかないと float16 と float32 が競合してエラーになる
with autocast("cuda"):
    image = pipe(prompt)["sample"][0]
image

Stable Diffusion を直接使う場合

README.md に従って設定する。 github.com

実行する前に scripts/txt2img.py を修正する

diff --git a/scripts/txt2img.py b/scripts/txt2img.py
index da77e1a..f40a835 100644
--- a/scripts/txt2img.py
+++ b/scripts/txt2img.py
@@ -186,6 +186,8 @@ def main():

     config = OmegaConf.load(f"{opt.config}")
     model = load_model_from_config(config, f"{opt.ckpt}")
+    # モデルを fp16に変換する
+    model = model.to(torch.float16)

     device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
     model = model.to(device)

また、標準のバッチサイズ3ではVRAMに乗らないため、実行時オプションで --n_samples 1 もしくは 2 を指定する*2

*1:規約ではNSFW禁止と明示されていないが、DeepFakeが禁止なので場合によっては抵触しうる

*2:2だとメモリ使用量がギリギリなので、時々失敗する