LoginSignup
3
5

Stable Diffusionを触ってみた

Last updated at Posted at 2023-08-08

テキストや画像から画像を生成する、生成aiの1つであるStable Diffusionを今更ながら触ってみました。

環境

  • windows 10
  • NVIDIA GeForce RTX 3070
  • CUDA 11.8
  • python 3.9.13

インストール手順

作業用のディレクトリを準備し、仮想環境を設定します。この後の作業はすべてこの仮想環境を有効化した状態で行います。

python3 -m venv stable_env
source stable_env/bin/activate

github リポジトリからリポジトリをクローンします。

git clone https://github.com/Stability-AI/stablediffusion.git

ここまでのディレクトリ構造は以下の通り。

workspace
  ├ stable_env         (仮想環境)
  └ stable_diffusion   (Stable Diffusionのソースコード)

とても簡単ですがこれだけで大丈夫です。
必要なパッケージをインストールします。requirements.txtが配置されているのでとてもラク。

pip install -r requirements.txt

モデルはHugging Faceからダウンロードしてきます。downloadボタンを押せば入手できるので、stable_diffusion/checkpointsに配置します。
下のような形ですね。

workspace
  ├ stable_env
  └ stablediffusion
      ├ assets
      ├ checkpoints
      :   └ (入手したモデル)
      :

これから説明するxformsのインストールはしなくてもコードは動きます。

xformsをインストールします。

cd ..
git clone https://github.com/facebookresearch/xformers.git
cd xformers
git submodule update --init --recursive
pip install -r requirements.txt
pip install -e .
cd ../stablediffusion

試し

以下のコードを打ち込み、実行します。

python scripts/txt2img.py --prompt "a professional photograph of an astronaut riding a horse" --ckpt <path/to/768model.ckpt/> --config configs/stable-diffusion/v2-inference-v.yaml --H 768 --W 768  

ここで各オプションについて軽く説明:

  • prompt: 画像生成するもとになるテキスト。
  • ckpt: 使用するモデルのパス。
  • config: モデルを構築する設定ファイルのパス。
  • H, W: 生成する画像の高さと幅。
  • device: Stable Diffusionを動かすデバイス。

deviceを指定しないとcpu上で動くようになっていますが、私の場合は以下のようなエラーが出ました。他にも同じように、cpu上で実行しようとすると出て来ている人がちょくちょく見られました。

RuntimeError: Expected attn_mask dtype to be bool or to match query dtype, but got attn_mask.dtype: float and  query.dtype: struct c10::BFloat16 instead.

上記の実行コードに--device cudaを追加して実行すると画像が生成されました。
一回の実行に対して9枚の画像が生成されるようです。

実行結果

promptをいくつか変更して試してみました。
太字が実行したpromptです。なお筆者の英語力についてはおおらかな目で見てください。

a professional photograph of an astronaut riding a horse

a japanese man sitting on the bench is in Kyoto

indian girl eat pasta

ところどころ不自然な部分はありますが、全体的にかなり写真チックなきれいな画像が出力されました。

終わりに

さっくり動かしましたが、結構面白かったです。最初にアメリカの国旗が出てきたから国を限定したpromptを指定してみましたが、とても分かりやすく反映されたなあと。これからさらに調査してみたいと思います。

参考

GitHub/Stability-AI

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5