sushann222 commited on
Commit
4127545
·
verified ·
1 Parent(s): e4085c3

Upload folder using huggingface_hub

Browse files
Files changed (35) hide show
  1. .gitattributes +47 -47
  2. README.md +46 -0
  3. assets/bag - Copy.gif +3 -0
  4. assets/bag.gif +3 -0
  5. assets/bag_official - Copy.gif +3 -0
  6. assets/bag_official.gif +3 -0
  7. assets/images/bag.png +0 -0
  8. assets/images/kunkun.png +0 -0
  9. assets/images/sculpture.png +0 -0
  10. assets/img1.jpg +3 -0
  11. assets/kunkun.gif +3 -0
  12. assets/kunkun_official.gif +3 -0
  13. assets/sculpture - Copy.gif +3 -0
  14. assets/sculpture.gif +3 -0
  15. assets/sculpture_official - Copy.gif +3 -0
  16. assets/sculpture_official.gif +3 -0
  17. assets/sv3doutputs.gif +3 -0
  18. convert/convert_sv3d.py +73 -0
  19. convert/convert_svd_to_diffusers.py +728 -0
  20. convert/sv3d_p.yaml +134 -0
  21. diffusers_sv3d/__init__.py +2 -0
  22. diffusers_sv3d/__pycache__/__init__.cpython-39.pyc +0 -0
  23. diffusers_sv3d/models/__init__.py +1 -0
  24. diffusers_sv3d/models/__pycache__/__init__.cpython-39.pyc +0 -0
  25. diffusers_sv3d/models/unets/__init__.py +1 -0
  26. diffusers_sv3d/models/unets/__pycache__/__init__.cpython-39.pyc +0 -0
  27. diffusers_sv3d/models/unets/__pycache__/unet_spatio_temporal_condition.cpython-39.pyc +0 -0
  28. diffusers_sv3d/models/unets/unet_spatio_temporal_condition.py +483 -0
  29. diffusers_sv3d/pipelines/__init__.py +1 -0
  30. diffusers_sv3d/pipelines/__pycache__/__init__.cpython-39.pyc +0 -0
  31. diffusers_sv3d/pipelines/stable_video_diffusion/__init__.py +1 -0
  32. diffusers_sv3d/pipelines/stable_video_diffusion/__pycache__/__init__.cpython-39.pyc +0 -0
  33. diffusers_sv3d/pipelines/stable_video_diffusion/__pycache__/pipeline_stable_video_3d_diffusion.cpython-39.pyc +0 -0
  34. diffusers_sv3d/pipelines/stable_video_diffusion/pipeline_stable_video_3d_diffusion.py +222 -0
  35. requirements.txt +5 -0
.gitattributes CHANGED
@@ -1,47 +1,47 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
36
- bag[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
37
- bag.gif filter=lfs diff=lfs merge=lfs -text
38
- bag_official[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
39
- bag_official.gif filter=lfs diff=lfs merge=lfs -text
40
- img1.jpg filter=lfs diff=lfs merge=lfs -text
41
- kunkun.gif filter=lfs diff=lfs merge=lfs -text
42
- kunkun_official.gif filter=lfs diff=lfs merge=lfs -text
43
- sculpture[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
44
- sculpture.gif filter=lfs diff=lfs merge=lfs -text
45
- sculpture_official[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
46
- sculpture_official.gif filter=lfs diff=lfs merge=lfs -text
47
- sv3doutputs.gif filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ assets/bag[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
37
+ assets/bag.gif filter=lfs diff=lfs merge=lfs -text
38
+ assets/bag_official[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
39
+ assets/bag_official.gif filter=lfs diff=lfs merge=lfs -text
40
+ assets/img1.jpg filter=lfs diff=lfs merge=lfs -text
41
+ assets/kunkun.gif filter=lfs diff=lfs merge=lfs -text
42
+ assets/kunkun_official.gif filter=lfs diff=lfs merge=lfs -text
43
+ assets/sculpture[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
44
+ assets/sculpture.gif filter=lfs diff=lfs merge=lfs -text
45
+ assets/sculpture_official[[:space:]]-[[:space:]]Copy.gif filter=lfs diff=lfs merge=lfs -text
46
+ assets/sculpture_official.gif filter=lfs diff=lfs merge=lfs -text
47
+ assets/sv3doutputs.gif filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # SV3D-diffusers
2
+
3
+ ![](assets/sv3doutputs.gif)
4
+
5
+ This repo provides scripts about:
6
+
7
+ 1. Spatio-temporal UNet (`SV3DUNetSpatioTemporalConditionModel`) and pipeline (`StableVideo3DDiffusionPipeline`) modified from [SVD](https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py) for [SV3D](https://sv3d.github.io) in the [diffusers](https://github.com/huggingface/diffusers) convention.
8
+
9
+ 2. Converting the [Stability-AI](https://github.com/Stability-AI/generative-models)'s [SV3D-p UNet checkpoint](https://huggingface.co/stabilityai/sv3d) to the [diffusers](https://github.com/huggingface/diffusers) convention.
10
+
11
+ 3. Infering the `SV3D-p` model with the [diffusers](https://github.com/huggingface/diffusers) library to synthesize a 21-frame orbital video around a 3D object from a single-view image (preprocessed by removing background and centering first).
12
+
13
+ Converted SV3D-p checkpoints have been uploaded to HuggingFace🤗 [chenguolin/sv3d-diffusers](https://huggingface.co/chenguolin/sv3d-diffusers).
14
+
15
+
16
+ ## 🚀 Usage
17
+ ```bash
18
+ git clone https://github.com/chenguolin/sv3d-diffusers.git
19
+ # Please install PyTorch first according to your CUDA version
20
+ pip3 install -r requirements.txt
21
+ # If you can't access to HuggingFace🤗, try:
22
+ # export HF_ENDPOINT=https://hf-mirror.com
23
+ python3 infer.py --output_dir out/ --image_path assets/images/sculpture.png --elevation 10 --half_precision --seed -1
24
+ ```
25
+ The synthesized video will save at `out/` as a `.gif` file.
26
+
27
+
28
+ ## 📸 Results
29
+ > Image preprocessing and random seed for different implementations are different, so the results are presented only for reference.
30
+
31
+ | Implementation | sculpture | bag | kunkun |
32
+ | :------------- | :------: | :----: | :----: |
33
+ | **SV3D-diffusers (Ours)** | ![](assets/sculpture.gif) | ![](assets/bag.gif) | ![](assets/kunkun.gif) |
34
+ | **Official SV3D** | ![](assets/sculpture_official.gif) | ![](assets/bag_official.gif) | ![](assets/kunkun_official.gif) |
35
+
36
+
37
+ ## 📚 Citation
38
+ If you find this repo helpful, please consider giving this repository a star 🌟 and citing the original SV3D paper.
39
+ ```
40
+ @inproceedings{voleti2024sv3d,
41
+ author={Voleti, Vikram and Yao, Chun-Han and Boss, Mark and Letts, Adam and Pankratz, David and Tochilkin, Dmitrii and Laforte, Christian and Rombach, Robin and Jampani, Varun},
42
+ title={{SV3D}: Novel Multi-view Synthesis and {3D} Generation from a Single Image using Latent Video Diffusion},
43
+ booktitle={European Conference on Computer Vision (ECCV)},
44
+ year={2024},
45
+ }
46
+ ```
assets/bag - Copy.gif ADDED

Git LFS Details

  • SHA256: 02f0a42d15d9d3afa7e2b1e38e925307cedb7412d71707da60c5e639b1b06fca
  • Pointer size: 132 Bytes
  • Size of remote file: 1.98 MB
assets/bag.gif ADDED

Git LFS Details

  • SHA256: 02f0a42d15d9d3afa7e2b1e38e925307cedb7412d71707da60c5e639b1b06fca
  • Pointer size: 132 Bytes
  • Size of remote file: 1.98 MB
assets/bag_official - Copy.gif ADDED

Git LFS Details

  • SHA256: 61e32660cbffc333f7cbf95130cb935802e2db26e23b6440cd5a7e9279bd1669
  • Pointer size: 132 Bytes
  • Size of remote file: 1.89 MB
assets/bag_official.gif ADDED

Git LFS Details

  • SHA256: 61e32660cbffc333f7cbf95130cb935802e2db26e23b6440cd5a7e9279bd1669
  • Pointer size: 132 Bytes
  • Size of remote file: 1.89 MB
assets/images/bag.png ADDED
assets/images/kunkun.png ADDED
assets/images/sculpture.png ADDED
assets/img1.jpg ADDED

Git LFS Details

  • SHA256: 55f4cadbb7173888de17041e89390b76f093ec37d4321bdae184f47c2bf0a7bc
  • Pointer size: 132 Bytes
  • Size of remote file: 1.72 MB
assets/kunkun.gif ADDED

Git LFS Details

  • SHA256: 9744275a633043e1cd50bd6f1e855229f3ac145f77f4e28d63ada0be79dea865
  • Pointer size: 132 Bytes
  • Size of remote file: 1.88 MB
assets/kunkun_official.gif ADDED

Git LFS Details

  • SHA256: 993bf5466602b9fe03b11ccb811149d419b2cfafb6ceaecf2d9b210b9005c1c3
  • Pointer size: 132 Bytes
  • Size of remote file: 1.61 MB
assets/sculpture - Copy.gif ADDED

Git LFS Details

  • SHA256: 3d930b86baef70bbf0371523acabdf21a900bccad73c156a88d588984922b587
  • Pointer size: 132 Bytes
  • Size of remote file: 1.94 MB
assets/sculpture.gif ADDED

Git LFS Details

  • SHA256: 3d930b86baef70bbf0371523acabdf21a900bccad73c156a88d588984922b587
  • Pointer size: 132 Bytes
  • Size of remote file: 1.94 MB
assets/sculpture_official - Copy.gif ADDED

Git LFS Details

  • SHA256: a31bd00aa622a649d3fd48eaed83dd646c309b24aed8caee01a0f30cb1ccce2d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
assets/sculpture_official.gif ADDED

Git LFS Details

  • SHA256: a31bd00aa622a649d3fd48eaed83dd646c309b24aed8caee01a0f30cb1ccce2d
  • Pointer size: 132 Bytes
  • Size of remote file: 1.44 MB
assets/sv3doutputs.gif ADDED

Git LFS Details

  • SHA256: 80c5c01caf1c2322919e708723bb99958bd725212b1240b93f1bc67953844214
  • Pointer size: 132 Bytes
  • Size of remote file: 2.1 MB
convert/convert_sv3d.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+
4
+ from huggingface_hub import hf_hub_download
5
+ import safetensors.torch
6
+ from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
7
+ from diffusers import (
8
+ AutoencoderKL,
9
+ # AutoencoderKLTemporalDecoder,
10
+ EulerDiscreteScheduler,
11
+ )
12
+
13
+ from convert.convert_svd_to_diffusers import (
14
+ convert_ldm_unet_checkpoint,
15
+ # convert_ldm_vae_checkpoint,
16
+ create_unet_diffusers_config,
17
+ )
18
+ from diffusers_sv3d import SV3DUNetSpatioTemporalConditionModel, StableVideo3DDiffusionPipeline
19
+
20
+ SVD_V1_CKPT = "stabilityai/stable-video-diffusion-img2vid-xt"
21
+ SD_V15_CKPT = "chenguolin/stable-diffusion-v1-5"
22
+ HF_HOME = "~/.cache/huggingface"
23
+ HF_TOKEN = ""
24
+ HF_USERNAME = ""
25
+
26
+ # os.environ["HF_ENDPOINT"] = "https://hf-mirror.com"
27
+ os.environ["HF_HOME"] = HF_HOME
28
+ os.environ["HF_USERNAME"] = HF_USERNAME
29
+
30
+
31
+ if __name__ == "__main__":
32
+ parser = argparse.ArgumentParser()
33
+ parser.add_argument("--original_ckpt_path", default=os.path.expanduser(f"{HF_HOME}/hub/models--stabilityai--sv3d/snapshots/31213729b4314a44b574ce7cc2d0c28356f097ed/sv3d_p.safetensors"), type=str, help="Path to the checkpoint to convert.")
34
+ parser.add_argument("--hf_token", default=HF_TOKEN, type=str, help="your HuggingFace token")
35
+ parser.add_argument("--config_path", default="convert/sv3d_p.yaml", type=str, help="Config filepath.")
36
+ parser.add_argument("--repo_name", default="sv3d-diffusers", type=str)
37
+ parser.add_argument("--push_to_hub", action="store_true")
38
+ args = parser.parse_args()
39
+
40
+ if not os.path.exists(args.original_ckpt_path):
41
+ token = HF_TOKEN # open(os.path.expanduser("~/.cache/huggingface/token"), "r").read()
42
+ hf_hub_download("stabilityai/sv3d", filename="sv3d_p.safetensors", token=token)
43
+ original_ckpt = safetensors.torch.load_file(args.original_ckpt_path, device="cpu")
44
+
45
+ from omegaconf import OmegaConf
46
+ config = OmegaConf.load(args.config_path)
47
+
48
+ unet_config = create_unet_diffusers_config(config, image_size=576)
49
+
50
+ ori_config = unet_config.copy()
51
+ unet_config.pop("attention_head_dim")
52
+ unet_config.pop("use_linear_projection")
53
+ unet_config.pop("class_embed_type")
54
+ unet_config.pop("addition_embed_type")
55
+ unet = SV3DUNetSpatioTemporalConditionModel(**unet_config)
56
+ unet_state_dict = convert_ldm_unet_checkpoint(original_ckpt, ori_config)
57
+ unet.load_state_dict(unet_state_dict, strict=True)
58
+
59
+ # unet.save_pretrained("out/sv3d-diffusers", push_to_hub=True)
60
+
61
+ vae = AutoencoderKL.from_pretrained(SD_V15_CKPT, subfolder="vae")
62
+ scheduler = EulerDiscreteScheduler.from_pretrained(SVD_V1_CKPT, subfolder="scheduler")
63
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(SVD_V1_CKPT, subfolder="image_encoder")
64
+ feature_extractor = CLIPImageProcessor.from_pretrained(SVD_V1_CKPT, subfolder="feature_extractor")
65
+
66
+ pipeline = StableVideo3DDiffusionPipeline(
67
+ image_encoder=image_encoder, feature_extractor=feature_extractor,
68
+ unet=unet, vae=vae,
69
+ scheduler=scheduler,
70
+ )
71
+
72
+ if args.push_to_hub:
73
+ pipeline.push_to_hub(args.repo_name)
convert/convert_svd_to_diffusers.py ADDED
@@ -0,0 +1,728 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/huggingface/diffusers/blob/main/scripts/convert_svd_to_diffusers.py
2
+ from diffusers.utils import is_accelerate_available, logging
3
+
4
+
5
+ if is_accelerate_available():
6
+ pass
7
+
8
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
9
+
10
+
11
+ def create_unet_diffusers_config(original_config, image_size: int, controlnet=False):
12
+ """
13
+ Creates a config for the diffusers based on the config of the LDM model.
14
+ """
15
+ if controlnet:
16
+ unet_params = original_config.model.params.control_stage_config.params
17
+ else:
18
+ if "unet_config" in original_config.model.params and original_config.model.params.unet_config is not None:
19
+ unet_params = original_config.model.params.unet_config.params
20
+ else:
21
+ unet_params = original_config.model.params.network_config.params
22
+
23
+ vae_params = original_config.model.params.first_stage_config.params.decoder_config.params
24
+
25
+ block_out_channels = [unet_params.model_channels * mult for mult in unet_params.channel_mult]
26
+
27
+ down_block_types = []
28
+ resolution = 1
29
+ for i in range(len(block_out_channels)):
30
+ block_type = (
31
+ "CrossAttnDownBlockSpatioTemporal"
32
+ if resolution in unet_params.attention_resolutions
33
+ else "DownBlockSpatioTemporal"
34
+ )
35
+ down_block_types.append(block_type)
36
+ if i != len(block_out_channels) - 1:
37
+ resolution *= 2
38
+
39
+ up_block_types = []
40
+ for i in range(len(block_out_channels)):
41
+ block_type = (
42
+ "CrossAttnUpBlockSpatioTemporal"
43
+ if resolution in unet_params.attention_resolutions
44
+ else "UpBlockSpatioTemporal"
45
+ )
46
+ up_block_types.append(block_type)
47
+ resolution //= 2
48
+
49
+ if unet_params.transformer_depth is not None:
50
+ transformer_layers_per_block = (
51
+ unet_params.transformer_depth
52
+ if isinstance(unet_params.transformer_depth, int)
53
+ else list(unet_params.transformer_depth)
54
+ )
55
+ else:
56
+ transformer_layers_per_block = 1
57
+
58
+ vae_scale_factor = 2 ** (len(vae_params.ch_mult) - 1)
59
+
60
+ head_dim = unet_params.num_heads if "num_heads" in unet_params else None
61
+ use_linear_projection = (
62
+ unet_params.use_linear_in_transformer if "use_linear_in_transformer" in unet_params else False
63
+ )
64
+ if use_linear_projection:
65
+ # stable diffusion 2-base-512 and 2-768
66
+ if head_dim is None:
67
+ head_dim_mult = unet_params.model_channels // unet_params.num_head_channels
68
+ head_dim = [head_dim_mult * c for c in list(unet_params.channel_mult)]
69
+
70
+ class_embed_type = None
71
+ addition_embed_type = None
72
+ addition_time_embed_dim = None
73
+ projection_class_embeddings_input_dim = None
74
+ context_dim = None
75
+
76
+ if unet_params.context_dim is not None:
77
+ context_dim = (
78
+ unet_params.context_dim if isinstance(unet_params.context_dim, int) else unet_params.context_dim[0]
79
+ )
80
+
81
+ if "num_classes" in unet_params:
82
+ if unet_params.num_classes == "sequential":
83
+ addition_time_embed_dim = 256
84
+ assert "adm_in_channels" in unet_params
85
+ projection_class_embeddings_input_dim = unet_params.adm_in_channels
86
+
87
+ config = {
88
+ "sample_size": image_size // vae_scale_factor,
89
+ "in_channels": unet_params.in_channels,
90
+ "down_block_types": tuple(down_block_types),
91
+ "block_out_channels": tuple(block_out_channels),
92
+ "layers_per_block": unet_params.num_res_blocks,
93
+ "cross_attention_dim": context_dim,
94
+ "attention_head_dim": tuple(head_dim),
95
+ "use_linear_projection": use_linear_projection,
96
+ "class_embed_type": class_embed_type,
97
+ "addition_embed_type": addition_embed_type,
98
+ "addition_time_embed_dim": addition_time_embed_dim,
99
+ "projection_class_embeddings_input_dim": projection_class_embeddings_input_dim,
100
+ "transformer_layers_per_block": transformer_layers_per_block,
101
+ }
102
+
103
+ if "disable_self_attentions" in unet_params:
104
+ config["only_cross_attention"] = unet_params.disable_self_attentions
105
+
106
+ if "num_classes" in unet_params and isinstance(unet_params.num_classes, int):
107
+ config["num_class_embeds"] = unet_params.num_classes
108
+
109
+ if controlnet:
110
+ config["conditioning_channels"] = unet_params.hint_channels
111
+ else:
112
+ config["out_channels"] = unet_params.out_channels
113
+ config["up_block_types"] = tuple(up_block_types)
114
+
115
+ return config
116
+
117
+
118
+ def assign_to_checkpoint(
119
+ paths,
120
+ checkpoint,
121
+ old_checkpoint,
122
+ attention_paths_to_split=None,
123
+ additional_replacements=None,
124
+ config=None,
125
+ mid_block_suffix="",
126
+ ):
127
+ """
128
+ This does the final conversion step: take locally converted weights and apply a global renaming to them. It splits
129
+ attention layers, and takes into account additional replacements that may arise.
130
+
131
+ Assigns the weights to the new checkpoint.
132
+ """
133
+ assert isinstance(paths, list), "Paths should be a list of dicts containing 'old' and 'new' keys."
134
+
135
+ # Splits the attention layers into three variables.
136
+ if attention_paths_to_split is not None:
137
+ for path, path_map in attention_paths_to_split.items():
138
+ old_tensor = old_checkpoint[path]
139
+ channels = old_tensor.shape[0] // 3
140
+
141
+ target_shape = (-1, channels) if len(old_tensor.shape) == 3 else (-1)
142
+
143
+ num_heads = old_tensor.shape[0] // config["num_head_channels"] // 3
144
+
145
+ old_tensor = old_tensor.reshape((num_heads, 3 * channels // num_heads) + old_tensor.shape[1:])
146
+ query, key, value = old_tensor.split(channels // num_heads, dim=1)
147
+
148
+ checkpoint[path_map["query"]] = query.reshape(target_shape)
149
+ checkpoint[path_map["key"]] = key.reshape(target_shape)
150
+ checkpoint[path_map["value"]] = value.reshape(target_shape)
151
+
152
+ if mid_block_suffix is not None:
153
+ mid_block_suffix = f".{mid_block_suffix}"
154
+ else:
155
+ mid_block_suffix = ""
156
+
157
+ for path in paths:
158
+ new_path = path["new"]
159
+
160
+ # These have already been assigned
161
+ if attention_paths_to_split is not None and new_path in attention_paths_to_split:
162
+ continue
163
+
164
+ # Global renaming happens here
165
+ new_path = new_path.replace("middle_block.0", f"mid_block.resnets.0{mid_block_suffix}")
166
+ new_path = new_path.replace("middle_block.1", "mid_block.attentions.0")
167
+ new_path = new_path.replace("middle_block.2", f"mid_block.resnets.1{mid_block_suffix}")
168
+
169
+ if additional_replacements is not None:
170
+ for replacement in additional_replacements:
171
+ new_path = new_path.replace(replacement["old"], replacement["new"])
172
+
173
+ # proj_attn.weight has to be converted from conv 1D to linear
174
+ is_attn_weight = "proj_attn.weight" in new_path or ("attentions" in new_path and "to_" in new_path)
175
+ shape = old_checkpoint[path["old"]].shape
176
+ if is_attn_weight and len(shape) == 3:
177
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0]
178
+ elif is_attn_weight and len(shape) == 4:
179
+ checkpoint[new_path] = old_checkpoint[path["old"]][:, :, 0, 0]
180
+ else:
181
+ checkpoint[new_path] = old_checkpoint[path["old"]]
182
+
183
+
184
+ def renew_attention_paths(old_list, n_shave_prefix_segments=0):
185
+ """
186
+ Updates paths inside attentions to the new naming scheme (local renaming)
187
+ """
188
+ mapping = []
189
+ for old_item in old_list:
190
+ new_item = old_item
191
+
192
+ # new_item = new_item.replace('norm.weight', 'group_norm.weight')
193
+ # new_item = new_item.replace('norm.bias', 'group_norm.bias')
194
+
195
+ # new_item = new_item.replace('proj_out.weight', 'proj_attn.weight')
196
+ # new_item = new_item.replace('proj_out.bias', 'proj_attn.bias')
197
+
198
+ # new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
199
+ new_item = new_item.replace("time_stack", "temporal_transformer_blocks")
200
+
201
+ new_item = new_item.replace("time_pos_embed.0.bias", "time_pos_embed.linear_1.bias")
202
+ new_item = new_item.replace("time_pos_embed.0.weight", "time_pos_embed.linear_1.weight")
203
+ new_item = new_item.replace("time_pos_embed.2.bias", "time_pos_embed.linear_2.bias")
204
+ new_item = new_item.replace("time_pos_embed.2.weight", "time_pos_embed.linear_2.weight")
205
+
206
+ mapping.append({"old": old_item, "new": new_item})
207
+
208
+ return mapping
209
+
210
+
211
+ def shave_segments(path, n_shave_prefix_segments=1):
212
+ """
213
+ Removes segments. Positive values shave the first segments, negative shave the last segments.
214
+ """
215
+ if n_shave_prefix_segments >= 0:
216
+ return ".".join(path.split(".")[n_shave_prefix_segments:])
217
+ else:
218
+ return ".".join(path.split(".")[:n_shave_prefix_segments])
219
+
220
+
221
+ def renew_resnet_paths(old_list, n_shave_prefix_segments=0):
222
+ """
223
+ Updates paths inside resnets to the new naming scheme (local renaming)
224
+ """
225
+ mapping = []
226
+ for old_item in old_list:
227
+ new_item = old_item.replace("in_layers.0", "norm1")
228
+ new_item = new_item.replace("in_layers.2", "conv1")
229
+
230
+ new_item = new_item.replace("out_layers.0", "norm2")
231
+ new_item = new_item.replace("out_layers.3", "conv2")
232
+
233
+ new_item = new_item.replace("emb_layers.1", "time_emb_proj")
234
+ new_item = new_item.replace("skip_connection", "conv_shortcut")
235
+
236
+ new_item = new_item.replace("time_stack.", "")
237
+
238
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
239
+
240
+ mapping.append({"old": old_item, "new": new_item})
241
+
242
+ return mapping
243
+
244
+
245
+ def convert_ldm_unet_checkpoint(
246
+ checkpoint, config, path=None, extract_ema=False, controlnet=False, skip_extract_state_dict=False
247
+ ):
248
+ """
249
+ Takes a state dict and a config, and returns a converted checkpoint.
250
+ """
251
+
252
+ if skip_extract_state_dict:
253
+ unet_state_dict = checkpoint
254
+ else:
255
+ # extract state_dict for UNet
256
+ unet_state_dict = {}
257
+ keys = list(checkpoint.keys())
258
+
259
+ unet_key = "model.diffusion_model."
260
+
261
+ # at least a 100 parameters have to start with `model_ema` in order for the checkpoint to be EMA
262
+ if sum(k.startswith("model_ema") for k in keys) > 100 and extract_ema:
263
+ logger.warning(f"Checkpoint {path} has both EMA and non-EMA weights.")
264
+ logger.warning(
265
+ "In this conversion only the EMA weights are extracted. If you want to instead extract the non-EMA"
266
+ " weights (useful to continue fine-tuning), please make sure to remove the `--extract_ema` flag."
267
+ )
268
+ for key in keys:
269
+ if key.startswith("model.diffusion_model"):
270
+ flat_ema_key = "model_ema." + "".join(key.split(".")[1:])
271
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(flat_ema_key)
272
+ else:
273
+ if sum(k.startswith("model_ema") for k in keys) > 100:
274
+ logger.warning(
275
+ "In this conversion only the non-EMA weights are extracted. If you want to instead extract the EMA"
276
+ " weights (usually better for inference), please make sure to add the `--extract_ema` flag."
277
+ )
278
+
279
+ for key in keys:
280
+ if key.startswith(unet_key):
281
+ unet_state_dict[key.replace(unet_key, "")] = checkpoint.pop(key)
282
+
283
+ new_checkpoint = {}
284
+
285
+ new_checkpoint["time_embedding.linear_1.weight"] = unet_state_dict["time_embed.0.weight"]
286
+ new_checkpoint["time_embedding.linear_1.bias"] = unet_state_dict["time_embed.0.bias"]
287
+ new_checkpoint["time_embedding.linear_2.weight"] = unet_state_dict["time_embed.2.weight"]
288
+ new_checkpoint["time_embedding.linear_2.bias"] = unet_state_dict["time_embed.2.bias"]
289
+
290
+ if config["class_embed_type"] is None:
291
+ # No parameters to port
292
+ ...
293
+ elif config["class_embed_type"] == "timestep" or config["class_embed_type"] == "projection":
294
+ new_checkpoint["class_embedding.linear_1.weight"] = unet_state_dict["label_emb.0.0.weight"]
295
+ new_checkpoint["class_embedding.linear_1.bias"] = unet_state_dict["label_emb.0.0.bias"]
296
+ new_checkpoint["class_embedding.linear_2.weight"] = unet_state_dict["label_emb.0.2.weight"]
297
+ new_checkpoint["class_embedding.linear_2.bias"] = unet_state_dict["label_emb.0.2.bias"]
298
+ else:
299
+ raise NotImplementedError(f"Not implemented `class_embed_type`: {config['class_embed_type']}")
300
+
301
+ # if config["addition_embed_type"] == "text_time":
302
+ new_checkpoint["add_embedding.linear_1.weight"] = unet_state_dict["label_emb.0.0.weight"]
303
+ new_checkpoint["add_embedding.linear_1.bias"] = unet_state_dict["label_emb.0.0.bias"]
304
+ new_checkpoint["add_embedding.linear_2.weight"] = unet_state_dict["label_emb.0.2.weight"]
305
+ new_checkpoint["add_embedding.linear_2.bias"] = unet_state_dict["label_emb.0.2.bias"]
306
+
307
+ new_checkpoint["conv_in.weight"] = unet_state_dict["input_blocks.0.0.weight"]
308
+ new_checkpoint["conv_in.bias"] = unet_state_dict["input_blocks.0.0.bias"]
309
+
310
+ new_checkpoint["conv_norm_out.weight"] = unet_state_dict["out.0.weight"]
311
+ new_checkpoint["conv_norm_out.bias"] = unet_state_dict["out.0.bias"]
312
+ new_checkpoint["conv_out.weight"] = unet_state_dict["out.2.weight"]
313
+ new_checkpoint["conv_out.bias"] = unet_state_dict["out.2.bias"]
314
+
315
+ # Retrieves the keys for the input blocks only
316
+ num_input_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "input_blocks" in layer})
317
+ input_blocks = {
318
+ layer_id: [key for key in unet_state_dict if f"input_blocks.{layer_id}" in key]
319
+ for layer_id in range(num_input_blocks)
320
+ }
321
+
322
+ # Retrieves the keys for the middle blocks only
323
+ num_middle_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "middle_block" in layer})
324
+ middle_blocks = {
325
+ layer_id: [key for key in unet_state_dict if f"middle_block.{layer_id}" in key]
326
+ for layer_id in range(num_middle_blocks)
327
+ }
328
+
329
+ # Retrieves the keys for the output blocks only
330
+ num_output_blocks = len({".".join(layer.split(".")[:2]) for layer in unet_state_dict if "output_blocks" in layer})
331
+ output_blocks = {
332
+ layer_id: [key for key in unet_state_dict if f"output_blocks.{layer_id}" in key]
333
+ for layer_id in range(num_output_blocks)
334
+ }
335
+
336
+ for i in range(1, num_input_blocks):
337
+ block_id = (i - 1) // (config["layers_per_block"] + 1)
338
+ layer_in_block_id = (i - 1) % (config["layers_per_block"] + 1)
339
+
340
+ spatial_resnets = [
341
+ key
342
+ for key in input_blocks[i]
343
+ if f"input_blocks.{i}.0" in key
344
+ and (
345
+ f"input_blocks.{i}.0.op" not in key
346
+ and f"input_blocks.{i}.0.time_stack" not in key
347
+ and f"input_blocks.{i}.0.time_mixer" not in key
348
+ )
349
+ ]
350
+ temporal_resnets = [key for key in input_blocks[i] if f"input_blocks.{i}.0.time_stack" in key]
351
+ # import ipdb; ipdb.set_trace()
352
+ attentions = [key for key in input_blocks[i] if f"input_blocks.{i}.1" in key]
353
+
354
+ if f"input_blocks.{i}.0.op.weight" in unet_state_dict:
355
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.weight"] = unet_state_dict.pop(
356
+ f"input_blocks.{i}.0.op.weight"
357
+ )
358
+ new_checkpoint[f"down_blocks.{block_id}.downsamplers.0.conv.bias"] = unet_state_dict.pop(
359
+ f"input_blocks.{i}.0.op.bias"
360
+ )
361
+
362
+ paths = renew_resnet_paths(spatial_resnets)
363
+ meta_path = {
364
+ "old": f"input_blocks.{i}.0",
365
+ "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}.spatial_res_block",
366
+ }
367
+ assign_to_checkpoint(
368
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
369
+ )
370
+
371
+ paths = renew_resnet_paths(temporal_resnets)
372
+ meta_path = {
373
+ "old": f"input_blocks.{i}.0",
374
+ "new": f"down_blocks.{block_id}.resnets.{layer_in_block_id}.temporal_res_block",
375
+ }
376
+ assign_to_checkpoint(
377
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
378
+ )
379
+
380
+ # TODO resnet time_mixer.mix_factor
381
+ if f"input_blocks.{i}.0.time_mixer.mix_factor" in unet_state_dict:
382
+ new_checkpoint[
383
+ f"down_blocks.{block_id}.resnets.{layer_in_block_id}.time_mixer.mix_factor"
384
+ ] = unet_state_dict[f"input_blocks.{i}.0.time_mixer.mix_factor"]
385
+
386
+ if len(attentions):
387
+ paths = renew_attention_paths(attentions)
388
+ meta_path = {"old": f"input_blocks.{i}.1", "new": f"down_blocks.{block_id}.attentions.{layer_in_block_id}"}
389
+ # import ipdb; ipdb.set_trace()
390
+ assign_to_checkpoint(
391
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
392
+ )
393
+
394
+ resnet_0 = middle_blocks[0]
395
+ attentions = middle_blocks[1]
396
+ resnet_1 = middle_blocks[2]
397
+
398
+ resnet_0_spatial = [key for key in resnet_0 if "time_stack" not in key and "time_mixer" not in key]
399
+ resnet_0_paths = renew_resnet_paths(resnet_0_spatial)
400
+ # import ipdb; ipdb.set_trace()
401
+ assign_to_checkpoint(
402
+ resnet_0_paths, new_checkpoint, unet_state_dict, config=config, mid_block_suffix="spatial_res_block"
403
+ )
404
+
405
+ resnet_0_temporal = [key for key in resnet_0 if "time_stack" in key and "time_mixer" not in key]
406
+ resnet_0_paths = renew_resnet_paths(resnet_0_temporal)
407
+ assign_to_checkpoint(
408
+ resnet_0_paths, new_checkpoint, unet_state_dict, config=config, mid_block_suffix="temporal_res_block"
409
+ )
410
+
411
+ resnet_1_spatial = [key for key in resnet_1 if "time_stack" not in key and "time_mixer" not in key]
412
+ resnet_1_paths = renew_resnet_paths(resnet_1_spatial)
413
+ assign_to_checkpoint(
414
+ resnet_1_paths, new_checkpoint, unet_state_dict, config=config, mid_block_suffix="spatial_res_block"
415
+ )
416
+
417
+ resnet_1_temporal = [key for key in resnet_1 if "time_stack" in key and "time_mixer" not in key]
418
+ resnet_1_paths = renew_resnet_paths(resnet_1_temporal)
419
+ assign_to_checkpoint(
420
+ resnet_1_paths, new_checkpoint, unet_state_dict, config=config, mid_block_suffix="temporal_res_block"
421
+ )
422
+
423
+ new_checkpoint["mid_block.resnets.0.time_mixer.mix_factor"] = unet_state_dict[
424
+ "middle_block.0.time_mixer.mix_factor"
425
+ ]
426
+ new_checkpoint["mid_block.resnets.1.time_mixer.mix_factor"] = unet_state_dict[
427
+ "middle_block.2.time_mixer.mix_factor"
428
+ ]
429
+
430
+ attentions_paths = renew_attention_paths(attentions)
431
+ meta_path = {"old": "middle_block.1", "new": "mid_block.attentions.0"}
432
+ assign_to_checkpoint(
433
+ attentions_paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
434
+ )
435
+
436
+ for i in range(num_output_blocks):
437
+ block_id = i // (config["layers_per_block"] + 1)
438
+ layer_in_block_id = i % (config["layers_per_block"] + 1)
439
+ output_block_layers = [shave_segments(name, 2) for name in output_blocks[i]]
440
+ output_block_list = {}
441
+
442
+ for layer in output_block_layers:
443
+ layer_id, layer_name = layer.split(".")[0], shave_segments(layer, 1)
444
+ if layer_id in output_block_list:
445
+ output_block_list[layer_id].append(layer_name)
446
+ else:
447
+ output_block_list[layer_id] = [layer_name]
448
+
449
+ if len(output_block_list) > 1:
450
+ spatial_resnets = [
451
+ key
452
+ for key in output_blocks[i]
453
+ if f"output_blocks.{i}.0" in key
454
+ and (f"output_blocks.{i}.0.time_stack" not in key and "time_mixer" not in key)
455
+ ]
456
+ # import ipdb; ipdb.set_trace()
457
+
458
+ temporal_resnets = [key for key in output_blocks[i] if f"output_blocks.{i}.0.time_stack" in key]
459
+
460
+ paths = renew_resnet_paths(spatial_resnets)
461
+ meta_path = {
462
+ "old": f"output_blocks.{i}.0",
463
+ "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}.spatial_res_block",
464
+ }
465
+ assign_to_checkpoint(
466
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
467
+ )
468
+
469
+ paths = renew_resnet_paths(temporal_resnets)
470
+ meta_path = {
471
+ "old": f"output_blocks.{i}.0",
472
+ "new": f"up_blocks.{block_id}.resnets.{layer_in_block_id}.temporal_res_block",
473
+ }
474
+ assign_to_checkpoint(
475
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
476
+ )
477
+
478
+ if f"output_blocks.{i}.0.time_mixer.mix_factor" in unet_state_dict:
479
+ new_checkpoint[
480
+ f"up_blocks.{block_id}.resnets.{layer_in_block_id}.time_mixer.mix_factor"
481
+ ] = unet_state_dict[f"output_blocks.{i}.0.time_mixer.mix_factor"]
482
+
483
+ output_block_list = {k: sorted(v) for k, v in output_block_list.items()}
484
+ if ["conv.bias", "conv.weight"] in output_block_list.values():
485
+ index = list(output_block_list.values()).index(["conv.bias", "conv.weight"])
486
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.weight"] = unet_state_dict[
487
+ f"output_blocks.{i}.{index}.conv.weight"
488
+ ]
489
+ new_checkpoint[f"up_blocks.{block_id}.upsamplers.0.conv.bias"] = unet_state_dict[
490
+ f"output_blocks.{i}.{index}.conv.bias"
491
+ ]
492
+
493
+ # Clear attentions as they have been attributed above.
494
+ if len(attentions) == 2:
495
+ attentions = []
496
+
497
+ attentions = [key for key in output_blocks[i] if f"output_blocks.{i}.1" in key and "conv" not in key]
498
+ if len(attentions):
499
+ paths = renew_attention_paths(attentions)
500
+ # import ipdb; ipdb.set_trace()
501
+ meta_path = {
502
+ "old": f"output_blocks.{i}.1",
503
+ "new": f"up_blocks.{block_id}.attentions.{layer_in_block_id}",
504
+ }
505
+ assign_to_checkpoint(
506
+ paths, new_checkpoint, unet_state_dict, additional_replacements=[meta_path], config=config
507
+ )
508
+ else:
509
+ spatial_layers = [
510
+ layer for layer in output_block_layers if "time_stack" not in layer and "time_mixer" not in layer
511
+ ]
512
+ resnet_0_paths = renew_resnet_paths(spatial_layers, n_shave_prefix_segments=1)
513
+ # import ipdb; ipdb.set_trace()
514
+ for path in resnet_0_paths:
515
+ old_path = ".".join(["output_blocks", str(i), path["old"]])
516
+ new_path = ".".join(
517
+ ["up_blocks", str(block_id), "resnets", str(layer_in_block_id), "spatial_res_block", path["new"]]
518
+ )
519
+
520
+ new_checkpoint[new_path] = unet_state_dict[old_path]
521
+
522
+ temporal_layers = [
523
+ layer for layer in output_block_layers if "time_stack" in layer and "time_mixer" not in key
524
+ ]
525
+ resnet_0_paths = renew_resnet_paths(temporal_layers, n_shave_prefix_segments=1)
526
+ # import ipdb; ipdb.set_trace()
527
+ for path in resnet_0_paths:
528
+ old_path = ".".join(["output_blocks", str(i), path["old"]])
529
+ new_path = ".".join(
530
+ ["up_blocks", str(block_id), "resnets", str(layer_in_block_id), "temporal_res_block", path["new"]]
531
+ )
532
+
533
+ new_checkpoint[new_path] = unet_state_dict[old_path]
534
+
535
+ new_checkpoint["up_blocks.0.resnets.0.time_mixer.mix_factor"] = unet_state_dict[
536
+ f"output_blocks.{str(i)}.0.time_mixer.mix_factor"
537
+ ]
538
+
539
+ return new_checkpoint
540
+
541
+
542
+ def conv_attn_to_linear(checkpoint):
543
+ keys = list(checkpoint.keys())
544
+ attn_keys = ["to_q.weight", "to_k.weight", "to_v.weight"]
545
+ for key in keys:
546
+ if ".".join(key.split(".")[-2:]) in attn_keys:
547
+ if checkpoint[key].ndim > 2:
548
+ checkpoint[key] = checkpoint[key][:, :, 0, 0]
549
+ elif "proj_attn.weight" in key:
550
+ if checkpoint[key].ndim > 2:
551
+ checkpoint[key] = checkpoint[key][:, :, 0]
552
+
553
+
554
+ def renew_vae_resnet_paths(old_list, n_shave_prefix_segments=0, is_temporal=False):
555
+ """
556
+ Updates paths inside resnets to the new naming scheme (local renaming)
557
+ """
558
+ mapping = []
559
+ for old_item in old_list:
560
+ new_item = old_item
561
+
562
+ # Temporal resnet
563
+ new_item = old_item.replace("in_layers.0", "norm1")
564
+ new_item = new_item.replace("in_layers.2", "conv1")
565
+
566
+ new_item = new_item.replace("out_layers.0", "norm2")
567
+ new_item = new_item.replace("out_layers.3", "conv2")
568
+
569
+ new_item = new_item.replace("skip_connection", "conv_shortcut")
570
+
571
+ new_item = new_item.replace("time_stack.", "temporal_res_block.")
572
+
573
+ # Spatial resnet
574
+ new_item = new_item.replace("conv1", "spatial_res_block.conv1")
575
+ new_item = new_item.replace("norm1", "spatial_res_block.norm1")
576
+
577
+ new_item = new_item.replace("conv2", "spatial_res_block.conv2")
578
+ new_item = new_item.replace("norm2", "spatial_res_block.norm2")
579
+
580
+ new_item = new_item.replace("nin_shortcut", "spatial_res_block.conv_shortcut")
581
+
582
+ new_item = new_item.replace("mix_factor", "spatial_res_block.time_mixer.mix_factor")
583
+
584
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
585
+
586
+ mapping.append({"old": old_item, "new": new_item})
587
+
588
+ return mapping
589
+
590
+
591
+ def renew_vae_attention_paths(old_list, n_shave_prefix_segments=0):
592
+ """
593
+ Updates paths inside attentions to the new naming scheme (local renaming)
594
+ """
595
+ mapping = []
596
+ for old_item in old_list:
597
+ new_item = old_item
598
+
599
+ new_item = new_item.replace("norm.weight", "group_norm.weight")
600
+ new_item = new_item.replace("norm.bias", "group_norm.bias")
601
+
602
+ new_item = new_item.replace("q.weight", "to_q.weight")
603
+ new_item = new_item.replace("q.bias", "to_q.bias")
604
+
605
+ new_item = new_item.replace("k.weight", "to_k.weight")
606
+ new_item = new_item.replace("k.bias", "to_k.bias")
607
+
608
+ new_item = new_item.replace("v.weight", "to_v.weight")
609
+ new_item = new_item.replace("v.bias", "to_v.bias")
610
+
611
+ new_item = new_item.replace("proj_out.weight", "to_out.0.weight")
612
+ new_item = new_item.replace("proj_out.bias", "to_out.0.bias")
613
+
614
+ new_item = shave_segments(new_item, n_shave_prefix_segments=n_shave_prefix_segments)
615
+
616
+ mapping.append({"old": old_item, "new": new_item})
617
+
618
+ return mapping
619
+
620
+
621
+ def convert_ldm_vae_checkpoint(checkpoint, config):
622
+ # extract state dict for VAE
623
+ vae_state_dict = {}
624
+ keys = list(checkpoint.keys())
625
+ vae_key = "first_stage_model." if any(k.startswith("first_stage_model.") for k in keys) else ""
626
+ for key in keys:
627
+ if key.startswith(vae_key):
628
+ vae_state_dict[key.replace(vae_key, "")] = checkpoint.get(key)
629
+
630
+ new_checkpoint = {}
631
+
632
+ new_checkpoint["encoder.conv_in.weight"] = vae_state_dict["encoder.conv_in.weight"]
633
+ new_checkpoint["encoder.conv_in.bias"] = vae_state_dict["encoder.conv_in.bias"]
634
+ new_checkpoint["encoder.conv_out.weight"] = vae_state_dict["encoder.conv_out.weight"]
635
+ new_checkpoint["encoder.conv_out.bias"] = vae_state_dict["encoder.conv_out.bias"]
636
+ new_checkpoint["encoder.conv_norm_out.weight"] = vae_state_dict["encoder.norm_out.weight"]
637
+ new_checkpoint["encoder.conv_norm_out.bias"] = vae_state_dict["encoder.norm_out.bias"]
638
+
639
+ new_checkpoint["decoder.conv_in.weight"] = vae_state_dict["decoder.conv_in.weight"]
640
+ new_checkpoint["decoder.conv_in.bias"] = vae_state_dict["decoder.conv_in.bias"]
641
+ new_checkpoint["decoder.conv_out.weight"] = vae_state_dict["decoder.conv_out.weight"]
642
+ new_checkpoint["decoder.conv_out.bias"] = vae_state_dict["decoder.conv_out.bias"]
643
+ new_checkpoint["decoder.conv_norm_out.weight"] = vae_state_dict["decoder.norm_out.weight"]
644
+ new_checkpoint["decoder.conv_norm_out.bias"] = vae_state_dict["decoder.norm_out.bias"]
645
+ new_checkpoint["decoder.time_conv_out.weight"] = vae_state_dict["decoder.time_mix_conv.weight"]
646
+ new_checkpoint["decoder.time_conv_out.bias"] = vae_state_dict["decoder.time_mix_conv.bias"]
647
+
648
+ # new_checkpoint["quant_conv.weight"] = vae_state_dict["quant_conv.weight"]
649
+ # new_checkpoint["quant_conv.bias"] = vae_state_dict["quant_conv.bias"]
650
+ # new_checkpoint["post_quant_conv.weight"] = vae_state_dict["post_quant_conv.weight"]
651
+ # new_checkpoint["post_quant_conv.bias"] = vae_state_dict["post_quant_conv.bias"]
652
+
653
+ # Retrieves the keys for the encoder down blocks only
654
+ num_down_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "encoder.down" in layer})
655
+ down_blocks = {
656
+ layer_id: [key for key in vae_state_dict if f"down.{layer_id}" in key] for layer_id in range(num_down_blocks)
657
+ }
658
+
659
+ # Retrieves the keys for the decoder up blocks only
660
+ num_up_blocks = len({".".join(layer.split(".")[:3]) for layer in vae_state_dict if "decoder.up" in layer})
661
+ up_blocks = {
662
+ layer_id: [key for key in vae_state_dict if f"up.{layer_id}" in key] for layer_id in range(num_up_blocks)
663
+ }
664
+
665
+ for i in range(num_down_blocks):
666
+ resnets = [key for key in down_blocks[i] if f"down.{i}" in key and f"down.{i}.downsample" not in key]
667
+
668
+ if f"encoder.down.{i}.downsample.conv.weight" in vae_state_dict:
669
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.weight"] = vae_state_dict.pop(
670
+ f"encoder.down.{i}.downsample.conv.weight"
671
+ )
672
+ new_checkpoint[f"encoder.down_blocks.{i}.downsamplers.0.conv.bias"] = vae_state_dict.pop(
673
+ f"encoder.down.{i}.downsample.conv.bias"
674
+ )
675
+
676
+ paths = renew_vae_resnet_paths(resnets)
677
+ meta_path = {"old": f"down.{i}.block", "new": f"down_blocks.{i}.resnets"}
678
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
679
+
680
+ mid_resnets = [key for key in vae_state_dict if "encoder.mid.block" in key]
681
+ num_mid_res_blocks = 2
682
+ for i in range(1, num_mid_res_blocks + 1):
683
+ resnets = [key for key in mid_resnets if f"encoder.mid.block_{i}" in key]
684
+
685
+ paths = renew_vae_resnet_paths(resnets)
686
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
687
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
688
+
689
+ mid_attentions = [key for key in vae_state_dict if "encoder.mid.attn" in key]
690
+ paths = renew_vae_attention_paths(mid_attentions)
691
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
692
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
693
+ conv_attn_to_linear(new_checkpoint)
694
+
695
+ for i in range(num_up_blocks):
696
+ block_id = num_up_blocks - 1 - i
697
+
698
+ resnets = [
699
+ key for key in up_blocks[block_id] if f"up.{block_id}" in key and f"up.{block_id}.upsample" not in key
700
+ ]
701
+
702
+ if f"decoder.up.{block_id}.upsample.conv.weight" in vae_state_dict:
703
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.weight"] = vae_state_dict[
704
+ f"decoder.up.{block_id}.upsample.conv.weight"
705
+ ]
706
+ new_checkpoint[f"decoder.up_blocks.{i}.upsamplers.0.conv.bias"] = vae_state_dict[
707
+ f"decoder.up.{block_id}.upsample.conv.bias"
708
+ ]
709
+
710
+ paths = renew_vae_resnet_paths(resnets)
711
+ meta_path = {"old": f"up.{block_id}.block", "new": f"up_blocks.{i}.resnets"}
712
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
713
+
714
+ mid_resnets = [key for key in vae_state_dict if "decoder.mid.block" in key]
715
+ num_mid_res_blocks = 2
716
+ for i in range(1, num_mid_res_blocks + 1):
717
+ resnets = [key for key in mid_resnets if f"decoder.mid.block_{i}" in key]
718
+
719
+ paths = renew_vae_resnet_paths(resnets)
720
+ meta_path = {"old": f"mid.block_{i}", "new": f"mid_block.resnets.{i - 1}"}
721
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
722
+
723
+ mid_attentions = [key for key in vae_state_dict if "decoder.mid.attn" in key]
724
+ paths = renew_vae_attention_paths(mid_attentions)
725
+ meta_path = {"old": "mid.attn_1", "new": "mid_block.attentions.0"}
726
+ assign_to_checkpoint(paths, new_checkpoint, vae_state_dict, additional_replacements=[meta_path], config=config)
727
+ conv_attn_to_linear(new_checkpoint)
728
+ return new_checkpoint
convert/sv3d_p.yaml ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copied from https://github.com/Stability-AI/generative-models/blob/main/scripts/sampling/configs/sv3d_p.yaml
2
+
3
+ model:
4
+ target: sgm.models.diffusion.DiffusionEngine
5
+ params:
6
+ scale_factor: 0.18215
7
+ disable_first_stage_autocast: True
8
+ ckpt_path: checkpoints/sv3d_p.safetensors
9
+
10
+ denoiser_config:
11
+ target: sgm.modules.diffusionmodules.denoiser.Denoiser
12
+ params:
13
+ scaling_config:
14
+ target: sgm.modules.diffusionmodules.denoiser_scaling.VScalingWithEDMcNoise
15
+
16
+ network_config:
17
+ target: sgm.modules.diffusionmodules.video_model.VideoUNet
18
+ params:
19
+ adm_in_channels: 1280
20
+ num_classes: sequential
21
+ use_checkpoint: True
22
+ in_channels: 8
23
+ out_channels: 4
24
+ model_channels: 320
25
+ attention_resolutions: [4, 2, 1]
26
+ num_res_blocks: 2
27
+ channel_mult: [1, 2, 4, 4]
28
+ num_head_channels: 64
29
+ use_linear_in_transformer: True
30
+ transformer_depth: 1
31
+ context_dim: 1024
32
+ spatial_transformer_attn_type: softmax-xformers
33
+ extra_ff_mix_layer: True
34
+ use_spatial_context: True
35
+ merge_strategy: learned_with_images
36
+ video_kernel_size: [3, 1, 1]
37
+
38
+ conditioner_config:
39
+ target: sgm.modules.GeneralConditioner
40
+ params:
41
+ emb_models:
42
+ - input_key: cond_frames_without_noise
43
+ is_trainable: False
44
+ target: sgm.modules.encoders.modules.FrozenOpenCLIPImagePredictionEmbedder
45
+ params:
46
+ n_cond_frames: 1
47
+ n_copies: 1
48
+ open_clip_embedding_config:
49
+ target: sgm.modules.encoders.modules.FrozenOpenCLIPImageEmbedder
50
+ params:
51
+ freeze: True
52
+
53
+ - input_key: cond_frames
54
+ is_trainable: False
55
+ target: sgm.modules.encoders.modules.VideoPredictionEmbedderWithEncoder
56
+ params:
57
+ disable_encoder_autocast: True
58
+ n_cond_frames: 1
59
+ n_copies: 1
60
+ is_ae: True
61
+ encoder_config:
62
+ target: sgm.models.autoencoder.AutoencoderKLModeOnly
63
+ params:
64
+ embed_dim: 4
65
+ monitor: val/rec_loss
66
+ ddconfig:
67
+ attn_type: vanilla-xformers
68
+ double_z: True
69
+ z_channels: 4
70
+ resolution: 256
71
+ in_channels: 3
72
+ out_ch: 3
73
+ ch: 128
74
+ ch_mult: [1, 2, 4, 4]
75
+ num_res_blocks: 2
76
+ attn_resolutions: []
77
+ dropout: 0.0
78
+ lossconfig:
79
+ target: torch.nn.Identity
80
+
81
+ - input_key: cond_aug
82
+ is_trainable: False
83
+ target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
84
+ params:
85
+ outdim: 256
86
+
87
+ - input_key: polars_rad
88
+ is_trainable: False
89
+ target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
90
+ params:
91
+ outdim: 512
92
+
93
+ - input_key: azimuths_rad
94
+ is_trainable: False
95
+ target: sgm.modules.encoders.modules.ConcatTimestepEmbedderND
96
+ params:
97
+ outdim: 512
98
+
99
+ first_stage_config:
100
+ target: sgm.models.autoencoder.AutoencodingEngine
101
+ params:
102
+ loss_config:
103
+ target: torch.nn.Identity
104
+ regularizer_config:
105
+ target: sgm.modules.autoencoding.regularizers.DiagonalGaussianRegularizer
106
+ encoder_config:
107
+ target: torch.nn.Identity
108
+ decoder_config:
109
+ target: sgm.modules.diffusionmodules.model.Decoder
110
+ params:
111
+ attn_type: vanilla-xformers
112
+ double_z: True
113
+ z_channels: 4
114
+ resolution: 256
115
+ in_channels: 3
116
+ out_ch: 3
117
+ ch: 128
118
+ ch_mult: [ 1, 2, 4, 4 ]
119
+ num_res_blocks: 2
120
+ attn_resolutions: [ ]
121
+ dropout: 0.0
122
+
123
+ sampler_config:
124
+ target: sgm.modules.diffusionmodules.sampling.EulerEDMSampler
125
+ params:
126
+ discretization_config:
127
+ target: sgm.modules.diffusionmodules.discretizer.EDMDiscretization
128
+ params:
129
+ sigma_max: 700.0
130
+
131
+ guider_config:
132
+ target: sgm.modules.diffusionmodules.guiders.TrianglePredictionGuider
133
+ params:
134
+ max_scale: 2.5
diffusers_sv3d/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ from .models import SV3DUNetSpatioTemporalConditionModel
2
+ from .pipelines import StableVideo3DDiffusionPipeline
diffusers_sv3d/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (284 Bytes). View file
 
diffusers_sv3d/models/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .unets import SV3DUNetSpatioTemporalConditionModel
diffusers_sv3d/models/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (226 Bytes). View file
 
diffusers_sv3d/models/unets/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .unet_spatio_temporal_condition import SV3DUNetSpatioTemporalConditionModel
diffusers_sv3d/models/unets/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (257 Bytes). View file
 
diffusers_sv3d/models/unets/__pycache__/unet_spatio_temporal_condition.cpython-39.pyc ADDED
Binary file (15 kB). View file
 
diffusers_sv3d/models/unets/unet_spatio_temporal_condition.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import *
2
+
3
+ from diffusers.models.unets.unet_spatio_temporal_condition import *
4
+
5
+
6
+ # Copied from diffusers.models.unets.unet_spatio_temporal_condition UNetSpatioTemporalConditionModel
7
+ class SV3DUNetSpatioTemporalConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
8
+ r"""
9
+ A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and
10
+ returns a sample shaped output.
11
+
12
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
13
+ for all models (such as downloading or saving).
14
+
15
+ Parameters:
16
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
17
+ Height and width of input/output sample.
18
+ in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample.
19
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
20
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`):
21
+ The tuple of downsample blocks to use.
22
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`):
23
+ The tuple of upsample blocks to use.
24
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
25
+ The tuple of output channels for each block.
26
+ addition_time_embed_dim: (`int`, defaults to 256):
27
+ Dimension to to encode the additional time ids.
28
+ projection_class_embeddings_input_dim (`int`, defaults to 768):
29
+ The dimension of the projection of encoded `added_time_ids`.
30
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
31
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
32
+ The dimension of the cross attention features.
33
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
34
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
35
+ [`~models.unets.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`],
36
+ [`~models.unets.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`],
37
+ [`~models.unets.unet_3d_blocks.UNetMidBlockSpatioTemporal`].
38
+ num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`):
39
+ The number of attention heads.
40
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
41
+ """
42
+
43
+ _supports_gradient_checkpointing = True
44
+
45
+ @register_to_config
46
+ def __init__(
47
+ self,
48
+ sample_size: Optional[int] = None,
49
+ in_channels: int = 8,
50
+ out_channels: int = 4,
51
+ down_block_types: Tuple[str] = (
52
+ "CrossAttnDownBlockSpatioTemporal",
53
+ "CrossAttnDownBlockSpatioTemporal",
54
+ "CrossAttnDownBlockSpatioTemporal",
55
+ "DownBlockSpatioTemporal",
56
+ ),
57
+ up_block_types: Tuple[str] = (
58
+ "UpBlockSpatioTemporal",
59
+ "CrossAttnUpBlockSpatioTemporal",
60
+ "CrossAttnUpBlockSpatioTemporal",
61
+ "CrossAttnUpBlockSpatioTemporal",
62
+ ),
63
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
64
+ addition_time_embed_dim: int = 256,
65
+ projection_class_embeddings_input_dim: int = 768,
66
+ layers_per_block: Union[int, Tuple[int]] = 2,
67
+ cross_attention_dim: Union[int, Tuple[int]] = 1024,
68
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
69
+ num_attention_heads: Union[int, Tuple[int]] = (5, 10, 20, 20),
70
+ num_frames: int = 25,
71
+ ):
72
+ super().__init__()
73
+
74
+ self.sample_size = sample_size
75
+
76
+ # Check inputs
77
+ if len(down_block_types) != len(up_block_types):
78
+ raise ValueError(
79
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
80
+ )
81
+
82
+ if len(block_out_channels) != len(down_block_types):
83
+ raise ValueError(
84
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
85
+ )
86
+
87
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
88
+ raise ValueError(
89
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
90
+ )
91
+
92
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
93
+ raise ValueError(
94
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
95
+ )
96
+
97
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
98
+ raise ValueError(
99
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
100
+ )
101
+
102
+ # input
103
+ self.conv_in = nn.Conv2d(
104
+ in_channels,
105
+ block_out_channels[0],
106
+ kernel_size=3,
107
+ padding=1,
108
+ )
109
+
110
+ # time
111
+ time_embed_dim = block_out_channels[0] * 4
112
+
113
+ self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0)
114
+ timestep_input_dim = block_out_channels[0]
115
+
116
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
117
+
118
+ self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0)
119
+ self.add_angle_proj = Timesteps(2*addition_time_embed_dim, True, downscale_freq_shift=0) # encode camera angles
120
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
121
+
122
+ self.down_blocks = nn.ModuleList([])
123
+ self.up_blocks = nn.ModuleList([])
124
+
125
+ if isinstance(num_attention_heads, int):
126
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
127
+
128
+ if isinstance(cross_attention_dim, int):
129
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
130
+
131
+ if isinstance(layers_per_block, int):
132
+ layers_per_block = [layers_per_block] * len(down_block_types)
133
+
134
+ if isinstance(transformer_layers_per_block, int):
135
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
136
+
137
+ blocks_time_embed_dim = time_embed_dim
138
+
139
+ # down
140
+ output_channel = block_out_channels[0]
141
+ for i, down_block_type in enumerate(down_block_types):
142
+ input_channel = output_channel
143
+ output_channel = block_out_channels[i]
144
+ is_final_block = i == len(block_out_channels) - 1
145
+
146
+ down_block = get_down_block(
147
+ down_block_type,
148
+ num_layers=layers_per_block[i],
149
+ transformer_layers_per_block=transformer_layers_per_block[i],
150
+ in_channels=input_channel,
151
+ out_channels=output_channel,
152
+ temb_channels=blocks_time_embed_dim,
153
+ add_downsample=not is_final_block,
154
+ resnet_eps=1e-5,
155
+ cross_attention_dim=cross_attention_dim[i],
156
+ num_attention_heads=num_attention_heads[i],
157
+ resnet_act_fn="silu",
158
+ )
159
+ self.down_blocks.append(down_block)
160
+
161
+ # mid
162
+ self.mid_block = UNetMidBlockSpatioTemporal(
163
+ block_out_channels[-1],
164
+ temb_channels=blocks_time_embed_dim,
165
+ transformer_layers_per_block=transformer_layers_per_block[-1],
166
+ cross_attention_dim=cross_attention_dim[-1],
167
+ num_attention_heads=num_attention_heads[-1],
168
+ )
169
+
170
+ # count how many layers upsample the images
171
+ self.num_upsamplers = 0
172
+
173
+ # up
174
+ reversed_block_out_channels = list(reversed(block_out_channels))
175
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
176
+ reversed_layers_per_block = list(reversed(layers_per_block))
177
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
178
+ reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
179
+
180
+ output_channel = reversed_block_out_channels[0]
181
+ for i, up_block_type in enumerate(up_block_types):
182
+ is_final_block = i == len(block_out_channels) - 1
183
+
184
+ prev_output_channel = output_channel
185
+ output_channel = reversed_block_out_channels[i]
186
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
187
+
188
+ # add upsample block for all BUT final layer
189
+ if not is_final_block:
190
+ add_upsample = True
191
+ self.num_upsamplers += 1
192
+ else:
193
+ add_upsample = False
194
+
195
+ up_block = get_up_block(
196
+ up_block_type,
197
+ num_layers=reversed_layers_per_block[i] + 1,
198
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
199
+ in_channels=input_channel,
200
+ out_channels=output_channel,
201
+ prev_output_channel=prev_output_channel,
202
+ temb_channels=blocks_time_embed_dim,
203
+ add_upsample=add_upsample,
204
+ resnet_eps=1e-5,
205
+ resolution_idx=i,
206
+ cross_attention_dim=reversed_cross_attention_dim[i],
207
+ num_attention_heads=reversed_num_attention_heads[i],
208
+ resnet_act_fn="silu",
209
+ )
210
+ self.up_blocks.append(up_block)
211
+ prev_output_channel = output_channel
212
+
213
+ # out
214
+ self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-5)
215
+ self.conv_act = nn.SiLU()
216
+
217
+ self.conv_out = nn.Conv2d(
218
+ block_out_channels[0],
219
+ out_channels,
220
+ kernel_size=3,
221
+ padding=1,
222
+ )
223
+
224
+ @property
225
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
226
+ r"""
227
+ Returns:
228
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
229
+ indexed by its weight name.
230
+ """
231
+ # set recursively
232
+ processors = {}
233
+
234
+ def fn_recursive_add_processors(
235
+ name: str,
236
+ module: torch.nn.Module,
237
+ processors: Dict[str, AttentionProcessor],
238
+ ):
239
+ if hasattr(module, "get_processor"):
240
+ processors[f"{name}.processor"] = module.get_processor()
241
+
242
+ for sub_name, child in module.named_children():
243
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
244
+
245
+ return processors
246
+
247
+ for name, module in self.named_children():
248
+ fn_recursive_add_processors(name, module, processors)
249
+
250
+ return processors
251
+
252
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
253
+ r"""
254
+ Sets the attention processor to use to compute attention.
255
+
256
+ Parameters:
257
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
258
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
259
+ for **all** `Attention` layers.
260
+
261
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
262
+ processor. This is strongly recommended when setting trainable attention processors.
263
+
264
+ """
265
+ count = len(self.attn_processors.keys())
266
+
267
+ if isinstance(processor, dict) and len(processor) != count:
268
+ raise ValueError(
269
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
270
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
271
+ )
272
+
273
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
274
+ if hasattr(module, "set_processor"):
275
+ if not isinstance(processor, dict):
276
+ module.set_processor(processor)
277
+ else:
278
+ module.set_processor(processor.pop(f"{name}.processor"))
279
+
280
+ for sub_name, child in module.named_children():
281
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
282
+
283
+ for name, module in self.named_children():
284
+ fn_recursive_attn_processor(name, module, processor)
285
+
286
+ def set_default_attn_processor(self):
287
+ """
288
+ Disables custom attention processors and sets the default attention implementation.
289
+ """
290
+ if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
291
+ processor = AttnProcessor()
292
+ else:
293
+ raise ValueError(
294
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
295
+ )
296
+
297
+ self.set_attn_processor(processor)
298
+
299
+ def _set_gradient_checkpointing(self, module, value=False):
300
+ if hasattr(module, "gradient_checkpointing"):
301
+ module.gradient_checkpointing = value
302
+
303
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
304
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
305
+ """
306
+ Sets the attention processor to use [feed forward
307
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
308
+
309
+ Parameters:
310
+ chunk_size (`int`, *optional*):
311
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
312
+ over each tensor of dim=`dim`.
313
+ dim (`int`, *optional*, defaults to `0`):
314
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
315
+ or dim=1 (sequence length).
316
+ """
317
+ if dim not in [0, 1]:
318
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
319
+
320
+ # By default chunk size is 1
321
+ chunk_size = chunk_size or 1
322
+
323
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
324
+ if hasattr(module, "set_chunk_feed_forward"):
325
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
326
+
327
+ for child in module.children():
328
+ fn_recursive_feed_forward(child, chunk_size, dim)
329
+
330
+ for module in self.children():
331
+ fn_recursive_feed_forward(module, chunk_size, dim)
332
+
333
+ def forward(
334
+ self,
335
+ sample: torch.Tensor,
336
+ timestep: Union[torch.Tensor, float, int],
337
+ encoder_hidden_states: torch.Tensor,
338
+ added_time_ids: Union[torch.Tensor, List[torch.Tensor]],
339
+ return_dict: bool = True,
340
+ ) -> Union[UNetSpatioTemporalConditionOutput, Tuple]:
341
+ r"""
342
+ The [`UNetSpatioTemporalConditionModel`] forward method.
343
+
344
+ Args:
345
+ sample (`torch.Tensor`):
346
+ The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
347
+ timestep (`torch.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
348
+ encoder_hidden_states (`torch.Tensor`):
349
+ The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`.
350
+ added_time_ids: (`torch.Tensor`):
351
+ The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
352
+ embeddings and added to the time embeddings.
353
+ return_dict (`bool`, *optional*, defaults to `True`):
354
+ Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead
355
+ of a plain tuple.
356
+ Returns:
357
+ [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
358
+ If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is
359
+ returned, otherwise a `tuple` is returned where the first element is the sample tensor.
360
+ """
361
+ # 1. time
362
+ timesteps = timestep
363
+ if not torch.is_tensor(timesteps):
364
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
365
+ # This would be a good case for the `match` statement (Python 3.10+)
366
+ is_mps = sample.device.type == "mps"
367
+ if isinstance(timestep, float):
368
+ dtype = torch.float32 if is_mps else torch.float64
369
+ else:
370
+ dtype = torch.int32 if is_mps else torch.int64
371
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
372
+ elif len(timesteps.shape) == 0:
373
+ timesteps = timesteps[None].to(sample.device)
374
+
375
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
376
+ batch_size, num_frames = sample.shape[:2]
377
+ timesteps = timesteps.expand(batch_size)
378
+
379
+ t_emb = self.time_proj(timesteps)
380
+
381
+ # `Timesteps` does not contain any weights and will always return f32 tensors
382
+ # but time_embedding might actually be running in fp16. so we need to cast here.
383
+ # there might be better ways to encapsulate this.
384
+ t_emb = t_emb.to(dtype=sample.dtype)
385
+
386
+ emb = self.time_embedding(t_emb)
387
+
388
+ if isinstance(added_time_ids, torch.Tensor):
389
+ time_embeds = self.add_time_proj(added_time_ids.flatten())
390
+ time_embeds = time_embeds.reshape((batch_size, -1))
391
+ time_embeds = time_embeds.to(emb.dtype)
392
+ aug_emb = self.add_embedding(time_embeds)
393
+ emb = emb + aug_emb
394
+
395
+ # Repeat the embeddings num_video_frames times
396
+ # emb: [batch, channels] -> [batch * frames, channels]
397
+ emb = emb.repeat_interleave(num_frames, dim=0)
398
+ elif isinstance(added_time_ids, list):
399
+ # Repeat the embeddings num_video_frames times
400
+ # emb: [batch, channels] -> [batch * frames, channels]
401
+ emb = emb.repeat_interleave(num_frames, dim=0)
402
+
403
+ cond_aug, polars, azimuths = added_time_ids
404
+ cond_aug_emb = self.add_time_proj(cond_aug.flatten())
405
+ polars_emb = self.add_angle_proj(polars.flatten())
406
+ azimuths_emb = self.add_angle_proj(azimuths.flatten())
407
+ time_embeds = torch.cat([cond_aug_emb, polars_emb, azimuths_emb],dim=1)
408
+ time_embeds = time_embeds.to(emb.dtype)
409
+ aug_emb = self.add_embedding(time_embeds)
410
+ emb = emb + aug_emb
411
+ else:
412
+ raise ValueError
413
+
414
+ # Flatten the batch and frames dimensions
415
+ # sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
416
+ sample = sample.flatten(0, 1)
417
+ # encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
418
+ encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)
419
+
420
+ # 2. pre-process
421
+ sample = self.conv_in(sample)
422
+
423
+ image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)
424
+
425
+ down_block_res_samples = (sample,)
426
+ for downsample_block in self.down_blocks:
427
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
428
+ sample, res_samples = downsample_block(
429
+ hidden_states=sample,
430
+ temb=emb,
431
+ encoder_hidden_states=encoder_hidden_states,
432
+ image_only_indicator=image_only_indicator,
433
+ )
434
+ else:
435
+ sample, res_samples = downsample_block(
436
+ hidden_states=sample,
437
+ temb=emb,
438
+ image_only_indicator=image_only_indicator,
439
+ )
440
+
441
+ down_block_res_samples += res_samples
442
+
443
+ # 4. mid
444
+ sample = self.mid_block(
445
+ hidden_states=sample,
446
+ temb=emb,
447
+ encoder_hidden_states=encoder_hidden_states,
448
+ image_only_indicator=image_only_indicator,
449
+ )
450
+
451
+ # 5. up
452
+ for i, upsample_block in enumerate(self.up_blocks):
453
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
454
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
455
+
456
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
457
+ sample = upsample_block(
458
+ hidden_states=sample,
459
+ temb=emb,
460
+ res_hidden_states_tuple=res_samples,
461
+ encoder_hidden_states=encoder_hidden_states,
462
+ image_only_indicator=image_only_indicator,
463
+ )
464
+ else:
465
+ sample = upsample_block(
466
+ hidden_states=sample,
467
+ temb=emb,
468
+ res_hidden_states_tuple=res_samples,
469
+ image_only_indicator=image_only_indicator,
470
+ )
471
+
472
+ # 6. post-process
473
+ sample = self.conv_norm_out(sample)
474
+ sample = self.conv_act(sample)
475
+ sample = self.conv_out(sample)
476
+
477
+ # 7. Reshape back to original shape
478
+ sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
479
+
480
+ if not return_dict:
481
+ return (sample,)
482
+
483
+ return UNetSpatioTemporalConditionOutput(sample=sample)
diffusers_sv3d/pipelines/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .stable_video_diffusion import StableVideo3DDiffusionPipeline
diffusers_sv3d/pipelines/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (240 Bytes). View file
 
diffusers_sv3d/pipelines/stable_video_diffusion/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .pipeline_stable_video_3d_diffusion import StableVideo3DDiffusionPipeline
diffusers_sv3d/pipelines/stable_video_diffusion/__pycache__/__init__.cpython-39.pyc ADDED
Binary file (275 Bytes). View file
 
diffusers_sv3d/pipelines/stable_video_diffusion/__pycache__/pipeline_stable_video_3d_diffusion.cpython-39.pyc ADDED
Binary file (5.03 kB). View file
 
diffusers_sv3d/pipelines/stable_video_diffusion/pipeline_stable_video_3d_diffusion.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers.pipelines.stable_video_diffusion.pipeline_stable_video_diffusion import _append_dims
2
+ from diffusers.pipelines.stable_video_diffusion.pipeline_stable_video_diffusion import *
3
+
4
+
5
+ # Copied from diffusers.pipelines.stable_video_diffusion.pipeline_stable_video_diffusion.StableVideoDiffusionPipeline
6
+ class StableVideo3DDiffusionPipeline(StableVideoDiffusionPipeline):
7
+ def __init__(
8
+ self,
9
+ vae: AutoencoderKLTemporalDecoder,
10
+ image_encoder: CLIPVisionModelWithProjection,
11
+ unet: UNetSpatioTemporalConditionModel,
12
+ scheduler: EulerDiscreteScheduler,
13
+ feature_extractor: CLIPImageProcessor,
14
+ ):
15
+ super().__init__(
16
+ vae,
17
+ image_encoder,
18
+ unet,
19
+ scheduler,
20
+ feature_extractor,
21
+ )
22
+
23
+ def _get_add_time_ids(
24
+ self,
25
+ noise_aug_strength: float,
26
+ polars_rad: List[float],
27
+ azimuths_rad: List[float],
28
+ dtype: torch.dtype,
29
+ batch_size: int,
30
+ num_videos_per_prompt: int,
31
+ do_classifier_free_guidance: bool,
32
+ ):
33
+ cond_aug = torch.tensor([noise_aug_strength]*len(polars_rad), dtype=dtype).repeat(batch_size * num_videos_per_prompt, 1)
34
+ polars_rad = torch.tensor(polars_rad, dtype=dtype).repeat(batch_size * num_videos_per_prompt, 1)
35
+ azimuths_rad = torch.tensor(azimuths_rad, dtype=dtype).repeat(batch_size * num_videos_per_prompt, 1)
36
+
37
+ if do_classifier_free_guidance:
38
+ cond_aug = torch.cat([cond_aug, cond_aug])
39
+ polars_rad = torch.cat([polars_rad, polars_rad])
40
+ azimuths_rad = torch.cat([azimuths_rad, azimuths_rad])
41
+
42
+ add_time_ids = [cond_aug, polars_rad, azimuths_rad]
43
+
44
+ return add_time_ids
45
+
46
+ @torch.no_grad()
47
+ def __call__(
48
+ self,
49
+ image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.Tensor],
50
+
51
+ polars_rad: List[float],
52
+ azimuths_rad: List[float],
53
+ triangle_cfg_scaling: bool = True,
54
+
55
+ height: Optional[int] = None,
56
+ width: Optional[int] = None,
57
+ num_frames: Optional[int] = None,
58
+ num_inference_steps: int = 25,
59
+ sigmas: Optional[List[float]] = None,
60
+ min_guidance_scale: float = 1.0,
61
+ max_guidance_scale: float = 2.5,
62
+ noise_aug_strength: float = 1e-5,
63
+ decode_chunk_size: Optional[int] = None,
64
+ num_videos_per_prompt: Optional[int] = 1,
65
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
66
+ latents: Optional[torch.Tensor] = None,
67
+ output_type: Optional[str] = "pil",
68
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
69
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
70
+ return_dict: bool = True,
71
+ ):
72
+ # 0. Default height and width to unet
73
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
74
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
75
+
76
+ num_frames = num_frames if num_frames is not None else self.unet.config.num_frames
77
+ decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames
78
+
79
+ # 1. Check inputs. Raise error if not correct
80
+ self.check_inputs(image, height, width)
81
+
82
+ # 2. Define call parameters
83
+ if isinstance(image, PIL.Image.Image):
84
+ batch_size = 1
85
+ elif isinstance(image, list):
86
+ batch_size = len(image)
87
+ else:
88
+ batch_size = image.shape[0]
89
+ device = self._execution_device
90
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
91
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
92
+ # corresponds to doing no classifier free guidance.
93
+ self._guidance_scale = max_guidance_scale
94
+
95
+ # 3. Encode input image
96
+ image_embeddings = self._encode_image(image, device, num_videos_per_prompt, self.do_classifier_free_guidance)
97
+
98
+ # 4. Encode input image using VAE
99
+ image = self.video_processor.preprocess(image, height=height, width=width).to(device)
100
+ noise = randn_tensor(image.shape, generator=generator, device=device, dtype=image.dtype)
101
+ image = image + noise_aug_strength * noise
102
+
103
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
104
+ if needs_upcasting:
105
+ self.vae.to(dtype=torch.float32)
106
+
107
+ image_latents = self._encode_vae_image(
108
+ image,
109
+ device=device,
110
+ num_videos_per_prompt=num_videos_per_prompt,
111
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
112
+ )
113
+ image_latents = image_latents.to(image_embeddings.dtype)
114
+
115
+ # cast back to fp16 if needed
116
+ if needs_upcasting:
117
+ self.vae.to(dtype=torch.float16)
118
+
119
+ # Repeat the image latents for each frame so we can concatenate them with the noise
120
+ # image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width]
121
+ image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)
122
+
123
+ # 5. Get Added Time IDs
124
+ added_time_ids = self._get_add_time_ids(
125
+ noise_aug_strength,
126
+ polars_rad,
127
+ azimuths_rad,
128
+ image_embeddings.dtype,
129
+ batch_size,
130
+ num_videos_per_prompt,
131
+ self.do_classifier_free_guidance,
132
+ )
133
+ added_time_ids = [a.to(device) for a in added_time_ids] # (cond_aug, polars_rad, azimuths_rad)
134
+
135
+ # 6. Prepare timesteps
136
+ timesteps, num_inference_steps = retrieve_timesteps(self.scheduler, num_inference_steps, device, None, sigmas)
137
+
138
+ # 7. Prepare latent variables
139
+ num_channels_latents = self.unet.config.in_channels
140
+ latents = self.prepare_latents(
141
+ batch_size * num_videos_per_prompt,
142
+ num_frames,
143
+ num_channels_latents,
144
+ height,
145
+ width,
146
+ image_embeddings.dtype,
147
+ device,
148
+ generator,
149
+ latents,
150
+ )
151
+ print(latents.shape)
152
+
153
+ # 8. Prepare guidance scale
154
+ if triangle_cfg_scaling:
155
+ # Triangle CFG scaling; the last view is input condition
156
+ guidance_scale = torch.cat([
157
+ torch.linspace(min_guidance_scale, max_guidance_scale, num_frames//2 + 1)[1:].unsqueeze(0),
158
+ torch.linspace(max_guidance_scale, min_guidance_scale, num_frames - num_frames//2 + 1)[1:].unsqueeze(0)
159
+ ], dim=-1)
160
+ else:
161
+ guidance_scale = torch.linspace(min_guidance_scale, max_guidance_scale, num_frames).unsqueeze(0)
162
+ guidance_scale = guidance_scale.to(device, latents.dtype)
163
+ guidance_scale = guidance_scale.repeat(batch_size * num_videos_per_prompt, 1)
164
+ guidance_scale = _append_dims(guidance_scale, latents.ndim)
165
+
166
+ self._guidance_scale = guidance_scale
167
+
168
+ # 9. Denoising loop
169
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
170
+ self._num_timesteps = len(timesteps)
171
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
172
+ for i, t in enumerate(timesteps):
173
+ # expand the latents if we are doing classifier free guidance
174
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
175
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
176
+
177
+ # Concatenate image_latents over channels dimension
178
+ latent_model_input = torch.cat([latent_model_input, image_latents], dim=2)
179
+
180
+ # predict the noise residual
181
+ noise_pred = self.unet(
182
+ latent_model_input,
183
+ t,
184
+ encoder_hidden_states=image_embeddings,
185
+ added_time_ids=added_time_ids,
186
+ return_dict=False,
187
+ )[0]
188
+
189
+ # perform guidance
190
+ if self.do_classifier_free_guidance:
191
+ noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
192
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
193
+
194
+ # compute the previous noisy sample x_t -> x_t-1
195
+ latents = self.scheduler.step(noise_pred, t, latents).prev_sample
196
+
197
+ if callback_on_step_end is not None:
198
+ callback_kwargs = {}
199
+ for k in callback_on_step_end_tensor_inputs:
200
+ callback_kwargs[k] = locals()[k]
201
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
202
+
203
+ latents = callback_outputs.pop("latents", latents)
204
+
205
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
206
+ progress_bar.update()
207
+
208
+ if not output_type == "latent":
209
+ # cast back to fp16 if needed
210
+ if needs_upcasting:
211
+ self.vae.to(dtype=torch.float16)
212
+ frames = self.decode_latents(latents, num_frames, decode_chunk_size)
213
+ frames = self.video_processor.postprocess_video(video=frames, output_type=output_type)
214
+ else:
215
+ frames = latents
216
+
217
+ self.maybe_free_model_hooks()
218
+
219
+ if not return_dict:
220
+ return frames
221
+
222
+ return StableVideoDiffusionPipelineOutput(frames=frames)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Pillow
2
+ numpy
3
+ transformers
4
+ diffusers
5
+ omegaconf