FangSen9000 Claude commited on
Commit ·
2f8d0cb
1
Parent(s): ac71c07
Add ControlNeXt-SVD-v2 integration and optimizations
Browse files- Add complete ControlNeXt-SVD-v2 model with pretrained weights
- Create optimized run_controlnext_fast.py with fp16 support and GEGLU patch
- Add conda environment configurations for controlnext
- Update README with optimized inference parameters
- Include generated video examples
- Add reference images for video generation
- Ensure all JPEG files are tracked with Git LFS
🤖 Generated with [Claude Code](https://claude.ai/code)
Co-Authored-By: Claude <noreply@anthropic.com>
This view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- ControlNeXt-SVD-v2/.gitattributes +1 -0
- ControlNeXt-SVD-v2/README.md +171 -0
- ControlNeXt-SVD-v2/dwpose/__init__.py +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/__init__.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/dwpose_detector.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/onnxdet.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/onnxpose.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/preprocess.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/util.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/__pycache__/wholebody.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/dwpose/dwpose_detector.py +90 -0
- ControlNeXt-SVD-v2/dwpose/onnxdet.py +145 -0
- ControlNeXt-SVD-v2/dwpose/onnxpose.py +375 -0
- ControlNeXt-SVD-v2/dwpose/preprocess.py +78 -0
- ControlNeXt-SVD-v2/dwpose/util.py +133 -0
- ControlNeXt-SVD-v2/dwpose/wholebody.py +57 -0
- ControlNeXt-SVD-v2/examples/demos/01-1.mp4 +3 -0
- ControlNeXt-SVD-v2/examples/demos/02-1.mp4 +3 -0
- ControlNeXt-SVD-v2/examples/demos/03-1.mp4 +3 -0
- ControlNeXt-SVD-v2/examples/demos/04-1.mp4 +3 -0
- ControlNeXt-SVD-v2/examples/facefusion/facefusion.jpg +3 -0
- ControlNeXt-SVD-v2/examples/ref_imgs/01.jpeg +3 -0
- ControlNeXt-SVD-v2/examples/ref_imgs/02.jpeg +3 -0
- ControlNeXt-SVD-v2/examples/ref_imgs/03.jpeg +3 -0
- ControlNeXt-SVD-v2/examples/ref_imgs/04.jpeg +3 -0
- ControlNeXt-SVD-v2/examples/video/01.mp4 +3 -0
- ControlNeXt-SVD-v2/examples/video/02.mp4 +3 -0
- ControlNeXt-SVD-v2/git_push2.log +15 -0
- ControlNeXt-SVD-v2/models/__pycache__/controlnext_vid_svd.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/models/__pycache__/unet_spatio_temporal_condition_controlnext.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/models/controlnext_vid_svd.py +176 -0
- ControlNeXt-SVD-v2/models/unet_spatio_temporal_condition_controlnext.py +517 -0
- ControlNeXt-SVD-v2/pipeline/__pycache__/pipeline_stable_video_diffusion_controlnext.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/pipeline/__pycache__/pipeline_stable_video_diffusion_controlnext.cpython-312.pyc +0 -0
- ControlNeXt-SVD-v2/pipeline/pipeline_stable_video_diffusion_controlnext.py +753 -0
- ControlNeXt-SVD-v2/pretrained/DWPose/dw-ll_ucoco_384.onnx +3 -0
- ControlNeXt-SVD-v2/pretrained/DWPose/yolox_l.onnx +3 -0
- ControlNeXt-SVD-v2/pretrained/controlnet.bin +3 -0
- ControlNeXt-SVD-v2/pretrained/unet.bin +3 -0
- ControlNeXt-SVD-v2/run_controlnext.py +282 -0
- ControlNeXt-SVD-v2/script.sh +15 -0
- ControlNeXt-SVD-v2/utils/__pycache__/pre_process.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/utils/__pycache__/scheduling_euler_discrete_karras_fix.cpython-310.pyc +0 -0
- ControlNeXt-SVD-v2/utils/pre_process.py +53 -0
- ControlNeXt-SVD-v2/utils/scheduling_euler_discrete_karras_fix.py +556 -0
- README.md +43 -2
- env/environment02_controlnext.yml +10 -0
- env/requirements02_controlnext.txt +15 -0
- generated_sign_video/output.mp4 +3 -0
.gitattributes
CHANGED
|
@@ -12,3 +12,4 @@
|
|
| 12 |
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 13 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 14 |
*.jpg filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 12 |
*.gif filter=lfs diff=lfs merge=lfs -text
|
| 13 |
*.png filter=lfs diff=lfs merge=lfs -text
|
| 14 |
*.jpg filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
ControlNeXt-SVD-v2/.gitattributes
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
*.jpeg filter=lfs diff=lfs merge=lfs -text
|
ControlNeXt-SVD-v2/README.md
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🌀 ControlNeXt-SVD-v2
|
| 2 |
+
|
| 3 |
+
This is our implementation of ControlNeXt based on [Stable Video Diffusion](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt-1-1). It can be seen as an attempt to replicate the implementation of [AnimateAnyone](https://github.com/HumanAIGC/AnimateAnyone) with a more concise and efficient architecture.
|
| 4 |
+
|
| 5 |
+
Compared to image generation, video generation poses significantly greater challenges. While direct training of the generation model using our method is feasible, we also employ various engineering strategies to enhance performance. Although they are irrespective of academic algorithms.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
> Please refer to [Examples](#examples) for further intuitive details.\
|
| 9 |
+
> Please refer to [Base model](#base-model) for more details of our used base model. \
|
| 10 |
+
> Please refer to [Inference](#inference) for more details regarding installation and inference.\
|
| 11 |
+
> Please refer to [Advanced Performance](#advanced-performance) for more details to achieve a better performance.\
|
| 12 |
+
> Please refer to [Limitations](#limitations) for more details about the limitations of current work.
|
| 13 |
+
|
| 14 |
+
# Examples
|
| 15 |
+
If you can't load the videos, you can also directly download them from [here](examples/demos) and [here](examples/video).
|
| 16 |
+
Or you can view them from our [Project Page](https://pbihao.github.io/projects/controlnext/index.html) or [BiliBili](https://www.bilibili.com/video/BV1wJYbebEE7/?buvid=YC4E03C93B119ADD4080B0958DE73F9DDCAC&from_spmid=dt.dt.video.0&is_story_h5=false&mid=y82Gz7uArS6jTQ6zuqJj3w%3D%3D&p=1&plat_id=114&share_from=ugc&share_medium=iphone&share_plat=ios&share_session_id=4E5549FC-0710-4030-BD2C-CDED80B46D08&share_source=WEIXIN&share_source=weixin&share_tag=s_i×tamp=1723123770&unique_k=XLZLhCq&up_id=176095810&vd_source=3791450598e16da25ecc2477fc7983db).
|
| 17 |
+
|
| 18 |
+
<table style="margin: 0 auto; border-collapse: collapse;">
|
| 19 |
+
<tr>
|
| 20 |
+
<td width="40%" style="border: none;">
|
| 21 |
+
<video width="100%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/9d45a00a-d3cd-48e1-aa78-1d3158bfd4f4" muted="false"></video>
|
| 22 |
+
</td>
|
| 23 |
+
<td width="40%" style="border: none;">
|
| 24 |
+
<video width="100%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/1004960a-82de-4f0d-a329-ba676b8cbd0d" muted="false"></video>
|
| 25 |
+
</td>
|
| 26 |
+
</tr>
|
| 27 |
+
<tr>
|
| 28 |
+
<td width="40%" style="border: none;">
|
| 29 |
+
<video width="100%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/7db1acd1-0c61-4855-91bb-e4e8f8989393" muted="false"></video>
|
| 30 |
+
</td>
|
| 31 |
+
<td width="40%" style="border: none;">
|
| 32 |
+
<video width="100%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/0f32df53-1827-404d-806a-23e65d357504" muted="false"></video>
|
| 33 |
+
</td>
|
| 34 |
+
</tr>
|
| 35 |
+
|
| 36 |
+
</table>
|
| 37 |
+
|
| 38 |
+
<video width="80%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/c69b4f34-0851-4637-a9ef-fb91beed5666" muted="false"></video>
|
| 39 |
+
|
| 40 |
+
<video width="80%" height="auto" style="display: block; margin: 0px auto;" controls autoplay loop src="https://github.com/user-attachments/assets/32a4d24b-bc39-4ea9-9fd4-ed78b4eec116" muted="false"></video>
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# Base Model
|
| 44 |
+
|
| 45 |
+
For the v2 version, we adopt the below operations to improve the performance:
|
| 46 |
+
* We have collected a higher-quality dataset with higher resolution to train our model.
|
| 47 |
+
* We have extended the training and inference batch frames to 24.
|
| 48 |
+
* We have extended the video height and width to a resolution of 576 × 1024.
|
| 49 |
+
* We conduct extensive continual training of SVD on human-related videos to enhance its ability to generate human-related content.
|
| 50 |
+
* We adopt fp32.
|
| 51 |
+
* We adopt the pose alignment during the inference following the related.
|
| 52 |
+
|
| 53 |
+
# Inference
|
| 54 |
+
|
| 55 |
+
1. Clone our repository
|
| 56 |
+
2. `cd ControlNeXt-SVD-v2`
|
| 57 |
+
3. Download the pretrained weight into `pretrained/` from [here](https://huggingface.co/Pbihao/ControlNeXt/tree/main/ControlNeXt-SVD/v2). (More details please refer to [Base Model](#base-model))
|
| 58 |
+
4. Download the DWPose weights including the [dw-ll_ucoco_384](https://drive.google.com/file/d/12L8E2oAgZy4VACGSK9RaZBZrfgx7VTA2/view?usp=sharing) and [yolox_l](https://drive.google.com/file/d/1w9pXC8tT0p9ndMN-CArp1__b2GbzewWI/view?usp=sharing) into `pretrained/DWPose`. For more details, please refer to [DWPose](https://github.com/IDEA-Research/DWPose):
|
| 59 |
+
```
|
| 60 |
+
├───pretrained
|
| 61 |
+
└───DWPose
|
| 62 |
+
| │───dw-ll_ucoco_384.onnx
|
| 63 |
+
| └───yolox_l.onnx
|
| 64 |
+
|
|
| 65 |
+
├───unet.bin
|
| 66 |
+
└───controlnet.bin
|
| 67 |
+
```
|
| 68 |
+
5. Run the scipt
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
CUDA_VISIBLE_DEVICES=0 python run_controlnext.py \
|
| 72 |
+
--pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
|
| 73 |
+
--output_dir outputs \
|
| 74 |
+
--max_frame_num 240 \
|
| 75 |
+
--guidance_scale 3 \
|
| 76 |
+
--batch_frames 24 \
|
| 77 |
+
--sample_stride 2 \
|
| 78 |
+
--overlap 6 \
|
| 79 |
+
--height 1024 \
|
| 80 |
+
--width 576 \
|
| 81 |
+
--controlnext_path pretrained/controlnet.bin \
|
| 82 |
+
--unet_path pretrained/unet.bin \
|
| 83 |
+
--validation_control_video_path examples/video/02.mp4 \
|
| 84 |
+
--ref_image_path examples/ref_imgs/01.jpeg
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
> --pretrained_model_name_or_path : pretrained base model, we pretrain and fintune models based on [SVD-XT1.1](https://huggingface.co/stabilityai/stable-video-diffusion-img2vid-xt-1-1)\
|
| 88 |
+
> --controlnet_model_name_or_path : the model path of controlnet (a light weight module) \
|
| 89 |
+
> --unet_model_name_or_path : the model path of unet \
|
| 90 |
+
> --ref_image_path: the path to the reference image \
|
| 91 |
+
> --overlap: The length of the overlapped frames for long-frame video generation. \
|
| 92 |
+
> --sample_stride: The length of the sampled stride for the conditional controls. You can set it to `1` to make more smooth generation wihile requires more computation.
|
| 93 |
+
|
| 94 |
+
5. Face Enhancement (Optional,Recommand for bad faces)
|
| 95 |
+
|
| 96 |
+
> Currently, the model is not specifically trained for IP consistency, as there are already many mature tools available. Additionally, alternatives like Animate Anyone also adopt such post-processing techniques.
|
| 97 |
+
|
| 98 |
+
a. Clone [Face Fusion](https://github.com/facefusion/facefusion): \
|
| 99 |
+
```git clone https://github.com/facefusion/facefusion```
|
| 100 |
+
|
| 101 |
+
b. Ensure to enter the directory:\
|
| 102 |
+
```cd facefusion```
|
| 103 |
+
|
| 104 |
+
c. Install facefusion (Recommand create a new virtual environment using conda to avoid conflicts):\
|
| 105 |
+
```python install.py```
|
| 106 |
+
|
| 107 |
+
d. Run the command:
|
| 108 |
+
```
|
| 109 |
+
python run.py \
|
| 110 |
+
-s ../outputs/demo.jpg \
|
| 111 |
+
-t ../outputs/demo.mp4 \
|
| 112 |
+
-o ../outputs/out.mp4 \
|
| 113 |
+
--headless \
|
| 114 |
+
--execution-providers cuda \
|
| 115 |
+
--face-selector-mode one
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
> -s: the reference image \
|
| 119 |
+
> -t: the path to the original video\
|
| 120 |
+
> -o: the path to store the refined video\
|
| 121 |
+
> --headless: no gui need\
|
| 122 |
+
> --execution-providers cuda: use cuda for acceleration (If available, most the cpu is enough)
|
| 123 |
+
|
| 124 |
+
# Advanced Performance
|
| 125 |
+
In this section, we will delve into additional details and my own experiences to enhance video generation. These factors are algorithm-independent and unrelated to academia, yet crucial for achieving superior results. Many closely related works incorporate these strategies.
|
| 126 |
+
|
| 127 |
+
### Reference Image
|
| 128 |
+
|
| 129 |
+
It is crucial to ensure that the reference image is clear and easily understandable, especially aligning the face of the reference with the pose.
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
### Face Enhencement
|
| 133 |
+
|
| 134 |
+
Most related works utilize face enhancement as part of the post-processing. This is especially relevant when generating videos based on images of unfamiliar individuals, such as friends, who were not included in the base model's pretraining and are therefore unseen and OOD data.
|
| 135 |
+
|
| 136 |
+
We recommand the [Facefusion](https://github.com/facefusion/facefusion
|
| 137 |
+
) for the post proct-processing. And please let us know if you have a better solution.
|
| 138 |
+
|
| 139 |
+
Please refer to [Facefusion](https://github.com/facefusion/facefusion
|
| 140 |
+
) for more details.
|
| 141 |
+
|
| 142 |
+

|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
### Continuously Finetune
|
| 146 |
+
|
| 147 |
+
To significantly enhance performance on a specific pose sequence, you can continuously fine-tune the model for just a few hundred steps.
|
| 148 |
+
|
| 149 |
+
We will release the related fine-tuning code later.
|
| 150 |
+
|
| 151 |
+
### Pose Generation
|
| 152 |
+
|
| 153 |
+
We adopt [DWPose](https://github.com/IDEA-Research/DWPose) for the pose generation, and follow the related work ([1](https://humanaigc.github.io/animate-anyone/), [2](https://tencent.github.io/MimicMotion/)) to align the pose.
|
| 154 |
+
|
| 155 |
+
# Limitations
|
| 156 |
+
|
| 157 |
+
## IP Consistency
|
| 158 |
+
|
| 159 |
+
We did not prioritize maintaining IP consistency during the development of the generation model and now rely on a helper model for face enhancement.
|
| 160 |
+
|
| 161 |
+
However, additional training can be implemented to ensure IP consistency moving forward.
|
| 162 |
+
|
| 163 |
+
This also leaves a possible direction for futher improvement.
|
| 164 |
+
|
| 165 |
+
## Base model
|
| 166 |
+
|
| 167 |
+
The base model plays a crucial role in generating human features, particularly hands and faces. We encourage collaboration to improve the base model for enhanced human-related video generation.
|
| 168 |
+
|
| 169 |
+
# TODO
|
| 170 |
+
|
| 171 |
+
* Training and finetune code
|
ControlNeXt-SVD-v2/dwpose/__init__.py
ADDED
|
File without changes
|
ControlNeXt-SVD-v2/dwpose/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (175 Bytes). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/dwpose_detector.cpython-310.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/onnxdet.cpython-310.pyc
ADDED
|
Binary file (4.72 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/onnxpose.cpython-310.pyc
ADDED
|
Binary file (10.6 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/preprocess.cpython-310.pyc
ADDED
|
Binary file (2.71 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/util.cpython-310.pyc
ADDED
|
Binary file (4.51 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/__pycache__/wholebody.cpython-310.pyc
ADDED
|
Binary file (1.89 kB). View file
|
|
|
ControlNeXt-SVD-v2/dwpose/dwpose_detector.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
|
| 6 |
+
from .wholebody import Wholebody
|
| 7 |
+
|
| 8 |
+
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
|
| 9 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 10 |
+
|
| 11 |
+
class DWposeDetector:
|
| 12 |
+
"""
|
| 13 |
+
A pose detect method for image-like data.
|
| 14 |
+
|
| 15 |
+
Parameters:
|
| 16 |
+
model_det: (str) serialized ONNX format model path,
|
| 17 |
+
such as https://huggingface.co/yzd-v/DWPose/blob/main/yolox_l.onnx
|
| 18 |
+
model_pose: (str) serialized ONNX format model path,
|
| 19 |
+
such as https://huggingface.co/yzd-v/DWPose/blob/main/dw-ll_ucoco_384.onnx
|
| 20 |
+
device: (str) 'cpu' or 'cuda:{device_id}'
|
| 21 |
+
"""
|
| 22 |
+
def __init__(self, model_det, model_pose, device='cpu'):
|
| 23 |
+
self.args = model_det, model_pose, device
|
| 24 |
+
|
| 25 |
+
def release_memory(self):
|
| 26 |
+
if hasattr(self, 'pose_estimation'):
|
| 27 |
+
del self.pose_estimation
|
| 28 |
+
import gc; gc.collect()
|
| 29 |
+
|
| 30 |
+
def __call__(self, oriImg):
|
| 31 |
+
if not hasattr(self, 'pose_estimation'):
|
| 32 |
+
self.pose_estimation = Wholebody(*self.args)
|
| 33 |
+
|
| 34 |
+
oriImg = oriImg.copy()
|
| 35 |
+
H, W, C = oriImg.shape
|
| 36 |
+
with torch.no_grad():
|
| 37 |
+
candidate, score = self.pose_estimation(oriImg)
|
| 38 |
+
nums, _, locs = candidate.shape
|
| 39 |
+
candidate[..., 0] /= float(W)
|
| 40 |
+
candidate[..., 1] /= float(H)
|
| 41 |
+
body = candidate[:, :18].copy()
|
| 42 |
+
body = body.reshape(nums * 18, locs)
|
| 43 |
+
subset = score[:, :18].copy()
|
| 44 |
+
for i in range(len(subset)):
|
| 45 |
+
for j in range(len(subset[i])):
|
| 46 |
+
if subset[i][j] > 0.3:
|
| 47 |
+
subset[i][j] = int(18 * i + j)
|
| 48 |
+
else:
|
| 49 |
+
subset[i][j] = -1
|
| 50 |
+
|
| 51 |
+
# un_visible = subset < 0.3
|
| 52 |
+
# candidate[un_visible] = -1
|
| 53 |
+
|
| 54 |
+
# foot = candidate[:, 18:24]
|
| 55 |
+
|
| 56 |
+
faces = candidate[:, 24:92]
|
| 57 |
+
|
| 58 |
+
hands = candidate[:, 92:113]
|
| 59 |
+
hands = np.vstack([hands, candidate[:, 113:]])
|
| 60 |
+
|
| 61 |
+
faces_score = score[:, 24:92]
|
| 62 |
+
hands_score = np.vstack([score[:, 92:113], score[:, 113:]])
|
| 63 |
+
|
| 64 |
+
bodies = dict(candidate=body, subset=subset, score=score[:, :18])
|
| 65 |
+
pose = dict(bodies=bodies, hands=hands, hands_score=hands_score, faces=faces, faces_score=faces_score)
|
| 66 |
+
|
| 67 |
+
return pose
|
| 68 |
+
|
| 69 |
+
# 检查哪个目录存在
|
| 70 |
+
if os.path.exists("ControlNeXt-SVD-v2/pretrained/DWPose/"):
|
| 71 |
+
model_det = "ControlNeXt-SVD-v2/pretrained/DWPose/yolox_l.onnx"
|
| 72 |
+
model_pose = "ControlNeXt-SVD-v2/pretrained/DWPose/dw-ll_ucoco_384.onnx"
|
| 73 |
+
elif os.path.exists("pretrained/DWPose/"):
|
| 74 |
+
model_det = "pretrained/DWPose/yolox_l.onnx"
|
| 75 |
+
model_pose = "pretrained/DWPose/dw-ll_ucoco_384.onnx"
|
| 76 |
+
else:
|
| 77 |
+
raise FileNotFoundError("找不到DWPose预训练模型目录")
|
| 78 |
+
|
| 79 |
+
dwpose_detector = DWposeDetector(
|
| 80 |
+
model_det=model_det,
|
| 81 |
+
model_pose=model_pose,
|
| 82 |
+
device=device
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
'''
|
| 86 |
+
dwpose_detector = DWposeDetector(
|
| 87 |
+
model_det="pretrained/DWPose/yolox_l.onnx",
|
| 88 |
+
model_pose="pretrained/DWPose/dw-ll_ucoco_384.onnx",
|
| 89 |
+
device=device)
|
| 90 |
+
'''
|
ControlNeXt-SVD-v2/dwpose/onnxdet.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import cv2
|
| 2 |
+
import numpy as np
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def nms(boxes, scores, nms_thr):
|
| 6 |
+
"""Single class NMS implemented in Numpy.
|
| 7 |
+
|
| 8 |
+
Args:
|
| 9 |
+
boxes (np.ndarray): shape=(N,4); N is number of boxes
|
| 10 |
+
scores (np.ndarray): the score of bboxes
|
| 11 |
+
nms_thr (float): the threshold in NMS
|
| 12 |
+
|
| 13 |
+
Returns:
|
| 14 |
+
List[int]: output bbox ids
|
| 15 |
+
"""
|
| 16 |
+
x1 = boxes[:, 0]
|
| 17 |
+
y1 = boxes[:, 1]
|
| 18 |
+
x2 = boxes[:, 2]
|
| 19 |
+
y2 = boxes[:, 3]
|
| 20 |
+
|
| 21 |
+
areas = (x2 - x1 + 1) * (y2 - y1 + 1)
|
| 22 |
+
order = scores.argsort()[::-1]
|
| 23 |
+
|
| 24 |
+
keep = []
|
| 25 |
+
while order.size > 0:
|
| 26 |
+
i = order[0]
|
| 27 |
+
keep.append(i)
|
| 28 |
+
xx1 = np.maximum(x1[i], x1[order[1:]])
|
| 29 |
+
yy1 = np.maximum(y1[i], y1[order[1:]])
|
| 30 |
+
xx2 = np.minimum(x2[i], x2[order[1:]])
|
| 31 |
+
yy2 = np.minimum(y2[i], y2[order[1:]])
|
| 32 |
+
|
| 33 |
+
w = np.maximum(0.0, xx2 - xx1 + 1)
|
| 34 |
+
h = np.maximum(0.0, yy2 - yy1 + 1)
|
| 35 |
+
inter = w * h
|
| 36 |
+
ovr = inter / (areas[i] + areas[order[1:]] - inter)
|
| 37 |
+
|
| 38 |
+
inds = np.where(ovr <= nms_thr)[0]
|
| 39 |
+
order = order[inds + 1]
|
| 40 |
+
|
| 41 |
+
return keep
|
| 42 |
+
|
| 43 |
+
def multiclass_nms(boxes, scores, nms_thr, score_thr):
|
| 44 |
+
"""Multiclass NMS implemented in Numpy. Class-aware version.
|
| 45 |
+
|
| 46 |
+
Args:
|
| 47 |
+
boxes (np.ndarray): shape=(N,4); N is number of boxes
|
| 48 |
+
scores (np.ndarray): the score of bboxes
|
| 49 |
+
nms_thr (float): the threshold in NMS
|
| 50 |
+
score_thr (float): the threshold of cls score
|
| 51 |
+
|
| 52 |
+
Returns:
|
| 53 |
+
np.ndarray: outputs bboxes coordinate
|
| 54 |
+
"""
|
| 55 |
+
final_dets = []
|
| 56 |
+
num_classes = scores.shape[1]
|
| 57 |
+
for cls_ind in range(num_classes):
|
| 58 |
+
cls_scores = scores[:, cls_ind]
|
| 59 |
+
valid_score_mask = cls_scores > score_thr
|
| 60 |
+
if valid_score_mask.sum() == 0:
|
| 61 |
+
continue
|
| 62 |
+
else:
|
| 63 |
+
valid_scores = cls_scores[valid_score_mask]
|
| 64 |
+
valid_boxes = boxes[valid_score_mask]
|
| 65 |
+
keep = nms(valid_boxes, valid_scores, nms_thr)
|
| 66 |
+
if len(keep) > 0:
|
| 67 |
+
cls_inds = np.ones((len(keep), 1)) * cls_ind
|
| 68 |
+
dets = np.concatenate(
|
| 69 |
+
[valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
|
| 70 |
+
)
|
| 71 |
+
final_dets.append(dets)
|
| 72 |
+
if len(final_dets) == 0:
|
| 73 |
+
return None
|
| 74 |
+
return np.concatenate(final_dets, 0)
|
| 75 |
+
|
| 76 |
+
def demo_postprocess(outputs, img_size, p6=False):
|
| 77 |
+
grids = []
|
| 78 |
+
expanded_strides = []
|
| 79 |
+
strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
|
| 80 |
+
|
| 81 |
+
hsizes = [img_size[0] // stride for stride in strides]
|
| 82 |
+
wsizes = [img_size[1] // stride for stride in strides]
|
| 83 |
+
|
| 84 |
+
for hsize, wsize, stride in zip(hsizes, wsizes, strides):
|
| 85 |
+
xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
|
| 86 |
+
grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
|
| 87 |
+
grids.append(grid)
|
| 88 |
+
shape = grid.shape[:2]
|
| 89 |
+
expanded_strides.append(np.full((*shape, 1), stride))
|
| 90 |
+
|
| 91 |
+
grids = np.concatenate(grids, 1)
|
| 92 |
+
expanded_strides = np.concatenate(expanded_strides, 1)
|
| 93 |
+
outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
|
| 94 |
+
outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
|
| 95 |
+
|
| 96 |
+
return outputs
|
| 97 |
+
|
| 98 |
+
def preprocess(img, input_size, swap=(2, 0, 1)):
|
| 99 |
+
if len(img.shape) == 3:
|
| 100 |
+
padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114
|
| 101 |
+
else:
|
| 102 |
+
padded_img = np.ones(input_size, dtype=np.uint8) * 114
|
| 103 |
+
|
| 104 |
+
r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
|
| 105 |
+
resized_img = cv2.resize(
|
| 106 |
+
img,
|
| 107 |
+
(int(img.shape[1] * r), int(img.shape[0] * r)),
|
| 108 |
+
interpolation=cv2.INTER_LINEAR,
|
| 109 |
+
).astype(np.uint8)
|
| 110 |
+
padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
|
| 111 |
+
|
| 112 |
+
padded_img = padded_img.transpose(swap)
|
| 113 |
+
padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
|
| 114 |
+
return padded_img, r
|
| 115 |
+
|
| 116 |
+
def inference_detector(session, oriImg):
|
| 117 |
+
"""run human detect
|
| 118 |
+
"""
|
| 119 |
+
input_shape = (640,640)
|
| 120 |
+
img, ratio = preprocess(oriImg, input_shape)
|
| 121 |
+
|
| 122 |
+
ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
|
| 123 |
+
output = session.run(None, ort_inputs)
|
| 124 |
+
predictions = demo_postprocess(output[0], input_shape)[0]
|
| 125 |
+
|
| 126 |
+
boxes = predictions[:, :4]
|
| 127 |
+
scores = predictions[:, 4:5] * predictions[:, 5:]
|
| 128 |
+
|
| 129 |
+
boxes_xyxy = np.ones_like(boxes)
|
| 130 |
+
boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2]/2.
|
| 131 |
+
boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3]/2.
|
| 132 |
+
boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2]/2.
|
| 133 |
+
boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3]/2.
|
| 134 |
+
boxes_xyxy /= ratio
|
| 135 |
+
dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
|
| 136 |
+
if dets is not None:
|
| 137 |
+
final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]
|
| 138 |
+
isscore = final_scores>0.3
|
| 139 |
+
iscat = final_cls_inds == 0
|
| 140 |
+
isbbox = [ i and j for (i, j) in zip(isscore, iscat)]
|
| 141 |
+
final_boxes = final_boxes[isbbox]
|
| 142 |
+
else:
|
| 143 |
+
final_boxes = np.array([])
|
| 144 |
+
|
| 145 |
+
return final_boxes
|
ControlNeXt-SVD-v2/dwpose/onnxpose.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import List, Tuple
|
| 2 |
+
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
import onnxruntime as ort
|
| 6 |
+
|
| 7 |
+
def preprocess(
|
| 8 |
+
img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)
|
| 9 |
+
) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
|
| 10 |
+
"""Do preprocessing for RTMPose model inference.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
img (np.ndarray): Input image in shape.
|
| 14 |
+
input_size (tuple): Input image size in shape (w, h).
|
| 15 |
+
|
| 16 |
+
Returns:
|
| 17 |
+
tuple:
|
| 18 |
+
- resized_img (np.ndarray): Preprocessed image.
|
| 19 |
+
- center (np.ndarray): Center of image.
|
| 20 |
+
- scale (np.ndarray): Scale of image.
|
| 21 |
+
"""
|
| 22 |
+
# get shape of image
|
| 23 |
+
img_shape = img.shape[:2]
|
| 24 |
+
out_img, out_center, out_scale = [], [], []
|
| 25 |
+
if len(out_bbox) == 0:
|
| 26 |
+
out_bbox = [[0, 0, img_shape[1], img_shape[0]]]
|
| 27 |
+
for i in range(len(out_bbox)):
|
| 28 |
+
x0 = out_bbox[i][0]
|
| 29 |
+
y0 = out_bbox[i][1]
|
| 30 |
+
x1 = out_bbox[i][2]
|
| 31 |
+
y1 = out_bbox[i][3]
|
| 32 |
+
bbox = np.array([x0, y0, x1, y1])
|
| 33 |
+
|
| 34 |
+
# get center and scale
|
| 35 |
+
center, scale = bbox_xyxy2cs(bbox, padding=1.25)
|
| 36 |
+
|
| 37 |
+
# do affine transformation
|
| 38 |
+
resized_img, scale = top_down_affine(input_size, scale, center, img)
|
| 39 |
+
|
| 40 |
+
# normalize image
|
| 41 |
+
mean = np.array([123.675, 116.28, 103.53])
|
| 42 |
+
std = np.array([58.395, 57.12, 57.375])
|
| 43 |
+
resized_img = (resized_img - mean) / std
|
| 44 |
+
|
| 45 |
+
out_img.append(resized_img)
|
| 46 |
+
out_center.append(center)
|
| 47 |
+
out_scale.append(scale)
|
| 48 |
+
|
| 49 |
+
return out_img, out_center, out_scale
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def inference(sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray:
|
| 53 |
+
"""Inference RTMPose model.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
sess (ort.InferenceSession): ONNXRuntime session.
|
| 57 |
+
img (np.ndarray): Input image in shape.
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
outputs (np.ndarray): Output of RTMPose model.
|
| 61 |
+
"""
|
| 62 |
+
all_out = []
|
| 63 |
+
# build input
|
| 64 |
+
for i in range(len(img)):
|
| 65 |
+
input = [img[i].transpose(2, 0, 1)]
|
| 66 |
+
|
| 67 |
+
# build output
|
| 68 |
+
sess_input = {sess.get_inputs()[0].name: input}
|
| 69 |
+
sess_output = []
|
| 70 |
+
for out in sess.get_outputs():
|
| 71 |
+
sess_output.append(out.name)
|
| 72 |
+
|
| 73 |
+
# run model
|
| 74 |
+
outputs = sess.run(sess_output, sess_input)
|
| 75 |
+
all_out.append(outputs)
|
| 76 |
+
|
| 77 |
+
return all_out
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def postprocess(outputs: List[np.ndarray],
|
| 81 |
+
model_input_size: Tuple[int, int],
|
| 82 |
+
center: Tuple[int, int],
|
| 83 |
+
scale: Tuple[int, int],
|
| 84 |
+
simcc_split_ratio: float = 2.0
|
| 85 |
+
) -> Tuple[np.ndarray, np.ndarray]:
|
| 86 |
+
"""Postprocess for RTMPose model output.
|
| 87 |
+
|
| 88 |
+
Args:
|
| 89 |
+
outputs (np.ndarray): Output of RTMPose model.
|
| 90 |
+
model_input_size (tuple): RTMPose model Input image size.
|
| 91 |
+
center (tuple): Center of bbox in shape (x, y).
|
| 92 |
+
scale (tuple): Scale of bbox in shape (w, h).
|
| 93 |
+
simcc_split_ratio (float): Split ratio of simcc.
|
| 94 |
+
|
| 95 |
+
Returns:
|
| 96 |
+
tuple:
|
| 97 |
+
- keypoints (np.ndarray): Rescaled keypoints.
|
| 98 |
+
- scores (np.ndarray): Model predict scores.
|
| 99 |
+
"""
|
| 100 |
+
all_key = []
|
| 101 |
+
all_score = []
|
| 102 |
+
for i in range(len(outputs)):
|
| 103 |
+
# use simcc to decode
|
| 104 |
+
simcc_x, simcc_y = outputs[i]
|
| 105 |
+
keypoints, scores = decode(simcc_x, simcc_y, simcc_split_ratio)
|
| 106 |
+
|
| 107 |
+
# rescale keypoints
|
| 108 |
+
keypoints = keypoints / model_input_size * scale[i] + center[i] - scale[i] / 2
|
| 109 |
+
all_key.append(keypoints[0])
|
| 110 |
+
all_score.append(scores[0])
|
| 111 |
+
|
| 112 |
+
return np.array(all_key), np.array(all_score)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def bbox_xyxy2cs(bbox: np.ndarray,
|
| 116 |
+
padding: float = 1.) -> Tuple[np.ndarray, np.ndarray]:
|
| 117 |
+
"""Transform the bbox format from (x,y,w,h) into (center, scale)
|
| 118 |
+
|
| 119 |
+
Args:
|
| 120 |
+
bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted
|
| 121 |
+
as (left, top, right, bottom)
|
| 122 |
+
padding (float): BBox padding factor that will be multilied to scale.
|
| 123 |
+
Default: 1.0
|
| 124 |
+
|
| 125 |
+
Returns:
|
| 126 |
+
tuple: A tuple containing center and scale.
|
| 127 |
+
- np.ndarray[float32]: Center (x, y) of the bbox in shape (2,) or
|
| 128 |
+
(n, 2)
|
| 129 |
+
- np.ndarray[float32]: Scale (w, h) of the bbox in shape (2,) or
|
| 130 |
+
(n, 2)
|
| 131 |
+
"""
|
| 132 |
+
# convert single bbox from (4, ) to (1, 4)
|
| 133 |
+
dim = bbox.ndim
|
| 134 |
+
if dim == 1:
|
| 135 |
+
bbox = bbox[None, :]
|
| 136 |
+
|
| 137 |
+
# get bbox center and scale
|
| 138 |
+
x1, y1, x2, y2 = np.hsplit(bbox, [1, 2, 3])
|
| 139 |
+
center = np.hstack([x1 + x2, y1 + y2]) * 0.5
|
| 140 |
+
scale = np.hstack([x2 - x1, y2 - y1]) * padding
|
| 141 |
+
|
| 142 |
+
if dim == 1:
|
| 143 |
+
center = center[0]
|
| 144 |
+
scale = scale[0]
|
| 145 |
+
|
| 146 |
+
return center, scale
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def _fix_aspect_ratio(bbox_scale: np.ndarray,
|
| 150 |
+
aspect_ratio: float) -> np.ndarray:
|
| 151 |
+
"""Extend the scale to match the given aspect ratio.
|
| 152 |
+
|
| 153 |
+
Args:
|
| 154 |
+
scale (np.ndarray): The image scale (w, h) in shape (2, )
|
| 155 |
+
aspect_ratio (float): The ratio of ``w/h``
|
| 156 |
+
|
| 157 |
+
Returns:
|
| 158 |
+
np.ndarray: The reshaped image scale in (2, )
|
| 159 |
+
"""
|
| 160 |
+
w, h = np.hsplit(bbox_scale, [1])
|
| 161 |
+
bbox_scale = np.where(w > h * aspect_ratio,
|
| 162 |
+
np.hstack([w, w / aspect_ratio]),
|
| 163 |
+
np.hstack([h * aspect_ratio, h]))
|
| 164 |
+
return bbox_scale
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray:
|
| 168 |
+
"""Rotate a point by an angle.
|
| 169 |
+
|
| 170 |
+
Args:
|
| 171 |
+
pt (np.ndarray): 2D point coordinates (x, y) in shape (2, )
|
| 172 |
+
angle_rad (float): rotation angle in radian
|
| 173 |
+
|
| 174 |
+
Returns:
|
| 175 |
+
np.ndarray: Rotated point in shape (2, )
|
| 176 |
+
"""
|
| 177 |
+
sn, cs = np.sin(angle_rad), np.cos(angle_rad)
|
| 178 |
+
rot_mat = np.array([[cs, -sn], [sn, cs]])
|
| 179 |
+
return rot_mat @ pt
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray:
|
| 183 |
+
"""To calculate the affine matrix, three pairs of points are required. This
|
| 184 |
+
function is used to get the 3rd point, given 2D points a & b.
|
| 185 |
+
|
| 186 |
+
The 3rd point is defined by rotating vector `a - b` by 90 degrees
|
| 187 |
+
anticlockwise, using b as the rotation center.
|
| 188 |
+
|
| 189 |
+
Args:
|
| 190 |
+
a (np.ndarray): The 1st point (x,y) in shape (2, )
|
| 191 |
+
b (np.ndarray): The 2nd point (x,y) in shape (2, )
|
| 192 |
+
|
| 193 |
+
Returns:
|
| 194 |
+
np.ndarray: The 3rd point.
|
| 195 |
+
"""
|
| 196 |
+
direction = a - b
|
| 197 |
+
c = b + np.r_[-direction[1], direction[0]]
|
| 198 |
+
return c
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def get_warp_matrix(center: np.ndarray,
|
| 202 |
+
scale: np.ndarray,
|
| 203 |
+
rot: float,
|
| 204 |
+
output_size: Tuple[int, int],
|
| 205 |
+
shift: Tuple[float, float] = (0., 0.),
|
| 206 |
+
inv: bool = False) -> np.ndarray:
|
| 207 |
+
"""Calculate the affine transformation matrix that can warp the bbox area
|
| 208 |
+
in the input image to the output size.
|
| 209 |
+
|
| 210 |
+
Args:
|
| 211 |
+
center (np.ndarray[2, ]): Center of the bounding box (x, y).
|
| 212 |
+
scale (np.ndarray[2, ]): Scale of the bounding box
|
| 213 |
+
wrt [width, height].
|
| 214 |
+
rot (float): Rotation angle (degree).
|
| 215 |
+
output_size (np.ndarray[2, ] | list(2,)): Size of the
|
| 216 |
+
destination heatmaps.
|
| 217 |
+
shift (0-100%): Shift translation ratio wrt the width/height.
|
| 218 |
+
Default (0., 0.).
|
| 219 |
+
inv (bool): Option to inverse the affine transform direction.
|
| 220 |
+
(inv=False: src->dst or inv=True: dst->src)
|
| 221 |
+
|
| 222 |
+
Returns:
|
| 223 |
+
np.ndarray: A 2x3 transformation matrix
|
| 224 |
+
"""
|
| 225 |
+
shift = np.array(shift)
|
| 226 |
+
src_w = scale[0]
|
| 227 |
+
dst_w = output_size[0]
|
| 228 |
+
dst_h = output_size[1]
|
| 229 |
+
|
| 230 |
+
# compute transformation matrix
|
| 231 |
+
rot_rad = np.deg2rad(rot)
|
| 232 |
+
src_dir = _rotate_point(np.array([0., src_w * -0.5]), rot_rad)
|
| 233 |
+
dst_dir = np.array([0., dst_w * -0.5])
|
| 234 |
+
|
| 235 |
+
# get four corners of the src rectangle in the original image
|
| 236 |
+
src = np.zeros((3, 2), dtype=np.float32)
|
| 237 |
+
src[0, :] = center + scale * shift
|
| 238 |
+
src[1, :] = center + src_dir + scale * shift
|
| 239 |
+
src[2, :] = _get_3rd_point(src[0, :], src[1, :])
|
| 240 |
+
|
| 241 |
+
# get four corners of the dst rectangle in the input image
|
| 242 |
+
dst = np.zeros((3, 2), dtype=np.float32)
|
| 243 |
+
dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
|
| 244 |
+
dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
|
| 245 |
+
dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
|
| 246 |
+
|
| 247 |
+
if inv:
|
| 248 |
+
warp_mat = cv2.getAffineTransform(np.float32(dst), np.float32(src))
|
| 249 |
+
else:
|
| 250 |
+
warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))
|
| 251 |
+
|
| 252 |
+
return warp_mat
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def top_down_affine(input_size: dict, bbox_scale: dict, bbox_center: dict,
|
| 256 |
+
img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
| 257 |
+
"""Get the bbox image as the model input by affine transform.
|
| 258 |
+
|
| 259 |
+
Args:
|
| 260 |
+
input_size (dict): The input size of the model.
|
| 261 |
+
bbox_scale (dict): The bbox scale of the img.
|
| 262 |
+
bbox_center (dict): The bbox center of the img.
|
| 263 |
+
img (np.ndarray): The original image.
|
| 264 |
+
|
| 265 |
+
Returns:
|
| 266 |
+
tuple: A tuple containing center and scale.
|
| 267 |
+
- np.ndarray[float32]: img after affine transform.
|
| 268 |
+
- np.ndarray[float32]: bbox scale after affine transform.
|
| 269 |
+
"""
|
| 270 |
+
w, h = input_size
|
| 271 |
+
warp_size = (int(w), int(h))
|
| 272 |
+
|
| 273 |
+
# reshape bbox to fixed aspect ratio
|
| 274 |
+
bbox_scale = _fix_aspect_ratio(bbox_scale, aspect_ratio=w / h)
|
| 275 |
+
|
| 276 |
+
# get the affine matrix
|
| 277 |
+
center = bbox_center
|
| 278 |
+
scale = bbox_scale
|
| 279 |
+
rot = 0
|
| 280 |
+
warp_mat = get_warp_matrix(center, scale, rot, output_size=(w, h))
|
| 281 |
+
|
| 282 |
+
# do affine transform
|
| 283 |
+
img = cv2.warpAffine(img, warp_mat, warp_size, flags=cv2.INTER_LINEAR)
|
| 284 |
+
|
| 285 |
+
return img, bbox_scale
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def get_simcc_maximum(simcc_x: np.ndarray,
|
| 289 |
+
simcc_y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
|
| 290 |
+
"""Get maximum response location and value from simcc representations.
|
| 291 |
+
|
| 292 |
+
Note:
|
| 293 |
+
instance number: N
|
| 294 |
+
num_keypoints: K
|
| 295 |
+
heatmap height: H
|
| 296 |
+
heatmap width: W
|
| 297 |
+
|
| 298 |
+
Args:
|
| 299 |
+
simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx)
|
| 300 |
+
simcc_y (np.ndarray): y-axis SimCC in shape (K, Wy) or (N, K, Wy)
|
| 301 |
+
|
| 302 |
+
Returns:
|
| 303 |
+
tuple:
|
| 304 |
+
- locs (np.ndarray): locations of maximum heatmap responses in shape
|
| 305 |
+
(K, 2) or (N, K, 2)
|
| 306 |
+
- vals (np.ndarray): values of maximum heatmap responses in shape
|
| 307 |
+
(K,) or (N, K)
|
| 308 |
+
"""
|
| 309 |
+
N, K, Wx = simcc_x.shape
|
| 310 |
+
simcc_x = simcc_x.reshape(N * K, -1)
|
| 311 |
+
simcc_y = simcc_y.reshape(N * K, -1)
|
| 312 |
+
|
| 313 |
+
# get maximum value locations
|
| 314 |
+
x_locs = np.argmax(simcc_x, axis=1)
|
| 315 |
+
y_locs = np.argmax(simcc_y, axis=1)
|
| 316 |
+
locs = np.stack((x_locs, y_locs), axis=-1).astype(np.float32)
|
| 317 |
+
max_val_x = np.amax(simcc_x, axis=1)
|
| 318 |
+
max_val_y = np.amax(simcc_y, axis=1)
|
| 319 |
+
|
| 320 |
+
# get maximum value across x and y axis
|
| 321 |
+
mask = max_val_x > max_val_y
|
| 322 |
+
max_val_x[mask] = max_val_y[mask]
|
| 323 |
+
vals = max_val_x
|
| 324 |
+
locs[vals <= 0.] = -1
|
| 325 |
+
|
| 326 |
+
# reshape
|
| 327 |
+
locs = locs.reshape(N, K, 2)
|
| 328 |
+
vals = vals.reshape(N, K)
|
| 329 |
+
|
| 330 |
+
return locs, vals
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def decode(simcc_x: np.ndarray, simcc_y: np.ndarray,
|
| 334 |
+
simcc_split_ratio) -> Tuple[np.ndarray, np.ndarray]:
|
| 335 |
+
"""Modulate simcc distribution with Gaussian.
|
| 336 |
+
|
| 337 |
+
Args:
|
| 338 |
+
simcc_x (np.ndarray[K, Wx]): model predicted simcc in x.
|
| 339 |
+
simcc_y (np.ndarray[K, Wy]): model predicted simcc in y.
|
| 340 |
+
simcc_split_ratio (int): The split ratio of simcc.
|
| 341 |
+
|
| 342 |
+
Returns:
|
| 343 |
+
tuple: A tuple containing center and scale.
|
| 344 |
+
- np.ndarray[float32]: keypoints in shape (K, 2) or (n, K, 2)
|
| 345 |
+
- np.ndarray[float32]: scores in shape (K,) or (n, K)
|
| 346 |
+
"""
|
| 347 |
+
keypoints, scores = get_simcc_maximum(simcc_x, simcc_y)
|
| 348 |
+
keypoints /= simcc_split_ratio
|
| 349 |
+
|
| 350 |
+
return keypoints, scores
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def inference_pose(session, out_bbox, oriImg):
|
| 354 |
+
"""run pose detect
|
| 355 |
+
|
| 356 |
+
Args:
|
| 357 |
+
session (ort.InferenceSession): ONNXRuntime session.
|
| 358 |
+
out_bbox (np.ndarray): bbox list
|
| 359 |
+
oriImg (np.ndarray): Input image in shape.
|
| 360 |
+
|
| 361 |
+
Returns:
|
| 362 |
+
tuple:
|
| 363 |
+
- keypoints (np.ndarray): Rescaled keypoints.
|
| 364 |
+
- scores (np.ndarray): Model predict scores.
|
| 365 |
+
"""
|
| 366 |
+
h, w = session.get_inputs()[0].shape[2:]
|
| 367 |
+
model_input_size = (w, h)
|
| 368 |
+
# preprocess for rtm-pose model inference.
|
| 369 |
+
resized_img, center, scale = preprocess(oriImg, out_bbox, model_input_size)
|
| 370 |
+
# run pose estimation for processed img
|
| 371 |
+
outputs = inference(session, resized_img)
|
| 372 |
+
# postprocess for rtm-pose model output.
|
| 373 |
+
keypoints, scores = postprocess(outputs, model_input_size, center, scale)
|
| 374 |
+
|
| 375 |
+
return keypoints, scores
|
ControlNeXt-SVD-v2/dwpose/preprocess.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from tqdm import tqdm
|
| 2 |
+
import decord
|
| 3 |
+
import numpy as np
|
| 4 |
+
|
| 5 |
+
from .util import draw_pose
|
| 6 |
+
from .dwpose_detector import dwpose_detector as dwprocessor
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def get_video_pose(
|
| 10 |
+
video_path: str,
|
| 11 |
+
ref_image: np.ndarray,
|
| 12 |
+
max_frame_num = None,
|
| 13 |
+
sample_stride: int=1):
|
| 14 |
+
"""preprocess ref image pose and video pose
|
| 15 |
+
|
| 16 |
+
Args:
|
| 17 |
+
video_path (str): video pose path
|
| 18 |
+
ref_image (np.ndarray): reference image
|
| 19 |
+
sample_stride (int, optional): Defaults to 1.
|
| 20 |
+
|
| 21 |
+
Returns:
|
| 22 |
+
np.ndarray: sequence of video pose
|
| 23 |
+
"""
|
| 24 |
+
# select ref-keypoint from reference pose for pose rescale
|
| 25 |
+
ref_pose = dwprocessor(ref_image)
|
| 26 |
+
ref_keypoint_id = [0, 1, 2, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
|
| 27 |
+
ref_keypoint_id = [i for i in ref_keypoint_id \
|
| 28 |
+
if len(ref_pose['bodies']['subset']) > 0 and ref_pose['bodies']['subset'][0][i] >= .0]
|
| 29 |
+
ref_body = ref_pose['bodies']['candidate'][ref_keypoint_id]
|
| 30 |
+
|
| 31 |
+
height, width, _ = ref_image.shape
|
| 32 |
+
|
| 33 |
+
# read input video
|
| 34 |
+
vr = decord.VideoReader(video_path, ctx=decord.cpu(0))
|
| 35 |
+
# sample_stride *= max(1, int(vr.get_avg_fps() / 24))
|
| 36 |
+
if max_frame_num is None:
|
| 37 |
+
max_frame_num = len(vr)
|
| 38 |
+
else:
|
| 39 |
+
max_frame_num = min(len(vr), max_frame_num * sample_stride)
|
| 40 |
+
|
| 41 |
+
frames = vr.get_batch(list(range(0, len(vr), sample_stride))).asnumpy()
|
| 42 |
+
detected_poses = [dwprocessor(frm) for frm in tqdm(frames, desc="DWPose")]
|
| 43 |
+
dwprocessor.release_memory()
|
| 44 |
+
|
| 45 |
+
detected_bodies = np.stack(
|
| 46 |
+
[p['bodies']['candidate'] for p in detected_poses if p['bodies']['candidate'].shape[0] == 18])[:,
|
| 47 |
+
ref_keypoint_id]
|
| 48 |
+
# compute linear-rescale params
|
| 49 |
+
ay, by = np.polyfit(detected_bodies[:, :, 1].flatten(), np.tile(ref_body[:, 1], len(detected_bodies)), 1)
|
| 50 |
+
fh, fw, _ = vr[0].shape
|
| 51 |
+
ax = ay / (fh / fw / height * width)
|
| 52 |
+
bx = np.mean(np.tile(ref_body[:, 0], len(detected_bodies)) - detected_bodies[:, :, 0].flatten() * ax)
|
| 53 |
+
a = np.array([ax, ay])
|
| 54 |
+
b = np.array([bx, by])
|
| 55 |
+
output_pose = []
|
| 56 |
+
# pose rescale
|
| 57 |
+
for detected_pose in detected_poses:
|
| 58 |
+
detected_pose['bodies']['candidate'] = detected_pose['bodies']['candidate'] * a + b
|
| 59 |
+
detected_pose['faces'] = detected_pose['faces'] * a + b
|
| 60 |
+
detected_pose['hands'] = detected_pose['hands'] * a + b
|
| 61 |
+
im = draw_pose(detected_pose, height, width)
|
| 62 |
+
output_pose.append(np.array(im))
|
| 63 |
+
return np.stack(output_pose)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def get_image_pose(ref_image):
|
| 67 |
+
"""process image pose
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
ref_image (np.ndarray): reference image pixel value
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
np.ndarray: pose visual image in RGB-mode
|
| 74 |
+
"""
|
| 75 |
+
height, width, _ = ref_image.shape
|
| 76 |
+
ref_pose = dwprocessor(ref_image)
|
| 77 |
+
pose_img = draw_pose(ref_pose, height, width)
|
| 78 |
+
return np.array(pose_img)
|
ControlNeXt-SVD-v2/dwpose/util.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import numpy as np
|
| 3 |
+
import matplotlib
|
| 4 |
+
import cv2
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
eps = 0.01
|
| 8 |
+
|
| 9 |
+
def alpha_blend_color(color, alpha):
|
| 10 |
+
"""blend color according to point conf
|
| 11 |
+
"""
|
| 12 |
+
return [int(c * alpha) for c in color]
|
| 13 |
+
|
| 14 |
+
def draw_bodypose(canvas, candidate, subset, score):
|
| 15 |
+
H, W, C = canvas.shape
|
| 16 |
+
candidate = np.array(candidate)
|
| 17 |
+
subset = np.array(subset)
|
| 18 |
+
|
| 19 |
+
stickwidth = 4
|
| 20 |
+
|
| 21 |
+
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
|
| 22 |
+
[10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
|
| 23 |
+
[1, 16], [16, 18], [3, 17], [6, 18]]
|
| 24 |
+
|
| 25 |
+
colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
|
| 26 |
+
[0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
|
| 27 |
+
[170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
|
| 28 |
+
|
| 29 |
+
for i in range(17):
|
| 30 |
+
for n in range(len(subset)):
|
| 31 |
+
index = subset[n][np.array(limbSeq[i]) - 1]
|
| 32 |
+
conf = score[n][np.array(limbSeq[i]) - 1]
|
| 33 |
+
if conf[0] < 0.3 or conf[1] < 0.3:
|
| 34 |
+
continue
|
| 35 |
+
Y = candidate[index.astype(int), 0] * float(W)
|
| 36 |
+
X = candidate[index.astype(int), 1] * float(H)
|
| 37 |
+
mX = np.mean(X)
|
| 38 |
+
mY = np.mean(Y)
|
| 39 |
+
length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
|
| 40 |
+
angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
|
| 41 |
+
polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
|
| 42 |
+
cv2.fillConvexPoly(canvas, polygon, alpha_blend_color(colors[i], conf[0] * conf[1]))
|
| 43 |
+
|
| 44 |
+
canvas = (canvas * 0.6).astype(np.uint8)
|
| 45 |
+
|
| 46 |
+
for i in range(18):
|
| 47 |
+
for n in range(len(subset)):
|
| 48 |
+
index = int(subset[n][i])
|
| 49 |
+
if index == -1:
|
| 50 |
+
continue
|
| 51 |
+
x, y = candidate[index][0:2]
|
| 52 |
+
conf = score[n][i]
|
| 53 |
+
x = int(x * W)
|
| 54 |
+
y = int(y * H)
|
| 55 |
+
cv2.circle(canvas, (int(x), int(y)), 4, alpha_blend_color(colors[i], conf), thickness=-1)
|
| 56 |
+
|
| 57 |
+
return canvas
|
| 58 |
+
|
| 59 |
+
def draw_handpose(canvas, all_hand_peaks, all_hand_scores):
|
| 60 |
+
H, W, C = canvas.shape
|
| 61 |
+
|
| 62 |
+
edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
|
| 63 |
+
[10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
|
| 64 |
+
|
| 65 |
+
for peaks, scores in zip(all_hand_peaks, all_hand_scores):
|
| 66 |
+
|
| 67 |
+
for ie, e in enumerate(edges):
|
| 68 |
+
x1, y1 = peaks[e[0]]
|
| 69 |
+
x2, y2 = peaks[e[1]]
|
| 70 |
+
x1 = int(x1 * W)
|
| 71 |
+
y1 = int(y1 * H)
|
| 72 |
+
x2 = int(x2 * W)
|
| 73 |
+
y2 = int(y2 * H)
|
| 74 |
+
score = int(scores[e[0]] * scores[e[1]] * 255)
|
| 75 |
+
if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
|
| 76 |
+
cv2.line(canvas, (x1, y1), (x2, y2),
|
| 77 |
+
matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * score, thickness=2)
|
| 78 |
+
|
| 79 |
+
for i, keyponit in enumerate(peaks):
|
| 80 |
+
x, y = keyponit
|
| 81 |
+
x = int(x * W)
|
| 82 |
+
y = int(y * H)
|
| 83 |
+
score = int(scores[i] * 255)
|
| 84 |
+
if x > eps and y > eps:
|
| 85 |
+
cv2.circle(canvas, (x, y), 4, (0, 0, score), thickness=-1)
|
| 86 |
+
return canvas
|
| 87 |
+
|
| 88 |
+
def draw_facepose(canvas, all_lmks, all_scores):
|
| 89 |
+
H, W, C = canvas.shape
|
| 90 |
+
for lmks, scores in zip(all_lmks, all_scores):
|
| 91 |
+
for lmk, score in zip(lmks, scores):
|
| 92 |
+
x, y = lmk
|
| 93 |
+
x = int(x * W)
|
| 94 |
+
y = int(y * H)
|
| 95 |
+
conf = int(score * 255)
|
| 96 |
+
if x > eps and y > eps:
|
| 97 |
+
cv2.circle(canvas, (x, y), 3, (conf, conf, conf), thickness=-1)
|
| 98 |
+
return canvas
|
| 99 |
+
|
| 100 |
+
def draw_pose(pose, H, W, ref_w=2160):
|
| 101 |
+
"""vis dwpose outputs
|
| 102 |
+
|
| 103 |
+
Args:
|
| 104 |
+
pose (List): DWposeDetector outputs in dwpose_detector.py
|
| 105 |
+
H (int): height
|
| 106 |
+
W (int): width
|
| 107 |
+
ref_w (int, optional) Defaults to 2160.
|
| 108 |
+
|
| 109 |
+
Returns:
|
| 110 |
+
np.ndarray: image pixel value in RGB mode
|
| 111 |
+
"""
|
| 112 |
+
bodies = pose['bodies']
|
| 113 |
+
faces = pose['faces']
|
| 114 |
+
hands = pose['hands']
|
| 115 |
+
candidate = bodies['candidate']
|
| 116 |
+
subset = bodies['subset']
|
| 117 |
+
|
| 118 |
+
sz = min(H, W)
|
| 119 |
+
sr = (ref_w / sz) if sz != ref_w else 1
|
| 120 |
+
|
| 121 |
+
########################################## create zero canvas ##################################################
|
| 122 |
+
canvas = np.zeros(shape=(int(H*sr), int(W*sr), 3), dtype=np.uint8)
|
| 123 |
+
|
| 124 |
+
########################################### draw body pose #####################################################
|
| 125 |
+
canvas = draw_bodypose(canvas, candidate, subset, score=bodies['score'])
|
| 126 |
+
|
| 127 |
+
########################################### draw hand pose #####################################################
|
| 128 |
+
canvas = draw_handpose(canvas, hands, pose['hands_score'])
|
| 129 |
+
|
| 130 |
+
########################################### draw face pose #####################################################
|
| 131 |
+
canvas = draw_facepose(canvas, faces, pose['faces_score'])
|
| 132 |
+
|
| 133 |
+
return cv2.cvtColor(cv2.resize(canvas, (W, H)), cv2.COLOR_BGR2RGB).transpose(2, 0, 1)
|
ControlNeXt-SVD-v2/dwpose/wholebody.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
import onnxruntime as ort
|
| 3 |
+
|
| 4 |
+
from .onnxdet import inference_detector
|
| 5 |
+
from .onnxpose import inference_pose
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class Wholebody:
|
| 9 |
+
"""detect human pose by dwpose
|
| 10 |
+
"""
|
| 11 |
+
def __init__(self, model_det, model_pose, device="cpu"):
|
| 12 |
+
providers = ['CPUExecutionProvider'] if device == 'cpu' else ['CUDAExecutionProvider']
|
| 13 |
+
provider_options = None if device == 'cpu' else [{'device_id': 0}]
|
| 14 |
+
|
| 15 |
+
self.session_det = ort.InferenceSession(
|
| 16 |
+
path_or_bytes=model_det, providers=providers, provider_options=provider_options
|
| 17 |
+
)
|
| 18 |
+
self.session_pose = ort.InferenceSession(
|
| 19 |
+
path_or_bytes=model_pose, providers=providers, provider_options=provider_options
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
def __call__(self, oriImg):
|
| 23 |
+
"""call to process dwpose-detect
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
oriImg (np.ndarray): detected image
|
| 27 |
+
|
| 28 |
+
"""
|
| 29 |
+
det_result = inference_detector(self.session_det, oriImg)
|
| 30 |
+
keypoints, scores = inference_pose(self.session_pose, det_result, oriImg)
|
| 31 |
+
|
| 32 |
+
keypoints_info = np.concatenate(
|
| 33 |
+
(keypoints, scores[..., None]), axis=-1)
|
| 34 |
+
# compute neck joint
|
| 35 |
+
neck = np.mean(keypoints_info[:, [5, 6]], axis=1)
|
| 36 |
+
# neck score when visualizing pred
|
| 37 |
+
neck[:, 2:4] = np.logical_and(
|
| 38 |
+
keypoints_info[:, 5, 2:4] > 0.3,
|
| 39 |
+
keypoints_info[:, 6, 2:4] > 0.3).astype(int)
|
| 40 |
+
new_keypoints_info = np.insert(
|
| 41 |
+
keypoints_info, 17, neck, axis=1)
|
| 42 |
+
mmpose_idx = [
|
| 43 |
+
17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3
|
| 44 |
+
]
|
| 45 |
+
openpose_idx = [
|
| 46 |
+
1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17
|
| 47 |
+
]
|
| 48 |
+
new_keypoints_info[:, openpose_idx] = \
|
| 49 |
+
new_keypoints_info[:, mmpose_idx]
|
| 50 |
+
keypoints_info = new_keypoints_info
|
| 51 |
+
|
| 52 |
+
keypoints, scores = keypoints_info[
|
| 53 |
+
..., :2], keypoints_info[..., 2]
|
| 54 |
+
|
| 55 |
+
return keypoints, scores
|
| 56 |
+
|
| 57 |
+
|
ControlNeXt-SVD-v2/examples/demos/01-1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2f8f419477be2c8454ca0ce7fcbe614879710994e4ccebbf006c07fd8ac5b247
|
| 3 |
+
size 3482865
|
ControlNeXt-SVD-v2/examples/demos/02-1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:563a5a671b41247e62e323aafd5a65d2ce5d4a88f98bc5158857182b583392d9
|
| 3 |
+
size 906438
|
ControlNeXt-SVD-v2/examples/demos/03-1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0003fa37e7e4bd6092bb1ea83e273749f9fa85eca355d25ed3b5189a8fac1d8c
|
| 3 |
+
size 1445212
|
ControlNeXt-SVD-v2/examples/demos/04-1.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a339cce96f23040220f1b511ea98c2485127a1feff046bf51ec4f88f05e181ce
|
| 3 |
+
size 1136007
|
ControlNeXt-SVD-v2/examples/facefusion/facefusion.jpg
ADDED
|
Git LFS Details
|
ControlNeXt-SVD-v2/examples/ref_imgs/01.jpeg
ADDED
|
Git LFS Details
|
ControlNeXt-SVD-v2/examples/ref_imgs/02.jpeg
ADDED
|
Git LFS Details
|
ControlNeXt-SVD-v2/examples/ref_imgs/03.jpeg
ADDED
|
Git LFS Details
|
ControlNeXt-SVD-v2/examples/ref_imgs/04.jpeg
ADDED
|
Git LFS Details
|
ControlNeXt-SVD-v2/examples/video/01.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b443ce7a45f5373d3c1dfab5131324756891d351496f93c577fe69c65cfc78ef
|
| 3 |
+
size 1584577
|
ControlNeXt-SVD-v2/examples/video/02.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a8da1ca1e6b2a1d14baa791b842462d294737a36ee976e307f2a813d6bc5681e
|
| 3 |
+
size 1329663
|
ControlNeXt-SVD-v2/git_push2.log
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Uploading LFS objects: 100% (25/25), 6.2 GB | 0 B/s, done.
|
| 2 |
+
remote: [31m-------------------------------------------------------------------------[0m
|
| 3 |
+
remote: [31mYour push was rejected because it contains binary files.[0m
|
| 4 |
+
remote: [31mPlease use https://git-lfs.github.com/ to store binary files.[0m
|
| 5 |
+
remote: [31mSee also: https://hf.co/docs/hub/repositories-getting-started#terminal[0m
|
| 6 |
+
remote: [31m[0m
|
| 7 |
+
remote: [31mOffending files:[0m
|
| 8 |
+
remote: [31m - ref_img_dict/01.jpeg (ref: refs/heads/main)[0m
|
| 9 |
+
remote: [31m - ref_img_dict/02.jpeg (ref: refs/heads/main)[0m
|
| 10 |
+
remote: [31m - ref_img_dict/03.jpeg (ref: refs/heads/main)[0m
|
| 11 |
+
remote: [31m - ref_img_dict/04.jpeg (ref: refs/heads/main)[0m
|
| 12 |
+
remote: [31m-------------------------------------------------------------------------[0m
|
| 13 |
+
To hf.co:datasets/FangSen9000/StableSigner
|
| 14 |
+
! [remote rejected] main -> main (pre-receive hook declined)
|
| 15 |
+
error: failed to push some refs to 'hf.co:datasets/FangSen9000/StableSigner'
|
ControlNeXt-SVD-v2/models/__pycache__/controlnext_vid_svd.cpython-310.pyc
ADDED
|
Binary file (4.63 kB). View file
|
|
|
ControlNeXt-SVD-v2/models/__pycache__/unet_spatio_temporal_condition_controlnext.cpython-310.pyc
ADDED
|
Binary file (16.8 kB). View file
|
|
|
ControlNeXt-SVD-v2/models/controlnext_vid_svd.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from torch import nn
|
| 5 |
+
|
| 6 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 7 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
| 8 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 9 |
+
from diffusers.models.resnet import Downsample2D, ResnetBlock2D
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class ControlNeXtSDVModel(ModelMixin, ConfigMixin):
|
| 13 |
+
_supports_gradient_checkpointing = True
|
| 14 |
+
|
| 15 |
+
@register_to_config
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
time_embed_dim = 256,
|
| 19 |
+
in_channels = [128, 128],
|
| 20 |
+
out_channels = [128, 256],
|
| 21 |
+
groups = [4, 8]
|
| 22 |
+
):
|
| 23 |
+
super().__init__()
|
| 24 |
+
|
| 25 |
+
self.time_proj = Timesteps(128, True, downscale_freq_shift=0)
|
| 26 |
+
self.time_embedding = TimestepEmbedding(128, time_embed_dim)
|
| 27 |
+
self.embedding = nn.Sequential(
|
| 28 |
+
nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1),
|
| 29 |
+
nn.GroupNorm(2, 64),
|
| 30 |
+
nn.ReLU(),
|
| 31 |
+
nn.Conv2d(64, 64, kernel_size=3),
|
| 32 |
+
nn.GroupNorm(2, 64),
|
| 33 |
+
nn.ReLU(),
|
| 34 |
+
nn.Conv2d(64, 128, kernel_size=3),
|
| 35 |
+
nn.GroupNorm(2, 128),
|
| 36 |
+
nn.ReLU(),
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
self.down_res = nn.ModuleList()
|
| 40 |
+
self.down_sample = nn.ModuleList()
|
| 41 |
+
for i in range(len(in_channels)):
|
| 42 |
+
self.down_res.append(
|
| 43 |
+
ResnetBlock2D(
|
| 44 |
+
in_channels=in_channels[i],
|
| 45 |
+
out_channels=out_channels[i],
|
| 46 |
+
temb_channels=time_embed_dim,
|
| 47 |
+
groups=groups[i]
|
| 48 |
+
),
|
| 49 |
+
)
|
| 50 |
+
self.down_sample.append(
|
| 51 |
+
Downsample2D(
|
| 52 |
+
out_channels[i],
|
| 53 |
+
use_conv=True,
|
| 54 |
+
out_channels=out_channels[i],
|
| 55 |
+
padding=1,
|
| 56 |
+
name="op",
|
| 57 |
+
)
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
self.mid_convs = nn.ModuleList()
|
| 61 |
+
self.mid_convs.append(nn.Sequential(
|
| 62 |
+
nn.Conv2d(
|
| 63 |
+
in_channels=out_channels[-1],
|
| 64 |
+
out_channels=out_channels[-1],
|
| 65 |
+
kernel_size=3,
|
| 66 |
+
stride=1,
|
| 67 |
+
padding=1
|
| 68 |
+
),
|
| 69 |
+
nn.ReLU(),
|
| 70 |
+
nn.GroupNorm(8, out_channels[-1]),
|
| 71 |
+
nn.Conv2d(
|
| 72 |
+
in_channels=out_channels[-1],
|
| 73 |
+
out_channels=out_channels[-1],
|
| 74 |
+
kernel_size=3,
|
| 75 |
+
stride=1,
|
| 76 |
+
padding=1
|
| 77 |
+
),
|
| 78 |
+
nn.GroupNorm(8, out_channels[-1]),
|
| 79 |
+
))
|
| 80 |
+
self.mid_convs.append(
|
| 81 |
+
nn.Conv2d(
|
| 82 |
+
in_channels=out_channels[-1],
|
| 83 |
+
out_channels=320,
|
| 84 |
+
kernel_size=1,
|
| 85 |
+
stride=1,
|
| 86 |
+
))
|
| 87 |
+
|
| 88 |
+
self.scale = 1.
|
| 89 |
+
|
| 90 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 91 |
+
if hasattr(module, "gradient_checkpointing"):
|
| 92 |
+
module.gradient_checkpointing = value
|
| 93 |
+
|
| 94 |
+
# Copied from diffusers.models.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
|
| 95 |
+
def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
|
| 96 |
+
"""
|
| 97 |
+
Sets the attention processor to use [feed forward
|
| 98 |
+
chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
|
| 99 |
+
|
| 100 |
+
Parameters:
|
| 101 |
+
chunk_size (`int`, *optional*):
|
| 102 |
+
The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
|
| 103 |
+
over each tensor of dim=`dim`.
|
| 104 |
+
dim (`int`, *optional*, defaults to `0`):
|
| 105 |
+
The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
|
| 106 |
+
or dim=1 (sequence length).
|
| 107 |
+
"""
|
| 108 |
+
if dim not in [0, 1]:
|
| 109 |
+
raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
|
| 110 |
+
|
| 111 |
+
# By default chunk size is 1
|
| 112 |
+
chunk_size = chunk_size or 1
|
| 113 |
+
|
| 114 |
+
def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
|
| 115 |
+
if hasattr(module, "set_chunk_feed_forward"):
|
| 116 |
+
module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
|
| 117 |
+
|
| 118 |
+
for child in module.children():
|
| 119 |
+
fn_recursive_feed_forward(child, chunk_size, dim)
|
| 120 |
+
|
| 121 |
+
for module in self.children():
|
| 122 |
+
fn_recursive_feed_forward(module, chunk_size, dim)
|
| 123 |
+
|
| 124 |
+
def forward(
|
| 125 |
+
self,
|
| 126 |
+
sample: torch.FloatTensor,
|
| 127 |
+
timestep: Union[torch.Tensor, float, int],
|
| 128 |
+
):
|
| 129 |
+
|
| 130 |
+
timesteps = timestep
|
| 131 |
+
if not torch.is_tensor(timesteps):
|
| 132 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
| 133 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
| 134 |
+
is_mps = sample.device.type == "mps"
|
| 135 |
+
if isinstance(timestep, float):
|
| 136 |
+
dtype = torch.float32 if is_mps else torch.float64
|
| 137 |
+
else:
|
| 138 |
+
dtype = torch.int32 if is_mps else torch.int64
|
| 139 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
| 140 |
+
elif len(timesteps.shape) == 0:
|
| 141 |
+
timesteps = timesteps[None].to(sample.device)
|
| 142 |
+
|
| 143 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 144 |
+
batch_size, num_frames = sample.shape[:2]
|
| 145 |
+
timesteps = timesteps.expand(batch_size)
|
| 146 |
+
|
| 147 |
+
t_emb = self.time_proj(timesteps)
|
| 148 |
+
|
| 149 |
+
# `Timesteps` does not contain any weights and will always return f32 tensors
|
| 150 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
| 151 |
+
# there might be better ways to encapsulate this.
|
| 152 |
+
t_emb = t_emb.to(dtype=sample.dtype)
|
| 153 |
+
|
| 154 |
+
emb_batch = self.time_embedding(t_emb)
|
| 155 |
+
|
| 156 |
+
# Flatten the batch and frames dimensions
|
| 157 |
+
# sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
|
| 158 |
+
sample = sample.flatten(0, 1)
|
| 159 |
+
# Repeat the embeddings num_video_frames times
|
| 160 |
+
# emb: [batch, channels] -> [batch * frames, channels]
|
| 161 |
+
emb = emb_batch.repeat_interleave(num_frames, dim=0)
|
| 162 |
+
|
| 163 |
+
sample = self.embedding(sample)
|
| 164 |
+
|
| 165 |
+
for res, downsample in zip(self.down_res, self.down_sample):
|
| 166 |
+
sample = res(sample, emb)
|
| 167 |
+
sample = downsample(sample, emb)
|
| 168 |
+
|
| 169 |
+
sample = self.mid_convs[0](sample) + sample
|
| 170 |
+
sample = self.mid_convs[1](sample)
|
| 171 |
+
|
| 172 |
+
return {
|
| 173 |
+
'output': sample,
|
| 174 |
+
'scale': self.scale,
|
| 175 |
+
}
|
| 176 |
+
|
ControlNeXt-SVD-v2/models/unet_spatio_temporal_condition_controlnext.py
ADDED
|
@@ -0,0 +1,517 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from dataclasses import dataclass
|
| 2 |
+
from typing import Dict, Optional, Tuple, Union
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
|
| 7 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 8 |
+
from diffusers.loaders import UNet2DConditionLoadersMixin
|
| 9 |
+
from diffusers.utils import BaseOutput, logging
|
| 10 |
+
from diffusers.models.attention_processor import CROSS_ATTENTION_PROCESSORS, AttentionProcessor, AttnProcessor
|
| 11 |
+
from diffusers.models.embeddings import TimestepEmbedding, Timesteps
|
| 12 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 13 |
+
from diffusers.models.unets.unet_3d_blocks import UNetMidBlockSpatioTemporal, get_down_block, get_up_block
|
| 14 |
+
import torch.nn.functional as F
|
| 15 |
+
|
| 16 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass
|
| 20 |
+
class UNetSpatioTemporalConditionOutput(BaseOutput):
|
| 21 |
+
"""
|
| 22 |
+
The output of [`UNetSpatioTemporalConditionModel`].
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
sample (`torch.FloatTensor` of shape `(batch_size, num_frames, num_channels, height, width)`):
|
| 26 |
+
The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
sample: torch.FloatTensor = None
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class UNetSpatioTemporalConditionControlNeXtModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
|
| 33 |
+
r"""
|
| 34 |
+
A conditional Spatio-Temporal UNet model that takes a noisy video frames, conditional state, and a timestep and returns a sample
|
| 35 |
+
shaped output.
|
| 36 |
+
|
| 37 |
+
This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
|
| 38 |
+
for all models (such as downloading or saving).
|
| 39 |
+
|
| 40 |
+
Parameters:
|
| 41 |
+
sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
|
| 42 |
+
Height and width of input/output sample.
|
| 43 |
+
in_channels (`int`, *optional*, defaults to 8): Number of channels in the input sample.
|
| 44 |
+
out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
|
| 45 |
+
down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "CrossAttnDownBlockSpatioTemporal", "DownBlockSpatioTemporal")`):
|
| 46 |
+
The tuple of downsample blocks to use.
|
| 47 |
+
up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal", "CrossAttnUpBlockSpatioTemporal")`):
|
| 48 |
+
The tuple of upsample blocks to use.
|
| 49 |
+
block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
|
| 50 |
+
The tuple of output channels for each block.
|
| 51 |
+
addition_time_embed_dim: (`int`, defaults to 256):
|
| 52 |
+
Dimension to to encode the additional time ids.
|
| 53 |
+
projection_class_embeddings_input_dim (`int`, defaults to 768):
|
| 54 |
+
The dimension of the projection of encoded `added_time_ids`.
|
| 55 |
+
layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
|
| 56 |
+
cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
|
| 57 |
+
The dimension of the cross attention features.
|
| 58 |
+
transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
|
| 59 |
+
The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
|
| 60 |
+
[`~models.unet_3d_blocks.CrossAttnDownBlockSpatioTemporal`], [`~models.unet_3d_blocks.CrossAttnUpBlockSpatioTemporal`],
|
| 61 |
+
[`~models.unet_3d_blocks.UNetMidBlockSpatioTemporal`].
|
| 62 |
+
num_attention_heads (`int`, `Tuple[int]`, defaults to `(5, 10, 10, 20)`):
|
| 63 |
+
The number of attention heads.
|
| 64 |
+
dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
_supports_gradient_checkpointing = True
|
| 68 |
+
|
| 69 |
+
@register_to_config
|
| 70 |
+
def __init__(
|
| 71 |
+
self,
|
| 72 |
+
sample_size: Optional[int] = None,
|
| 73 |
+
in_channels: int = 8,
|
| 74 |
+
out_channels: int = 4,
|
| 75 |
+
down_block_types: Tuple[str] = (
|
| 76 |
+
"CrossAttnDownBlockSpatioTemporal",
|
| 77 |
+
"CrossAttnDownBlockSpatioTemporal",
|
| 78 |
+
"CrossAttnDownBlockSpatioTemporal",
|
| 79 |
+
"DownBlockSpatioTemporal",
|
| 80 |
+
),
|
| 81 |
+
up_block_types: Tuple[str] = (
|
| 82 |
+
"UpBlockSpatioTemporal",
|
| 83 |
+
"CrossAttnUpBlockSpatioTemporal",
|
| 84 |
+
"CrossAttnUpBlockSpatioTemporal",
|
| 85 |
+
"CrossAttnUpBlockSpatioTemporal",
|
| 86 |
+
),
|
| 87 |
+
block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
|
| 88 |
+
addition_time_embed_dim: int = 256,
|
| 89 |
+
projection_class_embeddings_input_dim: int = 768,
|
| 90 |
+
layers_per_block: Union[int, Tuple[int]] = 2,
|
| 91 |
+
cross_attention_dim: Union[int, Tuple[int]] = 1024,
|
| 92 |
+
transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
|
| 93 |
+
num_attention_heads: Union[int, Tuple[int]] = (5, 10, 10, 20),
|
| 94 |
+
num_frames: int = 25,
|
| 95 |
+
upcast_attention: bool = False,
|
| 96 |
+
):
|
| 97 |
+
super().__init__()
|
| 98 |
+
|
| 99 |
+
self.sample_size = sample_size
|
| 100 |
+
|
| 101 |
+
# Check inputs
|
| 102 |
+
if len(down_block_types) != len(up_block_types):
|
| 103 |
+
raise ValueError(
|
| 104 |
+
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}."
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
if len(block_out_channels) != len(down_block_types):
|
| 108 |
+
raise ValueError(
|
| 109 |
+
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}."
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
|
| 113 |
+
raise ValueError(
|
| 114 |
+
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}."
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):
|
| 118 |
+
raise ValueError(
|
| 119 |
+
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}."
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
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}."
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
# input
|
| 128 |
+
self.conv_in = nn.Conv2d(
|
| 129 |
+
in_channels,
|
| 130 |
+
block_out_channels[0],
|
| 131 |
+
kernel_size=3,
|
| 132 |
+
padding=1,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# time
|
| 136 |
+
time_embed_dim = block_out_channels[0] * 4
|
| 137 |
+
|
| 138 |
+
self.time_proj = Timesteps(block_out_channels[0], True, downscale_freq_shift=0)
|
| 139 |
+
timestep_input_dim = block_out_channels[0]
|
| 140 |
+
|
| 141 |
+
self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
|
| 142 |
+
|
| 143 |
+
self.add_time_proj = Timesteps(addition_time_embed_dim, True, downscale_freq_shift=0)
|
| 144 |
+
self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
|
| 145 |
+
|
| 146 |
+
self.down_blocks = nn.ModuleList([])
|
| 147 |
+
self.up_blocks = nn.ModuleList([])
|
| 148 |
+
|
| 149 |
+
if isinstance(num_attention_heads, int):
|
| 150 |
+
num_attention_heads = (num_attention_heads,) * len(down_block_types)
|
| 151 |
+
|
| 152 |
+
if isinstance(cross_attention_dim, int):
|
| 153 |
+
cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
|
| 154 |
+
|
| 155 |
+
if isinstance(layers_per_block, int):
|
| 156 |
+
layers_per_block = [layers_per_block] * len(down_block_types)
|
| 157 |
+
|
| 158 |
+
if isinstance(transformer_layers_per_block, int):
|
| 159 |
+
transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
|
| 160 |
+
|
| 161 |
+
blocks_time_embed_dim = time_embed_dim
|
| 162 |
+
|
| 163 |
+
# down
|
| 164 |
+
output_channel = block_out_channels[0]
|
| 165 |
+
for i, down_block_type in enumerate(down_block_types):
|
| 166 |
+
input_channel = output_channel
|
| 167 |
+
output_channel = block_out_channels[i]
|
| 168 |
+
is_final_block = i == len(block_out_channels) - 1
|
| 169 |
+
|
| 170 |
+
down_block = get_down_block(
|
| 171 |
+
down_block_type,
|
| 172 |
+
num_layers=layers_per_block[i],
|
| 173 |
+
transformer_layers_per_block=transformer_layers_per_block[i],
|
| 174 |
+
in_channels=input_channel,
|
| 175 |
+
out_channels=output_channel,
|
| 176 |
+
temb_channels=blocks_time_embed_dim,
|
| 177 |
+
add_downsample=not is_final_block,
|
| 178 |
+
resnet_eps=1e-5,
|
| 179 |
+
cross_attention_dim=cross_attention_dim[i],
|
| 180 |
+
num_attention_heads=num_attention_heads[i],
|
| 181 |
+
resnet_act_fn="silu",
|
| 182 |
+
upcast_attention=upcast_attention,
|
| 183 |
+
)
|
| 184 |
+
self.down_blocks.append(down_block)
|
| 185 |
+
|
| 186 |
+
# mid
|
| 187 |
+
self.mid_block = UNetMidBlockSpatioTemporal(
|
| 188 |
+
block_out_channels[-1],
|
| 189 |
+
temb_channels=blocks_time_embed_dim,
|
| 190 |
+
transformer_layers_per_block=transformer_layers_per_block[-1],
|
| 191 |
+
cross_attention_dim=cross_attention_dim[-1],
|
| 192 |
+
num_attention_heads=num_attention_heads[-1],
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# count how many layers upsample the images
|
| 196 |
+
self.num_upsamplers = 0
|
| 197 |
+
|
| 198 |
+
# up
|
| 199 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
| 200 |
+
reversed_num_attention_heads = list(reversed(num_attention_heads))
|
| 201 |
+
reversed_layers_per_block = list(reversed(layers_per_block))
|
| 202 |
+
reversed_cross_attention_dim = list(reversed(cross_attention_dim))
|
| 203 |
+
reversed_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
|
| 204 |
+
|
| 205 |
+
output_channel = reversed_block_out_channels[0]
|
| 206 |
+
for i, up_block_type in enumerate(up_block_types):
|
| 207 |
+
is_final_block = i == len(block_out_channels) - 1
|
| 208 |
+
|
| 209 |
+
prev_output_channel = output_channel
|
| 210 |
+
output_channel = reversed_block_out_channels[i]
|
| 211 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
| 212 |
+
|
| 213 |
+
# add upsample block for all BUT final layer
|
| 214 |
+
if not is_final_block:
|
| 215 |
+
add_upsample = True
|
| 216 |
+
self.num_upsamplers += 1
|
| 217 |
+
else:
|
| 218 |
+
add_upsample = False
|
| 219 |
+
|
| 220 |
+
up_block = get_up_block(
|
| 221 |
+
up_block_type,
|
| 222 |
+
num_layers=reversed_layers_per_block[i] + 1,
|
| 223 |
+
transformer_layers_per_block=reversed_transformer_layers_per_block[i],
|
| 224 |
+
in_channels=input_channel,
|
| 225 |
+
out_channels=output_channel,
|
| 226 |
+
prev_output_channel=prev_output_channel,
|
| 227 |
+
temb_channels=blocks_time_embed_dim,
|
| 228 |
+
add_upsample=add_upsample,
|
| 229 |
+
resnet_eps=1e-5,
|
| 230 |
+
resolution_idx=i,
|
| 231 |
+
cross_attention_dim=reversed_cross_attention_dim[i],
|
| 232 |
+
num_attention_heads=reversed_num_attention_heads[i],
|
| 233 |
+
resnet_act_fn="silu",
|
| 234 |
+
upcast_attention=upcast_attention,
|
| 235 |
+
)
|
| 236 |
+
self.up_blocks.append(up_block)
|
| 237 |
+
prev_output_channel = output_channel
|
| 238 |
+
|
| 239 |
+
# out
|
| 240 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=32, eps=1e-5)
|
| 241 |
+
self.conv_act = nn.SiLU()
|
| 242 |
+
|
| 243 |
+
self.conv_out = nn.Conv2d(
|
| 244 |
+
block_out_channels[0],
|
| 245 |
+
out_channels,
|
| 246 |
+
kernel_size=3,
|
| 247 |
+
padding=1,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
@property
|
| 251 |
+
def attn_processors(self) -> Dict[str, AttentionProcessor]:
|
| 252 |
+
r"""
|
| 253 |
+
Returns:
|
| 254 |
+
`dict` of attention processors: A dictionary containing all attention processors used in the model with
|
| 255 |
+
indexed by its weight name.
|
| 256 |
+
"""
|
| 257 |
+
# set recursively
|
| 258 |
+
processors = {}
|
| 259 |
+
|
| 260 |
+
def fn_recursive_add_processors(
|
| 261 |
+
name: str,
|
| 262 |
+
module: torch.nn.Module,
|
| 263 |
+
processors: Dict[str, AttentionProcessor],
|
| 264 |
+
):
|
| 265 |
+
if hasattr(module, "get_processor"):
|
| 266 |
+
processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
|
| 267 |
+
|
| 268 |
+
for sub_name, child in module.named_children():
|
| 269 |
+
fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
|
| 270 |
+
|
| 271 |
+
return processors
|
| 272 |
+
|
| 273 |
+
for name, module in self.named_children():
|
| 274 |
+
fn_recursive_add_processors(name, module, processors)
|
| 275 |
+
|
| 276 |
+
return processors
|
| 277 |
+
|
| 278 |
+
def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
|
| 279 |
+
r"""
|
| 280 |
+
Sets the attention processor to use to compute attention.
|
| 281 |
+
|
| 282 |
+
Parameters:
|
| 283 |
+
processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
|
| 284 |
+
The instantiated processor class or a dictionary of processor classes that will be set as the processor
|
| 285 |
+
for **all** `Attention` layers.
|
| 286 |
+
|
| 287 |
+
If `processor` is a dict, the key needs to define the path to the corresponding cross attention
|
| 288 |
+
processor. This is strongly recommended when setting trainable attention processors.
|
| 289 |
+
|
| 290 |
+
"""
|
| 291 |
+
count = len(self.attn_processors.keys())
|
| 292 |
+
|
| 293 |
+
if isinstance(processor, dict) and len(processor) != count:
|
| 294 |
+
raise ValueError(
|
| 295 |
+
f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
|
| 296 |
+
f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
|
| 300 |
+
if hasattr(module, "set_processor"):
|
| 301 |
+
if not isinstance(processor, dict):
|
| 302 |
+
module.set_processor(processor)
|
| 303 |
+
else:
|
| 304 |
+
module.set_processor(processor.pop(f"{name}.processor"))
|
| 305 |
+
|
| 306 |
+
for sub_name, child in module.named_children():
|
| 307 |
+
fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
|
| 308 |
+
|
| 309 |
+
for name, module in self.named_children():
|
| 310 |
+
fn_recursive_attn_processor(name, module, processor)
|
| 311 |
+
|
| 312 |
+
def set_default_attn_processor(self):
|
| 313 |
+
"""
|
| 314 |
+
Disables custom attention processors and sets the default attention implementation.
|
| 315 |
+
"""
|
| 316 |
+
if all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
|
| 317 |
+
processor = AttnProcessor()
|
| 318 |
+
else:
|
| 319 |
+
raise ValueError(
|
| 320 |
+
f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
self.set_attn_processor(processor)
|
| 324 |
+
|
| 325 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
| 326 |
+
if hasattr(module, "gradient_checkpointing"):
|
| 327 |
+
module.gradient_checkpointing = value
|
| 328 |
+
|
| 329 |
+
# Copied from diffusers.models.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
|
| 330 |
+
def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
|
| 331 |
+
"""
|
| 332 |
+
Sets the attention processor to use [feed forward
|
| 333 |
+
chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
|
| 334 |
+
|
| 335 |
+
Parameters:
|
| 336 |
+
chunk_size (`int`, *optional*):
|
| 337 |
+
The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
|
| 338 |
+
over each tensor of dim=`dim`.
|
| 339 |
+
dim (`int`, *optional*, defaults to `0`):
|
| 340 |
+
The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
|
| 341 |
+
or dim=1 (sequence length).
|
| 342 |
+
"""
|
| 343 |
+
if dim not in [0, 1]:
|
| 344 |
+
raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
|
| 345 |
+
|
| 346 |
+
# By default chunk size is 1
|
| 347 |
+
chunk_size = chunk_size or 1
|
| 348 |
+
|
| 349 |
+
def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
|
| 350 |
+
if hasattr(module, "set_chunk_feed_forward"):
|
| 351 |
+
module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
|
| 352 |
+
|
| 353 |
+
for child in module.children():
|
| 354 |
+
fn_recursive_feed_forward(child, chunk_size, dim)
|
| 355 |
+
|
| 356 |
+
for module in self.children():
|
| 357 |
+
fn_recursive_feed_forward(module, chunk_size, dim)
|
| 358 |
+
|
| 359 |
+
def forward(
|
| 360 |
+
self,
|
| 361 |
+
sample: torch.FloatTensor,
|
| 362 |
+
timestep: Union[torch.Tensor, float, int],
|
| 363 |
+
encoder_hidden_states: torch.Tensor,
|
| 364 |
+
down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
|
| 365 |
+
mid_block_additional_residual: Optional[torch.Tensor] = None,
|
| 366 |
+
conditional_controls: Optional[torch.Tensor] = None,
|
| 367 |
+
return_dict: bool = True,
|
| 368 |
+
added_time_ids: torch.Tensor=None,
|
| 369 |
+
image_only_indicator: torch.Tensor=None,
|
| 370 |
+
) -> Union[UNetSpatioTemporalConditionOutput, Tuple]:
|
| 371 |
+
r"""
|
| 372 |
+
The [`UNetSpatioTemporalConditionModel`] forward method.
|
| 373 |
+
|
| 374 |
+
Args:
|
| 375 |
+
sample (`torch.FloatTensor`):
|
| 376 |
+
The noisy input tensor with the following shape `(batch, num_frames, channel, height, width)`.
|
| 377 |
+
timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
|
| 378 |
+
encoder_hidden_states (`torch.FloatTensor`):
|
| 379 |
+
The encoder hidden states with shape `(batch, sequence_length, cross_attention_dim)`.
|
| 380 |
+
added_time_ids: (`torch.FloatTensor`):
|
| 381 |
+
The additional time ids with shape `(batch, num_additional_ids)`. These are encoded with sinusoidal
|
| 382 |
+
embeddings and added to the time embeddings.
|
| 383 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 384 |
+
Whether or not to return a [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] instead of a plain
|
| 385 |
+
tuple.
|
| 386 |
+
Returns:
|
| 387 |
+
[`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] or `tuple`:
|
| 388 |
+
If `return_dict` is True, an [`~models.unet_slatio_temporal.UNetSpatioTemporalConditionOutput`] is returned, otherwise
|
| 389 |
+
a `tuple` is returned where the first element is the sample tensor.
|
| 390 |
+
"""
|
| 391 |
+
# 1. time
|
| 392 |
+
timesteps = timestep
|
| 393 |
+
if not torch.is_tensor(timesteps):
|
| 394 |
+
# TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
|
| 395 |
+
# This would be a good case for the `match` statement (Python 3.10+)
|
| 396 |
+
is_mps = sample.device.type == "mps"
|
| 397 |
+
if isinstance(timestep, float):
|
| 398 |
+
dtype = torch.float32 if is_mps else torch.float64
|
| 399 |
+
else:
|
| 400 |
+
dtype = torch.int32 if is_mps else torch.int64
|
| 401 |
+
timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
|
| 402 |
+
elif len(timesteps.shape) == 0:
|
| 403 |
+
timesteps = timesteps[None].to(sample.device)
|
| 404 |
+
|
| 405 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
| 406 |
+
batch_size, num_frames = sample.shape[:2]
|
| 407 |
+
timesteps = timesteps.expand(batch_size)
|
| 408 |
+
|
| 409 |
+
t_emb = self.time_proj(timesteps)
|
| 410 |
+
|
| 411 |
+
# `Timesteps` does not contain any weights and will always return f32 tensors
|
| 412 |
+
# but time_embedding might actually be running in fp16. so we need to cast here.
|
| 413 |
+
# there might be better ways to encapsulate this.
|
| 414 |
+
t_emb = t_emb.to(dtype=sample.dtype)
|
| 415 |
+
|
| 416 |
+
emb = self.time_embedding(t_emb)
|
| 417 |
+
|
| 418 |
+
time_embeds = self.add_time_proj(added_time_ids.flatten())
|
| 419 |
+
time_embeds = time_embeds.reshape((batch_size, -1))
|
| 420 |
+
time_embeds = time_embeds.to(emb.dtype)
|
| 421 |
+
aug_emb = self.add_embedding(time_embeds)
|
| 422 |
+
emb = emb + aug_emb
|
| 423 |
+
|
| 424 |
+
# Flatten the batch and frames dimensions
|
| 425 |
+
# sample: [batch, frames, channels, height, width] -> [batch * frames, channels, height, width]
|
| 426 |
+
sample = sample.flatten(0, 1)
|
| 427 |
+
# Repeat the embeddings num_video_frames times
|
| 428 |
+
# emb: [batch, channels] -> [batch * frames, channels]
|
| 429 |
+
emb = emb.repeat_interleave(num_frames, dim=0)
|
| 430 |
+
# encoder_hidden_states: [batch, 1, channels] -> [batch * frames, 1, channels]
|
| 431 |
+
encoder_hidden_states = encoder_hidden_states.repeat_interleave(num_frames, dim=0)
|
| 432 |
+
|
| 433 |
+
# 2. pre-process
|
| 434 |
+
sample = self.conv_in(sample)
|
| 435 |
+
if image_only_indicator is None:
|
| 436 |
+
image_only_indicator = torch.zeros(batch_size, num_frames, dtype=sample.dtype, device=sample.device)
|
| 437 |
+
|
| 438 |
+
down_block_res_samples = (sample,)
|
| 439 |
+
for idx,downsample_block in enumerate(self.down_blocks):
|
| 440 |
+
if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
|
| 441 |
+
sample, res_samples = downsample_block(
|
| 442 |
+
hidden_states=sample,
|
| 443 |
+
temb=emb,
|
| 444 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 445 |
+
image_only_indicator=image_only_indicator,
|
| 446 |
+
)
|
| 447 |
+
else:
|
| 448 |
+
sample, res_samples = downsample_block(
|
| 449 |
+
hidden_states=sample,
|
| 450 |
+
temb=emb,
|
| 451 |
+
image_only_indicator=image_only_indicator,
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
down_block_res_samples += res_samples
|
| 455 |
+
|
| 456 |
+
if idx == 0 and conditional_controls is not None:
|
| 457 |
+
scale = conditional_controls['scale']
|
| 458 |
+
conditional_controls = conditional_controls['output']
|
| 459 |
+
mean_latents, std_latents = torch.mean(sample, dim=(1, 2, 3), keepdim=True), torch.std(sample, dim=(1, 2, 3), keepdim=True)
|
| 460 |
+
mean_control, std_control = torch.mean(conditional_controls, dim=(1, 2, 3), keepdim=True), torch.std(conditional_controls, dim=(1, 2, 3), keepdim=True)
|
| 461 |
+
conditional_controls = (conditional_controls - mean_control) * (std_latents / (std_control + 1e-5)) + mean_latents
|
| 462 |
+
conditional_controls = F.adaptive_avg_pool2d(conditional_controls, sample.shape[-2:])
|
| 463 |
+
# 0.2: This superparameter is used to adjust the control level: increasing this value will strengthen the control level.
|
| 464 |
+
sample = sample + conditional_controls * scale * 0.2
|
| 465 |
+
|
| 466 |
+
if down_block_additional_residuals is not None:
|
| 467 |
+
new_down_block_res_samples = ()
|
| 468 |
+
|
| 469 |
+
for down_block_res_sample, down_block_additional_residual in zip(
|
| 470 |
+
down_block_res_samples, down_block_additional_residuals
|
| 471 |
+
):
|
| 472 |
+
down_block_res_sample = down_block_res_sample + down_block_additional_residual
|
| 473 |
+
new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)
|
| 474 |
+
|
| 475 |
+
down_block_res_samples = new_down_block_res_samples
|
| 476 |
+
|
| 477 |
+
# 4. mid
|
| 478 |
+
sample = self.mid_block(
|
| 479 |
+
hidden_states=sample,
|
| 480 |
+
temb=emb,
|
| 481 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 482 |
+
image_only_indicator=image_only_indicator,
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
# 5. up
|
| 486 |
+
for i, upsample_block in enumerate(self.up_blocks):
|
| 487 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
| 488 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
| 489 |
+
|
| 490 |
+
if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
|
| 491 |
+
sample = upsample_block(
|
| 492 |
+
hidden_states=sample,
|
| 493 |
+
temb=emb,
|
| 494 |
+
res_hidden_states_tuple=res_samples,
|
| 495 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 496 |
+
image_only_indicator=image_only_indicator,
|
| 497 |
+
)
|
| 498 |
+
else:
|
| 499 |
+
sample = upsample_block(
|
| 500 |
+
hidden_states=sample,
|
| 501 |
+
temb=emb,
|
| 502 |
+
res_hidden_states_tuple=res_samples,
|
| 503 |
+
image_only_indicator=image_only_indicator,
|
| 504 |
+
)
|
| 505 |
+
|
| 506 |
+
# 6. post-process
|
| 507 |
+
sample = self.conv_norm_out(sample)
|
| 508 |
+
sample = self.conv_act(sample)
|
| 509 |
+
sample = self.conv_out(sample)
|
| 510 |
+
|
| 511 |
+
# 7. Reshape back to original shape
|
| 512 |
+
sample = sample.reshape(batch_size, num_frames, *sample.shape[1:])
|
| 513 |
+
|
| 514 |
+
if not return_dict:
|
| 515 |
+
return (sample,)
|
| 516 |
+
|
| 517 |
+
return UNetSpatioTemporalConditionOutput(sample=sample)
|
ControlNeXt-SVD-v2/pipeline/__pycache__/pipeline_stable_video_diffusion_controlnext.cpython-310.pyc
ADDED
|
Binary file (21.7 kB). View file
|
|
|
ControlNeXt-SVD-v2/pipeline/__pycache__/pipeline_stable_video_diffusion_controlnext.cpython-312.pyc
ADDED
|
Binary file (33.8 kB). View file
|
|
|
ControlNeXt-SVD-v2/pipeline/pipeline_stable_video_diffusion_controlnext.py
ADDED
|
@@ -0,0 +1,753 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import Callable, Dict, List, Optional, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import PIL.Image
|
| 21 |
+
import torch
|
| 22 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
| 23 |
+
from models.controlnext_vid_svd import ControlNeXtSDVModel
|
| 24 |
+
|
| 25 |
+
from diffusers.image_processor import VaeImageProcessor
|
| 26 |
+
from diffusers.models import AutoencoderKLTemporalDecoder, UNetSpatioTemporalConditionModel
|
| 27 |
+
from diffusers.utils import BaseOutput, logging
|
| 28 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 29 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 30 |
+
from models.unet_spatio_temporal_condition_controlnext import UNetSpatioTemporalConditionControlNeXtModel
|
| 31 |
+
from utils.scheduling_euler_discrete_karras_fix import EulerDiscreteScheduler
|
| 32 |
+
#from diffusers.pipelines.utils import PIL_INTERPOLATION, BaseOutput, logging
|
| 33 |
+
from diffusers.pipelines.stable_video_diffusion.pipeline_stable_video_diffusion import StableVideoDiffusionPipeline
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 37 |
+
|
| 38 |
+
def _get_add_time_ids(
|
| 39 |
+
noise_aug_strength,
|
| 40 |
+
dtype,
|
| 41 |
+
batch_size,
|
| 42 |
+
fps=4,
|
| 43 |
+
motion_bucket_id=128,
|
| 44 |
+
unet=None,
|
| 45 |
+
):
|
| 46 |
+
add_time_ids = [fps, motion_bucket_id, noise_aug_strength]
|
| 47 |
+
|
| 48 |
+
passed_add_embed_dim = unet.config.addition_time_embed_dim * len(add_time_ids)
|
| 49 |
+
expected_add_embed_dim = unet.add_embedding.linear_1.in_features
|
| 50 |
+
|
| 51 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
| 52 |
+
raise ValueError(
|
| 53 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 57 |
+
# add_time_ids = add_time_ids.repeat(batch_size * num_videos_per_prompt, 1)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
return add_time_ids
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _append_dims(x, target_dims):
|
| 64 |
+
"""Appends dimensions to the end of a tensor until it has target_dims dimensions."""
|
| 65 |
+
dims_to_append = target_dims - x.ndim
|
| 66 |
+
if dims_to_append < 0:
|
| 67 |
+
raise ValueError(f"input has {x.ndim} dims but target_dims is {target_dims}, which is less")
|
| 68 |
+
return x[(...,) + (None,) * dims_to_append]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def tensor2vid(video: torch.Tensor, processor, output_type="np"):
|
| 72 |
+
# Based on:
|
| 73 |
+
# https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/pipelines/multi_modal/text_to_video_synthesis_pipeline.py#L78
|
| 74 |
+
|
| 75 |
+
batch_size, channels, num_frames, height, width = video.shape
|
| 76 |
+
outputs = []
|
| 77 |
+
for batch_idx in range(batch_size):
|
| 78 |
+
batch_vid = video[batch_idx].permute(1, 0, 2, 3)
|
| 79 |
+
batch_output = processor.postprocess(batch_vid, output_type)
|
| 80 |
+
|
| 81 |
+
outputs.append(batch_output)
|
| 82 |
+
|
| 83 |
+
return outputs
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass
|
| 87 |
+
class StableVideoDiffusionPipelineOutput(BaseOutput):
|
| 88 |
+
r"""
|
| 89 |
+
Output class for zero-shot text-to-video pipeline.
|
| 90 |
+
|
| 91 |
+
Args:
|
| 92 |
+
frames (`[List[PIL.Image.Image]`, `np.ndarray`]):
|
| 93 |
+
List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
|
| 94 |
+
num_channels)`.
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
frames: Union[List[PIL.Image.Image], np.ndarray]
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class StableVideoDiffusionPipelineControlNeXt(DiffusionPipeline):
|
| 101 |
+
r"""
|
| 102 |
+
Pipeline to generate video from an input image using Stable Video Diffusion.
|
| 103 |
+
|
| 104 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 105 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 106 |
+
|
| 107 |
+
Args:
|
| 108 |
+
vae ([`AutoencoderKL`]):
|
| 109 |
+
Variational Auto-Encoder (VAE) model to encode and decode images to and from latent representations.
|
| 110 |
+
image_encoder ([`~transformers.CLIPVisionModelWithProjection`]):
|
| 111 |
+
Frozen CLIP image-encoder ([laion/CLIP-ViT-H-14-laion2B-s32B-b79K](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K)).
|
| 112 |
+
unet ([`UNetSpatioTemporalConditionModel`]):
|
| 113 |
+
A `UNetSpatioTemporalConditionModel` to denoise the encoded image latents.
|
| 114 |
+
scheduler ([`EulerDiscreteScheduler`]):
|
| 115 |
+
A scheduler to be used in combination with `unet` to denoise the encoded image latents.
|
| 116 |
+
feature_extractor ([`~transformers.CLIPImageProcessor`]):
|
| 117 |
+
A `CLIPImageProcessor` to extract features from generated images.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
model_cpu_offload_seq = "image_encoder->unet->vae"
|
| 121 |
+
_callback_tensor_inputs = ["latents"]
|
| 122 |
+
|
| 123 |
+
def __init__(
|
| 124 |
+
self,
|
| 125 |
+
vae: AutoencoderKLTemporalDecoder,
|
| 126 |
+
image_encoder: CLIPVisionModelWithProjection,
|
| 127 |
+
unet: UNetSpatioTemporalConditionControlNeXtModel,
|
| 128 |
+
controlnext: ControlNeXtSDVModel,
|
| 129 |
+
scheduler: EulerDiscreteScheduler,
|
| 130 |
+
feature_extractor: CLIPImageProcessor,
|
| 131 |
+
):
|
| 132 |
+
super().__init__()
|
| 133 |
+
|
| 134 |
+
self.register_modules(
|
| 135 |
+
vae=vae,
|
| 136 |
+
image_encoder=image_encoder,
|
| 137 |
+
controlnext=controlnext,
|
| 138 |
+
unet=unet,
|
| 139 |
+
scheduler=scheduler,
|
| 140 |
+
feature_extractor=feature_extractor,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
|
| 144 |
+
self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def _encode_image(self, image, device, num_videos_per_prompt, do_classifier_free_guidance):
|
| 148 |
+
dtype = next(self.image_encoder.parameters()).dtype
|
| 149 |
+
|
| 150 |
+
if not isinstance(image, torch.Tensor):
|
| 151 |
+
image = self.image_processor.pil_to_numpy(image)
|
| 152 |
+
image = self.image_processor.numpy_to_pt(image)
|
| 153 |
+
|
| 154 |
+
# We normalize the image before resizing to match with the original implementation.
|
| 155 |
+
# Then we unnormalize it after resizing.
|
| 156 |
+
image = image * 2.0 - 1.0
|
| 157 |
+
image = _resize_with_antialiasing(image, (224, 224))
|
| 158 |
+
image = (image + 1.0) / 2.0
|
| 159 |
+
|
| 160 |
+
# Normalize the image with for CLIP input
|
| 161 |
+
image = self.feature_extractor(
|
| 162 |
+
images=image,
|
| 163 |
+
do_normalize=True,
|
| 164 |
+
do_center_crop=False,
|
| 165 |
+
do_resize=False,
|
| 166 |
+
do_rescale=False,
|
| 167 |
+
return_tensors="pt",
|
| 168 |
+
).pixel_values
|
| 169 |
+
|
| 170 |
+
image = image.to(device=device, dtype=dtype)
|
| 171 |
+
image_embeddings = self.image_encoder(image).image_embeds
|
| 172 |
+
image_embeddings = image_embeddings.unsqueeze(1)
|
| 173 |
+
|
| 174 |
+
# duplicate image embeddings for each generation per prompt, using mps friendly method
|
| 175 |
+
bs_embed, seq_len, _ = image_embeddings.shape
|
| 176 |
+
image_embeddings = image_embeddings.repeat(1, num_videos_per_prompt, 1)
|
| 177 |
+
image_embeddings = image_embeddings.view(bs_embed * num_videos_per_prompt, seq_len, -1)
|
| 178 |
+
|
| 179 |
+
if do_classifier_free_guidance:
|
| 180 |
+
negative_image_embeddings = torch.zeros_like(image_embeddings)
|
| 181 |
+
|
| 182 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 183 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 184 |
+
# to avoid doing two forward passes
|
| 185 |
+
image_embeddings = torch.cat([negative_image_embeddings, image_embeddings])
|
| 186 |
+
|
| 187 |
+
return image_embeddings
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _encode_vae_image(
|
| 191 |
+
self,
|
| 192 |
+
image: torch.Tensor,
|
| 193 |
+
device,
|
| 194 |
+
num_videos_per_prompt,
|
| 195 |
+
do_classifier_free_guidance,
|
| 196 |
+
):
|
| 197 |
+
image = image.to(device=device)
|
| 198 |
+
image_latents = self.vae.encode(image).latent_dist.mode()
|
| 199 |
+
|
| 200 |
+
if do_classifier_free_guidance:
|
| 201 |
+
negative_image_latents = torch.zeros_like(image_latents)
|
| 202 |
+
|
| 203 |
+
# For classifier free guidance, we need to do two forward passes.
|
| 204 |
+
# Here we concatenate the unconditional and text embeddings into a single batch
|
| 205 |
+
# to avoid doing two forward passes
|
| 206 |
+
image_latents = torch.cat([negative_image_latents, image_latents])
|
| 207 |
+
|
| 208 |
+
# duplicate image_latents for each generation per prompt, using mps friendly method
|
| 209 |
+
image_latents = image_latents.repeat(num_videos_per_prompt, 1, 1, 1)
|
| 210 |
+
|
| 211 |
+
return image_latents
|
| 212 |
+
|
| 213 |
+
def _get_add_time_ids(
|
| 214 |
+
self,
|
| 215 |
+
fps,
|
| 216 |
+
motion_bucket_id,
|
| 217 |
+
noise_aug_strength,
|
| 218 |
+
dtype,
|
| 219 |
+
batch_size,
|
| 220 |
+
num_videos_per_prompt,
|
| 221 |
+
do_classifier_free_guidance,
|
| 222 |
+
):
|
| 223 |
+
add_time_ids = [fps, motion_bucket_id, noise_aug_strength]
|
| 224 |
+
|
| 225 |
+
passed_add_embed_dim = self.unet.config.addition_time_embed_dim * len(add_time_ids)
|
| 226 |
+
expected_add_embed_dim = self.unet.add_embedding.linear_1.in_features
|
| 227 |
+
|
| 228 |
+
if expected_add_embed_dim != passed_add_embed_dim:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
f"Model expects an added time embedding vector of length {expected_add_embed_dim}, but a vector of {passed_add_embed_dim} was created. The model has an incorrect config. Please check `unet.config.time_embedding_type` and `text_encoder_2.config.projection_dim`."
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
add_time_ids = torch.tensor([add_time_ids], dtype=dtype)
|
| 234 |
+
add_time_ids = add_time_ids.repeat(batch_size * num_videos_per_prompt, 1)
|
| 235 |
+
|
| 236 |
+
if do_classifier_free_guidance:
|
| 237 |
+
add_time_ids = torch.cat([add_time_ids, add_time_ids])
|
| 238 |
+
|
| 239 |
+
return add_time_ids
|
| 240 |
+
|
| 241 |
+
def decode_latents(self, latents, num_frames, decode_chunk_size=14):
|
| 242 |
+
# [batch, frames, channels, height, width] -> [batch*frames, channels, height, width]
|
| 243 |
+
latents = latents.flatten(0, 1)
|
| 244 |
+
|
| 245 |
+
latents = 1 / self.vae.config.scaling_factor * latents
|
| 246 |
+
|
| 247 |
+
accepts_num_frames = "num_frames" in set(inspect.signature(self.vae.forward).parameters.keys())
|
| 248 |
+
|
| 249 |
+
# decode decode_chunk_size frames at a time to avoid OOM
|
| 250 |
+
frames = []
|
| 251 |
+
for i in range(0, latents.shape[0], decode_chunk_size):
|
| 252 |
+
num_frames_in = latents[i : i + decode_chunk_size].shape[0]
|
| 253 |
+
decode_kwargs = {}
|
| 254 |
+
# if accepts_num_frames:
|
| 255 |
+
# # we only pass num_frames_in if it's expected
|
| 256 |
+
# decode_kwargs["num_frames"] = num_frames_in
|
| 257 |
+
decode_kwargs["num_frames"] = num_frames_in
|
| 258 |
+
frame = self.vae.decode(latents[i : i + decode_chunk_size], **decode_kwargs).sample
|
| 259 |
+
frames.append(frame)
|
| 260 |
+
frames = torch.cat(frames, dim=0)
|
| 261 |
+
|
| 262 |
+
# [batch*frames, channels, height, width] -> [batch, channels, frames, height, width]
|
| 263 |
+
frames = frames.reshape(-1, num_frames, *frames.shape[1:]).permute(0, 2, 1, 3, 4)
|
| 264 |
+
|
| 265 |
+
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
|
| 266 |
+
frames = frames.float()
|
| 267 |
+
return frames
|
| 268 |
+
|
| 269 |
+
def check_inputs(self, image, height, width):
|
| 270 |
+
if (
|
| 271 |
+
not isinstance(image, torch.Tensor)
|
| 272 |
+
and not isinstance(image, PIL.Image.Image)
|
| 273 |
+
and not isinstance(image, list)
|
| 274 |
+
):
|
| 275 |
+
raise ValueError(
|
| 276 |
+
"`image` has to be of type `torch.FloatTensor` or `PIL.Image.Image` or `List[PIL.Image.Image]` but is"
|
| 277 |
+
f" {type(image)}"
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
if height % 8 != 0 or width % 8 != 0:
|
| 281 |
+
raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
|
| 282 |
+
|
| 283 |
+
def prepare_latents(
|
| 284 |
+
self,
|
| 285 |
+
batch_size,
|
| 286 |
+
num_frames,
|
| 287 |
+
num_channels_latents,
|
| 288 |
+
height,
|
| 289 |
+
width,
|
| 290 |
+
dtype,
|
| 291 |
+
device,
|
| 292 |
+
generator,
|
| 293 |
+
latents=None,
|
| 294 |
+
):
|
| 295 |
+
shape = (
|
| 296 |
+
batch_size,
|
| 297 |
+
num_frames,
|
| 298 |
+
num_channels_latents // 2,
|
| 299 |
+
height // self.vae_scale_factor,
|
| 300 |
+
width // self.vae_scale_factor,
|
| 301 |
+
)
|
| 302 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 303 |
+
raise ValueError(
|
| 304 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 305 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
if latents is None:
|
| 309 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 310 |
+
else:
|
| 311 |
+
latents = latents.to(device)
|
| 312 |
+
|
| 313 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
| 314 |
+
latents = latents * self.scheduler.init_noise_sigma
|
| 315 |
+
return latents
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def guidance_scale(self):
|
| 319 |
+
return self._guidance_scale
|
| 320 |
+
|
| 321 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 322 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 323 |
+
# corresponds to doing no classifier free guidance.
|
| 324 |
+
@property
|
| 325 |
+
def do_classifier_free_guidance(self):
|
| 326 |
+
return self._guidance_scale >= 1 and self.unet.config.time_cond_proj_dim is None
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def num_timesteps(self):
|
| 330 |
+
return self._num_timesteps
|
| 331 |
+
|
| 332 |
+
@torch.no_grad()
|
| 333 |
+
def __call__(
|
| 334 |
+
self,
|
| 335 |
+
image: Union[PIL.Image.Image, List[PIL.Image.Image], torch.FloatTensor],
|
| 336 |
+
controlnext_condition:Optional[torch.FloatTensor] = None,
|
| 337 |
+
height: int = 576,
|
| 338 |
+
width: int = 1024,
|
| 339 |
+
num_frames: Optional[int] = None,
|
| 340 |
+
num_inference_steps: int = 25,
|
| 341 |
+
min_guidance_scale: float = 1.0,
|
| 342 |
+
max_guidance_scale: float = 3.0,
|
| 343 |
+
fps: int = 7,
|
| 344 |
+
motion_bucket_id: int = 127,
|
| 345 |
+
noise_aug_strength: int = 0.02,
|
| 346 |
+
decode_chunk_size: Optional[int] = None,
|
| 347 |
+
num_videos_per_prompt: Optional[int] = 1,
|
| 348 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
| 349 |
+
latents: Optional[torch.FloatTensor] = None,
|
| 350 |
+
output_type: Optional[str] = "pil",
|
| 351 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
| 352 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
| 353 |
+
return_dict: bool = True,
|
| 354 |
+
controlnext_cond_scale=1.0,
|
| 355 |
+
batch_size=1,
|
| 356 |
+
overlap=5,
|
| 357 |
+
frames_per_batch = 14,
|
| 358 |
+
):
|
| 359 |
+
r"""
|
| 360 |
+
The call function to the pipeline for generation.
|
| 361 |
+
|
| 362 |
+
Args:
|
| 363 |
+
image (`PIL.Image.Image` or `List[PIL.Image.Image]` or `torch.FloatTensor`):
|
| 364 |
+
Image or images to guide image generation. If you provide a tensor, it needs to be compatible with
|
| 365 |
+
[`CLIPImageProcessor`](https://huggingface.co/lambdalabs/sd-image-variations-diffusers/blob/main/feature_extractor/preprocessor_config.json).
|
| 366 |
+
height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 367 |
+
The height in pixels of the generated image.
|
| 368 |
+
width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
|
| 369 |
+
The width in pixels of the generated image.
|
| 370 |
+
num_frames (`int`, *optional*):
|
| 371 |
+
The number of video frames to generate. Defaults to 14 for `stable-video-diffusion-img2vid` and to 25 for `stable-video-diffusion-img2vid-xt`
|
| 372 |
+
num_inference_steps (`int`, *optional*, defaults to 25):
|
| 373 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 374 |
+
expense of slower inference. This parameter is modulated by `strength`.
|
| 375 |
+
min_guidance_scale (`float`, *optional*, defaults to 1.0):
|
| 376 |
+
The minimum guidance scale. Used for the classifier free guidance with first frame.
|
| 377 |
+
max_guidance_scale (`float`, *optional*, defaults to 3.0):
|
| 378 |
+
The maximum guidance scale. Used for the classifier free guidance with last frame.
|
| 379 |
+
fps (`int`, *optional*, defaults to 7):
|
| 380 |
+
Frames per second. The rate at which the generated images shall be exported to a video after generation.
|
| 381 |
+
Note that Stable Diffusion Video's UNet was micro-conditioned on fps-1 during training.
|
| 382 |
+
motion_bucket_id (`int`, *optional*, defaults to 127):
|
| 383 |
+
The motion bucket ID. Used as conditioning for the generation. The higher the number the more motion will be in the video.
|
| 384 |
+
noise_aug_strength (`int`, *optional*, defaults to 0.02):
|
| 385 |
+
The amount of noise added to the init image, the higher it is the less the video will look like the init image. Increase it for more motion.
|
| 386 |
+
decode_chunk_size (`int`, *optional*):
|
| 387 |
+
The number of frames to decode at a time. The higher the chunk size, the higher the temporal consistency
|
| 388 |
+
between frames, but also the higher the memory consumption. By default, the decoder will decode all frames at once
|
| 389 |
+
for maximal quality. Reduce `decode_chunk_size` to reduce memory usage.
|
| 390 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 391 |
+
The number of images to generate per prompt.
|
| 392 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
| 393 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 394 |
+
generation deterministic.
|
| 395 |
+
latents (`torch.FloatTensor`, *optional*):
|
| 396 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 397 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 398 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 399 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
| 400 |
+
The output format of the generated image. Choose between `PIL.Image` or `np.array`.
|
| 401 |
+
callback_on_step_end (`Callable`, *optional*):
|
| 402 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
| 403 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
| 404 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
| 405 |
+
`callback_on_step_end_tensor_inputs`.
|
| 406 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
| 407 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 408 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 409 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 410 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 411 |
+
Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
|
| 412 |
+
plain tuple.
|
| 413 |
+
|
| 414 |
+
Returns:
|
| 415 |
+
[`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] or `tuple`:
|
| 416 |
+
If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableVideoDiffusionPipelineOutput`] is returned,
|
| 417 |
+
otherwise a `tuple` is returned where the first element is a list of list with the generated frames.
|
| 418 |
+
|
| 419 |
+
Examples:
|
| 420 |
+
|
| 421 |
+
```py
|
| 422 |
+
from diffusers import StableVideoDiffusionPipeline
|
| 423 |
+
from diffusers.utils import load_image, export_to_video
|
| 424 |
+
|
| 425 |
+
pipe = StableVideoDiffusionPipeline.from_pretrained("stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16")
|
| 426 |
+
pipe.to("cuda")
|
| 427 |
+
|
| 428 |
+
image = load_image("https://lh3.googleusercontent.com/y-iFOHfLTwkuQSUegpwDdgKmOjRSTvPxat63dQLB25xkTs4lhIbRUFeNBWZzYf370g=s1200")
|
| 429 |
+
image = image.resize((1024, 576))
|
| 430 |
+
|
| 431 |
+
frames = pipe(image, num_frames=25, decode_chunk_size=8).frames[0]
|
| 432 |
+
export_to_video(frames, "generated.mp4", fps=7)
|
| 433 |
+
```
|
| 434 |
+
"""
|
| 435 |
+
# 0. Default height and width to unet
|
| 436 |
+
height = height or self.unet.config.sample_size * self.vae_scale_factor
|
| 437 |
+
width = width or self.unet.config.sample_size * self.vae_scale_factor
|
| 438 |
+
|
| 439 |
+
num_frames = num_frames if num_frames is not None else self.unet.config.num_frames
|
| 440 |
+
decode_chunk_size = decode_chunk_size if decode_chunk_size is not None else num_frames
|
| 441 |
+
frames_per_batch = min(frames_per_batch, num_frames)
|
| 442 |
+
|
| 443 |
+
# 1. Check inputs. Raise error if not correct
|
| 444 |
+
self.check_inputs(image, height, width)
|
| 445 |
+
|
| 446 |
+
# 2. Define call parameters
|
| 447 |
+
#if isinstance(image, PIL.Image.Image):
|
| 448 |
+
# batch_size = 1
|
| 449 |
+
#elif isinstance(image, list):
|
| 450 |
+
# batch_size = len(image)
|
| 451 |
+
#else:
|
| 452 |
+
# batch_size = image.shape[0]
|
| 453 |
+
device = self._execution_device
|
| 454 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
| 455 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
| 456 |
+
# corresponds to doing no classifier free guidance.
|
| 457 |
+
do_classifier_free_guidance = max_guidance_scale >= 1.0
|
| 458 |
+
|
| 459 |
+
# 3. Encode input image
|
| 460 |
+
image_embeddings = self._encode_image(image, device, num_videos_per_prompt, do_classifier_free_guidance)
|
| 461 |
+
|
| 462 |
+
# NOTE: Stable Diffusion Video was conditioned on fps - 1, which
|
| 463 |
+
# is why it is reduced here.
|
| 464 |
+
# See: https://github.com/Stability-AI/generative-models/blob/ed0997173f98eaf8f4edf7ba5fe8f15c6b877fd3/scripts/sampling/simple_video_sample.py#L188
|
| 465 |
+
fps = fps - 1
|
| 466 |
+
|
| 467 |
+
# 4. Encode input image using VAE
|
| 468 |
+
image = self.image_processor.preprocess(image, height=height, width=width)
|
| 469 |
+
noise = randn_tensor(image.shape, generator=generator, device=image.device, dtype=image.dtype)
|
| 470 |
+
image = image + noise_aug_strength * noise #
|
| 471 |
+
|
| 472 |
+
needs_upcasting = (self.vae.dtype == torch.float16 or self.vae.dtype == torch.bfloat16) and self.vae.config.force_upcast
|
| 473 |
+
if needs_upcasting:
|
| 474 |
+
self_vae_dtype = self.vae.dtype
|
| 475 |
+
self.vae.to(dtype=torch.float32)
|
| 476 |
+
|
| 477 |
+
image_latents = self._encode_vae_image(image, device, num_videos_per_prompt, do_classifier_free_guidance)
|
| 478 |
+
image_latents = image_latents.to(image_embeddings.dtype)
|
| 479 |
+
|
| 480 |
+
# cast back to fp16 if needed
|
| 481 |
+
if needs_upcasting:
|
| 482 |
+
self.vae.to(dtype=self_vae_dtype)
|
| 483 |
+
|
| 484 |
+
# Repeat the image latents for each frame so we can concatenate them with the noise
|
| 485 |
+
# image_latents [batch, channels, height, width] ->[batch, num_frames, channels, height, width]
|
| 486 |
+
image_latents = image_latents.unsqueeze(1).repeat(1, num_frames, 1, 1, 1)
|
| 487 |
+
#image_latents = torch.cat([image_latents] * 2) if do_classifier_free_guidance else image_latents
|
| 488 |
+
|
| 489 |
+
# 5. Get Added Time IDs
|
| 490 |
+
added_time_ids = self._get_add_time_ids(
|
| 491 |
+
fps,
|
| 492 |
+
motion_bucket_id,
|
| 493 |
+
noise_aug_strength,
|
| 494 |
+
image_embeddings.dtype,
|
| 495 |
+
batch_size,
|
| 496 |
+
num_videos_per_prompt,
|
| 497 |
+
do_classifier_free_guidance,
|
| 498 |
+
)
|
| 499 |
+
added_time_ids = added_time_ids.to(device)
|
| 500 |
+
|
| 501 |
+
# 4. Prepare timesteps
|
| 502 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
| 503 |
+
timesteps = self.scheduler.timesteps
|
| 504 |
+
|
| 505 |
+
# 5. Prepare latent variables
|
| 506 |
+
|
| 507 |
+
num_channels_latents = self.unet.config.in_channels
|
| 508 |
+
latents = self.prepare_latents(
|
| 509 |
+
batch_size * num_videos_per_prompt,
|
| 510 |
+
num_frames,
|
| 511 |
+
num_channels_latents,
|
| 512 |
+
height,
|
| 513 |
+
width,
|
| 514 |
+
image_embeddings.dtype,
|
| 515 |
+
device,
|
| 516 |
+
generator,
|
| 517 |
+
latents,
|
| 518 |
+
)
|
| 519 |
+
#prepare controlnext condition
|
| 520 |
+
controlnext_condition = self.image_processor.preprocess(controlnext_condition, height=height, width=width)
|
| 521 |
+
controlnext_condition = (controlnext_condition + 1.0) / 2
|
| 522 |
+
controlnext_condition = controlnext_condition.unsqueeze(0)
|
| 523 |
+
if do_classifier_free_guidance:
|
| 524 |
+
controlnext_condition = torch.cat([controlnext_condition] * 2)
|
| 525 |
+
controlnext_condition = controlnext_condition.to(device, latents.dtype)
|
| 526 |
+
controlnext_condition_all = controlnext_condition
|
| 527 |
+
latents_all = latents
|
| 528 |
+
|
| 529 |
+
# 7. Prepare guidance scale
|
| 530 |
+
guidance_scale = torch.linspace(min_guidance_scale, max_guidance_scale, frames_per_batch).unsqueeze(0)
|
| 531 |
+
guidance_scale = guidance_scale.to(device, latents.dtype)
|
| 532 |
+
guidance_scale = guidance_scale.repeat(batch_size * num_videos_per_prompt, 1)
|
| 533 |
+
guidance_scale = _append_dims(guidance_scale, latents.ndim)
|
| 534 |
+
|
| 535 |
+
self._guidance_scale = guidance_scale
|
| 536 |
+
|
| 537 |
+
noise_aug_strength = 0.02 #"¯\_(ツ)_/¯
|
| 538 |
+
added_time_ids = _get_add_time_ids(
|
| 539 |
+
noise_aug_strength,
|
| 540 |
+
image_embeddings.dtype,
|
| 541 |
+
batch_size,
|
| 542 |
+
6,
|
| 543 |
+
128,
|
| 544 |
+
unet=self.unet,
|
| 545 |
+
)
|
| 546 |
+
if do_classifier_free_guidance:
|
| 547 |
+
added_time_ids = torch.cat([added_time_ids] * 2)
|
| 548 |
+
added_time_ids = added_time_ids.to(latents.device)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
# 8. Denoising loop
|
| 552 |
+
num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
|
| 553 |
+
self._num_timesteps = len(timesteps)
|
| 554 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 555 |
+
for i, t in enumerate(timesteps):
|
| 556 |
+
pred_tmp = torch.zeros_like(latents_all)
|
| 557 |
+
counter = torch.zeros((latents.shape[0], num_frames, 1, 1, 1 )).to(device=latents.device)
|
| 558 |
+
for batch, ind_start_idx in enumerate(range(0, num_frames-overlap, frames_per_batch-overlap)):
|
| 559 |
+
self.scheduler._step_index = None
|
| 560 |
+
if ind_start_idx + frames_per_batch > num_frames:
|
| 561 |
+
ind_start = num_frames - frames_per_batch
|
| 562 |
+
else:
|
| 563 |
+
ind_start = ind_start_idx
|
| 564 |
+
latents = latents_all[:,ind_start:ind_start+frames_per_batch].contiguous()
|
| 565 |
+
controlnext_condition = controlnext_condition_all[:,ind_start:ind_start+frames_per_batch].contiguous()
|
| 566 |
+
|
| 567 |
+
controlnext_condition[:, 0, ...] = controlnext_condition_all[:, 0, ...]
|
| 568 |
+
|
| 569 |
+
# expand the latents if we are doing classifier free guidance
|
| 570 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
| 571 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
| 572 |
+
|
| 573 |
+
controlnext_output = self.controlnext(
|
| 574 |
+
controlnext_condition,
|
| 575 |
+
t,
|
| 576 |
+
)
|
| 577 |
+
if do_classifier_free_guidance:
|
| 578 |
+
N = controlnext_output['output'].shape[0]
|
| 579 |
+
controlnext_output['scale'] = torch.tensor(controlnext_output['scale']).to(latent_model_input).repeat(N)[:, None, None, None]
|
| 580 |
+
controlnext_output['scale'][:N // 2] *= 0
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
# Concatenate image_latents over channels dimention
|
| 584 |
+
latent_model_input = torch.cat([latent_model_input, image_latents[:,ind_start:ind_start+frames_per_batch].contiguous()], dim=2)
|
| 585 |
+
|
| 586 |
+
|
| 587 |
+
# predict the noise residual
|
| 588 |
+
noise_pred = self.unet(
|
| 589 |
+
latent_model_input,
|
| 590 |
+
t,
|
| 591 |
+
encoder_hidden_states=image_embeddings,
|
| 592 |
+
added_time_ids=added_time_ids,
|
| 593 |
+
conditional_controls=controlnext_output,
|
| 594 |
+
return_dict=False,
|
| 595 |
+
)[0]
|
| 596 |
+
|
| 597 |
+
# perform guidance
|
| 598 |
+
if do_classifier_free_guidance:
|
| 599 |
+
noise_pred_uncond, noise_pred_cond = noise_pred.chunk(2)
|
| 600 |
+
noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_cond - noise_pred_uncond)
|
| 601 |
+
|
| 602 |
+
# compute the previous noisy sample x_t -> x_t-1
|
| 603 |
+
latents = self.scheduler.step(noise_pred, t, latents).prev_sample
|
| 604 |
+
|
| 605 |
+
if callback_on_step_end is not None:
|
| 606 |
+
callback_kwargs = {}
|
| 607 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 608 |
+
callback_kwargs[k] = locals()[k]
|
| 609 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 610 |
+
|
| 611 |
+
latents = callback_outputs.pop("latents", latents)
|
| 612 |
+
|
| 613 |
+
if ind_start == 0:
|
| 614 |
+
pred_tmp[:,ind_start:ind_start+frames_per_batch] += latents
|
| 615 |
+
counter[:,ind_start:ind_start+frames_per_batch] += 1
|
| 616 |
+
else:
|
| 617 |
+
pred_tmp[:,ind_start + 1 : ind_start+frames_per_batch] += latents[:, 1:, ...]
|
| 618 |
+
counter[:,ind_start + 1:ind_start+frames_per_batch] += 1
|
| 619 |
+
pred_tmp /= counter
|
| 620 |
+
latents_all = pred_tmp
|
| 621 |
+
|
| 622 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
| 623 |
+
progress_bar.update()
|
| 624 |
+
latents = latents_all
|
| 625 |
+
|
| 626 |
+
if not output_type == "latent":
|
| 627 |
+
# cast back to fp16 if needed
|
| 628 |
+
if needs_upcasting:
|
| 629 |
+
self.vae.to(dtype=self_vae_dtype)
|
| 630 |
+
frames = self.decode_latents(latents, num_frames, decode_chunk_size)
|
| 631 |
+
frames = tensor2vid(frames, self.image_processor, output_type=output_type)
|
| 632 |
+
else:
|
| 633 |
+
frames = latents
|
| 634 |
+
|
| 635 |
+
self.maybe_free_model_hooks()
|
| 636 |
+
|
| 637 |
+
if not return_dict:
|
| 638 |
+
return frames
|
| 639 |
+
|
| 640 |
+
return StableVideoDiffusionPipelineOutput(frames=frames)
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
# resizing utils
|
| 644 |
+
# TODO: clean up later
|
| 645 |
+
def _resize_with_antialiasing(input, size, interpolation="bicubic", align_corners=True):
|
| 646 |
+
|
| 647 |
+
if input.ndim == 3:
|
| 648 |
+
input = input.unsqueeze(0) # Add a batch dimension
|
| 649 |
+
|
| 650 |
+
h, w = input.shape[-2:]
|
| 651 |
+
factors = (h / size[0], w / size[1])
|
| 652 |
+
|
| 653 |
+
# First, we have to determine sigma
|
| 654 |
+
# Taken from skimage: https://github.com/scikit-image/scikit-image/blob/v0.19.2/skimage/transform/_warps.py#L171
|
| 655 |
+
sigmas = (
|
| 656 |
+
max((factors[0] - 1.0) / 2.0, 0.001),
|
| 657 |
+
max((factors[1] - 1.0) / 2.0, 0.001),
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
# Now kernel size. Good results are for 3 sigma, but that is kind of slow. Pillow uses 1 sigma
|
| 661 |
+
# https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
|
| 662 |
+
# But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now
|
| 663 |
+
ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
|
| 664 |
+
|
| 665 |
+
# Make sure it is odd
|
| 666 |
+
if (ks[0] % 2) == 0:
|
| 667 |
+
ks = ks[0] + 1, ks[1]
|
| 668 |
+
|
| 669 |
+
if (ks[1] % 2) == 0:
|
| 670 |
+
ks = ks[0], ks[1] + 1
|
| 671 |
+
|
| 672 |
+
input = _gaussian_blur2d(input, ks, sigmas)
|
| 673 |
+
|
| 674 |
+
output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
|
| 675 |
+
return output
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _compute_padding(kernel_size):
|
| 679 |
+
"""Compute padding tuple."""
|
| 680 |
+
# 4 or 6 ints: (padding_left, padding_right,padding_top,padding_bottom)
|
| 681 |
+
# https://pytorch.org/docs/stable/nn.html#torch.nn.functional.pad
|
| 682 |
+
if len(kernel_size) < 2:
|
| 683 |
+
raise AssertionError(kernel_size)
|
| 684 |
+
computed = [k - 1 for k in kernel_size]
|
| 685 |
+
|
| 686 |
+
# for even kernels we need to do asymmetric padding :(
|
| 687 |
+
out_padding = 2 * len(kernel_size) * [0]
|
| 688 |
+
|
| 689 |
+
for i in range(len(kernel_size)):
|
| 690 |
+
computed_tmp = computed[-(i + 1)]
|
| 691 |
+
|
| 692 |
+
pad_front = computed_tmp // 2
|
| 693 |
+
pad_rear = computed_tmp - pad_front
|
| 694 |
+
|
| 695 |
+
out_padding[2 * i + 0] = pad_front
|
| 696 |
+
out_padding[2 * i + 1] = pad_rear
|
| 697 |
+
|
| 698 |
+
return out_padding
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
def _filter2d(input, kernel):
|
| 702 |
+
# prepare kernel
|
| 703 |
+
b, c, h, w = input.shape
|
| 704 |
+
tmp_kernel = kernel[:, None, ...].to(device=input.device, dtype=input.dtype)
|
| 705 |
+
|
| 706 |
+
tmp_kernel = tmp_kernel.expand(-1, c, -1, -1)
|
| 707 |
+
|
| 708 |
+
height, width = tmp_kernel.shape[-2:]
|
| 709 |
+
|
| 710 |
+
padding_shape: list[int] = _compute_padding([height, width])
|
| 711 |
+
input = torch.nn.functional.pad(input, padding_shape, mode="reflect")
|
| 712 |
+
|
| 713 |
+
# kernel and input tensor reshape to align element-wise or batch-wise params
|
| 714 |
+
tmp_kernel = tmp_kernel.reshape(-1, 1, height, width)
|
| 715 |
+
input = input.view(-1, tmp_kernel.size(0), input.size(-2), input.size(-1))
|
| 716 |
+
|
| 717 |
+
# convolve the tensor with the kernel.
|
| 718 |
+
output = torch.nn.functional.conv2d(input, tmp_kernel, groups=tmp_kernel.size(0), padding=0, stride=1)
|
| 719 |
+
|
| 720 |
+
out = output.view(b, c, h, w)
|
| 721 |
+
return out
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
def _gaussian(window_size: int, sigma):
|
| 725 |
+
if isinstance(sigma, float):
|
| 726 |
+
sigma = torch.tensor([[sigma]])
|
| 727 |
+
|
| 728 |
+
batch_size = sigma.shape[0]
|
| 729 |
+
|
| 730 |
+
x = (torch.arange(window_size, device=sigma.device, dtype=sigma.dtype) - window_size // 2).expand(batch_size, -1)
|
| 731 |
+
|
| 732 |
+
if window_size % 2 == 0:
|
| 733 |
+
x = x + 0.5
|
| 734 |
+
|
| 735 |
+
gauss = torch.exp(-x.pow(2.0) / (2 * sigma.pow(2.0)))
|
| 736 |
+
|
| 737 |
+
return gauss / gauss.sum(-1, keepdim=True)
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
def _gaussian_blur2d(input, kernel_size, sigma):
|
| 741 |
+
if isinstance(sigma, tuple):
|
| 742 |
+
sigma = torch.tensor([sigma], dtype=input.dtype)
|
| 743 |
+
else:
|
| 744 |
+
sigma = sigma.to(dtype=input.dtype)
|
| 745 |
+
|
| 746 |
+
ky, kx = int(kernel_size[0]), int(kernel_size[1])
|
| 747 |
+
bs = sigma.shape[0]
|
| 748 |
+
kernel_x = _gaussian(kx, sigma[:, 1].view(bs, 1))
|
| 749 |
+
kernel_y = _gaussian(ky, sigma[:, 0].view(bs, 1))
|
| 750 |
+
out_x = _filter2d(input, kernel_x[..., None, :])
|
| 751 |
+
out = _filter2d(out_x, kernel_y[..., None])
|
| 752 |
+
|
| 753 |
+
return out
|
ControlNeXt-SVD-v2/pretrained/DWPose/dw-ll_ucoco_384.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:724f4ff2439ed61afb86fb8a1951ec39c6220682803b4a8bd4f598cd913b1843
|
| 3 |
+
size 134399116
|
ControlNeXt-SVD-v2/pretrained/DWPose/yolox_l.onnx
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7860ae79de6c89a3c1eb72ae9a2756c0ccfbe04b7791bb5880afabd97855a411
|
| 3 |
+
size 216746733
|
ControlNeXt-SVD-v2/pretrained/controlnet.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2a60c6e9cfde16adb1d2bf41b8a19a4929b0ba5b206d8bdf7125329c2a684b7c
|
| 3 |
+
size 14122234
|
ControlNeXt-SVD-v2/pretrained/unet.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e32948c7a02516705df5c3bb5f4d852200f15a08d5a3335304d66fe8cda351df
|
| 3 |
+
size 6099004486
|
ControlNeXt-SVD-v2/run_controlnext.py
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import numpy as np
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from pipeline.pipeline_stable_video_diffusion_controlnext import StableVideoDiffusionPipelineControlNeXt
|
| 6 |
+
from models.controlnext_vid_svd import ControlNeXtSDVModel
|
| 7 |
+
from models.unet_spatio_temporal_condition_controlnext import UNetSpatioTemporalConditionControlNeXtModel
|
| 8 |
+
from transformers import CLIPVisionModelWithProjection
|
| 9 |
+
import re
|
| 10 |
+
from diffusers import AutoencoderKLTemporalDecoder
|
| 11 |
+
from moviepy.editor import ImageSequenceClip
|
| 12 |
+
from decord import VideoReader
|
| 13 |
+
import argparse
|
| 14 |
+
from safetensors.torch import load_file
|
| 15 |
+
from utils.pre_process import preprocess
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def write_mp4(video_path, samples, fps=14, audio_bitrate="192k"):
|
| 19 |
+
clip = ImageSequenceClip(samples, fps=fps)
|
| 20 |
+
clip.write_videofile(video_path, audio_codec="aac", audio_bitrate=audio_bitrate,
|
| 21 |
+
ffmpeg_params=["-crf", "18", "-preset", "slow"])
|
| 22 |
+
|
| 23 |
+
def save_vid_side_by_side(batch_output, validation_control_images, output_folder, fps):
|
| 24 |
+
# Helper function to convert tensors to PIL images and save as GIF
|
| 25 |
+
flattened_batch_output = [img for sublist in batch_output for img in sublist]
|
| 26 |
+
video_path = output_folder+'/test_1.mp4'
|
| 27 |
+
final_images = []
|
| 28 |
+
outputs = []
|
| 29 |
+
# Helper function to concatenate images horizontally
|
| 30 |
+
def get_concat_h(im1, im2):
|
| 31 |
+
dst = Image.new('RGB', (im1.width + im2.width, max(im1.height, im2.height)))
|
| 32 |
+
dst.paste(im1, (0, 0))
|
| 33 |
+
dst.paste(im2, (im1.width, 0))
|
| 34 |
+
return dst
|
| 35 |
+
for image_list in zip(validation_control_images, flattened_batch_output):
|
| 36 |
+
predict_img = image_list[1].resize(image_list[0].size)
|
| 37 |
+
result = get_concat_h(image_list[0], predict_img)
|
| 38 |
+
final_images.append(np.array(result))
|
| 39 |
+
outputs.append(np.array(predict_img))
|
| 40 |
+
write_mp4(video_path, final_images, fps=fps)
|
| 41 |
+
|
| 42 |
+
output_path = output_folder + "/output.mp4"
|
| 43 |
+
write_mp4(output_path, outputs, fps=fps)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def load_images_from_folder_to_pil(folder):
|
| 47 |
+
images = []
|
| 48 |
+
valid_extensions = {".jpg", ".jpeg", ".png", ".bmp", ".gif", ".tiff"} # Add or remove extensions as needed
|
| 49 |
+
|
| 50 |
+
# Function to extract frame number from the filename
|
| 51 |
+
def frame_number(filename):
|
| 52 |
+
# First, try the pattern 'frame_x_7fps'
|
| 53 |
+
new_pattern_match = re.search(r'frame_(\d+)_7fps', filename)
|
| 54 |
+
if new_pattern_match:
|
| 55 |
+
return int(new_pattern_match.group(1))
|
| 56 |
+
# If the new pattern is not found, use the original digit extraction method
|
| 57 |
+
matches = re.findall(r'\d+', filename)
|
| 58 |
+
if matches:
|
| 59 |
+
if matches[-1] == '0000' and len(matches) > 1:
|
| 60 |
+
return int(matches[-2]) # Return the second-to-last sequence if the last is '0000'
|
| 61 |
+
return int(matches[-1]) # Otherwise, return the last sequence
|
| 62 |
+
return float('inf') # Return 'inf'
|
| 63 |
+
|
| 64 |
+
# Sorting files based on frame number
|
| 65 |
+
sorted_files = sorted(os.listdir(folder), key=frame_number)
|
| 66 |
+
# Load images in sorted order
|
| 67 |
+
for filename in sorted_files:
|
| 68 |
+
ext = os.path.splitext(filename)[1].lower()
|
| 69 |
+
if ext in valid_extensions:
|
| 70 |
+
img = Image.open(os.path.join(folder, filename)).convert('RGB')
|
| 71 |
+
images.append(img)
|
| 72 |
+
|
| 73 |
+
return images
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def load_images_from_video_to_pil(video_path):
|
| 77 |
+
images = []
|
| 78 |
+
|
| 79 |
+
vr = VideoReader(video_path)
|
| 80 |
+
length = len(vr)
|
| 81 |
+
|
| 82 |
+
for idx in range(length):
|
| 83 |
+
frame = vr[idx].asnumpy()
|
| 84 |
+
images.append(Image.fromarray(frame))
|
| 85 |
+
return images
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def parse_args():
|
| 89 |
+
parser = argparse.ArgumentParser(
|
| 90 |
+
description="Script to train Stable Diffusion XL for InstructPix2Pix."
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
parser.add_argument(
|
| 94 |
+
"--pretrained_model_name_or_path",
|
| 95 |
+
type=str,
|
| 96 |
+
default=None,
|
| 97 |
+
required=True
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
parser.add_argument(
|
| 101 |
+
"--validation_control_images_folder",
|
| 102 |
+
type=str,
|
| 103 |
+
default=None,
|
| 104 |
+
required=False,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
parser.add_argument(
|
| 108 |
+
"--validation_control_video_path",
|
| 109 |
+
type=str,
|
| 110 |
+
default=None,
|
| 111 |
+
required=False,
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
parser.add_argument(
|
| 115 |
+
"--output_dir",
|
| 116 |
+
type=str,
|
| 117 |
+
default=None,
|
| 118 |
+
required=True
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
parser.add_argument(
|
| 122 |
+
"--height",
|
| 123 |
+
type=int,
|
| 124 |
+
default=768,
|
| 125 |
+
required=False
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
parser.add_argument(
|
| 129 |
+
"--width",
|
| 130 |
+
type=int,
|
| 131 |
+
default=512,
|
| 132 |
+
required=False
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
parser.add_argument(
|
| 136 |
+
"--guidance_scale",
|
| 137 |
+
type=float,
|
| 138 |
+
default=2.,
|
| 139 |
+
required=False
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
parser.add_argument(
|
| 143 |
+
"--num_inference_steps",
|
| 144 |
+
type=int,
|
| 145 |
+
default=25,
|
| 146 |
+
required=False
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
parser.add_argument(
|
| 151 |
+
"--controlnext_path",
|
| 152 |
+
type=str,
|
| 153 |
+
default=None,
|
| 154 |
+
required=True
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--unet_path",
|
| 159 |
+
type=str,
|
| 160 |
+
default=None,
|
| 161 |
+
required=True
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--max_frame_num",
|
| 166 |
+
type=int,
|
| 167 |
+
default=50,
|
| 168 |
+
required=False
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
parser.add_argument(
|
| 172 |
+
"--ref_image_path",
|
| 173 |
+
type=str,
|
| 174 |
+
default=None,
|
| 175 |
+
required=True
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
parser.add_argument(
|
| 179 |
+
"--batch_frames",
|
| 180 |
+
type=int,
|
| 181 |
+
default=14,
|
| 182 |
+
required=False
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
parser.add_argument(
|
| 186 |
+
"--overlap",
|
| 187 |
+
type=int,
|
| 188 |
+
default=4,
|
| 189 |
+
required=False
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
parser.add_argument(
|
| 193 |
+
"--sample_stride",
|
| 194 |
+
type=int,
|
| 195 |
+
default=2,
|
| 196 |
+
required=False
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
args = parser.parse_args()
|
| 200 |
+
return args
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def load_tensor(tensor_path):
|
| 204 |
+
if os.path.splitext(tensor_path)[1] == '.bin':
|
| 205 |
+
return torch.load(tensor_path)
|
| 206 |
+
elif os.path.splitext(tensor_path)[1] == ".safetensors":
|
| 207 |
+
return load_file(tensor_path)
|
| 208 |
+
else:
|
| 209 |
+
print("without supported tensors")
|
| 210 |
+
os._exit()
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
# Main script
|
| 214 |
+
if __name__ == "__main__":
|
| 215 |
+
args = parse_args()
|
| 216 |
+
|
| 217 |
+
assert (args.validation_control_images_folder is None) ^ (args.validation_control_video_path is None), "must and only one of [validation_control_images_folder, validation_control_video_path] should be given"
|
| 218 |
+
|
| 219 |
+
unet = UNetSpatioTemporalConditionControlNeXtModel.from_pretrained(
|
| 220 |
+
args.pretrained_model_name_or_path,
|
| 221 |
+
subfolder="unet",
|
| 222 |
+
low_cpu_mem_usage=True,
|
| 223 |
+
)
|
| 224 |
+
controlnext = ControlNeXtSDVModel()
|
| 225 |
+
controlnext.load_state_dict(load_tensor(args.controlnext_path))
|
| 226 |
+
unet.load_state_dict(load_tensor(args.unet_path), strict=False)
|
| 227 |
+
|
| 228 |
+
image_encoder = CLIPVisionModelWithProjection.from_pretrained(
|
| 229 |
+
args.pretrained_model_name_or_path, subfolder="image_encoder")
|
| 230 |
+
vae = AutoencoderKLTemporalDecoder.from_pretrained(
|
| 231 |
+
args.pretrained_model_name_or_path, subfolder="vae")
|
| 232 |
+
|
| 233 |
+
pipeline = StableVideoDiffusionPipelineControlNeXt.from_pretrained(
|
| 234 |
+
args.pretrained_model_name_or_path,
|
| 235 |
+
controlnext=controlnext,
|
| 236 |
+
unet=unet,
|
| 237 |
+
vae=vae,
|
| 238 |
+
image_encoder=image_encoder)
|
| 239 |
+
# pipeline.to(dtype=torch.float16)
|
| 240 |
+
pipeline.enable_model_cpu_offload()
|
| 241 |
+
|
| 242 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 243 |
+
|
| 244 |
+
# Inference and saving loop
|
| 245 |
+
# ref_image = Image.open(args.ref_image_path).convert('RGB')
|
| 246 |
+
# ref_image = ref_image.resize((args.width, args.height))
|
| 247 |
+
# validation_control_images = [img.resize((args.width, args.height)) for img in validation_control_images]
|
| 248 |
+
|
| 249 |
+
validation_control_images, ref_image = preprocess(args.validation_control_video_path, args.ref_image_path, width=args.width, height=args.height, max_frame_num=args.max_frame_num, sample_stride=args.sample_stride)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
final_result = []
|
| 253 |
+
frames = args.batch_frames
|
| 254 |
+
num_frames = min(args.max_frame_num, len(validation_control_images))
|
| 255 |
+
|
| 256 |
+
for i in range(num_frames):
|
| 257 |
+
validation_control_images[i] = Image.fromarray(np.array(validation_control_images[i]))
|
| 258 |
+
|
| 259 |
+
video_frames = pipeline(
|
| 260 |
+
ref_image,
|
| 261 |
+
validation_control_images[:num_frames],
|
| 262 |
+
decode_chunk_size=2,
|
| 263 |
+
num_frames=num_frames,
|
| 264 |
+
motion_bucket_id=127.0,
|
| 265 |
+
fps=7,
|
| 266 |
+
controlnext_cond_scale=1.0,
|
| 267 |
+
width=args.width,
|
| 268 |
+
height=args.height,
|
| 269 |
+
min_guidance_scale=args.guidance_scale,
|
| 270 |
+
max_guidance_scale=args.guidance_scale,
|
| 271 |
+
frames_per_batch=frames,
|
| 272 |
+
num_inference_steps=args.num_inference_steps,
|
| 273 |
+
overlap=args.overlap).frames[0]
|
| 274 |
+
final_result.append(video_frames)
|
| 275 |
+
|
| 276 |
+
fps =VideoReader(args.validation_control_video_path).get_avg_fps() // args.sample_stride
|
| 277 |
+
|
| 278 |
+
save_vid_side_by_side(
|
| 279 |
+
final_result,
|
| 280 |
+
validation_control_images[:num_frames],
|
| 281 |
+
args.output_dir,
|
| 282 |
+
fps=fps)
|
ControlNeXt-SVD-v2/script.sh
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
CUDA_VISIBLE_DEVICES=0 python run_controlnext.py \
|
| 2 |
+
--pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
|
| 3 |
+
--output_dir outputs \
|
| 4 |
+
--max_frame_num 240 \
|
| 5 |
+
--guidance_scale 3 \
|
| 6 |
+
--batch_frames 24 \
|
| 7 |
+
--sample_stride 2 \
|
| 8 |
+
--overlap 6 \
|
| 9 |
+
--height 1024 \
|
| 10 |
+
--width 576 \
|
| 11 |
+
--controlnext_path pretrained/controlnet.bin \
|
| 12 |
+
--unet_path pretrained/unet.bin \
|
| 13 |
+
--validation_control_video_path examples/video/02.mp4 \
|
| 14 |
+
--ref_image_path examples/ref_imgs/01.jpeg
|
| 15 |
+
|
ControlNeXt-SVD-v2/utils/__pycache__/pre_process.cpython-310.pyc
ADDED
|
Binary file (1.93 kB). View file
|
|
|
ControlNeXt-SVD-v2/utils/__pycache__/scheduling_euler_discrete_karras_fix.cpython-310.pyc
ADDED
|
Binary file (18 kB). View file
|
|
|
ControlNeXt-SVD-v2/utils/pre_process.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import logging
|
| 4 |
+
import math
|
| 5 |
+
from omegaconf import OmegaConf
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch.jit
|
| 11 |
+
from torchvision.datasets.folder import pil_loader
|
| 12 |
+
from torchvision.transforms.functional import pil_to_tensor, resize, center_crop
|
| 13 |
+
from torchvision.transforms.functional import to_pil_image
|
| 14 |
+
from dwpose.preprocess import get_image_pose, get_video_pose
|
| 15 |
+
|
| 16 |
+
ASPECT_RATIO = 9 / 16
|
| 17 |
+
|
| 18 |
+
def preprocess(video_path, image_path, width=576, height=1024, sample_stride=2, max_frame_num=None):
|
| 19 |
+
"""preprocess ref image pose and video pose
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
video_path (str): input video pose path
|
| 23 |
+
image_path (str): reference image path
|
| 24 |
+
resolution (int, optional): Defaults to 576.
|
| 25 |
+
sample_stride (int, optional): Defaults to 2.
|
| 26 |
+
"""
|
| 27 |
+
image_pixels = pil_loader(image_path)
|
| 28 |
+
image_pixels = pil_to_tensor(image_pixels) # (c, h, w)
|
| 29 |
+
h, w = image_pixels.shape[-2:]
|
| 30 |
+
############################ compute target h/w according to original aspect ratio ###############################
|
| 31 |
+
# if h>w:
|
| 32 |
+
# w_target, h_target = resolution, int(resolution / ASPECT_RATIO // 64) * 64
|
| 33 |
+
# else:
|
| 34 |
+
# w_target, h_target = int(resolution / ASPECT_RATIO // 64) * 64, resolution
|
| 35 |
+
w_target, h_target = width, height
|
| 36 |
+
h_w_ratio = float(h) / float(w)
|
| 37 |
+
if h_w_ratio < h_target / w_target:
|
| 38 |
+
h_resize, w_resize = h_target, math.ceil(h_target / h_w_ratio)
|
| 39 |
+
else:
|
| 40 |
+
h_resize, w_resize = math.ceil(w_target * h_w_ratio), w_target
|
| 41 |
+
image_pixels = resize(image_pixels, [h_resize, w_resize], antialias=None)
|
| 42 |
+
image_pixels = center_crop(image_pixels, [h_target, w_target])
|
| 43 |
+
image_pixels = image_pixels.permute((1, 2, 0)).numpy()
|
| 44 |
+
##################################### get image&video pose value #################################################
|
| 45 |
+
image_pose = get_image_pose(image_pixels)
|
| 46 |
+
video_pose = get_video_pose(video_path, image_pixels, sample_stride=sample_stride, max_frame_num=max_frame_num)
|
| 47 |
+
pose_pixels = np.concatenate([np.expand_dims(image_pose, 0), video_pose])
|
| 48 |
+
# image_pixels = np.transpose(np.expand_dims(image_pixels, 0), (0, 3, 1, 2))
|
| 49 |
+
image_pixels = Image.fromarray(image_pixels)
|
| 50 |
+
pose_pixels = [Image.fromarray(p.transpose((1,2,0))) for p in pose_pixels]
|
| 51 |
+
# return torch.from_numpy(pose_pixels.copy()) / 127.5 - 1, torch.from_numpy(image_pixels) / 127.5 - 1
|
| 52 |
+
return pose_pixels, image_pixels
|
| 53 |
+
|
ControlNeXt-SVD-v2/utils/scheduling_euler_discrete_karras_fix.py
ADDED
|
@@ -0,0 +1,556 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023 Katherine Crowson and The HuggingFace Team. All rights reserved.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import math
|
| 16 |
+
from dataclasses import dataclass
|
| 17 |
+
from typing import List, Optional, Tuple, Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
| 23 |
+
from diffusers.utils import BaseOutput, logging
|
| 24 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 25 |
+
from diffusers.schedulers.scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass
|
| 33 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->EulerDiscrete
|
| 34 |
+
class EulerDiscreteSchedulerOutput(BaseOutput):
|
| 35 |
+
"""
|
| 36 |
+
Output class for the scheduler's `step` function output.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
| 40 |
+
Computed sample `(x_{t-1})` of previous timestep. `prev_sample` should be used as next model input in the
|
| 41 |
+
denoising loop.
|
| 42 |
+
pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
| 43 |
+
The predicted denoised sample `(x_{0})` based on the model output from the current timestep.
|
| 44 |
+
`pred_original_sample` can be used to preview progress or for guidance.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
prev_sample: torch.FloatTensor
|
| 48 |
+
pred_original_sample: Optional[torch.FloatTensor] = None
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
|
| 52 |
+
def betas_for_alpha_bar(
|
| 53 |
+
num_diffusion_timesteps,
|
| 54 |
+
max_beta=0.999,
|
| 55 |
+
alpha_transform_type="cosine",
|
| 56 |
+
):
|
| 57 |
+
"""
|
| 58 |
+
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
|
| 59 |
+
(1-beta) over time from t = [0,1].
|
| 60 |
+
|
| 61 |
+
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
|
| 62 |
+
to that part of the diffusion process.
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
Args:
|
| 66 |
+
num_diffusion_timesteps (`int`): the number of betas to produce.
|
| 67 |
+
max_beta (`float`): the maximum beta to use; use values lower than 1 to
|
| 68 |
+
prevent singularities.
|
| 69 |
+
alpha_transform_type (`str`, *optional*, default to `cosine`): the type of noise schedule for alpha_bar.
|
| 70 |
+
Choose from `cosine` or `exp`
|
| 71 |
+
|
| 72 |
+
Returns:
|
| 73 |
+
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
|
| 74 |
+
"""
|
| 75 |
+
if alpha_transform_type == "cosine":
|
| 76 |
+
|
| 77 |
+
def alpha_bar_fn(t):
|
| 78 |
+
return math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2
|
| 79 |
+
|
| 80 |
+
elif alpha_transform_type == "exp":
|
| 81 |
+
|
| 82 |
+
def alpha_bar_fn(t):
|
| 83 |
+
return math.exp(t * -12.0)
|
| 84 |
+
|
| 85 |
+
else:
|
| 86 |
+
raise ValueError(f"Unsupported alpha_tranform_type: {alpha_transform_type}")
|
| 87 |
+
|
| 88 |
+
betas = []
|
| 89 |
+
for i in range(num_diffusion_timesteps):
|
| 90 |
+
t1 = i / num_diffusion_timesteps
|
| 91 |
+
t2 = (i + 1) / num_diffusion_timesteps
|
| 92 |
+
betas.append(min(1 - alpha_bar_fn(t2) / alpha_bar_fn(t1), max_beta))
|
| 93 |
+
return torch.tensor(betas, dtype=torch.float32)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
# Copied from diffusers.schedulers.scheduling_ddim.rescale_zero_terminal_snr
|
| 97 |
+
def rescale_zero_terminal_snr(betas):
|
| 98 |
+
"""
|
| 99 |
+
Rescales betas to have zero terminal SNR Based on https://arxiv.org/pdf/2305.08891.pdf (Algorithm 1)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
Args:
|
| 103 |
+
betas (`torch.FloatTensor`):
|
| 104 |
+
the betas that the scheduler is being initialized with.
|
| 105 |
+
|
| 106 |
+
Returns:
|
| 107 |
+
`torch.FloatTensor`: rescaled betas with zero terminal SNR
|
| 108 |
+
"""
|
| 109 |
+
# Convert betas to alphas_bar_sqrt
|
| 110 |
+
alphas = 1.0 - betas
|
| 111 |
+
alphas_cumprod = torch.cumprod(alphas, dim=0)
|
| 112 |
+
alphas_bar_sqrt = alphas_cumprod.sqrt()
|
| 113 |
+
|
| 114 |
+
# Store old values.
|
| 115 |
+
alphas_bar_sqrt_0 = alphas_bar_sqrt[0].clone()
|
| 116 |
+
alphas_bar_sqrt_T = alphas_bar_sqrt[-1].clone()
|
| 117 |
+
|
| 118 |
+
# Shift so the last timestep is zero.
|
| 119 |
+
alphas_bar_sqrt -= alphas_bar_sqrt_T
|
| 120 |
+
|
| 121 |
+
# Scale so the first timestep is back to the old value.
|
| 122 |
+
alphas_bar_sqrt *= alphas_bar_sqrt_0 / (alphas_bar_sqrt_0 - alphas_bar_sqrt_T)
|
| 123 |
+
|
| 124 |
+
# Convert alphas_bar_sqrt to betas
|
| 125 |
+
alphas_bar = alphas_bar_sqrt**2 # Revert sqrt
|
| 126 |
+
alphas = alphas_bar[1:] / alphas_bar[:-1] # Revert cumprod
|
| 127 |
+
alphas = torch.cat([alphas_bar[0:1], alphas])
|
| 128 |
+
betas = 1 - alphas
|
| 129 |
+
|
| 130 |
+
return betas
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class EulerDiscreteScheduler(SchedulerMixin, ConfigMixin):
|
| 134 |
+
"""
|
| 135 |
+
Euler scheduler.
|
| 136 |
+
|
| 137 |
+
This model inherits from [`SchedulerMixin`] and [`ConfigMixin`]. Check the superclass documentation for the generic
|
| 138 |
+
methods the library implements for all schedulers such as loading and saving.
|
| 139 |
+
|
| 140 |
+
Args:
|
| 141 |
+
num_train_timesteps (`int`, defaults to 1000):
|
| 142 |
+
The number of diffusion steps to train the model.
|
| 143 |
+
beta_start (`float`, defaults to 0.0001):
|
| 144 |
+
The starting `beta` value of inference.
|
| 145 |
+
beta_end (`float`, defaults to 0.02):
|
| 146 |
+
The final `beta` value.
|
| 147 |
+
beta_schedule (`str`, defaults to `"linear"`):
|
| 148 |
+
The beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
|
| 149 |
+
`linear` or `scaled_linear`.
|
| 150 |
+
trained_betas (`np.ndarray`, *optional*):
|
| 151 |
+
Pass an array of betas directly to the constructor to bypass `beta_start` and `beta_end`.
|
| 152 |
+
prediction_type (`str`, defaults to `epsilon`, *optional*):
|
| 153 |
+
Prediction type of the scheduler function; can be `epsilon` (predicts the noise of the diffusion process),
|
| 154 |
+
`sample` (directly predicts the noisy sample`) or `v_prediction` (see section 2.4 of [Imagen
|
| 155 |
+
Video](https://imagen.research.google/video/paper.pdf) paper).
|
| 156 |
+
interpolation_type(`str`, defaults to `"linear"`, *optional*):
|
| 157 |
+
The interpolation type to compute intermediate sigmas for the scheduler denoising steps. Should be on of
|
| 158 |
+
`"linear"` or `"log_linear"`.
|
| 159 |
+
use_karras_sigmas (`bool`, *optional*, defaults to `False`):
|
| 160 |
+
Whether to use Karras sigmas for step sizes in the noise schedule during the sampling process. If `True`,
|
| 161 |
+
the sigmas are determined according to a sequence of noise levels {σi}.
|
| 162 |
+
timestep_spacing (`str`, defaults to `"linspace"`):
|
| 163 |
+
The way the timesteps should be scaled. Refer to Table 2 of the [Common Diffusion Noise Schedules and
|
| 164 |
+
Sample Steps are Flawed](https://huggingface.co/papers/2305.08891) for more information.
|
| 165 |
+
steps_offset (`int`, defaults to 0):
|
| 166 |
+
An offset added to the inference steps. You can use a combination of `offset=1` and
|
| 167 |
+
`set_alpha_to_one=False` to make the last step use step 0 for the previous alpha product like in Stable
|
| 168 |
+
Diffusion.
|
| 169 |
+
rescale_betas_zero_snr (`bool`, defaults to `False`):
|
| 170 |
+
Whether to rescale the betas to have zero terminal SNR. This enables the model to generate very bright and
|
| 171 |
+
dark samples instead of limiting it to samples with medium brightness. Loosely related to
|
| 172 |
+
[`--offset_noise`](https://github.com/huggingface/diffusers/blob/74fd735eb073eb1d774b1ab4154a0876eb82f055/examples/dreambooth/train_dreambooth.py#L506).
|
| 173 |
+
"""
|
| 174 |
+
|
| 175 |
+
_compatibles = [e.name for e in KarrasDiffusionSchedulers]
|
| 176 |
+
order = 1
|
| 177 |
+
|
| 178 |
+
@register_to_config
|
| 179 |
+
def __init__(
|
| 180 |
+
self,
|
| 181 |
+
num_train_timesteps: int = 1000,
|
| 182 |
+
beta_start: float = 0.0001,
|
| 183 |
+
beta_end: float = 0.02,
|
| 184 |
+
beta_schedule: str = "linear",
|
| 185 |
+
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
|
| 186 |
+
prediction_type: str = "epsilon",
|
| 187 |
+
interpolation_type: str = "linear",
|
| 188 |
+
use_karras_sigmas: Optional[bool] = False,
|
| 189 |
+
sigma_min: Optional[float] = None,
|
| 190 |
+
sigma_max: Optional[float] = None,
|
| 191 |
+
timestep_spacing: str = "linspace",
|
| 192 |
+
timestep_type: str = "discrete", # can be "discrete" or "continuous"
|
| 193 |
+
steps_offset: int = 0,
|
| 194 |
+
rescale_betas_zero_snr: bool = False,
|
| 195 |
+
):
|
| 196 |
+
if trained_betas is not None:
|
| 197 |
+
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
|
| 198 |
+
elif beta_schedule == "linear":
|
| 199 |
+
self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
|
| 200 |
+
elif beta_schedule == "scaled_linear":
|
| 201 |
+
# this schedule is very specific to the latent diffusion model.
|
| 202 |
+
self.betas = torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
|
| 203 |
+
elif beta_schedule == "squaredcos_cap_v2":
|
| 204 |
+
# Glide cosine schedule
|
| 205 |
+
self.betas = betas_for_alpha_bar(num_train_timesteps)
|
| 206 |
+
else:
|
| 207 |
+
raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
|
| 208 |
+
|
| 209 |
+
if rescale_betas_zero_snr:
|
| 210 |
+
self.betas = rescale_zero_terminal_snr(self.betas)
|
| 211 |
+
|
| 212 |
+
self.alphas = 1.0 - self.betas
|
| 213 |
+
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
|
| 214 |
+
|
| 215 |
+
if rescale_betas_zero_snr:
|
| 216 |
+
# Close to 0 without being 0 so first sigma is not inf
|
| 217 |
+
# FP16 smallest positive subnormal works well here
|
| 218 |
+
self.alphas_cumprod[-1] = 2**-24
|
| 219 |
+
|
| 220 |
+
sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
|
| 221 |
+
timesteps = np.linspace(0, num_train_timesteps - 1, num_train_timesteps, dtype=float)[::-1].copy()
|
| 222 |
+
|
| 223 |
+
sigmas = sigmas[::-1].copy()
|
| 224 |
+
|
| 225 |
+
if self.use_karras_sigmas:
|
| 226 |
+
log_sigmas = np.log(sigmas)
|
| 227 |
+
sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=num_train_timesteps)
|
| 228 |
+
timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas])
|
| 229 |
+
|
| 230 |
+
sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32)
|
| 231 |
+
|
| 232 |
+
# setable values
|
| 233 |
+
self.num_inference_steps = None
|
| 234 |
+
|
| 235 |
+
# TODO: Support the full EDM scalings for all prediction types and timestep types
|
| 236 |
+
if timestep_type == "continuous" and prediction_type == "v_prediction":
|
| 237 |
+
self.timesteps = torch.Tensor([0.25 * sigma.log() for sigma in sigmas])
|
| 238 |
+
else:
|
| 239 |
+
self.timesteps = torch.from_numpy(timesteps.astype(np.float32))
|
| 240 |
+
|
| 241 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 242 |
+
|
| 243 |
+
self.is_scale_input_called = False
|
| 244 |
+
self.use_karras_sigmas = use_karras_sigmas
|
| 245 |
+
|
| 246 |
+
self._step_index = None
|
| 247 |
+
|
| 248 |
+
@property
|
| 249 |
+
def init_noise_sigma(self):
|
| 250 |
+
# standard deviation of the initial noise distribution
|
| 251 |
+
max_sigma = max(self.sigmas) if isinstance(self.sigmas, list) else self.sigmas.max()
|
| 252 |
+
if self.config.timestep_spacing in ["linspace", "trailing"]:
|
| 253 |
+
return max_sigma
|
| 254 |
+
|
| 255 |
+
return (max_sigma**2 + 1) ** 0.5
|
| 256 |
+
|
| 257 |
+
@property
|
| 258 |
+
def step_index(self):
|
| 259 |
+
"""
|
| 260 |
+
The index counter for current timestep. It will increae 1 after each scheduler step.
|
| 261 |
+
"""
|
| 262 |
+
return self._step_index
|
| 263 |
+
|
| 264 |
+
def scale_model_input(
|
| 265 |
+
self, sample: torch.FloatTensor, timestep: Union[float, torch.FloatTensor]
|
| 266 |
+
) -> torch.FloatTensor:
|
| 267 |
+
"""
|
| 268 |
+
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
|
| 269 |
+
current timestep. Scales the denoising model input by `(sigma**2 + 1) ** 0.5` to match the Euler algorithm.
|
| 270 |
+
|
| 271 |
+
Args:
|
| 272 |
+
sample (`torch.FloatTensor`):
|
| 273 |
+
The input sample.
|
| 274 |
+
timestep (`int`, *optional*):
|
| 275 |
+
The current timestep in the diffusion chain.
|
| 276 |
+
|
| 277 |
+
Returns:
|
| 278 |
+
`torch.FloatTensor`:
|
| 279 |
+
A scaled input sample.
|
| 280 |
+
"""
|
| 281 |
+
if self.step_index is None:
|
| 282 |
+
self._init_step_index(timestep)
|
| 283 |
+
|
| 284 |
+
sigma = self.sigmas[self.step_index]
|
| 285 |
+
sample = sample / ((sigma**2 + 1) ** 0.5)
|
| 286 |
+
|
| 287 |
+
self.is_scale_input_called = True
|
| 288 |
+
return sample
|
| 289 |
+
|
| 290 |
+
def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
|
| 291 |
+
"""
|
| 292 |
+
Sets the discrete timesteps used for the diffusion chain (to be run before inference).
|
| 293 |
+
|
| 294 |
+
Args:
|
| 295 |
+
num_inference_steps (`int`):
|
| 296 |
+
The number of diffusion steps used when generating samples with a pre-trained model.
|
| 297 |
+
device (`str` or `torch.device`, *optional*):
|
| 298 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
| 299 |
+
"""
|
| 300 |
+
self.num_inference_steps = num_inference_steps
|
| 301 |
+
|
| 302 |
+
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
|
| 303 |
+
if self.config.timestep_spacing == "linspace":
|
| 304 |
+
timesteps = np.linspace(0, self.config.num_train_timesteps - 1, num_inference_steps, dtype=np.float32)[
|
| 305 |
+
::-1
|
| 306 |
+
].copy()
|
| 307 |
+
elif self.config.timestep_spacing == "leading":
|
| 308 |
+
step_ratio = self.config.num_train_timesteps // self.num_inference_steps
|
| 309 |
+
# creates integer timesteps by multiplying by ratio
|
| 310 |
+
# casting to int to avoid issues when num_inference_step is power of 3
|
| 311 |
+
timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()[::-1].copy().astype(np.float32)
|
| 312 |
+
timesteps += self.config.steps_offset
|
| 313 |
+
elif self.config.timestep_spacing == "trailing":
|
| 314 |
+
step_ratio = self.config.num_train_timesteps / self.num_inference_steps
|
| 315 |
+
# creates integer timesteps by multiplying by ratio
|
| 316 |
+
# casting to int to avoid issues when num_inference_step is power of 3
|
| 317 |
+
timesteps = (np.arange(self.config.num_train_timesteps, 0, -step_ratio)).round().copy().astype(np.float32)
|
| 318 |
+
timesteps -= 1
|
| 319 |
+
else:
|
| 320 |
+
raise ValueError(
|
| 321 |
+
f"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'."
|
| 322 |
+
)
|
| 323 |
+
|
| 324 |
+
sigmas = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5)
|
| 325 |
+
log_sigmas = np.log(sigmas)
|
| 326 |
+
|
| 327 |
+
if self.config.interpolation_type == "linear":
|
| 328 |
+
sigmas = np.interp(timesteps, np.arange(0, len(sigmas)), sigmas)
|
| 329 |
+
elif self.config.interpolation_type == "log_linear":
|
| 330 |
+
sigmas = torch.linspace(np.log(sigmas[-1]), np.log(sigmas[0]), num_inference_steps + 1).exp().numpy()
|
| 331 |
+
else:
|
| 332 |
+
raise ValueError(
|
| 333 |
+
f"{self.config.interpolation_type} is not implemented. Please specify interpolation_type to either"
|
| 334 |
+
" 'linear' or 'log_linear'"
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if self.use_karras_sigmas:
|
| 338 |
+
sigmas = self._convert_to_karras(in_sigmas=sigmas, num_inference_steps=self.num_inference_steps)
|
| 339 |
+
timesteps = np.array([self._sigma_to_t(sigma, log_sigmas) for sigma in sigmas])
|
| 340 |
+
|
| 341 |
+
sigmas = torch.from_numpy(sigmas).to(dtype=torch.float32, device=device)
|
| 342 |
+
|
| 343 |
+
# TODO: Support the full EDM scalings for all prediction types and timestep types
|
| 344 |
+
if self.config.timestep_type == "continuous" and self.config.prediction_type == "v_prediction":
|
| 345 |
+
self.timesteps = torch.Tensor([0.25 * sigma.log() for sigma in sigmas]).to(device=device)
|
| 346 |
+
else:
|
| 347 |
+
self.timesteps = torch.from_numpy(timesteps.astype(np.float32)).to(device=device)
|
| 348 |
+
|
| 349 |
+
self.sigmas = torch.cat([sigmas, torch.zeros(1, device=sigmas.device)])
|
| 350 |
+
self._step_index = None
|
| 351 |
+
|
| 352 |
+
def _sigma_to_t(self, sigma, log_sigmas):
|
| 353 |
+
# get log sigma
|
| 354 |
+
log_sigma = np.log(np.maximum(sigma, 1e-10))
|
| 355 |
+
|
| 356 |
+
# get distribution
|
| 357 |
+
dists = log_sigma - log_sigmas[:, np.newaxis]
|
| 358 |
+
|
| 359 |
+
# get sigmas range
|
| 360 |
+
low_idx = np.cumsum((dists >= 0), axis=0).argmax(axis=0).clip(max=log_sigmas.shape[0] - 2)
|
| 361 |
+
high_idx = low_idx + 1
|
| 362 |
+
|
| 363 |
+
low = log_sigmas[low_idx]
|
| 364 |
+
high = log_sigmas[high_idx]
|
| 365 |
+
|
| 366 |
+
# interpolate sigmas
|
| 367 |
+
w = (low - log_sigma) / (low - high)
|
| 368 |
+
w = np.clip(w, 0, 1)
|
| 369 |
+
|
| 370 |
+
# transform interpolation to time range
|
| 371 |
+
t = (1 - w) * low_idx + w * high_idx
|
| 372 |
+
t = t.reshape(sigma.shape)
|
| 373 |
+
return t
|
| 374 |
+
|
| 375 |
+
# Copied from https://github.com/crowsonkb/k-diffusion/blob/686dbad0f39640ea25c8a8c6a6e56bb40eacefa2/k_diffusion/sampling.py#L17
|
| 376 |
+
def _convert_to_karras(self, in_sigmas: torch.FloatTensor, num_inference_steps) -> torch.FloatTensor:
|
| 377 |
+
"""Constructs the noise schedule of Karras et al. (2022)."""
|
| 378 |
+
|
| 379 |
+
# Hack to make sure that other schedulers which copy this function don't break
|
| 380 |
+
# TODO: Add this logic to the other schedulers
|
| 381 |
+
if hasattr(self.config, "sigma_min"):
|
| 382 |
+
sigma_min = self.config.sigma_min
|
| 383 |
+
else:
|
| 384 |
+
sigma_min = None
|
| 385 |
+
|
| 386 |
+
if hasattr(self.config, "sigma_max"):
|
| 387 |
+
sigma_max = self.config.sigma_max
|
| 388 |
+
else:
|
| 389 |
+
sigma_max = None
|
| 390 |
+
|
| 391 |
+
sigma_min = sigma_min if sigma_min is not None else in_sigmas[-1].item()
|
| 392 |
+
sigma_max = sigma_max if sigma_max is not None else in_sigmas[0].item()
|
| 393 |
+
|
| 394 |
+
rho = 7.0 # 7.0 is the value used in the paper
|
| 395 |
+
ramp = np.linspace(0, 1, num_inference_steps)
|
| 396 |
+
min_inv_rho = sigma_min ** (1 / rho)
|
| 397 |
+
max_inv_rho = sigma_max ** (1 / rho)
|
| 398 |
+
sigmas = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho
|
| 399 |
+
return sigmas
|
| 400 |
+
|
| 401 |
+
def _init_step_index(self, timestep):
|
| 402 |
+
if isinstance(timestep, torch.Tensor):
|
| 403 |
+
timestep = timestep.to(self.timesteps.device)
|
| 404 |
+
|
| 405 |
+
index_candidates = (self.timesteps == timestep).nonzero()
|
| 406 |
+
|
| 407 |
+
# The sigma index that is taken for the **very** first `step`
|
| 408 |
+
# is always the second index (or the last index if there is only 1)
|
| 409 |
+
# This way we can ensure we don't accidentally skip a sigma in
|
| 410 |
+
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
|
| 411 |
+
if len(index_candidates) > 1:
|
| 412 |
+
step_index = index_candidates[1]
|
| 413 |
+
else:
|
| 414 |
+
step_index = index_candidates[0]
|
| 415 |
+
|
| 416 |
+
self._step_index = step_index.item()
|
| 417 |
+
|
| 418 |
+
def step(
|
| 419 |
+
self,
|
| 420 |
+
model_output: torch.FloatTensor,
|
| 421 |
+
timestep: Union[float, torch.FloatTensor],
|
| 422 |
+
sample: torch.FloatTensor,
|
| 423 |
+
s_churn: float = 0.0,
|
| 424 |
+
s_tmin: float = 0.0,
|
| 425 |
+
s_tmax: float = float("inf"),
|
| 426 |
+
s_noise: float = 1.0,
|
| 427 |
+
generator: Optional[torch.Generator] = None,
|
| 428 |
+
return_dict: bool = True,
|
| 429 |
+
) -> Union[EulerDiscreteSchedulerOutput, Tuple]:
|
| 430 |
+
"""
|
| 431 |
+
Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
|
| 432 |
+
process from the learned model outputs (most often the predicted noise).
|
| 433 |
+
|
| 434 |
+
Args:
|
| 435 |
+
model_output (`torch.FloatTensor`):
|
| 436 |
+
The direct output from learned diffusion model.
|
| 437 |
+
timestep (`float`):
|
| 438 |
+
The current discrete timestep in the diffusion chain.
|
| 439 |
+
sample (`torch.FloatTensor`):
|
| 440 |
+
A current instance of a sample created by the diffusion process.
|
| 441 |
+
s_churn (`float`):
|
| 442 |
+
s_tmin (`float`):
|
| 443 |
+
s_tmax (`float`):
|
| 444 |
+
s_noise (`float`, defaults to 1.0):
|
| 445 |
+
Scaling factor for noise added to the sample.
|
| 446 |
+
generator (`torch.Generator`, *optional*):
|
| 447 |
+
A random number generator.
|
| 448 |
+
return_dict (`bool`):
|
| 449 |
+
Whether or not to return a [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or
|
| 450 |
+
tuple.
|
| 451 |
+
|
| 452 |
+
Returns:
|
| 453 |
+
[`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] or `tuple`:
|
| 454 |
+
If return_dict is `True`, [`~schedulers.scheduling_euler_discrete.EulerDiscreteSchedulerOutput`] is
|
| 455 |
+
returned, otherwise a tuple is returned where the first element is the sample tensor.
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
if (
|
| 459 |
+
isinstance(timestep, int)
|
| 460 |
+
or isinstance(timestep, torch.IntTensor)
|
| 461 |
+
or isinstance(timestep, torch.LongTensor)
|
| 462 |
+
):
|
| 463 |
+
raise ValueError(
|
| 464 |
+
(
|
| 465 |
+
"Passing integer indices (e.g. from `enumerate(timesteps)`) as timesteps to"
|
| 466 |
+
" `EulerDiscreteScheduler.step()` is not supported. Make sure to pass"
|
| 467 |
+
" one of the `scheduler.timesteps` as a timestep."
|
| 468 |
+
),
|
| 469 |
+
)
|
| 470 |
+
|
| 471 |
+
if not self.is_scale_input_called:
|
| 472 |
+
logger.warning(
|
| 473 |
+
"The `scale_model_input` function should be called before `step` to ensure correct denoising. "
|
| 474 |
+
"See `StableDiffusionPipeline` for a usage example."
|
| 475 |
+
)
|
| 476 |
+
|
| 477 |
+
if self.step_index is None:
|
| 478 |
+
self._init_step_index(timestep)
|
| 479 |
+
|
| 480 |
+
# Upcast to avoid precision issues when computing prev_sample
|
| 481 |
+
sample = sample.to(torch.float32)
|
| 482 |
+
|
| 483 |
+
sigma = self.sigmas[self.step_index]
|
| 484 |
+
|
| 485 |
+
gamma = min(s_churn / (len(self.sigmas) - 1), 2**0.5 - 1) if s_tmin <= sigma <= s_tmax else 0.0
|
| 486 |
+
|
| 487 |
+
noise = randn_tensor(
|
| 488 |
+
model_output.shape, dtype=model_output.dtype, device=model_output.device, generator=generator
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
eps = noise * s_noise
|
| 492 |
+
sigma_hat = sigma * (gamma + 1)
|
| 493 |
+
|
| 494 |
+
if gamma > 0:
|
| 495 |
+
sample = sample + eps * (sigma_hat**2 - sigma**2) ** 0.5
|
| 496 |
+
|
| 497 |
+
# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
|
| 498 |
+
# NOTE: "original_sample" should not be an expected prediction_type but is left in for
|
| 499 |
+
# backwards compatibility
|
| 500 |
+
if self.config.prediction_type == "original_sample" or self.config.prediction_type == "sample":
|
| 501 |
+
pred_original_sample = model_output
|
| 502 |
+
elif self.config.prediction_type == "epsilon":
|
| 503 |
+
pred_original_sample = sample - sigma_hat * model_output
|
| 504 |
+
elif self.config.prediction_type == "v_prediction":
|
| 505 |
+
# denoised = model_output * c_out + input * c_skip
|
| 506 |
+
pred_original_sample = model_output * (-sigma / (sigma**2 + 1) ** 0.5) + (sample / (sigma**2 + 1))
|
| 507 |
+
else:
|
| 508 |
+
raise ValueError(
|
| 509 |
+
f"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`"
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
# 2. Convert to an ODE derivative
|
| 513 |
+
derivative = (sample - pred_original_sample) / sigma_hat
|
| 514 |
+
|
| 515 |
+
dt = self.sigmas[self.step_index + 1] - sigma_hat
|
| 516 |
+
|
| 517 |
+
prev_sample = sample + derivative * dt
|
| 518 |
+
|
| 519 |
+
# Cast sample back to model compatible dtype
|
| 520 |
+
prev_sample = prev_sample.to(model_output.dtype)
|
| 521 |
+
|
| 522 |
+
# upon completion increase step index by one
|
| 523 |
+
self._step_index += 1
|
| 524 |
+
|
| 525 |
+
if not return_dict:
|
| 526 |
+
return (prev_sample,)
|
| 527 |
+
|
| 528 |
+
return EulerDiscreteSchedulerOutput(prev_sample=prev_sample, pred_original_sample=pred_original_sample)
|
| 529 |
+
|
| 530 |
+
def add_noise(
|
| 531 |
+
self,
|
| 532 |
+
original_samples: torch.FloatTensor,
|
| 533 |
+
noise: torch.FloatTensor,
|
| 534 |
+
timesteps: torch.FloatTensor,
|
| 535 |
+
) -> torch.FloatTensor:
|
| 536 |
+
# Make sure sigmas and timesteps have the same device and dtype as original_samples
|
| 537 |
+
sigmas = self.sigmas.to(device=original_samples.device, dtype=original_samples.dtype)
|
| 538 |
+
if original_samples.device.type == "mps" and torch.is_floating_point(timesteps):
|
| 539 |
+
# mps does not support float64
|
| 540 |
+
schedule_timesteps = self.timesteps.to(original_samples.device, dtype=torch.float32)
|
| 541 |
+
timesteps = timesteps.to(original_samples.device, dtype=torch.float32)
|
| 542 |
+
else:
|
| 543 |
+
schedule_timesteps = self.timesteps.to(original_samples.device)
|
| 544 |
+
timesteps = timesteps.to(original_samples.device)
|
| 545 |
+
|
| 546 |
+
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps]
|
| 547 |
+
|
| 548 |
+
sigma = sigmas[step_indices].flatten()
|
| 549 |
+
while len(sigma.shape) < len(original_samples.shape):
|
| 550 |
+
sigma = sigma.unsqueeze(-1)
|
| 551 |
+
|
| 552 |
+
noisy_samples = original_samples + noise * sigma
|
| 553 |
+
return noisy_samples
|
| 554 |
+
|
| 555 |
+
def __len__(self):
|
| 556 |
+
return self.config.num_train_timesteps
|
README.md
CHANGED
|
@@ -17,9 +17,9 @@ The entire project is divided into two parts: `text_or_gloss2pose` and `pose2vid
|
|
| 17 |
|
| 18 |
1. conda env create -f env/environment01_dwpose.yml
|
| 19 |
2. run `conda activate dwpose`
|
| 20 |
-
3. run `pip install env/requirements01_dwpose.txt`
|
| 21 |
4. put raw sign viseos, like `tools-new-2025/input/test_dataset`
|
| 22 |
-
5. cd `
|
| 23 |
6. run `python pipeline00_extract_split_video_to_image.py` (Default frame rate is 30fps, and the video will be automatically cropped to a square shape.)
|
| 24 |
7. run `python pipeline01_extract_dwpose_from_video.py` (It will generate files other than npz. We usually don't need them and can comment out the relevant code.)
|
| 25 |
8. run `conda deactivate`, we finish the preprocess.
|
|
@@ -45,6 +45,47 @@ python text2pose.py --gloss "afternoon" --width 640 --height 480 --fps 25
|
|
| 45 |
|
| 46 |
## tutorial03 render pose video
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
# For Users
|
| 50 |
|
|
|
|
| 17 |
|
| 18 |
1. conda env create -f env/environment01_dwpose.yml
|
| 19 |
2. run `conda activate dwpose`
|
| 20 |
+
3. run `pip install -r env/requirements01_dwpose.txt`
|
| 21 |
4. put raw sign viseos, like `tools-new-2025/input/test_dataset`
|
| 22 |
+
5. cd `StableSigner/tools-new-2025/main`
|
| 23 |
6. run `python pipeline00_extract_split_video_to_image.py` (Default frame rate is 30fps, and the video will be automatically cropped to a square shape.)
|
| 24 |
7. run `python pipeline01_extract_dwpose_from_video.py` (It will generate files other than npz. We usually don't need them and can comment out the relevant code.)
|
| 25 |
8. run `conda deactivate`, we finish the preprocess.
|
|
|
|
| 45 |
|
| 46 |
## tutorial03 render pose video
|
| 47 |
|
| 48 |
+
1. cd StableSigner
|
| 49 |
+
2. conda env create -f env/environment02_controlnext.yml
|
| 50 |
+
3. run `conda activate controlnext`
|
| 51 |
+
4. run `pip install -r env/requirements02_controlnext.txt`
|
| 52 |
+
|
| 53 |
+
```python
|
| 54 |
+
CUDA_VISIBLE_DEVICES=0 python ControlNeXt-SVD-v2/run_controlnext.py \
|
| 55 |
+
--pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
|
| 56 |
+
--output_dir generated_sign_video \
|
| 57 |
+
--max_frame_num 240 \
|
| 58 |
+
--guidance_scale 3 \
|
| 59 |
+
--batch_frames 24 \
|
| 60 |
+
--sample_stride 2 \
|
| 61 |
+
--overlap 4 \
|
| 62 |
+
--height 768 \
|
| 63 |
+
--width 512 \
|
| 64 |
+
--controlnext_path ControlNeXt-SVD-v2/pretrained/controlnet.bin \
|
| 65 |
+
--unet_path ControlNeXt-SVD-v2/pretrained/unet.bin \
|
| 66 |
+
--validation_control_video_path ControlNeXt-SVD-v2/examples/video/02.mp4 \
|
| 67 |
+
--ref_image_path ref_img_dict/03.jpeg
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
<!-- official
|
| 71 |
+
```python
|
| 72 |
+
CUDA_VISIBLE_DEVICES=0 python ControlNeXt-SVD-v2/run_controlnext.py \
|
| 73 |
+
--pretrained_model_name_or_path stabilityai/stable-video-diffusion-img2vid-xt-1-1 \
|
| 74 |
+
--output_dir generated_sign_video \
|
| 75 |
+
--max_frame_num 240 \
|
| 76 |
+
--guidance_scale 3 \
|
| 77 |
+
--batch_frames 24 \
|
| 78 |
+
--sample_stride 2 \
|
| 79 |
+
--overlap 6 \
|
| 80 |
+
--height 1024 \
|
| 81 |
+
--width 576 \
|
| 82 |
+
--controlnext_path ControlNeXt-SVD-v2/pretrained/controlnet.bin \
|
| 83 |
+
--unet_path ControlNeXt-SVD-v2/pretrained/unet.bin \
|
| 84 |
+
--validation_control_video_path ControlNeXt-SVD-v2/examples/video/02.mp4 \
|
| 85 |
+
--ref_image_path ControlNeXt-SVD-v2/examples/ref_imgs/01.jpeg
|
| 86 |
+
```
|
| 87 |
+
-->
|
| 88 |
+
|
| 89 |
|
| 90 |
# For Users
|
| 91 |
|
env/environment02_controlnext.yml
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: controlnext
|
| 2 |
+
channels:
|
| 3 |
+
- pytorch
|
| 4 |
+
- conda-forge
|
| 5 |
+
- nvidia
|
| 6 |
+
- defaults
|
| 7 |
+
- bioconda
|
| 8 |
+
- anaconda
|
| 9 |
+
dependencies:
|
| 10 |
+
- python=3.10
|
env/requirements02_controlnext.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
torchvision
|
| 3 |
+
moviepy==1.0.3
|
| 4 |
+
opencv-python
|
| 5 |
+
omegaconf
|
| 6 |
+
onnxruntime
|
| 7 |
+
pillow
|
| 8 |
+
matplotlib
|
| 9 |
+
numpy
|
| 10 |
+
transformers
|
| 11 |
+
diffusers
|
| 12 |
+
safetensors
|
| 13 |
+
peft
|
| 14 |
+
decord
|
| 15 |
+
einops
|
generated_sign_video/output.mp4
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cd8e1c631af4113c8fe07bc7a64edccd5885c2b6e507ab89c3b369742dc8ab5d
|
| 3 |
+
size 3325227
|