DiffusersでTextual Inversionを試してみる(Stable Diffusion v1.4のファインチューニング)

はじめに

Textual Inversionとは既存モデルに対して数枚の画像でファインチューニングする手法です。

今回はStable Diffusion v1.4のファインチューニングを行いました。

基本的には後述する公式チュートリアルを実行しただけです。

環境構築

PC環境

Windows 11
CUDA 11.6.2
Python 3.10.9
Git for Windows 2.39.0

Python環境の構築

pip install torch==1.13.1+cu116 torchvision==0.14.1+cu116 --extra-index-url https://download.pytorch.org/whl/cu116
pip install git+https://github.com/huggingface/diffusers.git
pip install git+https://github.com/huggingface/transformers.git
pip install accelerate==0.15.0 scipy==1.10.0
pip install datasets==2.8.0 ftfy==6.1.1 modelcards==0.1.6 tensorboard==2.11.2
pip install xformers==0.0.16rc425
pip install safetensors==0.2.8

事前準備

Stable Diffusion v1.4のダウンロード

git lfs install --skip-smudge
git clone https://huggingface.co/CompVis/stable-diffusion-v1-4



上記実行後に手動で以下をダウンロードしました。

stable-diffusion-v1-4\safety_checker\pytorch_model.bin
stable-diffusion-v1-4\text_encoder\pytorch_model.bin
stable-diffusion-v1-4\unet\diffusion_pytorch_model.bin
stable-diffusion-v1-4\vae\diffusion_pytorch_model.bin



下記は削除しました。残っているとうまくいきませんでした。

stable-diffusion-v1-4\safety_checker\model.safetensors
stable-diffusion-v1-4\text_encoder\model.safetensors
stable-diffusion-v1-4\unet\diffusion_pytorch_model.safetensors
stable-diffusion-v1-4\vae\diffusion_pytorch_model.safetensors

Pythonスクリプトのダウンロード

こちらを使用させて頂きました。

使用する画像のダウンロード

こちらから6枚の画像をダウンロードさせて頂きました。

「toy_data」という名前のフォルダを作成してその中に6枚の画像を保存しました。

画像のサイズはまちまちですがそのままでOKです。


実行

学習

accelerate config
------------------------------------------------------------------------------------------------------------------------
In which compute environment are you running?
This machine
------------------------------------------------------------------------------------------------------------------------
Which type of machine are you using?
No distributed training
Do you want to run your training on CPU only (even if a GPU is available)? [yes/NO]:NO
Do you wish to optimize your script with torch dynamo?[yes/NO]:NO
Do you want to use DeepSpeed? [yes/NO]: NO
What GPU(s) (by id) should be used for training on this machine as a comma-seperated list? [all]:all
------------------------------------------------------------------------------------------------------------------------
Do you wish to use FP16 or BF16 (mixed precision)?
fp16
accelerate launch textual_inversion.py ^
--pretrained_model_name_or_path="stable-diffusion-v1-4" ^
--train_data_dir="toy_data" ^
--learnable_property="object" ^
--placeholder_token="<cat-toy>" ^
--initializer_token="toy" ^
--resolution=512 ^
--train_batch_size=1 ^
--gradient_accumulation_steps=4 ^
--max_train_steps=500 ^
--learning_rate=5.0e-04 ^
--scale_lr ^
--lr_scheduler="constant" ^
--lr_warmup_steps=0 ^
--output_dir="textual_inversion_cat"

コマンドプロンプトを使用しているので改行が「^」になっています。
各自の環境にあわせて下さい。

推論

import torch
from diffusers import StableDiffusionPipeline

model_id = "textual_inversion_cat"
pipe = StableDiffusionPipeline.from_pretrained(model_id,torch_dtype=torch.float16).to("cuda")

prompt = "A <cat-toy> backpack"

image = pipe(prompt, num_inference_steps=50, guidance_scale=7.5).images[0]

image.save("result.png")

公式チュートリアル

huggingface.co
github.com

参考にさせて頂いたサイト

note.com

その他

RTX 3080 VRAM 12GBで学習可能でした。

ただしVRAMを11.8GB使用しています。

追記

LoRA(Low-Rank Adaptation)の記事も書きました。
touch-sp.hatenablog.com