見出し画像

WSL2でAnimateDiffを試してみる

テキストからアニメーションを生成する「AnimateDiff」を試してみます。
モデルの準備がちょっと大変です。


準備

python関連

いつものとおり。

python3 -m venv animatediff
cd $_
source bin/activate

続いて、git clone。

git clone https://github.com/guoyww/AnimateDiff.git
cd AnimateDiff

pip installです。対象パッケージを、environment.yamlを覗いて確認します。

$ cat environment.yaml
name: animatediff
channels:
  - pytorch
  - nvidia
dependencies:
  - python=3.10
  - pytorch=1.13.1
  - torchvision=0.14.1
  - torchaudio=0.13.1
  - pytorch-cuda=11.7
  - pip
  - pip:
    - diffusers==0.11.1
    - transformers==4.25.1
    - xformers==0.0.16
    - imageio==2.27.0
    - decord==0.6.0
    - gdown
    - einops
    - omegaconf
    - safetensors
    - gradio
    - wandb

diffuserはversion指定しないと動かないので注意。

pip install torch transformers accelerate
pip install gdown einops omegaconf safetensors gradio wandb
pip install xformers imageio 
pip diffuser==0.11.1

pip listはこんな感じです。

$ pip list
Package                   Version
------------------------- ------------
accelerate                0.25.0
aiofiles                  23.2.1
altair                    5.2.0
annotated-types           0.6.0
antlr4-python3-runtime    4.9.3
anyio                     3.7.1
appdirs                   1.4.4
attrs                     23.1.0
beautifulsoup4            4.12.2
certifi                   2023.11.17
charset-normalizer        3.3.2
click                     8.1.7
colorama                  0.4.6
contourpy                 1.2.0
cycler                    0.12.1
diffusers                 0.11.1
docker-pycreds            0.4.0
einops                    0.7.0
exceptiongroup            1.2.0
fastapi                   0.104.1
ffmpy                     0.3.1
filelock                  3.13.1
fonttools                 4.46.0
fsspec                    2023.12.0
gdown                     4.7.1
gitdb                     4.0.11
GitPython                 3.1.40
gradio                    4.8.0
gradio_client             0.7.1
h11                       0.14.0
httpcore                  1.0.2
httpx                     0.25.2
huggingface-hub           0.19.4
idna                      3.6
imageio                   2.33.0
importlib-metadata        7.0.0
importlib-resources       6.1.1
Jinja2                    3.1.2
jsonschema                4.20.0
jsonschema-specifications 2023.11.2
kiwisolver                1.4.5
markdown-it-py            3.0.0
MarkupSafe                2.1.3
matplotlib                3.8.2
mdurl                     0.1.2
mpmath                    1.3.0
networkx                  3.2.1
numpy                     1.26.2
nvidia-cublas-cu12        12.1.3.1
nvidia-cuda-cupti-cu12    12.1.105
nvidia-cuda-nvrtc-cu12    12.1.105
nvidia-cuda-runtime-cu12  12.1.105
nvidia-cudnn-cu12         8.9.2.26
nvidia-cufft-cu12         11.0.2.54
nvidia-curand-cu12        10.3.2.106
nvidia-cusolver-cu12      11.4.5.107
nvidia-cusparse-cu12      12.1.0.106
nvidia-nccl-cu12          2.18.1
nvidia-nvjitlink-cu12     12.3.101
nvidia-nvtx-cu12          12.1.105
omegaconf                 2.3.0
orjson                    3.9.10
packaging                 23.2
pandas                    2.1.3
Pillow                    10.1.0
pip                       22.0.2
protobuf                  4.25.1
psutil                    5.9.6
pydantic                  2.5.2
pydantic_core             2.14.5
pydub                     0.25.1
Pygments                  2.17.2
pyparsing                 3.1.1
PySocks                   1.7.1
python-dateutil           2.8.2
python-multipart          0.0.6
pytz                      2023.3.post1
PyYAML                    6.0.1
referencing               0.31.1
regex                     2023.10.3
requests                  2.31.0
rich                      13.7.0
rpds-py                   0.13.2
safetensors               0.4.1
semantic-version          2.10.0
sentry-sdk                1.38.0
setproctitle              1.3.3
setuptools                59.6.0
shellingham               1.5.4
six                       1.16.0
smmap                     5.0.1
sniffio                   1.3.0
soupsieve                 2.5
starlette                 0.27.0
sympy                     1.12
tokenizers                0.15.0
tomlkit                   0.12.0
toolz                     0.12.0
torch                     2.1.1
torchaudio                2.1.1
torchvision               0.16.1
tqdm                      4.66.1
transformers              4.35.2
triton                    2.1.0
typer                     0.9.0
typing_extensions         4.8.0
tzdata                    2023.3
urllib3                   2.1.0
uvicorn                   0.24.0.post1
wandb                     0.16.0
websockets                11.0.3
xformers                  0.0.22.post7
zipp                      3.17.0

AnimateDiffが使用するモデルなど

modelsディリクトリの下を確認すると4つ子ディレクトリがあります。いずれにも「モデルを置きなさい」という名前のファイルが格納されています。

$ ls -1 models/*
models/DreamBooth_LoRA:
'Put personalized T2I checkpoints here.txt'

models/MotionLoRA:
'Put MotionLoRA checkpoints here.txt'

models/Motion_Module:
'Put motion module checkpoints here.txt'

models/StableDiffusion:
'Put diffusers stable-diffusion-v1-5 repo here.txt'

そう、これらディレクトリに適切なモデルのファイルを格納しておく必要があります。

git cloneした中身をみると、download_bashscriptsディリクトリにshell scriptが格納されています。これらを参考にしてモデルのファイルを格納していきましょう。

$ $ ls -1 download_bashscripts/
0-MotionModule.sh
1-ToonYou.sh
2-Lyriel.sh
3-RcnzCartoon.sh
4-MajicMix.sh
5-RealisticVision.sh
6-Tusun.sh
7-FilmVelvia.sh
8-GhibliBackground.sh
$

1.Motion Module
0-MotionModule.shを用いれば良い・・・のですが、動かしてみると最新のv2ではないファイルがダウンロードされました。このため、このスクリプトは使用せず、以下のコマンドでgetします。

 wget -P models/Motion_Module https://huggingface.co/guoyww/animatediff/resolve/main/mm_sd_v15_v2.ckpt

2.DreamBooth_LoRA
1~8で始まるスクリプトのいずれかを実行します。今回は、5-RealisticVision.shを用います。保存されたファイル名を記憶しておきましょう。あとで説明する「プロンプトの作成」で使用します。

$ bash ./download_bashscripts/5-RealisticVision.sh
https://civitai.com/api/download/models/29460
Resolving civitai.com (civitai.com)... 104.18.23.206, 104.18.22.206, 2606:4700::6812:17ce, ...
Connecting to civitai.com (civitai.com)|104.18.23.206|:443... connected.
HTTP request sent, awaiting response... 307 Temporary Redirect

(snip)

HTTP request sent, awaiting response... 200 OK
Length: 2132650523 (2.0G) [application/octet-stream]
Saving to: ‘models/DreamBooth_LoRA/realisticVisionV60B1_v20Novae.safetensors’
(snip)

3.Motion LoRA
こちらはスクリプトが見当たらないので、以下のようなスクリプトで、wgetしてきます。

FILES="v2_lora_PanLeft.ckpt
v2_lora_PanRight.ckpt
v2_lora_RollingAnticlockwise.ckpt
v2_lora_RollingClockwise.ckpt
v2_lora_TiltDown.ckpt
v2_lora_TiltUp.ckpt
v2_lora_ZoomIn.ckpt
v2_lora_ZoomOut.ckpt"

for f in $FILES; do
    wget -P models/MotionLoRA https://huggingface.co/guoyww/animatediff/resolve/main/$f
done

4.Stable Diffusion
こちらはgit cloneします。

git clone -b fp16 https://huggingface.co/runwayml/stable-diffusion-v1-5 models/StableDiffusion/stable-diffusion-v1-5

これでモデルのダウンロードは完了です。

プロンプトの作成

configsディレクトリの下の方にプロンプトが記されたファイルがあります。

$ pwd
/path/to/venv/animatediff/AnimateDiff
$ ls -1 configs/prompts/v2/
5-RealisticVision-MotionLoRA.yaml
5-RealisticVision.yaml
$

5-RealisticVision-MotionLoRA.yamlを参考にして、yamlファイルを編集することにします。

$ pwd
/path/to/venv/animatediff/AnimateDiff
$ cp configs/prompts/v2/5-RealisticVision-MotionLoRA.yaml .

コピーしたファイルを編集した結果が以下です。

  • とりあえず、ZoomInだけに絞る

  • dreambooth_pathのファイル名の変更。 

$ cat 5-RealisticVision-MotionLoRA.yaml
ZoomIn:
  inference_config: "configs/inference/inference-v2.yaml"
  motion_module:
    - "models/Motion_Module/mm_sd_v15_v2.ckpt"

  motion_module_lora_configs:
    - path:  "models/MotionLoRA/v2_lora_ZoomIn.ckpt"
      alpha: 1.0

  dreambooth_path: "models/DreamBooth_LoRA/realisticVisionV60B1_v20Novae.safetensors"
  lora_model_path: ""

  seed:           45987230
  steps:          25
  guidance_scale: 7.5

  prompt:
    - "photo of Fuji-san, storm weather, wind, waves, lightning, 8k uhd, dslr, soft lighting, high quality, film grain, Fujifilm XT3"

  n_prompt:
    - "blur, haze, deformed iris, deformed pupils, semi-realistic, cgi, 3d, render, sketch, cartoon, drawing, anime, mutated hands and fingers, deformed, distorted, disfigured, poorly drawn, bad anatomy, wrong anatomy, extra limb, missing limb, floating limbs, disconnected limbs, mutation, mutated, ugly, disgusting, amputation"
$

これで準備が整いました。

アニメーションGIFの生成

ランタイムエラー発生…

コマンド実行すると、

python -m scripts.animate --config ./5-RealisticVision-MotionLoRA.yaml --pretrained_model_path models/StableDiffusion/stable-diffusion-v1-5

あれ・・・。エラーが発生。

RuntimeError: Error(s) in loading state_dict for CLIPTextModel:
	Unexpected key(s) in state_dict: "text_model.embeddings.position_ids". 

ググると、同じようなエラーが発生している模様。

以下のように、1行修正します。

$ git diff
diff --git a/animatediff/utils/convert_from_ckpt.py b/animatediff/utils/convert_from_ckpt.py
index 9ee269d..23e4b79 100644
--- a/animatediff/utils/convert_from_ckpt.py
+++ b/animatediff/utils/convert_from_ckpt.py
@@ -723,7 +723,7 @@ def convert_ldm_clip_checkpoint(checkpoint):
         if key.startswith("cond_stage_model.transformer"):
             text_model_dict[key[len("cond_stage_model.transformer.") :]] = checkpoint[key]

-    text_model.load_state_dict(text_model_dict)
+    text_model.load_state_dict(text_model_dict, strict=False)

     return text_model

$

2度目の実行

待つこと数分…。

$ python -m scripts.animate --config ./5-RealisticVision-MotionLoRA.yaml --pretrained_model_path models/StableDiffusion/stable-diffusion-v1-5
loaded temporal unet's pretrained weights from models/StableDiffusion/stable-diffusion-v1-5/unet ...
### missing keys: 588;
### unexpected keys: 0;
### Temporal Module Parameters: 453.20928 M
/path/to/venv/animatediff/AnimateDiff/animatediff/pipelines/pipeline_animation.py:70: FutureWarning: The configuration file of this scheduler: DDIMScheduler {
  "_class_name": "DDIMScheduler",
  "_diffusers_version": "0.11.1",
  "beta_end": 0.012,
  "beta_schedule": "linear",
  "beta_start": 0.00085,
  "clip_sample": true,
  "num_train_timesteps": 1000,
  "prediction_type": "epsilon",
  "set_alpha_to_one": true,
  "steps_offset": 0,
  "trained_betas": null
}
 is outdated. `steps_offset` should be set to 1 instead of 0. Please make sure to update the config accordingly as leaving `steps_offset` might led to incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json` file
  deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
/path/to/venv/animatediff/AnimateDiff/animatediff/pipelines/pipeline_animation.py:83: FutureWarning: The configuration file of this scheduler: DDIMScheduler {
  "_class_name": "DDIMScheduler",
  "_diffusers_version": "0.11.1",
  "beta_end": 0.012,
  "beta_schedule": "linear",
  "beta_start": 0.00085,
  "clip_sample": true,
  "num_train_timesteps": 1000,
  "prediction_type": "epsilon",
  "set_alpha_to_one": true,
  "steps_offset": 1,
  "trained_betas": null
}
 has not set the configuration `clip_sample`. `clip_sample` should be set to False in the configuration file. Please make sure to update the config accordingly as not setting `clip_sample` in the config might lead to incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json` file
  deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
load motion module from models/Motion_Module/mm_sd_v15_v2.ckpt
load dreambooth model from models/DreamBooth_LoRA/realisticVisionV60B1_v20Novae.safetensors
load motion LoRA from models/MotionLoRA/v2_lora_ZoomIn.ckpt
current seed: 45987230
sampling photo of Fuji-san, storm weather, wind, waves, lightning, 8k uhd, dslr, soft lighting, high quality, film grain, Fujifilm XT3 ...
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 25/25 [02:21<00:00,  5.67s/it]
100%|██████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 16/16 [00:01<00:00, 11.06it/s]
save to samples/5-RealisticVision-MotionLoRA-2023-12-06T02-28-02/sample/photo-of-Fuji-san,-storm-weather,-wind,-waves,-lightning,-8k-uhd,.gif
$

できました。

AnimateDiffより「ズームイン!富士山」

リソース使用量

GPUとメモリ使用量はこんな感じです。溢れてます。とほほ。

この記事が気に入ったらサポートをしてみませんか?