diff --git a/One-to-All-Animation b/One-to-All-Animation
deleted file mode 160000
index fc608e58e3956f26aebf44a4387701f5d64ffd4a..0000000000000000000000000000000000000000
--- a/One-to-All-Animation
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit fc608e58e3956f26aebf44a4387701f5d64ffd4a
diff --git a/One-to-All-Animation/LICENSE b/One-to-All-Animation/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/One-to-All-Animation/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/README.md b/One-to-All-Animation/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..cd0b07fa2bc7592c74a0795c09b1277805e31722
--- /dev/null
+++ b/One-to-All-Animation/README.md
@@ -0,0 +1,310 @@
+
+
+
+
+ One-to-All Animation: Alignment-Free
Character Animation
+ and Image Pose Transfer
+
+
+
+Shijun Shi1*, Jing Xu2*, Zhihang Li3, Chunli Peng4, Xiaoda Yang5, Lijing Lu3,
Kai Hu1†, Jiangning Zhang5†
+
+
+
+1Jiangnan University
+2University of Science and Technology of China
+3Chinese Academy of Sciences
+4Beijing University of Posts and Telecommunications
+5Zhejiang University
+
+
+
+*Equal contribution †Corresponding authors
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+## 🌟 Highlights
+
+We provide a **complete and reproducible** training and evaluation pipeline:
+
+- ✅ **Full Training Code**: Three-stage progressive training from scratch
+- ✅ **Complete Benchmarks**: Reproduction code and pre-trained checkpoints
+- ✅ **Flexible Training Codebase**: Multi-resolution, multi-aspect-ratio, and multi-frame training codebase
+- ✅ **Datasets**: Pre-processed open-source datasets + self-collected cartoon data
+
+
+
+## 🔥 Update
+- [2025.12] [kijai's ComfyUI WanVideoWrapper](https://github.com/kijai/ComfyUI-WanVideoWrapper) now integrates One‑to‑All Animation 14B! Huge thanks to **kijai** for the amazing work!!! **Note**: Our model supports both retargeted pose and direct pose (with reference preprocessing) from the original video. In addition, using lighter colors for the facial skeleton and landmarks helps achieve better identity consistency.
+- [2025.11] Paper reproduction and evaluation code released.
+- [2025.11] [Sample training data and Benchmark](https://huggingface.co/datasets/MochunniaN1/One-to-All-sub) on HuggingFace released.
+- [2025.11] Inference and Training codes are released.
+- [2025.11] [1.3B-v1](https://huggingface.co/MochunniaN1/One-to-All-1.3b_1), [1.3B-v2](https://huggingface.co/MochunniaN1/One-to-All-1.3b_2) and [14B](https://huggingface.co/MochunniaN1/One-to-All-14b) checkpoints are released.
+
+
+
+## 🎭 Showcase
+
+Our model can adapt a single reference image to various motion patterns, demonstrating flexible motion control capabilities.
+
+#### 14B Model
+
+
+
+ | Reference |
+ Motion 1 |
+ Motion 2 |
+ Motion 3 |
+
+
+  |
+  |
+  |
+  |
+
+
+  |
+  |
+  |
+  |
+
+
+
+
+
+#### 1.3B Model
+The 1.3 B model also delivers strong performance (from 1.3b_2 ckpt).
+
+
+
+ | Reference |
+ Motion 1 |
+ Motion 2 |
+ Motion 3 |
+
+
+  |
+  |
+  |
+  |
+
+
+
+Also support longer video & out-of-domain cases
+
+
+
+
+
+
+
+
+## 🔧 Dependencies and Installation
+
+1. Clone Repo
+ ```bash
+ git clone https://github.com/ssj9596/One-to-All-Animation.git
+ cd One-to-All-Animation
+ ```
+
+2. Create Conda Environment and Install Dependencies
+ ```bash
+ # create new conda env
+ conda create -n one-to-all python=3.12
+ conda activate one-to-all
+
+ # install pytorch
+ pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 --index-url https://download.pytorch.org/whl/cu124
+ # or
+ pip install torch==2.5.1 torchvision==0.20.1 torchaudio==2.5.1 -i https://mirrors.aliyun.com/pypi/simple/
+
+ # install python dependencies
+ pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
+
+
+ # (Recommended) install flash attention 3 (or 2) from source:
+ # https://github.com/Dao-AILab/flash-attention
+ ```
+
+3. Download Models
+
+ - Download pretrained models
+ ```bash
+ cd ./pretrained_models
+ bash download_pretrained_models.py
+ ```
+
+ - Download checkpoints
+ ```bash
+ cd ./checkpoints
+ bash download_checkpoints.py
+ ```
+
+ > 💡 **Tip**: Edit the script and uncomment the specific models you want to download.
+ > - **1.3B_1**: Best performance on video benchmark among 1.3B models (paper results).
+ > - **1.3B_2**: Further trained on v1 with large camera movement data and increased image ratio. Better for dynamic video generation. Best on image benchmark (paper results).
+ > - **14B**: Best overall performance among 14B models (paper results).
+
+
+
+
+## ☕️ Quick Inference
+
+We provide several examples in the [`examples`](./examples) folder.
+Run the following commands to try it out:
+
+```bash
+# Step 1: Prepare model input
+cd video-generation
+python infer_preprocess.py
+
+# Step 2: Run inference with your preferred model
+python inference_1.3b.py # For 1.3B model
+# or
+python inference_14b.py # For 14B model
+```
+You can enter the script to modify the input path.
+
+
+
+## 🎬 Training from scratch
+
+>💡 **Data Collection Required**: We find current open-source datasets are not sufficient for training from scratch. We strongly recommend collecting *at least 3,000 additional high-quality video samples* for better results.
+
+We divide the training process into several steps to help you train from scratch (using 1.3B as an example).
+
+1. Download Pretrained Models
+
+ Download the base model from HuggingFace: [Wan-AI/Wan2.1-T2V-1.3B-Diffusers](https://huggingface.co/Wan-AI/Wan2.1-T2V-1.3B-Diffusers)
+
+2. Download Training Datasets and Pose Pool
+
+ ```bash
+ cd datasets
+ bash setup_datasets.sh
+ ```
+
+ This will download and prepare:
+ - Training datasets (open-source + cartoon): `datasets/opensource_dataset/`
+ - Pose pool for face enhancement: `datasets/opensource_pose_pool/`
+
+
+ Manual Download Links
+
+ - [opensource_dataset](https://huggingface.co/datasets/MochunniaN1/One-to-All-sub/tree/main/opensource_dataset)
+ - [opensource_pose_pool](https://huggingface.co/datasets/MochunniaN1/One-to-All-sub/tree/main/opensource_pose_pool)
+
+
+
+3. Training
+
+ We provide three-stage training scripts:
+ * Stage 1: Reference Extractor
+
+ ```bash
+ cd video-generation
+ bash training_scripts/train1.3b_only_refextractor_2d.sh
+ # Convert checkpoint to FP32
+ cd outputs_wanx1.3b/train1.3b_only_refextractor_2d/checkpoint-xxx
+ mkdir fp32_model_xxx
+ python zero_to_fp32.py . fp32_model_xxx --safe_serialization
+ # Run inference (update model path in inference_refextractor.py first)
+ cd ../../../
+ # Edit inference_refextractor.py and change ckpt_path to:
+ # ./outputs_wanx1.3b/train1.3b_only_refextractor_2d/checkpoint-xxx/fp32_model_xxx
+ python inference_refextractor.py
+ ```
+
+ * Stage 2: Pose Control
+ ```bash
+ bash training_scripts/train1.3b_posecontrol_prefix_2d.sh
+ ```
+ * Stage 3: Token Replace for Long video generation
+ ```bash
+ bash training_scripts/train1.3b_posecontrol_prefix_2d_tokenreplace.sh
+ ```
+ > 💡 **Training Notes**:
+ > - **Each stage uses different training resolutions** - check the scripts for specific resolution settings
+ > - **Fine-tuning from our checkpoints**: If you want to continue training from our pre-trained models, directly use the *Stage 3 script* and modify the checkpoint path
+
+
+
+## 📊 Reproduce Paper Results
+
+We provide scripts to reproduce the quantitative results reported in our paper.
+
+1. Download Benchmark
+ ```bash
+ cd benchmark
+ bash setup_datasets.sh
+ ```
+2. Prepare Model Input
+ ```bash
+ cd ../video-generation
+ python reproduce/infer_preprocess.py
+ ```
+3. Run Inference
+
+ We provide inference scripts for different model sizes and datasets:
+ ```bash
+ # TikTok dataset
+ python reproduce/inference_tiktok1.3b.py # 1.3B model
+ python reproduce/inference_tiktok14b.py # 14B model
+
+ # Cartoon dataset
+ python reproduce/inference_cartoon1.3b.py # 1.3B model
+ python reproduce/inference_cartoon14b.py # 14B model
+
+4. Prepare gt/pred pairs for Judge
+ ```bash
+ cd ../benchmark
+ # TikTok dataset
+ python prepare_eval_frames_tiktok.py
+ # Cartoon dataset
+ python prepare_eval_frames_cartoon.py
+ ```
+
+5. Run judge
+ ```bash
+ # prepare DisCo environment and lpips fvd ckpt for judge
+ cd DisCo
+ # TikTok dataset
+ bash eval_tiktok.sh
+ python summary.py
+ ```
+
+
+
+## Acknowledgments
+
+Our project is based on [opensora](https://github.com/hpcaitech/Open-Sora). Some codes are brought from [StableAnimator](https://github.com/Francis-Rings/StableAnimator) and [Wan-Animate](https://github.com/Wan-Video/Wan2.2). Thanks for their awesome works.
+
+## 📝 Citation
+If you find our work helpful or inspiring, please feel free to cite it.
+
+```bibtex
+@article{shi2025one,
+ title={One-to-All Animation: Alignment-Free Character Animation and Image Pose Transfer},
+ author={Shi, Shijun and Xu, Jing and Li, Zhihang and Peng, Chunli and Yang, Xiaoda and Lu, Lijing and Hu, Kai and Zhang, Jiangning},
+ journal={arXiv preprint arXiv:2511.22940},
+ year={2025}
+}
+```
+## 📄 License
+This repository is released under the [Apache License 2.0](LICENSE).
+
+## 📧 Contact
+If you have any questions, please feel free to reach us at `ssj180123@gmail.com`
diff --git a/One-to-All-Animation/assets/1.3b_examples/combined_video1.gif b/One-to-All-Animation/assets/1.3b_examples/combined_video1.gif
new file mode 100644
index 0000000000000000000000000000000000000000..5b99c91ff902e4ca50542618efd35fdaee695d72
--- /dev/null
+++ b/One-to-All-Animation/assets/1.3b_examples/combined_video1.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:487ba3d6c6c1cecc9143ed3d8522b57aaf4b7b66f967183426c8f52c9e5f3994
+size 4244973
diff --git a/One-to-All-Animation/assets/1.3b_examples/combined_video2.gif b/One-to-All-Animation/assets/1.3b_examples/combined_video2.gif
new file mode 100644
index 0000000000000000000000000000000000000000..6d488dffb452e229210cb6c88093645255b612ad
--- /dev/null
+++ b/One-to-All-Animation/assets/1.3b_examples/combined_video2.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c8ea42da6e9950a799be78d7858f7d1af3eb065bfd263b9f7dd0e473d23ce650
+size 3022496
diff --git a/One-to-All-Animation/assets/1.3b_examples/ref3_motion1_1.3b.gif b/One-to-All-Animation/assets/1.3b_examples/ref3_motion1_1.3b.gif
new file mode 100644
index 0000000000000000000000000000000000000000..facf40c3dc31c5aff535b6ed3b24c5842dcfd0de
--- /dev/null
+++ b/One-to-All-Animation/assets/1.3b_examples/ref3_motion1_1.3b.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:ebc323fa945867c1bee235c9323464841ea0a0ed739ec1e41fe856c00fcf3246
+size 4052382
diff --git a/One-to-All-Animation/assets/1.3b_examples/ref3_motion2_1.3b.gif b/One-to-All-Animation/assets/1.3b_examples/ref3_motion2_1.3b.gif
new file mode 100644
index 0000000000000000000000000000000000000000..ea0c80d48c156e7cc96d880c6de3060ce2420a42
--- /dev/null
+++ b/One-to-All-Animation/assets/1.3b_examples/ref3_motion2_1.3b.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:96794e244c648f7056512afc5a768a1b0c0e5baa48e80155250e52d1191d4450
+size 6757753
diff --git a/One-to-All-Animation/assets/1.3b_examples/ref3_motion3_1.3b.gif b/One-to-All-Animation/assets/1.3b_examples/ref3_motion3_1.3b.gif
new file mode 100644
index 0000000000000000000000000000000000000000..3fea18e98d414d1ccd5c451efd9870a4e639331e
--- /dev/null
+++ b/One-to-All-Animation/assets/1.3b_examples/ref3_motion3_1.3b.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3349b0bf3532a26991ea1a3b884c156320c64b6f982bbaf727d9d5761800d4a5
+size 4973294
diff --git a/One-to-All-Animation/assets/14b_examples/ref_1_motion1.gif b/One-to-All-Animation/assets/14b_examples/ref_1_motion1.gif
new file mode 100644
index 0000000000000000000000000000000000000000..a7f78e129d58558eb018662ef880188ce0ff5c01
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_1_motion1.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:8a5fcf5f2e35bcd10bfdaf31ff302a8dcd74c44bbb92db971d4b86f1c57c01c8
+size 4115233
diff --git a/One-to-All-Animation/assets/14b_examples/ref_1_motion2.gif b/One-to-All-Animation/assets/14b_examples/ref_1_motion2.gif
new file mode 100644
index 0000000000000000000000000000000000000000..e45d685ea985216ee34d7e5e77c8006860df98a6
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_1_motion2.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:c47bcde2ac8be5302d3ffa392dc21ba795212546afa44b8480ddb1670d26dab6
+size 6961611
diff --git a/One-to-All-Animation/assets/14b_examples/ref_1_motion3.gif b/One-to-All-Animation/assets/14b_examples/ref_1_motion3.gif
new file mode 100644
index 0000000000000000000000000000000000000000..c1d34a32da8714b8c492834054f300593fc4bd99
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_1_motion3.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:2b906b415cef7da4750dae4a8b24b0e119caaa640b089c1d4cc8d7a6cbf41c14
+size 5009624
diff --git a/One-to-All-Animation/assets/14b_examples/ref_2_motion1.gif b/One-to-All-Animation/assets/14b_examples/ref_2_motion1.gif
new file mode 100644
index 0000000000000000000000000000000000000000..486406772fc48c9017d328a1d179bd5a21cb7c34
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_2_motion1.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:886d569704ddc2b2d8c078c9ba4c475dae36176a4d28220eb0e59e898fe76c6b
+size 3220342
diff --git a/One-to-All-Animation/assets/14b_examples/ref_2_motion2.gif b/One-to-All-Animation/assets/14b_examples/ref_2_motion2.gif
new file mode 100644
index 0000000000000000000000000000000000000000..e0e3d3dd11c588d908f79e566a72e531357f02a1
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_2_motion2.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:1a110deda30864c3da83620adb17a882938945650f241aa8853efb31063028da
+size 5419208
diff --git a/One-to-All-Animation/assets/14b_examples/ref_2_motion3.gif b/One-to-All-Animation/assets/14b_examples/ref_2_motion3.gif
new file mode 100644
index 0000000000000000000000000000000000000000..d4ca6205bdae521e76187bbcd205be4be95124a2
--- /dev/null
+++ b/One-to-All-Animation/assets/14b_examples/ref_2_motion3.gif
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b624d7ab4e9d8fd1e755b20a37ab24522673003f62a3354184544ceb5ae0969d
+size 3834533
diff --git a/One-to-All-Animation/benchmark/DisCo/.gitignore b/One-to-All-Animation/benchmark/DisCo/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..095abd39d4535f4bd2e9ff02d30ea0bc90de0dff
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/.gitignore
@@ -0,0 +1,74 @@
+aux_data
+azcopy
+vis_temp
+.amltconfig
+*.pt
+scripts/webvid_train_filelist.*
+scripts/webvid_val_filelist.*
+tool/ori.png
+tool/gt.jpg
+src/taming-transformers
+src/clip
+.vscode
+xiyin_datasets
+tiktok_datasets
+blob_dir
+blob
+.amltconfig
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+ C extensions
+*.so
+
+# Distribution / packaging
+bin/
+build/
+develop-eggs/
+dist/
+eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+*.egg-info/
+.installed.cfg
+*.egg
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+.tox/
+.coverage
+.cache
+nosetests.xml
+coverage.xml
+
+# Translations
+*.mo
+
+# Mr Developer
+.mr.developer.cfg
+.project
+.pydevproject
+
+# Rope
+.ropeproject
+
+# Django stuff:
+*.log
+*.pot
+
+# Sphinx documentation
+docs/_build/
+
+# dirs
+/save_results
+/pretrain_model
+/command
+/cocoapi
+debug.sh
diff --git a/One-to-All-Animation/benchmark/DisCo/LICENSE b/One-to-All-Animation/benchmark/DisCo/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/benchmark/DisCo/PREPRO.md b/One-to-All-Animation/benchmark/DisCo/PREPRO.md
new file mode 100644
index 0000000000000000000000000000000000000000..3cc14bd6b549966eabfd9f5153ce3e8a56e773d2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/PREPRO.md
@@ -0,0 +1,107 @@
+Here we provide the scripts for reference to automatically process the foreground mask and generate the human skeleton.
+
+The target dataset which need to be processed should be like:
+
+```
+Target Dataset
+└── 001/
+ ├── 0000.png
+ └── 0001.png
+ ...
+└── 002/
+ ├── 0000.png
+ └── 0001.png
+ ...
+```
+
+
+
+### Grounded-SAM
+
+#### Installation
+
+```
+# 1. Follow the official repo (https://github.com/IDEA-Research/Grounded-Segment-Anything) for package installation
+
+# 2. download the pre-trained weights
+wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
+wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
+```
+
+#### Run
+
+```
+python ./annotator/grounded-sam/run.py --dataset_root /path/to/target/dataset
+```
+
+
+
+
+
+### OpenPose
+
+#### Installation
+
+```
+# 1. Follow the pytorch-openpose repo (https://github.com/Hzzone/pytorch-openpose) for package installation
+
+# 2. download the pre-trained weights
+wget -O body_pose_model.pth https://www.dropbox.com/sh/7xbup2qsn7vvjxo/AABaYNMvvNVFRWqyDXl7KQUxa/body_pose_model.pth?dl=1
+```
+
+#### Run
+
+```
+python ./annotator/openpose/run.py --dataset_root /path/to/target/dataset
+```
+
+
+
+
+
+### TSV preparation
+
+After running Grounded SAM and OpenPose, prepare the data structured as below:
+
+```
+Target Dataset
+└── 001/
+ ├── 0000.png
+ ├── 0001.png
+ ├── ...
+ ├────── groundsam
+ | ├── 000001.png.mask.jpg
+ | ├── 000002.png.mask.jpg
+ | └── ...
+ └────── openpose_json
+ ├── 000001.png.json
+ ├── 000002.png.json
+ └── ...
+└── 002/
+ ├── 0000.png
+ ├── 0001.png
+ ├── ...
+ ├────── groundsam
+ | ├── 000001.png.mask.jpg
+ | ├── 000002.png.mask.jpg
+ | └── ...
+ └────── openpose_json
+ ├── 000001.png.json
+ ├── 000002.png.json
+ └── ...
+```
+
+We also provide a preprocessed toy dataset as example. You may find the example dataset in folder `./tsv_example/toy_dataset`
+
+Run the following script to convert your dataset to tsv format
+
+```
+python ./tsv_example/create_custom_dataset_tsvs.py --split train --root_folder PATH_TO_YOUR_DATASET_FOLDER --output_folder PATH_TO_DESIRED_FOLDER
+```
+
+For instance, `PATH_TO_YOUR_DATASET_FOLDER=./tsv_example/toy_dataset` and `PATH_TO_DESIRED_FOLDER=./tsv_example/toy_dataset/tsv`
+
+
+### TSV visualization
+
+Once the tsv files are generated, we provide a jupyter notebook for data visualization. Please refer to `visualize_tsv.ipynb` for details.
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/README.md b/One-to-All-Animation/benchmark/DisCo/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..ae1ae7e758ac25cb91aaba9515b3ab4b23c17d04
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/README.md
@@ -0,0 +1,426 @@
+# DisCo: Disentangled Control for Realistic Human Dance Generation
+
+
[](https://colab.research.google.com/drive/1dErsSwSEdcAyP6V_mqayW0qdPuoHSz-j?usp=sharing) [](https://youtu.be/D_mPPjUCDjE)
+
+[Tan Wang*](https://wangt-cn.github.io/), [Linjie Li*](https://scholar.google.com/citations?user=WR875gYAAAAJ&hl=en), [Kevin Lin*](https://scholar.google.com/citations?hl=en&user=LKSy1kwAAAAJ), [Yuanhao Zhai](https://www.yhzhai.com/), [Chung-Ching Lin](https://scholar.google.com/citations?hl=en&user=legkbM0AAAAJ), [Zhengyuan Yang](https://scholar.google.com/citations?hl=en&user=rP02ve8AAAAJ), [Hanwang Zhang](https://scholar.google.com/citations?hl=en&user=YG0DFyYAAAAJ), [Zicheng Liu](https://scholar.google.com/citations?hl=en&user=bkALdvsAAAAJ), [Lijuan Wang](https://scholar.google.com/citations?hl=en&user=cDcWXuIAAAAJ)
+
+**Nanyang Technological University | Microsoft Azure AI | University at Buffalo**
+
+[](https://youtu.be/D_mPPjUCDjE "DisCo: Disentangled Control for Referring Human Dance Generation in Real World")
+
+
+
+## :fire: News
+* **[2024.07.15]** We present [IDOL](https://yhzhai.github.io/idol/), an enhancement of DisCo that simultaneously generates video and depth, enabling realistic 2.5D video synthesis.
+* **[2024.04.08]** DisCo has been accepted by CVPR24. Please check the latest version of paper on [ArXiv](https://arxiv.org/abs/2307.00040).
+* **[2023.12.30]** Update [slides](https://drive.google.com/file/d/1AlN3Thg46RlH5uhLK-ZAIivo-C8IJeif/view?usp=sharing) about introducing DisCo and summarizing recent works.
+* **[2023.11.30]** Update DisCo w/ temporal module.
+* **[2023.10.12]** Update the new ArXiv version of DisCo (Add temporal module; Synchronize FVD computation with MCVD; More baselines and visualizations, etc)
+* **[2023.07.21]** Update the [construction guide](https://github.com/Wangt-CN/DisCo/blob/main/PREPRO.md) of the TSV file.
+* **[2023.07.08]** Update the [Colab](https://colab.research.google.com/drive/1dErsSwSEdcAyP6V_mqayW0qdPuoHSz-j?usp=sharing) Demo (make sure our code/demo can be run on any machine)!
+* **[2023.07.03]** Provide the local demo deployment [example code](https://github.com/Wangt-CN/DisCo#-demo). Now you can try our demo on you own dev machine!
+* **[2023.07.03]** We update the Pre-training [tsv data](https://github.com/Wangt-CN/DisCo#1-human-attribute-pre-training).
+* **[2023.06.28]** We have released DisCo Human Attribute Pre-training Code.
+* **[2023.06.21]** DisCo Human Image Editing [Demo](https://b9652ca65fb3fab63a.gradio.live/) is released! Have a try!
+* **[2023.06.21]** We release the human-specific fine-tuning [code](https://github.com/Wangt-CN/DisCo#human-specific-fine-tuning) for reference. Come and build your own specific dance model!
+* **[2023.06.21]** Release the code for [general fine-tuning](https://github.com/Wangt-CN/DisCo#fine-tuning-with-disentangled-control).
+* **[2023.06.21]** We release the human attribute pre-trained checkpoint and the fine-tuning checkpoint.
+
+
+
+
+
+##### Other following projects you may find interesting:
+
+
+* [Animate Anyone](https://arxiv.org/abs/2311.17117), from Alibaba
+* [MagicAnimate](https://arxiv.org/abs/2311.16498), from TikTok
+* [MagicDance](https://arxiv.org/abs/2311.12052), from TikTok
+
+
+##### Comparison of recent works:
+
+
+
+
+
+## 🎨 Gradio Demo
+
+#### Launch Demo Locally (Video dance generation demo is on the way!)
+
+1. Download the fine-tuning checkpoint [model](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/EpEPp_6rFtFComv49I0bkKkBfqiJhFnbraiZSN0LjXpzHw) (our demo uses this [checkpoint](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/En3vpzKndr1OoBUoDhTCZvEBorQiXEhJzi6mYWNELVWnpg?e=AIrGlx), you can also use your own model); Download the [sd-image-variation](https://huggingface.co/lambdalabs/sd-image-variations-diffusers) via `git clone https://huggingface.co/lambdalabs/sd-image-variations-diffusers`.
+
+2. Run the [jupyter notebook](https://github.com/Wangt-CN/DisCo/blob/main/human_img_edit_gradio.ipynb) file. All the required code/command are already set up. Remember to revise the pretrained model path `--pretrained_model` and `--pretrained_model_path (sd-va)` in `manual_args = [xxx]`.
+
+3. After running, this jupyter will automatically launch the demo with your local dev GPU. You can visit the demo with the web link provided at the end of the notebook.
+
+4. Or you can refer to our deployment with Colab [](https://colab.research.google.com/drive/1dErsSwSEdcAyP6V_mqayW0qdPuoHSz-j?usp=sharing). All the code are deployed from scratch!
+
+
+
+##### [[Online Gradio Demo]](https://b9652ca65fb3fab63a.gradio.live/) (Temporal)
+
+
+
+
+
+
+
+
+
+
+## 📝 Introduction
+
+In this project, we introduce **DisCo** as a generalized referring human dance generation toolkit, which supports both **human image & video generation** with **multiple usage cases** (pre-training, fine-tuning, and human-specific fine-tuning), especially good in real-world scenarios.
+
+
+
+#### ✨Compared to existing works, DisCo achieves:
+
+- **Generalizability** to a large-scale real-world human **without human-specific fine-tuning** (We also support [human-specific fine-tuning](https://github.com/Wangt-CN/DisCo#human-specific-fine-tuning)). Previous methods only support generation for a specific domain of human, e.g., [DreamPose](https://github.com/johannakarras/DreamPose) only generate fashion model with easy catwalk pose.
+
+- Current **SOTA results** for referring human dance generation.
+
+- Extensive usage cases and applications (see [project page](https://disco-dance.github.io/index.html) for more details).
+
+- An easy-to-follow framework, supporting **efficient training** (x-formers, FP16 training, deepspeed, wandb) and **a wide range of possible research directions** (pre-training -> fine-tuning -> human-specific fine-tuning).
+
+
+
+#### 🌟With this project, you can get:
+
+- *\[User\]*: Just try our online demo! Or deploy the model inference locally.
+- *\[Researcher\]*: An easy-to-use codebase for re-implementation and development.
+- *\[Researcher\]*: A large amount of research directions for further improvement.
+
+
+
+
+
+## 🚀 Getting Started
+
+### Installation
+
+```sh
+## after py3.8 env initialization
+pip install --user torch==1.12.1+cu113 torchvision==0.13.1+cu113 -f https://download.pytorch.org/whl/torch_stable.html
+pip install --user progressbar psutil pymongo simplejson yacs boto3 pyyaml ete3 easydict deprecated future django orderedset python-magic datasets h5py omegaconf einops ipdb
+pip install --user --exists-action w -r requirements.txt
+pip install git+https://github.com/microsoft/azfuse.git
+
+
+## for acceleration
+pip install --user deepspeed==0.6.3
+pip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers
+
+## you may need to downgrade prototbuf to 3.20.x
+pip install protobuf==3.20.0
+```
+
+
+
+### Data Preparation
+
+##### 1. Human Attribute Pre-training
+
+We create a human image subset (700K Images) filtered from existing image corpus for human attribute pre-training:
+
+| Dataset | COCO (Single Person) | TikTok Style | DeepFashion2 | SHHQ-1.0 | LAION-Human |
+| -------- | :------------------: | :----------: | :----------: | :------: | :---------: |
+| **Size** | 20K | 124K | 276K | 40K | 240K |
+
+The pre-processed pre-training data with the efficient TSV data format can be downloaded [**here (Google Drive)**](https://drive.google.com/file/d/1N9gioWnkb3ZZytmT3Nzx4VjXjHxLsVB9/view?usp=sharing).
+
+```
+Data Root
+└── composite/
+ ├── train_xxx.yaml # The path need to be then specified in the training args
+ └── val_xxx.yaml
+ ...
+└── TikTokDance/
+ ├── xxx_images.tsv
+ └── xxx_poses.tsv
+ ...
+└── coco/
+ ├── xxx_images.tsv
+ └── xxx_poses.tsv
+```
+
+
+
+##### 2. Fine-tuning with Disentangled Control
+
+We use the [TikTok dataset](https://www.yasamin.page/hdnet_tiktok) for the fine-tuning.
+
+We have already pre-processed the tiktok data with the efficient TSV format which can be downloaded **[here (Google Drive)](https://drive.google.com/file/d/1_b4naNB1QozGL-tKyHwSSYzTw8RIh5z3/view?usp=sharing)**. (Note that we only use the 1st frame of each TikTok video as the reference image.)
+
+The data folder structure should be like:
+
+```
+Data Root
+└── composite_offset/
+ ├── train_xxx.yaml # The path need to be then specified in the training args
+ └── val_xxx.yaml
+ ...
+└── TikTokDance/
+ ├── xxx_images.tsv
+ └── xxx_poses.tsv
+ ...
+```
+
+*PS: If you want to use your own data resource but with our TSV data structure, please follow [PREPRO.MD](https://github.com/Wangt-CN/DisCo/blob/main/PREPRO.md) for reference.
+
+
+
+
+
+### Human Attribute Pre-training
+
+
+
+
+
+
+**Training:**
+
+```
+AZFUSE_USE_FUSE=0 QD_USE_LINEIDX_8B=0 NCCL_ASYNC_ERROR_HANDLING=0 python finetune_sdm_yaml.py --cf config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv_strongrand.py --do_train --root_dir /home1/wangtan/code/ms_internship2/github_repo/run_test \
+--local_train_batch_size 64 --local_eval_batch_size 64 --log_dir exp/tiktok_pretrain \
+--epochs 40 --deepspeed --eval_step 2000 --save_step 2000 --gradient_accumulate_steps 1 \
+--learning_rate 1e-3 --fix_dist_seed --loss_target "noise" \
+--train_yaml ./blob_dir/debug_output/video_sythesis/dataset/composite/train_TiktokDance-coco-single_person-Lindsey_0411_youtube-SHHQ-1.0-deepfashion2-laion_human-masks-single_cap.yaml --val_yaml ./blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-coco-single_person-SHHQ-1.0-masks-single_cap.yaml \
+--unet_unfreeze_type "transblocks" --refer_sdvae --ref_null_caption False --combine_clip_local --combine_use_mask \
+--conds "masks" --max_eval_samples 2000 --strong_aug_stage1 --node_split_sampler 0
+```
+
+
+
+**Pre-trained Model Checkpoint: [OneDrive](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/EoH8KHplKPhGrIdKN6sPx_ABpurpPjNAvU3KdFgaPwNfJQ)**
+
+
+
+
+### Fine-tuning with Disentangled Control
+
+
+
+
+
+
+
+
+
+#### 1. Modify the config file
+
+Download the `sd-image-variations-diffusers` from official [diffusers repo](https://huggingface.co/lambdalabs/sd-image-variations-diffusers) and put it according to the config file `pretrained_model_path`. Or you can also choose to modify the `pretrained_model_path`.
+
+
+
+
+
+#### 2. w/o Classifier-Free Guidance (CFG)
+
+**Training:**
+
+[*To enable WANDB, set up the wandb key in `utils/lib.py`]
+
+[*To employ **multiple GPU running**, try to add `mpirun -np {GPU NUM}` before the `python`.]
+
+```shell
+WANDB_ENABLE=0 AZFUSE_USE_FUSE=0 NCCL_ASYNC_ERROR_HANDLING=0 mpirun -np 8 python finetune_sdm_yaml.py --cf config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py \
+--do_train --root_dir /home1/wangtan/code/ms_internship2/github_repo/run_test \
+--local_train_batch_size 32 \
+--local_eval_batch_size 32 \
+--log_dir exp/tiktok_ft \
+--epochs 20 --deepspeed \
+--eval_step 500 --save_step 500 \
+--gradient_accumulate_steps 1 \
+--learning_rate 2e-4 --fix_dist_seed --loss_target "noise" \
+--train_yaml /home/wangtan/data/disco/yaml_file/train_TiktokDance-poses-masks.yaml \
+--val_yaml /home/wangtan/data/disco/yaml_file/new10val_TiktokDance-poses-masks.yaml \
+--unet_unfreeze_type "all" \
+--guidance_scale 3 \
+--refer_sdvae \
+--ref_null_caption False \
+--combine_clip_local --combine_use_mask \
+--conds "poses" "masks" \
+--stage1_pretrain_path /path/to/pretrained_model_checkpoint/mp_rank_00_model_states.pt
+```
+
+
+
+
+
+**Visualization:**
+
+To run the visualization, just change `--do_train` to `--eval_visu` . You can also specify the visualization folder name with `'--eval_save_filename' xxx`.
+
+
+
+**Evaluation:**
+
+You first need to run the evaluation to get the results. Then we use `gen_eval.sh` to one-stop get the evaluation metrics for {exp_dir_path}/{prediction_folder_name}
+
+```shell
+bash gen_eval.sh {exp_dir_path} {exp_dir_path}/{prediction_folder_name}
+```
+For example,
+```
+bash gen_eval.sh /home/kevintw/code/disco/github2/DisCo/save_results/TikTok_cfg_check /home/kevintw/code/disco/github2/DisCo/save_results/TikTok_cfg_check/pred_gs1.5_scale-cond1.0-ref1.0/
+```
+
+You may need to download the [pre-trained vision model](https://drive.google.com/file/d/1J8w3fGj6H6kmcW9G8Ff6tRQofblaG5Vn/view?usp=sharing) and revise the path in `gen_eval.sh` for achieving fvd metric.
+
+##### Model Checkpoint (OneDrive): [TikTok Training Data](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/Em8tYZ_J_51On_cMQDtOpqoBRG9H3tZNd2Mm48DFh3sypA?e=cyBgJQ) | [More TikTok-Style Training Data](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/En3vpzKndr1OoBUoDhTCZvEBorQiXEhJzi6mYWNELVWnpg?e=AIrGlx)
+
+
+
+
+
+
+
+#### 3. w/ Classifier-Free Guidance (CFG) [CFG can bring a slightly better results]
+
+**Training (add the following args into the training script of w/o CFG):**
+
+```
+--drop_ref 0.05 # probability to dropout the reference image during training
+--guidance_scale 1.5 # the scale of the CFG
+```
+
+**Visualization:**
+
+To run the visualization, just change `--do_train` to `--eval_visu` . You can also specify the visualization folder name with `'--eval_save_filename' xxx`. (Remember to also specify the `--guidance_scale`)
+
+You can also check our command bash file `config/command_bash/tiktok_cfg.sh` for reference.
+
+
+**Evaluation:**
+
+Same with above
+
+
+
+##### Model Checkpoint (OneDrive): [TikTok Training Data](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/EpJSOWGzrnlNn99nC691G8wBF-JnbuYCbgbHMRg6TQFAxg?e=QUJJOL) | [More TikTok-Style Training Data](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/EiDYzx84T8pMhrDtcoIU5w0By9ysDotKzmezShKkX8aE4g?e=zzLuEA)
+
+
+
+#### 4. Temporal module fine-tuning
+**Training:**
+After training the image DisCo model, we further incorporate temporal convolutional layers and temporal attention layers to improve the temporal smoothness. Note that the content for argument `--pretrained_model` should be the image DisCo model checkpoint, instead of stage 1 pre-trained checkpoint.
+```shell
+AZFUSE_USE_FUSE=0 NCCL_ASYNC_ERROR_HANDLING=0 python finetune_sdm_yaml.py --cf config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv_temdisco_temp_attn.py \
+--do_train --root_dir /home1/wangtan/code/ms_internship2/github_repo/run_test \
+--local_train_batch_size 2 \
+--local_eval_batch_size 2 \
+--log_dir exp/tiktok_ft \
+--epochs 20 --deepspeed \
+--eval_step 500 --save_step 500 \
+--gradient_accumulate_steps 1 \
+--learning_rate 1e-4 --fix_dist_seed --loss_target "noise" \
+--train_yaml /home/wangtan/data/disco/yaml_file/train_TiktokDance-poses-masks.yaml \
+--val_yaml /home/wangtan/data/disco/yaml_file/new10val_TiktokDance-poses-masks.yaml \
+--unet_unfreeze_type "all" \
+--refer_sdvae \
+--ref_null_caption False \
+--combine_clip_local --combine_use_mask \
+--train_sample_interval 4 \
+--nframe 16 \
+--frame_interval 1 \
+--conds "poses" "masks" \
+--pretrained_model /path/to/pretrained_model/mp_rank_00_model_states.pt
+```
+
+**Evaluation:**
+Simply replace the previous `gen_eval.sh` script with the `gen_eval_tm.sh` script, as follows. GT folder path will be filled in automatically.
+
+```shell
+bash gen_eval_tm.sh {exp_dir_path} {exp_dir_path}/{prediction_folder_name}
+```
+
+##### Model checkpoint: [TikTok training data (w/ CFG)](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/Er5Ch49FzUdHpfBiZy3uN3cB87Zq8g4c9idEEzESdEy0qg?e=R3W7ij) | [More TikTok-Style Training Data (w/ CFG)](https://entuedu-my.sharepoint.com/:f:/g/personal/tan317_e_ntu_edu_sg/Evp1AG1ExZBIni78RIH2bMUBmg-orFvvIAPcfnGQ_lCZGQ?e=nTr0ci)
+
+
+
+#### 5. Possible issue for FVD metric reproduction
+
+Please first check the github issue and response [here](https://github.com/Wangt-CN/DisCo/issues/25#issuecomment-1716394151). We have validated the checkpoint results on A100 GPU. If you still cannot reproduce the results, please open an issue or send me the email.
+
+
+
+### Human-Specific Fine-tuning
+
+
+
+
+
+#### 1. Prepare dataset that you want to use for training
+
+- Prepare a human-specific video or a set of human images
+
+- Use Grounded-SAM and OpenPose to obtain human mask and human skeleton for each training image (See [PREPRO.MD](https://github.com/Wangt-CN/DisCo/blob/main/PREPRO.md) for more details)
+
+- For human-specific fine-tuning, we recommend to directly use raw image/mask/pose for training rather than build TSV file. If you still want to use TSV file structure to prepare your data, please follow [PREPRO.MD](https://github.com/Wangt-CN/DisCo/blob/main/PREPRO.md) for reference.
+
+
+
+#### 2. Run the following script for human-specific fine-tuning:
+
+For parameter tuning, recommend to first tune the `learning-rate` and `unet_unfreeze_type`.
+
+```python
+AZFUSE_USE_FUSE=0 NCCL_ASYNC_ERROR_HANDLING=0 python finetune_sdm_yaml.py \
+--cf config/ref_attn_clip_combine_controlnet_imgspecific_ft/webtan_S256L16_xformers_upsquare.py --do_train --root_dir /path/of/saving/root \
+--local_train_batch_size 32 --local_eval_batch_size 32 --log_dir exp/human_specific_ft/ \
+--epochs 20 --deepspeed --eval_step 500 --save_step 500 --gradient_accumulate_steps 1 \
+--learning_rate 1e-3 --fix_dist_seed --loss_target "noise" \
+--unet_unfreeze_type "crossattn" \
+--refer_sdvae --ref_null_caption False --combine_clip_local --combine_use_mask --conds "poses" "masks" \
+--freeze_pose True --freeze_background False \
+--pretrained_model /path/to/the/ft_model_checkpoint \
+--ft_iters 500 --ft_one_ref_image False --ft_idx dataset/folder/name --strong_aug_stage1 True --strong_rand_stage2 True
+```
+
+
+## Notes
+
+#### 1. Possible issue for FVD metric reproduction
+
+Please first check the github issue and response [here](https://github.com/Wangt-CN/DisCo/issues/25#issuecomment-1716394151). We have validated the checkpoint results on A100 GPU. If you still cannot reproduce the results, please open an issue or send me the email.
+
+#### 2. PSNR metric
+
+We thank @Delicious-Bitter-Melon for for highlighting a potential numerical overflow issue in the implementation of the PSNR metric. This issue has been resolved in codebase, and the updated score is reflected in our latest version. It's important to note that this correction does not alter the trend or affect the overall conclusions.
+
+#### 3. DisCo is not limited to upper-human.
+
+Please check our latest paper for its generalizability. It can be easily achieved by incorporating extensive image scaling augmentations during the training phase.
+
+
+
+
+## Release Plan
+
+- [x] Code for "Fine-tuning with Disentangled Control"
+- [x] Code for "Human-Specific Fine-tuning"
+- [x] Model Checkpoints for Pre-training and Fine-tuning
+- [x] HuggingFace Demo
+- [x] Code for "Human Attribute Pre-training"
+
+
+
+
+
+## Citation
+
+If you use our work in your research, please cite:
+
+```
+@article{wang2023disco,
+ title={Disco: Disentangled control for realistic human dance generation},
+ author={Wang, Tan and Li, Linjie and Lin, Kevin and Zhai, Yuanhao and Lin, Chung-Ching and Yang, Zhengyuan and Zhang, Hanwang and Liu, Zicheng and Wang, Lijuan},
+ journal={arXiv preprint arXiv:2307.00040},
+ year={2023}
+}
+```
+
diff --git a/One-to-All-Animation/benchmark/DisCo/agent.py b/One-to-All-Animation/benchmark/DisCo/agent.py
new file mode 100644
index 0000000000000000000000000000000000000000..ca4301482402bfa9c728a9ab403cb83179eb8a6d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/agent.py
@@ -0,0 +1,1302 @@
+from utils.lib import *
+from utils.dist import (
+ is_main_process, get_world_size,
+ reduce_dict, get_local_rank, synchronize,
+ get_rank,)
+from utils.metric_logger import log_dict_to_wandb, setup_wandb, log_img_to_wandb
+from utils.misc import humanbytes
+from utils.deepspeed import get_deepspeed_config, fp32_to_fp16
+import deepspeed
+from torch import nn
+import torch.nn.functional as F
+from utils.basic_utils import move_to_cuda
+from utils.common import ensure_directory
+from utils.wutils_ldm import (
+ complex_to_device, logger, ensure_dirname, file2data, data2file,
+ Meter, Timer, adaptively_load_state_dict, get_parameters, ldm_tensor2img_wt, ldm_tensor2img)
+import wandb
+
+
+class WarmupLinearLR(T.optim.lr_scheduler._LRScheduler):
+ def __init__(
+ self,
+ optimizer,
+ max_iter,
+ min_lr=1e-8,
+ warmup_ratio=0.1,
+ last_epoch=-1,
+ ):
+ self.max_iter = max_iter
+ self.min_lr = min_lr
+ self.warmup_ratio = warmup_ratio
+ self.warmup_iters = int(warmup_ratio*max_iter)
+ super(WarmupLinearLR, self).__init__(optimizer, last_epoch)
+
+ def get_lr_factor(self):
+ tot_step = self.max_iter
+ warmup_step = self.warmup_iters
+ step = self.last_epoch
+ if step < warmup_step:
+ return max(0, step / warmup_step)
+ elif step > tot_step:
+ step = tot_step
+ return max(0, (tot_step-step)/(tot_step-warmup_step))
+
+ def get_lr(self):
+ warmup_factor = self.get_lr_factor()
+ return [
+ max(self.min_lr, base_lr * warmup_factor)
+ for base_lr in self.base_lrs
+ ]
+
+
+class WarmupLinearConstantLR(T.optim.lr_scheduler._LRScheduler):
+ def __init__(
+ self,
+ optimizer,
+ max_iter,
+ min_lr=1e-8,
+ warmup_ratio=0.1,
+ last_epoch=-1,
+ ):
+ self.max_iter = max_iter
+ self.min_lr = min_lr
+ self.warmup_ratio = warmup_ratio
+ self.warmup_iters = int(warmup_ratio*max_iter)
+ super(WarmupLinearConstantLR, self).__init__(optimizer, last_epoch)
+
+ def get_lr_factor(self):
+ tot_step = self.max_iter
+ warmup_step = self.warmup_iters
+ step = self.last_epoch
+ if step < warmup_step:
+ return max(0, step / warmup_step)
+ elif step >= warmup_step:
+ return 1. # constant base lr
+
+ def get_lr(self):
+ warmup_factor = self.get_lr_factor()
+ return [
+ max(self.min_lr, base_lr * warmup_factor)
+ for base_lr in self.base_lrs
+ ]
+
+
+class Agent():
+ def __init__(self, args, model=None, optimizer=None, scheduler=None):
+ super().__init__()
+ self.args, self.model = args, model
+ self.log_dir = args.log_dir
+ if optimizer is None:
+ if self.args.do_train:
+ logger.warning("Missing optimizer, check if its intended to train without optimizer")
+ self.optimizer = optimizer
+ if scheduler is None:
+ if self.args.do_train:
+ logger.warning("Missing scheduler, check if its intended to train without scheduler")
+ self.scheduler = scheduler
+
+ self.pretrained_model = self.args.pretrained_model
+ # Load Pretrained Models.
+ if self.pretrained_model:
+ if not self.args.deepspeed:
+ self.from_pretrained(self.pretrained_model)
+ # else:
+ # if not os.path.exists(self.pretrained_model + "/latest"):
+ # logger.warning(
+ # f"Pretrained deepspeed checkpoint path does not exists, {self.pretrained_model + '/latest'}")
+ self.scaler = T.cuda.amp.GradScaler()
+ self.local_rank = get_local_rank()
+ self.rank = get_rank()
+
+ self.enable_collect = True
+ if is_main_process:
+ ensure_directory(self.log_dir)
+ self.metric_filename = os.path.join(self.log_dir, 'metric.json')
+ self.last_checkpoint_filename = 'last.pth'
+ # self.best_checkpoint_filename = 'best.pth'
+ # self.each_checkpoint_filename = 'epoch%s.pth'
+ self.epoch = -1
+ self.global_step = -1
+
+ if self.args.n_gpu == 0:
+ logger.warning("No support on CPU")
+ self.device = T.device("cuda")
+
+ self.debug_dataloader = getattr(args, 'debug_dataloader', False)
+
+ def setup_wandb(self):
+ if WANDB_ENABLE and not self.args.debug:
+ setup_wandb(self.args, project=self.args.wandb_project,
+ name=self.args.project_name)
+
+ def log_dict_to_wandb(self, log_dict, step=-1):
+ if WANDB_ENABLE and not self.args.debug:
+ if step == -1:
+ step = self.global_step
+ log_dict_to_wandb(log_dict, step)
+
+ def log_img_to_wandb(self, label_imgs, cond_imgs, ref_imgs, pred_imgs, step=-1, prefix=''):
+ if WANDB_ENABLE and not self.args.debug:
+ if step == -1:
+ step = self.global_step
+ img_dict = defaultdict(list)
+
+ for i in range(len(pred_imgs)):
+ img_dict[f"{prefix}_pred_img"].append(wandb.Image(ldm_tensor2img(pred_imgs[i])))
+ if label_imgs is not None:
+ img_dict[f"{prefix}_label_img"].append(wandb.Image(ldm_tensor2img(label_imgs[i], preprocess=True)))
+ if cond_imgs is not None:
+ img_dict[f"{prefix}_cond_img"].append(wandb.Image(ldm_tensor2img(cond_imgs[i])))
+ if ref_imgs is not None:
+ img_dict[f"{prefix}_ref_img"].append(wandb.Image(ldm_tensor2img(ref_imgs[i], preprocess=True)))
+ log_img_to_wandb(img_dict, step)
+
+ def update_metric_file(self, metric):
+ if os.path.exists(self.metric_filename):
+ r = file2data(self.metric_filename, printable=False)
+ data2file(dict(r, **metric), self.metric_filename, override=True)
+ else:
+ data2file(metric, self.metric_filename)
+
+ def reduce_dict(self, data):
+ return reduce_dict(data)
+
+ def reduce_mean(self, v):
+ world_size = get_world_size()
+ if world_size < 2:
+ return v
+ else:
+ v = T.tensor(v).cuda()
+ DIST.all_reduce(v)
+ v = v.item() / world_size
+ return v
+
+ def move_model_to_cuda(self):
+ if self.debug_dataloader: # debug only, ugly workaround to run on local small gpu servers
+ return
+ self.model.to(self.device)
+ if self.optimizer is not None:
+ if isinstance(self.optimizer, list):
+ for i in range(len(self.optimizer)):
+ self.optimizer[i].load_state_dict(
+ complex_to_device(self.optimizer[i].state_dict(), device=self.device))
+ else:
+ self.optimizer.load_state_dict(
+ complex_to_device(self.optimizer.state_dict(), device=self.device))
+
+ def prepare_dist_model(self):
+ if not self.args.dist:
+ logger.info('Successfully built models with %s parameters' % get_parameters(self.model))
+ return
+ if self.args.deepspeed:
+ if isinstance(self.optimizer, list):
+ raise ValueError("A list of optimizers are not supported with deepspeed, or IDK how to make it work with deepspeed")
+ config = get_deepspeed_config(self.args)
+
+ if self.pretrained_model and not self.pretrained_model.endswith(".pth"):
+ print('Specify the load model path, not use deepspeed but the pytorch original load func')
+ self.load_checkpoint_for_deepspeed_diff_gpu(self.pretrained_model) # load pt model with default pytorch
+
+ self.model, self.optimizer, _, _ = deepspeed.initialize(
+ config_params=config,
+ model=self.model,
+ optimizer=self.optimizer,
+ lr_scheduler=self.scheduler)
+
+ if self.pretrained_model and self.pretrained_model.endswith(".pth"):
+ logger.warning(f'Loading pre-trained model from {self.pretrained_model}')
+ tag = self.pretrained_model.split("/")[-1]
+ dir_ = self.pretrained_model.replace(tag, "")
+ self.model.load_checkpoint(
+ dir_, tag=tag,
+ load_optimizer_states=False,
+ load_lr_scheduler_states=False,
+ load_module_only=True,
+ load_module_strict=False)
+
+ if self.args.resume:
+ if os.path.exists(os.path.join(self.log_dir, "latest")):
+ logger.warning(f'Resuming.... from {os.path.join(self.log_dir, "latest")}')
+ self.model.load_checkpoint(
+ self.log_dir,
+ load_optimizer_states=True,
+ load_lr_scheduler_states=True,
+ load_module_strict=True)
+ self.global_step = self.model.global_steps * self.args.gradient_accumulate_steps
+ else:
+ logger.warning(f'Resuming failed, path does not exists {os.path.join(self.log_dir, "latest")}')
+ else:
+ self.model = T.nn.parallel.DistributedDataParallel(
+ self.model,
+ device_ids=[self.local_rank],
+ output_device=self.local_rank,
+ find_unused_parameters=self.args.find_unused_parameters)
+ if not self.args.do_train:
+ self.model.eval()
+ logger.info('Successfully built models with %s parameters' % get_parameters(self.model))
+
+ def prepare_batch(self, batch):
+ batch = move_to_cuda(batch)
+ if self.args.deepspeed:
+ batch = fp32_to_fp16(batch)
+ return batch
+
+ def forward_step(self, batch):
+ if self.args.use_amp:
+ with T.autocast(device_type='cuda'):
+ out = self.model(batch)
+ else:
+ out = self.model(batch)
+ return out
+
+ def backward_step(self, loss):
+ if self.args.deepspeed:
+ self.model.backward(loss)
+ elif self.args.use_amp:
+ self.scaler.scale(loss).backward()
+
+ else:
+ loss.backward()
+
+ def grad_clip(self):
+ if self.args.deepspeed:
+ # haddled by deepspeed
+ return
+ if self.args.max_grad_norm > 0:
+ if self.args.use_amp:
+ self.scaler.unscale_(self.optimizer)
+ # Since the gradients of optimizer's assigned
+ # params are unscaled, clips as usual:
+ T.nn.utils.clip_grad_norm_(
+ self.model.parameters(), self.args.max_grad_norm)
+
+ def step(self, optimizer_idx=-1):
+ if optimizer_idx >= 0 and isinstance(self.optimizer, list):
+ optimizer = self.optimizer[optimizer_idx]
+ else:
+ optimizer = self.optimizer
+ if self.args.deepspeed:
+ # Not sure how to step one optimizer at a time
+ self.model.step()
+ elif self.args.use_amp:
+ self.scaler.step(optimizer)
+ self.scaler.update()
+ optimizer.zero_grad()
+ else:
+ optimizer.step()
+ optimizer.zero_grad()
+
+ def train(self, train_loader, eval_loader=None, use_tqdm=None,
+ inner_collect_fn=None):
+ if self.args.resume:
+ if not self.args.deepspeed:
+ if os.path.exists(os.path.join(self.log_dir, self.last_checkpoint_filename)):
+ self.load_checkpoint(self.last_checkpoint_filename)
+ else:
+ if is_main_process():
+ logger.warning('Dangerous! You set resume=False. Auto cleaning all the logs under %s' % self.log_dir)
+ ensure_dirname(self.log_dir, override=True)
+
+ self.move_model_to_cuda()
+ if self.args.dist:
+ self.prepare_dist_model()
+
+ epoch_iter = range(self.epoch + 1, self.args.epochs, 1)
+ if len(epoch_iter):
+ logger.warning('Start train & val phase...')
+ else:
+ logger.warning('Skip train & val phase...')
+ logger.warning(
+ f'Train examples: {len(train_loader.dataset)}, image size {train_loader.dataset.img_size},\n'
+ f'\t\tVal examples: {len(eval_loader.dataset)}, {len(eval_loader)}\n'
+ f'\t\tepochs: {self.args.epochs}, iters: {self.args.num_iters}, \n'
+ f'\t\titer_per_ep: {self.args.iter_per_ep}, eval_step: {self.args.eval_step}, save_step: {self.args.save_step},\n'
+ f'\t\tglobal_batch_size: {self.args.train_batch_size}, local_batch_size: {self.args.local_train_batch_size}.')
+
+ # Train & Eval phase
+ for epoch in epoch_iter:
+ self.epoch = epoch
+ # Train phase
+ train_meter, train_time = self.train_fn(train_loader,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, self.args.epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ metric = {'Epoch%s' % (epoch + 1): {'train': {**train_meter.avg, **{'time': train_time}}}}
+
+ if is_main_process():
+ self.update_metric_file(metric)
+ if (epoch + 1) % self.args.save_step == 0:
+ self.save_checkpoint(self.last_checkpoint_filename)
+
+ if (epoch + 1) % self.args.eval_step == 0:
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, self.args.epochs, eval_time, eval_meter.avg))
+
+ # Update metric with eval metrics
+ metric['Epoch%s' % (epoch + 1)].update({'eval': {**eval_meter.avg, **{'time': eval_time}}})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+
+ def train_fn(self, train_loader, use_tqdm=True):
+ self.model.train()
+ train_meter = Meter()
+ train_timer = Timer()
+ train_iter = tqdm(train_loader, total=len(train_loader), disable=not use_tqdm)
+ for step, inputs in enumerate(train_iter):
+ for optimizer_idx in range(len(self.optimizer)):
+ if not getattr(self.optimizer[optimizer_idx], 'is_enabled', lambda x: True)(self.epoch):
+ continue
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.epoch * len(train_loader) + step
+ self.global_step = inputs['global_step']
+ inputs['optimizer_idx'] = optimizer_idx
+
+ inputs = self.prepare_batch(inputs)
+ outputs = self.forward_step(inputs)
+ self.check_outputs(outputs)
+
+ if optimizer_idx == 0:
+ self.backward_step(outputs['loss_total'])
+ else:
+ self.backward_step(outputs[f'loss_total_{optimizer_idx}'])
+ # outputs['loss_total_%s' % optimizer_idx].backward()
+
+ if (step + 1) % self.args.gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ self.grad_clip()
+ self.step(optimizer_idx)
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ if self.scheduler:
+ self.scheduler.step()
+
+ train_iter.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+ return train_meter, train_time
+
+ def eval(self, eval_loader, inner_collect_fn=None, use_tqdm=True, enc_dec_only=False):
+ # This function is used to do evaluating after training.
+ if not self.pretrained_model:
+ logger.warning('You should create a new config file and specify pretrained_model in Args when using eval.')
+ # Wrap models before evaluating. This will support ddp evaluating.
+ self.move_model_to_cuda()
+ if self.args.dist:
+ self.prepare_dist_model()
+ eval_meter, eval_time = self.eval_fn(
+ eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm, enc_dec_only=enc_dec_only)
+ logger.info('[Rank %s] Valid Time: %s\n %s' % (self.rank, eval_time, eval_meter.avg))
+
+ def eval_trainsample(self, train_loader, eval_loader, inner_collect_fn=None, use_tqdm=True, enc_dec_only=False):
+ # This function is used to do evaluating with training sample.
+ if not self.pretrained_model:
+ logger.warning('You should create a new config file and specify pretrained_model in Args when using eval.')
+ # Wrap models before evaluating. This will support ddp evaluating.
+ self.move_model_to_cuda()
+ if self.args.dist:
+ self.prepare_dist_model()
+ eval_meter, eval_time = self.eval_fn_trainsample(
+ train_loader, eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm, enc_dec_only=enc_dec_only)
+ logger.info('[Rank %s] Valid Time: %s\n %s' % (self.rank, eval_time, eval_meter.avg))
+
+ def eval_demo_pre(self):
+ if not self.pretrained_model:
+ logger.warning('You should create a new config file and specify pretrained_model in Args when using eval.')
+ # Wrap models before evaluating. This will support ddp evaluating.
+ self.move_model_to_cuda()
+ if self.args.dist:
+ self.prepare_dist_model()
+
+ def eval_demo_run_masked(self, input_batch, eval_dataset, enc_dec_only=False):
+ input_batch = eval_dataset.preprocess_masked_input(*input_batch)
+ output_image = self.eval_fn_demo(
+ input_batch, enc_dec_only=enc_dec_only)
+ return output_image
+
+ def eval_fn(
+ self,
+ eval_loader,
+ inner_collect_fn=None,
+ use_tqdm=True,
+ compute_fid=True,
+ enc_dec_only=False,
+ train_eval_input=None,
+ ):
+ # TODO Note that eval_fn supports ddp. So we do not need to unwrap things here.
+ self.model.eval()
+ eval_meter = Meter()
+ eval_timer = Timer()
+ eval_save_filename = self.args.eval_save_filename
+ if enc_dec_only:
+ eval_save_filename += "_enc_dec_only"
+ with T.no_grad():
+ eval_loader = (
+ tqdm(eval_loader, total=len(eval_loader)) if use_tqdm else eval_loader
+ )
+ for batch_idx, inputs in enumerate(eval_loader):
+ T.cuda.empty_cache()
+ if enc_dec_only:
+ inputs["enc_dec_only"] = True
+ inputs = self.prepare_batch(inputs)
+ outputs = self.forward_step(inputs)
+ metric_and_loss = {
+ k: v
+ for k, v in outputs.items()
+ if k.split("_")[0] in ["metric", "loss"]
+ }
+
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ eval_meter.update(metric_and_loss)
+
+ if inner_collect_fn and self.enable_collect:
+ remove_key = inputs.pop("enc_dec_only", None)
+ gt_save_path, pred_save_path = inner_collect_fn(
+ self.args,
+ inputs,
+ outputs,
+ self.log_dir,
+ self.global_step,
+ eval_save_filename,
+ )
+
+ if batch_idx == 0:
+ inputs = defaultdict(lambda: None, inputs)
+ try:
+ label_imgs = inputs["label_imgs"]
+ cond_imgs = inputs["cond_imgs"]
+ ref_imgs = inputs["reference_img"]
+ pred_imgs = outputs["logits_imgs"]
+ except: # for video model
+ label_imgs = inputs["label_img_seq"][:, :, 0]
+ cond_imgs = inputs["cond_img_seq"][:, :, 0]
+ ref_imgs = inputs["reference_img"]
+ pred_imgs = outputs["logits_img_seq"][:, :, 0]
+ self.log_img_to_wandb(
+ label_imgs, cond_imgs, ref_imgs, pred_imgs, prefix="val"
+ )
+
+ if (
+ train_eval_input
+ ): # run a simple-round training sample to check if it is over-fitting
+ print(
+ "run a single-round training sample inference to check if over-fitting"
+ )
+ inputs = train_eval_input
+ T.cuda.empty_cache()
+ if enc_dec_only:
+ inputs["enc_dec_only"] = True
+ inputs = self.prepare_batch(inputs)
+ outputs = self.forward_step(inputs)
+
+ ### vis image for training single round sample ###
+ inputs = defaultdict(lambda: None, inputs)
+ try:
+ label_imgs = inputs["label_imgs"]
+ cond_imgs = inputs["cond_imgs"]
+ ref_imgs = inputs["reference_img"]
+ pred_imgs = outputs["logits_imgs"]
+ except: # for video model
+ label_imgs = inputs["label_img_seq"][:, :, 0]
+ cond_imgs = inputs["cond_img_seq"][:, :, 0]
+ ref_imgs = inputs["reference_img"]
+ pred_imgs = outputs["logits_img_seq"][:, :, 0]
+ self.log_img_to_wandb(
+ label_imgs, cond_imgs, ref_imgs, pred_imgs, prefix="train"
+ )
+
+ eval_meter = self.get_eval_metrics(
+ eval_meter, eval_save_filename, gt_save_path, pred_save_path
+ )
+ eval_time = eval_timer.elapse(True)
+
+ self.model.train()
+ return eval_meter, eval_time
+
+ def eval_fn_demo(self, input_batch, enc_dec_only=False):
+ self.model.eval()
+ with T.no_grad():
+ inputs = input_batch
+ T.cuda.empty_cache()
+ if enc_dec_only:
+ inputs['enc_dec_only'] = True
+ inputs = self.prepare_batch(inputs)
+ outputs = self.forward_step(inputs)
+
+ from PIL import Image
+ def tensor2pil(images, resize_img=False, img_target_size=None):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image.squeeze(), mode="L").resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
+ else:
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image).resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
+
+ output_image = tensor2pil(outputs['logits_imgs'].squeeze(), resize_img=self.args.pos_resize_img, img_target_size=None)[0]
+ return output_image
+
+
+ def get_eval_metrics(self, eval_meter, eval_save_filename, gt_save_path=None, pred_save_path=None):
+ synchronize()
+ if self.global_step <= 0:
+ eval_log_dir = os.path.join(self.log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(self.log_dir, 'eval_step_%d' % (self.global_step))
+
+ if gt_save_path:
+ gt_folder = gt_save_path
+ else:
+ gt_folder = os.path.join(eval_log_dir, 'gt_png')
+ if not os.path.exists(gt_folder):
+ gt_folder = os.path.join(eval_log_dir, 'gt')
+
+ if pred_save_path:
+ pred_folder = pred_save_path
+ else:
+ pred_folder = os.path.join(eval_log_dir, 'pred_png')
+ if not os.path.exists(pred_folder):
+ pred_folder = os.path.join(eval_log_dir, 'pred')
+
+ if os.path.exists(gt_folder) and os.path.exists(pred_folder):
+ if is_main_process():
+ try:
+ from tool.cleanfid.fid import compute_fid
+ result = compute_fid(gt_folder, pred_folder)
+ logger.info(f"FID is {result}")
+ eval_meter.update({'FID': result})
+ except Exception as e:
+ logger.warning(f"Failed to calculate FID, {e}")
+ else:
+ logger.warning(
+ f'Failed to calculate FID, gt {gt_folder}, {os.path.exists(gt_folder)}\npred {pred_folder}, {os.path.exists(pred_folder)}')
+
+ gt_folder = os.path.join(eval_log_dir, 'gt_gif')
+ if not os.path.exists(gt_folder):
+ gt_folder = os.path.join(eval_log_dir, 'gt')
+ pred_folder = os.path.join(eval_log_dir, 'pred_gif')
+ if not os.path.exists(pred_folder):
+ pred_folder = os.path.join(eval_log_dir, 'pred')
+
+ if os.path.exists(gt_folder) and os.path.exists(pred_folder):
+ if is_main_process():
+ try:
+ from tool.metrics.metric_center import get_all_eval_scores
+ result = get_all_eval_scores(
+ self.args.root_dir, gt_folder, pred_folder,
+ sample_duration=self.args.max_video_len,
+ metrics=['fid-img', 'fid-vid', 'fvd'])
+ logger.info(f"Video gen eval {result}")
+ eval_meter.update(result)
+ except Exception as e:
+ logger.warning(f"Failed to eval video gen, {e}")
+ else:
+ logger.warning(
+ f'Failed to eval video gen, gt {gt_folder}, {os.path.exists(gt_folder)}\npred {pred_folder}, {os.path.exists(pred_folder)}')
+
+ if self.args.eval_visu and is_main_process() and len({**eval_meter.avg}):
+ json.dump({**eval_meter.avg}, open(f"{eval_log_dir}/metrics.json", "w"))
+ synchronize()
+ return eval_meter
+
+ def train_eval_by_iter(self, train_loader, eval_loader=None, use_tqdm=True, inner_collect_fn=None):
+
+ if self.args.num_iters:
+ logger.warning('Start train & val phase...')
+ self.setup_wandb()
+ else:
+ logger.warning('Skip train & val phase...')
+ return
+ logger.warning(
+ f'Train examples: {len(train_loader.dataset)}, Val examples: {len(eval_loader.dataset)}, {len(eval_loader)}\n'
+ f'\t\tepochs: {self.args.epochs}, iters: {self.args.num_iters}, \n'
+ f'\t\titer_per_ep: {self.args.iter_per_ep}, eval_step: {self.args.eval_step}, save_step: {self.args.save_step},\n'
+ f'\t\tglobal_batch_size: {self.args.train_batch_size}, local_batch_size: {self.args.local_train_batch_size}.')
+
+ # Train & Eval phase
+ train_pbar = tqdm(total=len(train_loader), disable=not use_tqdm)
+ train_meter = Meter()
+ train_timer = Timer()
+ metric = defaultdict(dict)
+ if self.global_step > 0:
+ train_pbar.update(self.global_step)
+ else:
+ self.global_step = 0
+
+ if self.args.eval_before_train and self.global_step == 0:
+ logger.warning("Saving model...")
+ self.save_checkpoint(str(self.global_step) + '.pth')
+ logger.warning("Evaluating...")
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid before train. Time: %s\n %s' %
+ (self.rank, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_ep': v for k, v in val_meter_log.items()}, step=0)
+ val_meter_log.update({'time': eval_time})
+ metric['Epoch 0'].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+
+ self.model.train()
+ train_iter = iter(train_loader)
+ while self.global_step < len(train_loader):
+ try:
+ inputs = next(train_iter)
+ except StopIteration:
+ logger.warning("Reaching end of the train_loader, terminating training loop")
+ break
+ self.epoch = (self.global_step + 1) // self.args.iter_per_ep
+ for optimizer_idx in range(len(self.optimizer)):
+ if not getattr(self.optimizer[optimizer_idx], 'is_enabled', lambda x: True)(self.epoch):
+ continue
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.global_step
+ inputs['optimizer_idx'] = optimizer_idx
+
+ inputs = self.prepare_batch(inputs)
+ T.cuda.empty_cache()
+ outputs = self.forward_step(inputs)
+
+ self.check_outputs(outputs)
+ T.cuda.empty_cache()
+ if optimizer_idx == 0:
+ self.backward_step(outputs['loss_total'])
+ else:
+ self.backward_step(outputs[f'loss_total_{optimizer_idx}'])
+
+ if (self.global_step + 1) % self.args.gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ self.grad_clip()
+ self.step(optimizer_idx)
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+ self.log_dict_to_wandb(metric_and_loss)
+
+ if self.scheduler:
+ self.scheduler.step()
+
+ # if (self.global_step + 1) % (self.args.save_step*self.args.iter_per_ep) == 0:
+ # self.save_checkpoint(str(self.global_step) + '.pth')
+ train_pbar.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+
+ if (self.global_step + 1) % self.args.iter_per_ep == 0:
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, self.epoch + 1, self.args.epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ tr_meter_log = {**train_meter.avg,}
+ self.log_dict_to_wandb({f'{k}_ep': v for k, v in tr_meter_log.items()})
+ tr_meter_log.update({'time': train_time})
+ metric['Epoch%s' % (self.epoch + 1)].update( {'train': tr_meter_log})
+
+ if is_main_process():
+ self.update_metric_file(metric)
+ if (self.epoch + 1) % self.args.save_step == 0:
+ logger.warning("Saving model...")
+ self.save_checkpoint(str(self.global_step) + '.pth')
+ self.save_checkpoint(self.last_checkpoint_filename)
+ # copy_file(self.last_checkpoint_filename, self.each_checkpoint_filename % str(epoch + 1),
+ # override=True) # TODO sometimes we need to copy file
+
+ if (self.epoch + 1) % self.args.eval_step == 0:
+ logger.warning("Evaluating...")
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, self.epoch + 1, self.args.epochs, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_ep': v for k, v in val_meter_log.items()})
+ val_meter_log.update({'time': eval_time})
+ metric['Epoch%s' % (self.epoch + 1)].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+ train_meter = Meter()
+ train_timer = Timer()
+ self.global_step += 1
+ train_pbar.update(1)
+ if (self.epoch + 1) % self.args.save_step != 0:
+ logger.warning("Saving model...")
+ self.save_checkpoint(str(self.global_step) + '.pth')
+ self.save_checkpoint(self.last_checkpoint_filename)
+
+ if (self.epoch + 1) % self.args.eval_step != 0:
+ logger.warning("Evaluating...")
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(
+ eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, self.epoch + 1, self.args.epochs, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_ep': v for k, v in val_meter_log.items()})
+ val_meter_log.update({'time': eval_time})
+ metric['Epoch%s' % (self.epoch + 1)].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+
+ def check_outputs(self, outputs):
+ error_message = 'Model output must be a dict. The key must be "class_subclass" format.' \
+ ' "class" can only be loss, metric, or logits. "subclass" should be a string.' \
+ ' But got an unexpected key %s'
+ loss_total_list = [e for e in outputs.keys() if e.startswith('loss_total')]
+ if not loss_total_list:
+ raise ValueError('Model output must contain a key startswith "loss_total"!')
+
+ for k, v in outputs.items():
+ split_res = k.split('_')
+ if len(split_res) < 2:
+ raise ValueError(error_message % k)
+ if k.split('_')[0] not in ['loss', 'metric', 'logits']:
+ raise ValueError(error_message % k)
+
+ def from_pretrained(self, pretrained_model):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load pretrained models into wrapped models, ensure self.models is CPU.")
+ if isinstance(pretrained_model, str):
+ logger.warning('Loading Pretrained Model Path: %s...' % pretrained_model)
+ pretrained_dict = file2data(pretrained_model, map_location='cpu')
+ if 'models' in pretrained_dict:
+ pretrained_dict = pretrained_dict['models']
+ elif 'model' in pretrained_dict:
+ pretrained_dict = pretrained_dict['model']
+ else:
+ logger.warning('Loading Given Pretrained Dict...')
+ pretrained_dict = pretrained_model
+ adaptively_load_state_dict(self.model, pretrained_dict)
+
+ def load_checkpoint(self, checkpoint_filename):
+ if not self.args.deepspeed:
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load checkpoint into wrapped models, ensure self.models is CPU.")
+ checkpoint = file2data(checkpoint_filename, map_location='cpu')
+ adaptively_load_state_dict(self.model, checkpoint['models'])
+ if isinstance(self.optimizer, list):
+ if len(self.optimizer) > 1:
+ for i, optimizer in enumerate(self.optimizer):
+ adaptively_load_state_dict(self.optimizer[i], checkpoint['optimizer'][i])
+
+ elif len(self.optimizer) == 1:
+ adaptively_load_state_dict(self.optimizer[0], checkpoint['optimizer'])
+ else:
+ adaptively_load_state_dict(self.optimizer, checkpoint['optimizer'])
+ if self.scheduler:
+ adaptively_load_state_dict(self.scheduler, checkpoint['scheduler'])
+
+ self.epoch = checkpoint['epoch'] - 1
+ self.global_step = checkpoint['global_step'] - 1
+
+ # IMPORTANT! The models will be wrapped automatically.
+ logger.warning('Loaded checkpoint %s of epoch %s (global_step %s)' % (
+ checkpoint_filename, checkpoint['epoch'],
+ checkpoint['global_step']))
+ else:
+ self.model.load_checkpoint(self.log_dir, checkpoint_filename)
+ logger.warning('Loaded checkpoint %s' % (checkpoint_filename))
+
+ def load_checkpoint_for_deepspeed_diff_gpu(self, checkpoint_filename):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load checkpoint into wrapped models, ensure self.models is CPU.")
+ checkpoint = file2data(checkpoint_filename, map_location='cpu')
+ adaptively_load_state_dict(self.model, checkpoint['module'])
+
+ # IMPORTANT! The models will be wrapped automatically.
+ logger.warning('Loaded checkpoint %s of global_step %s' % (
+ checkpoint_filename,
+ checkpoint['global_steps']))
+
+
+ def save_checkpoint(self, checkpoint_filename):
+ if not self.args.deepspeed:
+ if not is_main_process():
+ return
+ checkpoint_filename = os.path.join(self.log_dir, checkpoint_filename)
+ model_to_save = self.model.module if hasattr(self.model, 'module') else self.model
+ if isinstance(self.optimizer, list):
+ if len(self.optimizer) > 1:
+ optimizer_to_save = [optimizer.state_dict() for optimizer in self.optimizer]
+ elif len(self.optimizer) == 1:
+ optimizer_to_save = self.optimizer[0].state_dict()
+ else:
+ optimizer_to_save = self.optimizer.state_dict()
+ checkpoint = {
+ 'models': model_to_save.state_dict(),
+ 'optimizer': optimizer_to_save,
+ 'epoch': self.epoch + 1,
+ 'global_step': self.global_step + 1
+ }
+ if self.scheduler:
+ checkpoint['scheduler'] = self.scheduler.state_dict()
+ data2file(checkpoint, checkpoint_filename, override=True)
+ logger.warning('Saved epoch %s (global_step %s) to %s.' % (
+ checkpoint['epoch'], checkpoint['global_step'],
+ checkpoint_filename))
+ return
+ else:
+ if self.args.debug and checkpoint_filename != self.last_checkpoint_filename:
+ logger.warning(
+ f"skip saving models with deepspeed to "
+ f"{self.log_dir}/{checkpoint_filename} in debug mode")
+ return
+ self.model.save_checkpoint(self.log_dir, tag=checkpoint_filename)
+ return
+
+ def log_memory(self, ep=-1, step=-1):
+ if ep == -1 and step == -1:
+ step = self.global_step
+ step_str = f"global step: {step},"
+ else:
+ step_str = f"ep: {ep}, step: {step},"
+
+ memory = humanbytes(T.cuda.max_memory_allocated())
+ lr_base = f'{self.optimizer.param_groups[0]["lr"]:.2e}'
+ lr_head = f'{self.optimizer.param_groups[2]["lr"]:.2e}'
+ lr_xmodal = f'{self.optimizer.param_groups[4]["lr"]:.2e}'
+ self.log_dict_to_wandb({'lr_base': float(lr_base)}, step)
+ self.log_dict_to_wandb({'lr_head': float(lr_head)}, step)
+ self.log_dict_to_wandb({'lr_xmodal': float(lr_xmodal)}, step)
+ return f"{step_str} lr_base: {lr_base}, " +\
+ f"lr_head: {lr_head}, lr_xmodal: {lr_xmodal}, max memory: {memory}"
+
+ def build_optimizer(self):
+ param_optimizer = list(self.model.named_parameters())
+ no_decay = [
+ "bias",
+ "LayerNorm.bias",
+ "LayerNorm.weight",
+ "norm.bias",
+ "norm.weight",
+ "norm1.bias",
+ "norm1.weight",
+ "norm2.bias",
+ "norm2.weight",
+ ]
+ head_names = ["fc_mtm", "fc"]
+ cross_modal_names = ["cross_modal", "i2t", "t2i"]
+ lr_mult_head = self.args.lr_mult_head
+ lr_mult_cross_modal = self.args.lr_mult_cross_modal
+
+ wd = self.args.decay
+ lr = self.args.lr
+
+
+ optimizer_grouped_parameters = [
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if not any(nd in n for nd in no_decay)
+ and not any(bb in n for bb in head_names)
+ and not any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": wd,
+ "lr": lr,
+ },
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if any(nd in n for nd in no_decay)
+ and not any(bb in n for bb in head_names)
+ and not any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": 0.0,
+ "lr": lr,
+ },
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if not any(nd in n for nd in no_decay)
+ and any(bb in n for bb in head_names)
+ and not any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": wd,
+ "lr": lr * lr_mult_head,
+ },
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if any(nd in n for nd in no_decay)
+ and any(bb in n for bb in head_names)
+ and not any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": 0.0,
+ "lr": lr * lr_mult_head,
+ },
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if not any(nd in n for nd in no_decay)
+ and not any(bb in n for bb in head_names)
+ and any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": wd,
+ "lr": lr * lr_mult_cross_modal,
+ },
+ {
+ "params": [
+ p
+ for n, p in param_optimizer
+ if any(nd in n for nd in no_decay)
+ and not any(bb in n for bb in head_names)
+ and any(ht in n for ht in cross_modal_names)
+ ],
+ "weight_decay": 0.0,
+ "lr": lr * lr_mult_cross_modal,
+ },
+ ]
+ optzr = T.optim.AdamW(
+ optimizer_grouped_parameters, lr=lr,
+ betas=(0.9, 0.98))
+ return optzr
+
+ def setup_model_for_training(self):
+ if self.args.resume:
+ if not self.args.deepspeed:
+ if os.path.exists(os.path.join(self.log_dir, self.last_checkpoint_filename)):
+ logger.warning(f'Resuming.... from {self.last_checkpoint_filename}')
+ self.load_checkpoint(self.last_checkpoint_filename)
+ else:
+ if isinstance(self.optimizer, list):
+ raise ValueError("self.optimizer is a list, which is incompatible with deepspeed")
+ else:
+ if is_main_process():
+ logger.warning('Dangerous! You set resume=False. Auto cleaning all the logs under %s' % self.log_dir)
+ ensure_dirname(self.log_dir, override=True)
+ if hasattr(self.model, "init_ddpm"):
+ # for LDM only
+ logger.warning('Init ddpm and freeze cond_model/first_stage_vqe_model.')
+ self.model.init_ddpm()
+ self.move_model_to_cuda()
+ self.prepare_dist_model()
+
+
+
+class Agent_LDM(Agent):
+ def __init__(self, args, model, optimizer=None, scheduler=None):
+ super().__init__(args, model, optimizer, scheduler)
+ ### add to use stage 1 pretrain attr model to initialize the weight
+ if self.args.stage1_pretrain_path is not None:
+ print('### Using stage 1 attribute pretrain model to initialize the weights ###')
+ pretrain_model_state = file2data(self.args.stage1_pretrain_path, map_location='cpu')
+ # pre-process to the weight name
+ new_state = {}
+ for k, v in pretrain_model_state['module'].items():
+ if k.startswith('controlnet.'):
+ new_key = k[:11] + 'nets.1.' + k[11:]
+ new_state[new_key] = v
+ else:
+ new_state[k] = v
+ ### load
+ adaptively_load_state_dict(model, new_state)
+
+
+ def train(self, train_loader, eval_loader=None, use_tqdm=True,
+ inner_collect_fn=None):
+ if self.args.resume:
+ if not self.args.deepspeed:
+ if os.path.exists(os.path.join(self.log_dir, self.last_checkpoint_filename)):
+ logger.warning(f'Resuming.... from {self.last_checkpoint_filename}')
+ self.load_checkpoint(self.last_checkpoint_filename)
+ else:
+ if is_main_process():
+ logger.warning('Dangerous! You set resume=False. Auto cleaning all the logs under %s' % self.log_dir)
+ ensure_dirname(self.log_dir, override=True)
+
+ self.model.init_ddpm()
+ self.move_model_to_cuda()
+ if self.args.dist:
+ self.prepare_dist_model()
+
+ epoch_iter = range(self.epoch + 1, self.args.epochs, 1)
+ if len(epoch_iter):
+ logger.warning('Start train & val phase...')
+ else:
+ logger.warning('Skip train & val phase...')
+ logger.warning(
+ f'Train examples: {len(train_loader.dataset)}, image size {train_loader.dataset.img_size},\n'
+ f'\t\tVal examples: {len(eval_loader.dataset)}, {len(eval_loader)}\n'
+ f'\t\tepochs: {self.args.epochs}, iters: {self.args.num_iters}, \n'
+ f'\t\titer_per_ep: {self.args.iter_per_ep}, eval_step: {self.args.eval_step}, save_step: {self.args.save_step},\n'
+ f'\t\tglobal_batch_size: {self.args.train_batch_size}, local_batch_size: {self.args.local_train_batch_size}.')
+
+ # Train & Eval phase
+ for epoch in epoch_iter:
+ self.epoch = epoch
+ # Train phase
+ train_meter, train_time = self.train_fn(train_loader,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, self.args.epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ metric = {'Epoch%s' % (epoch + 1): {'train': {**train_meter.avg, **{'time': train_time}}}}
+
+ if is_main_process():
+ self.update_metric_file(metric)
+ if (epoch + 1) % self.args.save_step == 0:
+ self.save_checkpoint(self.last_checkpoint_filename)
+
+ if (epoch + 1) % self.args.eval_step == 0:
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, self.args.epochs, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ metric['Epoch%s' % (self.epoch + 1)].update({'eval': {**eval_meter.avg, **{'time': eval_time}}})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+
+ def train_fn(self, train_loader, use_tqdm=True):
+ self.model.train()
+ train_meter = Meter()
+ train_timer = Timer()
+ train_iter = tqdm(train_loader, total=len(train_loader), disable=not use_tqdm)
+ for step, inputs in enumerate(train_iter):
+ if not getattr(self.optimizer, 'is_enabled', lambda x: True)(self.epoch * len(train_loader) + step):
+ continue # adjust to sdm KL-VAE
+ inputs = complex_to_device(inputs, self.device)
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.epoch * len(train_loader) + step
+ self.global_step = inputs['global_step']
+
+ inputs = self.prepare_batch(inputs)
+ outputs = self.forward_step(inputs)
+
+ self.check_outputs(outputs)
+ self.backward_step(outputs['loss_total'])
+
+ if not self.args.deepspeed:
+ if (step + 1) % self.args.gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ self.grad_clip()
+ self.step()
+ if self.scheduler:
+ self.scheduler.step()
+ else:
+ self.grad_clip()
+ self.step()
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ if (self.global_step + 1) % (int(getattr(self.args, 'save_setp', 8000)) + 1) == 0:
+ self.save_checkpoint(str(self.global_step) + '.pth')
+ train_iter.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+ return train_meter, train_time
+
+ def train_eval_by_iter(self, train_loader, eval_loader=None, use_tqdm=True, inner_collect_fn=None):
+ if self.args.num_iters:
+ logger.warning('Start train & val phase...')
+ self.setup_wandb()
+ else:
+ logger.warning('Skip train & val phase...')
+ return
+ logger.warning(
+ f'Train examples: {len(train_loader.dataset)}, image size {train_loader.dataset.img_size},\n'
+ f'\t\tVal examples: {len(eval_loader.dataset)}, {len(eval_loader)}\n'
+ f'\t\tepochs: {self.args.epochs}, iters: {self.args.num_iters}, \n'
+ f'\t\titer_per_ep: {self.args.iter_per_ep}, eval_step: {self.args.eval_step}, save_step: {self.args.save_step},\n'
+ f'\t\tglobal_batch_size: {self.args.train_batch_size}, local_batch_size: {self.args.local_train_batch_size}.')
+
+ # Train & Eval phase
+ train_pbar = tqdm(total=len(train_loader), disable=not use_tqdm)
+ train_meter = Meter()
+ train_timer = Timer()
+ metric = defaultdict(dict)
+ if self.global_step > 0:
+ train_pbar.update(self.global_step)
+ else:
+ self.global_step = 0
+
+ if self.args.eval_before_train and self.global_step == 0:
+ # logger.warning("Saving model...")
+ # self.save_checkpoint(str(self.global_step) + '.pth')
+ if eval_loader:
+ if self.args.eval_enc_dec_only:
+ logger.warning("Evaluating enc_dec_only...")
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm, enc_dec_only=True)
+ logger.info('[Rank %s] Valid enc_dec_only before train. Time: %s\n %s' %
+ (self.rank, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_enc_dec_only': v for k, v in val_meter_log.items()}, step=0)
+ val_meter_log.update({'time': eval_time})
+ metric['Step 0_enc_dec_only'].update({'eval': val_meter_log})
+ logger.warning("Evaluating ZS...")
+
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid before train. Time: %s\n %s' %
+ (self.rank, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_step': v for k, v in val_meter_log.items()}, step=0)
+ val_meter_log.update({'time': eval_time})
+ metric['Step 0'].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+ # update tqdm to have previous info, load train_loader
+ self.model.train()
+ train_iter = iter(train_loader)
+ while self.global_step < len(train_loader):
+ try:
+ inputs = next(train_iter)
+ except StopIteration:
+ logger.warning("Reaching end of the train_loader, terminating training loop")
+ break
+
+ self.epoch = (self.global_step + 1) // self.args.iter_per_ep
+ if not getattr(self.optimizer, 'is_enabled', lambda x: True)(self.global_step):
+ continue # adjust to sdm KL-VAE
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.global_step
+
+ inputs = self.prepare_batch(inputs)
+ T.cuda.empty_cache()
+ outputs = self.forward_step(inputs)
+
+ self.check_outputs(outputs)
+ T.cuda.empty_cache()
+ self.backward_step(outputs['loss_total'])
+
+ if not self.args.deepspeed:
+ if (self.global_step + 1) % self.args.gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ self.grad_clip()
+ self.step()
+ if self.scheduler:
+ self.scheduler.step()
+ else:
+ # gradient_accumulation handled by deepspeed
+ self.grad_clip()
+ self.step()
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ # if (self.global_step + 1) % (self.args.save_step*self.args.iter_per_ep) == 0:
+ # self.save_checkpoint(str(self.global_step) + '.pth')
+ train_pbar.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+
+ if (self.global_step + 1) % self.args.iter_per_ep == 0:
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, self.epoch + 1, self.args.epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ tr_meter_log = {**train_meter.avg }
+ self.log_dict_to_wandb({f'{k}_ep': v for k, v in tr_meter_log.items()})
+ tr_meter_log.update({'time': train_time})
+ metric['Epoch%s' % (self.epoch + 1)].update( {'train': tr_meter_log})
+
+ if is_main_process():
+ self.update_metric_file(metric)
+
+ if (self.global_step + 1) % self.args.save_step == 0:
+ logger.warning("Saving model...")
+ self.save_checkpoint(str(self.global_step) + '.pth')
+ if not self.args.deepspeed:
+ self.save_checkpoint(self.last_checkpoint_filename)
+
+ # T.cuda.empty_cache()
+ if (self.global_step + 1) % self.args.eval_step == 0:
+ logger.warning("Evaluating...")
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm, train_eval_input=inputs) # sample a single round training sample to test whether over-fitting
+ logger.info('[Rank %s] Valid Step: %d, Time: %s\n %s' %
+ (self.rank, self.global_step, eval_time, eval_meter.avg))
+ # Update metric with eval metrics
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_step': v for k, v in val_meter_log.items()})
+ self.log_dict_to_wandb({f'{k}_iter': v for k, v in {**train_meter.avg}.items()})
+ self.log_dict_to_wandb({'lr_paramgp0_iter': self.optimizer.param_groups[0]["lr"]})
+ val_meter_log.update({'time': eval_time})
+ metric['Step%s' % (self.global_step + 1)].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
+ # T.cuda.empty_cache()
+ train_meter = Meter()
+ train_timer = Timer()
+ self.global_step += 1
+ train_pbar.update(1)
+ if self.global_step % self.args.save_step != 0:
+ logger.warning("Saving model...")
+ self.save_checkpoint(self.last_checkpoint_filename)
+
+ if self.global_step % self.args.eval_step != 0:
+ logger.warning("Evaluating...")
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Step: %d, Time: %s\n %s' %
+ (self.rank, self.global_step, eval_time, eval_meter.avg))
+ val_meter_log = {**eval_meter.avg}
+ self.log_dict_to_wandb({f'{k}_step': v for k, v in val_meter_log.items()})
+ val_meter_log.update({'time': eval_time})
+ metric['Step%s' % (self.global_step)].update({'eval': val_meter_log})
+
+ # Save metric file
+ if is_main_process():
+ self.update_metric_file(metric)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Dockerfile b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Dockerfile
new file mode 100644
index 0000000000000000000000000000000000000000..4ff4c54d08f12bcc5fd8e09434dd2875da467aa4
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Dockerfile
@@ -0,0 +1,11 @@
+FROM pytorch/pytorch:1.13.1-cuda11.6-cudnn8-devel
+
+COPY . /home/appuser
+WORKDIR /home/appuser
+RUN apt-get update && apt-get install ffmpeg libsm6 libxext6 -y
+# Below is for https://github.com/IDEA-Research/Grounded-Segment-Anything/issues/53
+ENV CUDA_HOME /usr/local/cuda-11.6/
+RUN python -m pip install -e segment_anything
+RUN python -m pip install -e GroundingDINO
+RUN pip install --upgrade diffusers[torch]
+RUN pip install opencv-python pycocotools matplotlib onnxruntime onnx ipykernel
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b1395e94b016dd1b95b4c7e3ed493e1d0b342917
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2020 - present, Facebook, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..b6610df03d409633e572ef49d67a445d35a63967
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/README.md
@@ -0,0 +1,163 @@
+# Grounding DINO
+
+---
+
+[](https://arxiv.org/abs/2303.05499)
+[](https://youtu.be/wxWDt5UiwY8)
+[](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/zero-shot-object-detection-with-grounding-dino.ipynb)
+[](https://youtu.be/cMa77r3YrDk)
+[](https://huggingface.co/spaces/ShilongLiu/Grounding_DINO_demo)
+
+[](https://paperswithcode.com/sota/zero-shot-object-detection-on-mscoco?p=grounding-dino-marrying-dino-with-grounded) \
+[](https://paperswithcode.com/sota/zero-shot-object-detection-on-odinw?p=grounding-dino-marrying-dino-with-grounded) \
+[](https://paperswithcode.com/sota/object-detection-on-coco-minival?p=grounding-dino-marrying-dino-with-grounded) \
+[](https://paperswithcode.com/sota/object-detection-on-coco?p=grounding-dino-marrying-dino-with-grounded)
+
+
+
+Official PyTorch implementation of [Grounding DINO](https://arxiv.org/abs/2303.05499), a stronger open-set object detector. Code is available now!
+
+
+## Highlight
+
+- **Open-Set Detection.** Detect **everything** with language!
+- **High Performancce.** COCO zero-shot **52.5 AP** (training without COCO data!). COCO fine-tune **63.0 AP**.
+- **Flexible.** Collaboration with Stable Diffusion for Image Editting.
+
+## News
+[2023/03/28] A YouTube [video](https://youtu.be/cMa77r3YrDk) about Grounding DINO and basic object detection prompt engineering. [[SkalskiP](https://github.com/SkalskiP)] \
+[2023/03/28] Add a [demo](https://huggingface.co/spaces/ShilongLiu/Grounding_DINO_demo) on Hugging Face Space! \
+[2023/03/27] Support CPU-only mode. Now the model can run on machines without GPUs.\
+[2023/03/25] A [demo](https://colab.research.google.com/github/roboflow-ai/notebooks/blob/main/notebooks/zero-shot-object-detection-with-grounding-dino.ipynb) for Grounding DINO is available at Colab. [[SkalskiP](https://github.com/SkalskiP)] \
+[2023/03/22] Code is available Now!
+
+
+
+Description
+
+
+
+
+
+
+## TODO
+
+- [x] Release inference code and demo.
+- [x] Release checkpoints.
+- [ ] Grounding DINO with Stable Diffusion and GLIGEN demos.
+- [ ] Release training codes.
+
+## Install
+
+If you have a CUDA environment, please make sure the environment variable `CUDA_HOME` is set. It will be compiled under CPU-only mode if no CUDA available.
+
+```bash
+pip install -e .
+```
+
+## Demo
+
+```bash
+CUDA_VISIBLE_DEVICES=6 python demo/inference_on_a_image.py \
+ -c /path/to/config \
+ -p /path/to/checkpoint \
+ -i .asset/cats.png \
+ -o "outputs/0" \
+ -t "cat ear." \
+ [--cpu-only] # open it for cpu mode
+```
+See the `demo/inference_on_a_image.py` for more details.
+
+**Web UI**
+
+We also provide a demo code to integrate Grounding DINO with Gradio Web UI. See the file `demo/gradio_app.py` for more details.
+
+## Checkpoints
+
+
+
+
+
+ |
+ name |
+ backbone |
+ Data |
+ box AP on COCO |
+ Checkpoint |
+ Config |
+
+
+
+
+ | 1 |
+ GroundingDINO-T |
+ Swin-T |
+ O365,GoldG,Cap4M |
+ 48.4 (zero-shot) / 57.2 (fine-tune) |
+ Github link | HF link |
+ link |
+
+
+
+
+## Results
+
+
+
+COCO Object Detection Results
+
+
+
+
+
+
+ODinW Object Detection Results
+
+
+
+
+
+
+Marrying Grounding DINO with Stable Diffusion for Image Editing
+
+
+
+
+
+
+Marrying Grounding DINO with GLIGEN for more Detailed Image Editing
+
+
+
+
+## Model
+
+Includes: a text backbone, an image backbone, a feature enhancer, a language-guided query selection, and a cross-modality decoder.
+
+
+
+
+## Acknowledgement
+
+Our model is related to [DINO](https://github.com/IDEA-Research/DINO) and [GLIP](https://github.com/microsoft/GLIP). Thanks for their great work!
+
+We also thank great previous work including DETR, Deformable DETR, SMCA, Conditional DETR, Anchor DETR, Dynamic DETR, DAB-DETR, DN-DETR, etc. More related work are available at [Awesome Detection Transformer](https://github.com/IDEACVR/awesome-detection-transformer). A new toolbox [detrex](https://github.com/IDEA-Research/detrex) is available as well.
+
+Thanks [Stable Diffusion](https://github.com/Stability-AI/StableDiffusion) and [GLIGEN](https://github.com/gligen/GLIGEN) for their awesome models.
+
+
+## Citation
+
+If you find our work helpful for your research, please consider citing the following BibTeX entry.
+
+```bibtex
+@inproceedings{ShilongLiu2023GroundingDM,
+ title={Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection},
+ author={Shilong Liu and Zhaoyang Zeng and Tianhe Ren and Feng Li and Hao Zhang and Jie Yang and Chunyuan Li and Jianwei Yang and Hang Su and Jun Zhu and Lei Zhang},
+ year={2023}
+}
+```
+
+
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinB.cfg.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinB.cfg.py
new file mode 100644
index 0000000000000000000000000000000000000000..f490c4bbd598a35de43d36ceafcbd769e7ff21bf
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinB.cfg.py
@@ -0,0 +1,43 @@
+batch_size = 1
+modelname = "groundingdino"
+backbone = "swin_B_384_22k"
+position_embedding = "sine"
+pe_temperatureH = 20
+pe_temperatureW = 20
+return_interm_indices = [1, 2, 3]
+backbone_freeze_keywords = None
+enc_layers = 6
+dec_layers = 6
+pre_norm = False
+dim_feedforward = 2048
+hidden_dim = 256
+dropout = 0.0
+nheads = 8
+num_queries = 900
+query_dim = 4
+num_patterns = 0
+num_feature_levels = 4
+enc_n_points = 4
+dec_n_points = 4
+two_stage_type = "standard"
+two_stage_bbox_embed_share = False
+two_stage_class_embed_share = False
+transformer_activation = "relu"
+dec_pred_bbox_embed_share = True
+dn_box_noise_scale = 1.0
+dn_label_noise_ratio = 0.5
+dn_label_coef = 1.0
+dn_bbox_coef = 1.0
+embed_init_tgt = True
+dn_labelbook_size = 2000
+max_text_len = 256
+text_encoder_type = "bert-base-uncased"
+use_text_enhancer = True
+use_fusion_layer = True
+use_checkpoint = True
+use_transformer_ckpt = True
+use_text_cross_attention = True
+text_dropout = 0.0
+fusion_dropout = 0.0
+fusion_droppath = 0.1
+sub_sentence_present = True
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py
new file mode 100644
index 0000000000000000000000000000000000000000..9158d5f6260ec74bded95377d382387430d7cd70
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py
@@ -0,0 +1,43 @@
+batch_size = 1
+modelname = "groundingdino"
+backbone = "swin_T_224_1k"
+position_embedding = "sine"
+pe_temperatureH = 20
+pe_temperatureW = 20
+return_interm_indices = [1, 2, 3]
+backbone_freeze_keywords = None
+enc_layers = 6
+dec_layers = 6
+pre_norm = False
+dim_feedforward = 2048
+hidden_dim = 256
+dropout = 0.0
+nheads = 8
+num_queries = 900
+query_dim = 4
+num_patterns = 0
+num_feature_levels = 4
+enc_n_points = 4
+dec_n_points = 4
+two_stage_type = "standard"
+two_stage_bbox_embed_share = False
+two_stage_class_embed_share = False
+transformer_activation = "relu"
+dec_pred_bbox_embed_share = True
+dn_box_noise_scale = 1.0
+dn_label_noise_ratio = 0.5
+dn_label_coef = 1.0
+dn_bbox_coef = 1.0
+embed_init_tgt = True
+dn_labelbook_size = 2000
+max_text_len = 256
+text_encoder_type = "bert-base-uncased"
+use_text_enhancer = True
+use_fusion_layer = True
+use_checkpoint = True
+use_transformer_ckpt = True
+use_text_cross_attention = True
+text_dropout = 0.0
+fusion_dropout = 0.0
+fusion_droppath = 0.1
+sub_sentence_present = True
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/transforms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..91cf9269e4b31008a3ddca34a19b038a9b399991
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/datasets/transforms.py
@@ -0,0 +1,311 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Transforms and data augmentation for both image + bbox.
+"""
+import os
+import random
+
+import PIL
+import torch
+import torchvision.transforms as T
+import torchvision.transforms.functional as F
+
+from groundingdino.util.box_ops import box_xyxy_to_cxcywh
+from groundingdino.util.misc import interpolate
+
+
+def crop(image, target, region):
+ cropped_image = F.crop(image, *region)
+
+ target = target.copy()
+ i, j, h, w = region
+
+ # should we do something wrt the original size?
+ target["size"] = torch.tensor([h, w])
+
+ fields = ["labels", "area", "iscrowd", "positive_map"]
+
+ if "boxes" in target:
+ boxes = target["boxes"]
+ max_size = torch.as_tensor([w, h], dtype=torch.float32)
+ cropped_boxes = boxes - torch.as_tensor([j, i, j, i])
+ cropped_boxes = torch.min(cropped_boxes.reshape(-1, 2, 2), max_size)
+ cropped_boxes = cropped_boxes.clamp(min=0)
+ area = (cropped_boxes[:, 1, :] - cropped_boxes[:, 0, :]).prod(dim=1)
+ target["boxes"] = cropped_boxes.reshape(-1, 4)
+ target["area"] = area
+ fields.append("boxes")
+
+ if "masks" in target:
+ # FIXME should we update the area here if there are no boxes?
+ target["masks"] = target["masks"][:, i : i + h, j : j + w]
+ fields.append("masks")
+
+ # remove elements for which the boxes or masks that have zero area
+ if "boxes" in target or "masks" in target:
+ # favor boxes selection when defining which elements to keep
+ # this is compatible with previous implementation
+ if "boxes" in target:
+ cropped_boxes = target["boxes"].reshape(-1, 2, 2)
+ keep = torch.all(cropped_boxes[:, 1, :] > cropped_boxes[:, 0, :], dim=1)
+ else:
+ keep = target["masks"].flatten(1).any(1)
+
+ for field in fields:
+ if field in target:
+ target[field] = target[field][keep]
+
+ if os.environ.get("IPDB_SHILONG_DEBUG", None) == "INFO":
+ # for debug and visualization only.
+ if "strings_positive" in target:
+ target["strings_positive"] = [
+ _i for _i, _j in zip(target["strings_positive"], keep) if _j
+ ]
+
+ return cropped_image, target
+
+
+def hflip(image, target):
+ flipped_image = F.hflip(image)
+
+ w, h = image.size
+
+ target = target.copy()
+ if "boxes" in target:
+ boxes = target["boxes"]
+ boxes = boxes[:, [2, 1, 0, 3]] * torch.as_tensor([-1, 1, -1, 1]) + torch.as_tensor(
+ [w, 0, w, 0]
+ )
+ target["boxes"] = boxes
+
+ if "masks" in target:
+ target["masks"] = target["masks"].flip(-1)
+
+ return flipped_image, target
+
+
+def resize(image, target, size, max_size=None):
+ # size can be min_size (scalar) or (w, h) tuple
+
+ def get_size_with_aspect_ratio(image_size, size, max_size=None):
+ w, h = image_size
+ if max_size is not None:
+ min_original_size = float(min((w, h)))
+ max_original_size = float(max((w, h)))
+ if max_original_size / min_original_size * size > max_size:
+ size = int(round(max_size * min_original_size / max_original_size))
+
+ if (w <= h and w == size) or (h <= w and h == size):
+ return (h, w)
+
+ if w < h:
+ ow = size
+ oh = int(size * h / w)
+ else:
+ oh = size
+ ow = int(size * w / h)
+
+ return (oh, ow)
+
+ def get_size(image_size, size, max_size=None):
+ if isinstance(size, (list, tuple)):
+ return size[::-1]
+ else:
+ return get_size_with_aspect_ratio(image_size, size, max_size)
+
+ size = get_size(image.size, size, max_size)
+ rescaled_image = F.resize(image, size)
+
+ if target is None:
+ return rescaled_image, None
+
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(rescaled_image.size, image.size))
+ ratio_width, ratio_height = ratios
+
+ target = target.copy()
+ if "boxes" in target:
+ boxes = target["boxes"]
+ scaled_boxes = boxes * torch.as_tensor(
+ [ratio_width, ratio_height, ratio_width, ratio_height]
+ )
+ target["boxes"] = scaled_boxes
+
+ if "area" in target:
+ area = target["area"]
+ scaled_area = area * (ratio_width * ratio_height)
+ target["area"] = scaled_area
+
+ h, w = size
+ target["size"] = torch.tensor([h, w])
+
+ if "masks" in target:
+ target["masks"] = (
+ interpolate(target["masks"][:, None].float(), size, mode="nearest")[:, 0] > 0.5
+ )
+
+ return rescaled_image, target
+
+
+def pad(image, target, padding):
+ # assumes that we only pad on the bottom right corners
+ padded_image = F.pad(image, (0, 0, padding[0], padding[1]))
+ if target is None:
+ return padded_image, None
+ target = target.copy()
+ # should we do something wrt the original size?
+ target["size"] = torch.tensor(padded_image.size[::-1])
+ if "masks" in target:
+ target["masks"] = torch.nn.functional.pad(target["masks"], (0, padding[0], 0, padding[1]))
+ return padded_image, target
+
+
+class ResizeDebug(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ return resize(img, target, self.size)
+
+
+class RandomCrop(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ region = T.RandomCrop.get_params(img, self.size)
+ return crop(img, target, region)
+
+
+class RandomSizeCrop(object):
+ def __init__(self, min_size: int, max_size: int, respect_boxes: bool = False):
+ # respect_boxes: True to keep all boxes
+ # False to tolerence box filter
+ self.min_size = min_size
+ self.max_size = max_size
+ self.respect_boxes = respect_boxes
+
+ def __call__(self, img: PIL.Image.Image, target: dict):
+ init_boxes = len(target["boxes"])
+ max_patience = 10
+ for i in range(max_patience):
+ w = random.randint(self.min_size, min(img.width, self.max_size))
+ h = random.randint(self.min_size, min(img.height, self.max_size))
+ region = T.RandomCrop.get_params(img, [h, w])
+ result_img, result_target = crop(img, target, region)
+ if (
+ not self.respect_boxes
+ or len(result_target["boxes"]) == init_boxes
+ or i == max_patience - 1
+ ):
+ return result_img, result_target
+ return result_img, result_target
+
+
+class CenterCrop(object):
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, img, target):
+ image_width, image_height = img.size
+ crop_height, crop_width = self.size
+ crop_top = int(round((image_height - crop_height) / 2.0))
+ crop_left = int(round((image_width - crop_width) / 2.0))
+ return crop(img, target, (crop_top, crop_left, crop_height, crop_width))
+
+
+class RandomHorizontalFlip(object):
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, img, target):
+ if random.random() < self.p:
+ return hflip(img, target)
+ return img, target
+
+
+class RandomResize(object):
+ def __init__(self, sizes, max_size=None):
+ assert isinstance(sizes, (list, tuple))
+ self.sizes = sizes
+ self.max_size = max_size
+
+ def __call__(self, img, target=None):
+ size = random.choice(self.sizes)
+ return resize(img, target, size, self.max_size)
+
+
+class RandomPad(object):
+ def __init__(self, max_pad):
+ self.max_pad = max_pad
+
+ def __call__(self, img, target):
+ pad_x = random.randint(0, self.max_pad)
+ pad_y = random.randint(0, self.max_pad)
+ return pad(img, target, (pad_x, pad_y))
+
+
+class RandomSelect(object):
+ """
+ Randomly selects between transforms1 and transforms2,
+ with probability p for transforms1 and (1 - p) for transforms2
+ """
+
+ def __init__(self, transforms1, transforms2, p=0.5):
+ self.transforms1 = transforms1
+ self.transforms2 = transforms2
+ self.p = p
+
+ def __call__(self, img, target):
+ if random.random() < self.p:
+ return self.transforms1(img, target)
+ return self.transforms2(img, target)
+
+
+class ToTensor(object):
+ def __call__(self, img, target):
+ return F.to_tensor(img), target
+
+
+class RandomErasing(object):
+ def __init__(self, *args, **kwargs):
+ self.eraser = T.RandomErasing(*args, **kwargs)
+
+ def __call__(self, img, target):
+ return self.eraser(img), target
+
+
+class Normalize(object):
+ def __init__(self, mean, std):
+ self.mean = mean
+ self.std = std
+
+ def __call__(self, image, target=None):
+ image = F.normalize(image, mean=self.mean, std=self.std)
+ if target is None:
+ return image, None
+ target = target.copy()
+ h, w = image.shape[-2:]
+ if "boxes" in target:
+ boxes = target["boxes"]
+ boxes = box_xyxy_to_cxcywh(boxes)
+ boxes = boxes / torch.tensor([w, h, w, h], dtype=torch.float32)
+ target["boxes"] = boxes
+ return image, target
+
+
+class Compose(object):
+ def __init__(self, transforms):
+ self.transforms = transforms
+
+ def __call__(self, image, target):
+ for t in self.transforms:
+ image, target = t(image, target)
+ return image, target
+
+ def __repr__(self):
+ format_string = self.__class__.__name__ + "("
+ for t in self.transforms:
+ format_string += "\n"
+ format_string += " {0}".format(t)
+ format_string += "\n)"
+ return format_string
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2af819d61d589cfec2e0ca46612a7456f42b831a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/__init__.py
@@ -0,0 +1,15 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+from .groundingdino import build_groundingdino
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..76e4b272b479a26c63d120c818c140870cd8c287
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/__init__.py
@@ -0,0 +1 @@
+from .backbone import build_backbone
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/backbone.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8340c723fad8e07e2fc62daaa3912487498814b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/backbone.py
@@ -0,0 +1,221 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+"""
+Backbone modules.
+"""
+
+from typing import Dict, List
+
+import torch
+import torch.nn.functional as F
+import torchvision
+from torch import nn
+from torchvision.models._utils import IntermediateLayerGetter
+
+from groundingdino.util.misc import NestedTensor, clean_state_dict, is_main_process
+
+from .position_encoding import build_position_encoding
+from .swin_transformer import build_swin_transformer
+
+
+class FrozenBatchNorm2d(torch.nn.Module):
+ """
+ BatchNorm2d where the batch statistics and the affine parameters are fixed.
+
+ Copy-paste from torchvision.misc.ops with added eps before rqsrt,
+ without which any other models than torchvision.models.resnet[18,34,50,101]
+ produce nans.
+ """
+
+ def __init__(self, n):
+ super(FrozenBatchNorm2d, self).__init__()
+ self.register_buffer("weight", torch.ones(n))
+ self.register_buffer("bias", torch.zeros(n))
+ self.register_buffer("running_mean", torch.zeros(n))
+ self.register_buffer("running_var", torch.ones(n))
+
+ def _load_from_state_dict(
+ self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ ):
+ num_batches_tracked_key = prefix + "num_batches_tracked"
+ if num_batches_tracked_key in state_dict:
+ del state_dict[num_batches_tracked_key]
+
+ super(FrozenBatchNorm2d, self)._load_from_state_dict(
+ state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
+ )
+
+ def forward(self, x):
+ # move reshapes to the beginning
+ # to make it fuser-friendly
+ w = self.weight.reshape(1, -1, 1, 1)
+ b = self.bias.reshape(1, -1, 1, 1)
+ rv = self.running_var.reshape(1, -1, 1, 1)
+ rm = self.running_mean.reshape(1, -1, 1, 1)
+ eps = 1e-5
+ scale = w * (rv + eps).rsqrt()
+ bias = b - rm * scale
+ return x * scale + bias
+
+
+class BackboneBase(nn.Module):
+ def __init__(
+ self,
+ backbone: nn.Module,
+ train_backbone: bool,
+ num_channels: int,
+ return_interm_indices: list,
+ ):
+ super().__init__()
+ for name, parameter in backbone.named_parameters():
+ if (
+ not train_backbone
+ or "layer2" not in name
+ and "layer3" not in name
+ and "layer4" not in name
+ ):
+ parameter.requires_grad_(False)
+
+ return_layers = {}
+ for idx, layer_index in enumerate(return_interm_indices):
+ return_layers.update(
+ {"layer{}".format(5 - len(return_interm_indices) + idx): "{}".format(layer_index)}
+ )
+
+ # if len:
+ # if use_stage1_feature:
+ # return_layers = {"layer1": "0", "layer2": "1", "layer3": "2", "layer4": "3"}
+ # else:
+ # return_layers = {"layer2": "0", "layer3": "1", "layer4": "2"}
+ # else:
+ # return_layers = {'layer4': "0"}
+ self.body = IntermediateLayerGetter(backbone, return_layers=return_layers)
+ self.num_channels = num_channels
+
+ def forward(self, tensor_list: NestedTensor):
+ xs = self.body(tensor_list.tensors)
+ out: Dict[str, NestedTensor] = {}
+ for name, x in xs.items():
+ m = tensor_list.mask
+ assert m is not None
+ mask = F.interpolate(m[None].float(), size=x.shape[-2:]).to(torch.bool)[0]
+ out[name] = NestedTensor(x, mask)
+ # import ipdb; ipdb.set_trace()
+ return out
+
+
+class Backbone(BackboneBase):
+ """ResNet backbone with frozen BatchNorm."""
+
+ def __init__(
+ self,
+ name: str,
+ train_backbone: bool,
+ dilation: bool,
+ return_interm_indices: list,
+ batch_norm=FrozenBatchNorm2d,
+ ):
+ if name in ["resnet18", "resnet34", "resnet50", "resnet101"]:
+ backbone = getattr(torchvision.models, name)(
+ replace_stride_with_dilation=[False, False, dilation],
+ pretrained=is_main_process(),
+ norm_layer=batch_norm,
+ )
+ else:
+ raise NotImplementedError("Why you can get here with name {}".format(name))
+ # num_channels = 512 if name in ('resnet18', 'resnet34') else 2048
+ assert name not in ("resnet18", "resnet34"), "Only resnet50 and resnet101 are available."
+ assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]]
+ num_channels_all = [256, 512, 1024, 2048]
+ num_channels = num_channels_all[4 - len(return_interm_indices) :]
+ super().__init__(backbone, train_backbone, num_channels, return_interm_indices)
+
+
+class Joiner(nn.Sequential):
+ def __init__(self, backbone, position_embedding):
+ super().__init__(backbone, position_embedding)
+
+ def forward(self, tensor_list: NestedTensor):
+ xs = self[0](tensor_list)
+ out: List[NestedTensor] = []
+ pos = []
+ for name, x in xs.items():
+ out.append(x)
+ # position encoding
+ pos.append(self[1](x).to(x.tensors.dtype))
+
+ return out, pos
+
+
+def build_backbone(args):
+ """
+ Useful args:
+ - backbone: backbone name
+ - lr_backbone:
+ - dilation
+ - return_interm_indices: available: [0,1,2,3], [1,2,3], [3]
+ - backbone_freeze_keywords:
+ - use_checkpoint: for swin only for now
+
+ """
+ position_embedding = build_position_encoding(args)
+ train_backbone = True
+ if not train_backbone:
+ raise ValueError("Please set lr_backbone > 0")
+ return_interm_indices = args.return_interm_indices
+ assert return_interm_indices in [[0, 1, 2, 3], [1, 2, 3], [3]]
+ args.backbone_freeze_keywords
+ use_checkpoint = getattr(args, "use_checkpoint", False)
+
+ if args.backbone in ["resnet50", "resnet101"]:
+ backbone = Backbone(
+ args.backbone,
+ train_backbone,
+ args.dilation,
+ return_interm_indices,
+ batch_norm=FrozenBatchNorm2d,
+ )
+ bb_num_channels = backbone.num_channels
+ elif args.backbone in [
+ "swin_T_224_1k",
+ "swin_B_224_22k",
+ "swin_B_384_22k",
+ "swin_L_224_22k",
+ "swin_L_384_22k",
+ ]:
+ pretrain_img_size = int(args.backbone.split("_")[-2])
+ backbone = build_swin_transformer(
+ args.backbone,
+ pretrain_img_size=pretrain_img_size,
+ out_indices=tuple(return_interm_indices),
+ dilation=False,
+ use_checkpoint=use_checkpoint,
+ )
+
+ bb_num_channels = backbone.num_features[4 - len(return_interm_indices) :]
+ else:
+ raise NotImplementedError("Unknown backbone {}".format(args.backbone))
+
+ assert len(bb_num_channels) == len(
+ return_interm_indices
+ ), f"len(bb_num_channels) {len(bb_num_channels)} != len(return_interm_indices) {len(return_interm_indices)}"
+
+ model = Joiner(backbone, position_embedding)
+ model.num_channels = bb_num_channels
+ assert isinstance(
+ bb_num_channels, List
+ ), "bb_num_channels is expected to be a List but {}".format(type(bb_num_channels))
+ # import ipdb; ipdb.set_trace()
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/position_encoding.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/position_encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..eac7e896bbe85a670824bfe8ef487d0535d5bd99
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/position_encoding.py
@@ -0,0 +1,186 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copied from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+"""
+Various positional encodings for the transformer.
+"""
+import math
+
+import torch
+from torch import nn
+
+from groundingdino.util.misc import NestedTensor
+
+
+class PositionEmbeddingSine(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one
+ used by the Attention is all you need paper, generalized to work on images.
+ """
+
+ def __init__(self, num_pos_feats=64, temperature=10000, normalize=False, scale=None):
+ super().__init__()
+ self.num_pos_feats = num_pos_feats
+ self.temperature = temperature
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ self.scale = scale
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ mask = tensor_list.mask
+ assert mask is not None
+ not_mask = ~mask
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
+ if self.normalize:
+ eps = 1e-6
+ # if os.environ.get("SHILONG_AMP", None) == '1':
+ # eps = 1e-4
+ # else:
+ # eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
+
+ dim_t = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_t = self.temperature ** (2 * (dim_t // 2) / self.num_pos_feats)
+
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ pos_x = torch.stack(
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos_y = torch.stack(
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+
+class PositionEmbeddingSineHW(nn.Module):
+ """
+ This is a more standard version of the position embedding, very similar to the one
+ used by the Attention is all you need paper, generalized to work on images.
+ """
+
+ def __init__(
+ self, num_pos_feats=64, temperatureH=10000, temperatureW=10000, normalize=False, scale=None
+ ):
+ super().__init__()
+ self.num_pos_feats = num_pos_feats
+ self.temperatureH = temperatureH
+ self.temperatureW = temperatureW
+ self.normalize = normalize
+ if scale is not None and normalize is False:
+ raise ValueError("normalize should be True if scale is passed")
+ if scale is None:
+ scale = 2 * math.pi
+ self.scale = scale
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ mask = tensor_list.mask
+ assert mask is not None
+ not_mask = ~mask
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
+
+ # import ipdb; ipdb.set_trace()
+
+ if self.normalize:
+ eps = 1e-6
+ y_embed = y_embed / (y_embed[:, -1:, :] + eps) * self.scale
+ x_embed = x_embed / (x_embed[:, :, -1:] + eps) * self.scale
+
+ dim_tx = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_tx = self.temperatureW ** (2 * (torch.div(dim_tx, 2, rounding_mode='floor')) / self.num_pos_feats)
+ pos_x = x_embed[:, :, :, None] / dim_tx
+
+ dim_ty = torch.arange(self.num_pos_feats, dtype=torch.float32, device=x.device)
+ dim_ty = self.temperatureH ** (2 * (torch.div(dim_ty, 2, rounding_mode='floor')) / self.num_pos_feats)
+ pos_y = y_embed[:, :, :, None] / dim_ty
+
+ pos_x = torch.stack(
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos_y = torch.stack(
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()), dim=4
+ ).flatten(3)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+
+ # import ipdb; ipdb.set_trace()
+
+ return pos
+
+
+class PositionEmbeddingLearned(nn.Module):
+ """
+ Absolute pos embedding, learned.
+ """
+
+ def __init__(self, num_pos_feats=256):
+ super().__init__()
+ self.row_embed = nn.Embedding(50, num_pos_feats)
+ self.col_embed = nn.Embedding(50, num_pos_feats)
+ self.reset_parameters()
+
+ def reset_parameters(self):
+ nn.init.uniform_(self.row_embed.weight)
+ nn.init.uniform_(self.col_embed.weight)
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+ h, w = x.shape[-2:]
+ i = torch.arange(w, device=x.device)
+ j = torch.arange(h, device=x.device)
+ x_emb = self.col_embed(i)
+ y_emb = self.row_embed(j)
+ pos = (
+ torch.cat(
+ [
+ x_emb.unsqueeze(0).repeat(h, 1, 1),
+ y_emb.unsqueeze(1).repeat(1, w, 1),
+ ],
+ dim=-1,
+ )
+ .permute(2, 0, 1)
+ .unsqueeze(0)
+ .repeat(x.shape[0], 1, 1, 1)
+ )
+ return pos
+
+
+def build_position_encoding(args):
+ N_steps = args.hidden_dim // 2
+ if args.position_embedding in ("v2", "sine"):
+ # TODO find a better way of exposing other arguments
+ position_embedding = PositionEmbeddingSineHW(
+ N_steps,
+ temperatureH=args.pe_temperatureH,
+ temperatureW=args.pe_temperatureW,
+ normalize=True,
+ )
+ elif args.position_embedding in ("v3", "learned"):
+ position_embedding = PositionEmbeddingLearned(N_steps)
+ else:
+ raise ValueError(f"not supported {args.position_embedding}")
+
+ return position_embedding
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..1c66194deb5dd370e797e57e2712f44303e568cc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/backbone/swin_transformer.py
@@ -0,0 +1,802 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# --------------------------------------------------------
+# modified from https://github.com/SwinTransformer/Swin-Transformer-Object-Detection/blob/master/mmdet/models/backbones/swin_transformer.py
+# --------------------------------------------------------
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+from timm.models.layers import DropPath, to_2tuple, trunc_normal_
+
+from groundingdino.util.misc import NestedTensor
+
+
+class Mlp(nn.Module):
+ """Multilayer perceptron."""
+
+ def __init__(
+ self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.0
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+def window_partition(x, window_size):
+ """
+ Args:
+ x: (B, H, W, C)
+ window_size (int): window size
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
+ B, H, W, C = x.shape
+ x = x.view(B, H // window_size, window_size, W // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows
+
+
+def window_reverse(windows, window_size, H, W):
+ """
+ Args:
+ windows: (num_windows*B, window_size, window_size, C)
+ window_size (int): Window size
+ H (int): Height of image
+ W (int): Width of image
+ Returns:
+ x: (B, H, W, C)
+ """
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
+ x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
+ return x
+
+
+class WindowAttention(nn.Module):
+ """Window based multi-head self attention (W-MSA) module with relative position bias.
+ It supports both of shifted and non-shifted window.
+ Args:
+ dim (int): Number of input channels.
+ window_size (tuple[int]): The height and width of the window.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
+ """
+
+ def __init__(
+ self,
+ dim,
+ window_size,
+ num_heads,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop=0.0,
+ proj_drop=0.0,
+ ):
+
+ super().__init__()
+ self.dim = dim
+ self.window_size = window_size # Wh, Ww
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = qk_scale or head_dim**-0.5
+
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1), num_heads)
+ ) # 2*Wh-1 * 2*Ww-1, nH
+
+ # get pair-wise relative position index for each token inside the window
+ coords_h = torch.arange(self.window_size[0])
+ coords_w = torch.arange(self.window_size[1])
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] # 2, Wh*Ww, Wh*Ww
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous() # Wh*Ww, Wh*Ww, 2
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
+ self.register_buffer("relative_position_index", relative_position_index)
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ trunc_normal_(self.relative_position_bias_table, std=0.02)
+ self.softmax = nn.Softmax(dim=-1)
+
+ def forward(self, x, mask=None):
+ """Forward function.
+ Args:
+ x: input features with shape of (num_windows*B, N, C)
+ mask: (0/-inf) mask with shape of (num_windows, Wh*Ww, Wh*Ww) or None
+ """
+ B_, N, C = x.shape
+ qkv = (
+ self.qkv(x)
+ .reshape(B_, N, 3, self.num_heads, C // self.num_heads)
+ .permute(2, 0, 3, 1, 4)
+ )
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
+
+ q = q * self.scale
+ attn = q @ k.transpose(-2, -1)
+
+ relative_position_bias = self.relative_position_bias_table[
+ self.relative_position_index.view(-1)
+ ].view(
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
+ ) # Wh*Ww,Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(
+ 2, 0, 1
+ ).contiguous() # nH, Wh*Ww, Wh*Ww
+ attn = attn + relative_position_bias.unsqueeze(0)
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N) + mask.unsqueeze(1).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+ else:
+ attn = self.softmax(attn)
+
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+class SwinTransformerBlock(nn.Module):
+ """Swin Transformer Block.
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (int): Window size.
+ shift_size (int): Shift size for SW-MSA.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float, optional): Stochastic depth rate. Default: 0.0
+ act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(
+ self,
+ dim,
+ num_heads,
+ window_size=7,
+ shift_size=0,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ act_layer=nn.GELU,
+ norm_layer=nn.LayerNorm,
+ ):
+ super().__init__()
+ self.dim = dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.shift_size = shift_size
+ self.mlp_ratio = mlp_ratio
+ assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size"
+
+ self.norm1 = norm_layer(dim)
+ self.attn = WindowAttention(
+ dim,
+ window_size=to_2tuple(self.window_size),
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ )
+
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(
+ in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop
+ )
+
+ self.H = None
+ self.W = None
+
+ def forward(self, x, mask_matrix):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ mask_matrix: Attention mask for cyclic shift.
+ """
+ B, L, C = x.shape
+ H, W = self.H, self.W
+ assert L == H * W, "input feature has wrong size"
+
+ shortcut = x
+ x = self.norm1(x)
+ x = x.view(B, H, W, C)
+
+ # pad feature maps to multiples of window size
+ pad_l = pad_t = 0
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
+ x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b))
+ _, Hp, Wp, _ = x.shape
+
+ # cyclic shift
+ if self.shift_size > 0:
+ shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
+ attn_mask = mask_matrix
+ else:
+ shifted_x = x
+ attn_mask = None
+
+ # partition windows
+ x_windows = window_partition(
+ shifted_x, self.window_size
+ ) # nW*B, window_size, window_size, C
+ x_windows = x_windows.view(
+ -1, self.window_size * self.window_size, C
+ ) # nW*B, window_size*window_size, C
+
+ # W-MSA/SW-MSA
+ attn_windows = self.attn(x_windows, mask=attn_mask) # nW*B, window_size*window_size, C
+
+ # merge windows
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
+ shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C
+
+ # reverse cyclic shift
+ if self.shift_size > 0:
+ x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
+ else:
+ x = shifted_x
+
+ if pad_r > 0 or pad_b > 0:
+ x = x[:, :H, :W, :].contiguous()
+
+ x = x.view(B, H * W, C)
+
+ # FFN
+ x = shortcut + self.drop_path(x)
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
+
+ return x
+
+
+class PatchMerging(nn.Module):
+ """Patch Merging Layer
+ Args:
+ dim (int): Number of input channels.
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ """
+
+ def __init__(self, dim, norm_layer=nn.LayerNorm):
+ super().__init__()
+ self.dim = dim
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
+ self.norm = norm_layer(4 * dim)
+
+ def forward(self, x, H, W):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ """
+ B, L, C = x.shape
+ assert L == H * W, "input feature has wrong size"
+
+ x = x.view(B, H, W, C)
+
+ # padding
+ pad_input = (H % 2 == 1) or (W % 2 == 1)
+ if pad_input:
+ x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2))
+
+ x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C
+ x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C
+ x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C
+ x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C
+ x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C
+ x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C
+
+ x = self.norm(x)
+ x = self.reduction(x)
+
+ return x
+
+
+class BasicLayer(nn.Module):
+ """A basic Swin Transformer layer for one stage.
+ Args:
+ dim (int): Number of feature channels
+ depth (int): Depths of this stage.
+ num_heads (int): Number of attention head.
+ window_size (int): Local window size. Default: 7.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set.
+ drop (float, optional): Dropout rate. Default: 0.0
+ attn_drop (float, optional): Attention dropout rate. Default: 0.0
+ drop_path (float | tuple[float], optional): Stochastic depth rate. Default: 0.0
+ norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm
+ downsample (nn.Module | None, optional): Downsample layer at the end of the layer. Default: None
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ """
+
+ def __init__(
+ self,
+ dim,
+ depth,
+ num_heads,
+ window_size=7,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ norm_layer=nn.LayerNorm,
+ downsample=None,
+ use_checkpoint=False,
+ ):
+ super().__init__()
+ self.window_size = window_size
+ self.shift_size = window_size // 2
+ self.depth = depth
+ self.use_checkpoint = use_checkpoint
+
+ # build blocks
+ self.blocks = nn.ModuleList(
+ [
+ SwinTransformerBlock(
+ dim=dim,
+ num_heads=num_heads,
+ window_size=window_size,
+ shift_size=0 if (i % 2 == 0) else window_size // 2,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop,
+ attn_drop=attn_drop,
+ drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path,
+ norm_layer=norm_layer,
+ )
+ for i in range(depth)
+ ]
+ )
+
+ # patch merging layer
+ if downsample is not None:
+ self.downsample = downsample(dim=dim, norm_layer=norm_layer)
+ else:
+ self.downsample = None
+
+ def forward(self, x, H, W):
+ """Forward function.
+ Args:
+ x: Input feature, tensor size (B, H*W, C).
+ H, W: Spatial resolution of the input feature.
+ """
+
+ # calculate attention mask for SW-MSA
+ Hp = int(np.ceil(H / self.window_size)) * self.window_size
+ Wp = int(np.ceil(W / self.window_size)) * self.window_size
+ img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1
+ h_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ w_slices = (
+ slice(0, -self.window_size),
+ slice(-self.window_size, -self.shift_size),
+ slice(-self.shift_size, None),
+ )
+ cnt = 0
+ for h in h_slices:
+ for w in w_slices:
+ img_mask[:, h, w, :] = cnt
+ cnt += 1
+
+ mask_windows = window_partition(
+ img_mask, self.window_size
+ ) # nW, window_size, window_size, 1
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(
+ attn_mask == 0, float(0.0)
+ )
+
+ for blk in self.blocks:
+ blk.H, blk.W = H, W
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(blk, x, attn_mask)
+ else:
+ x = blk(x, attn_mask)
+ if self.downsample is not None:
+ x_down = self.downsample(x, H, W)
+ Wh, Ww = (H + 1) // 2, (W + 1) // 2
+ return x, H, W, x_down, Wh, Ww
+ else:
+ return x, H, W, x, H, W
+
+
+class PatchEmbed(nn.Module):
+ """Image to Patch Embedding
+ Args:
+ patch_size (int): Patch token size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ norm_layer (nn.Module, optional): Normalization layer. Default: None
+ """
+
+ def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None):
+ super().__init__()
+ patch_size = to_2tuple(patch_size)
+ self.patch_size = patch_size
+
+ self.in_chans = in_chans
+ self.embed_dim = embed_dim
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
+ if norm_layer is not None:
+ self.norm = norm_layer(embed_dim)
+ else:
+ self.norm = None
+
+ def forward(self, x):
+ """Forward function."""
+ # padding
+ _, _, H, W = x.size()
+ if W % self.patch_size[1] != 0:
+ x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1]))
+ if H % self.patch_size[0] != 0:
+ x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0]))
+
+ x = self.proj(x) # B C Wh Ww
+ if self.norm is not None:
+ Wh, Ww = x.size(2), x.size(3)
+ x = x.flatten(2).transpose(1, 2)
+ x = self.norm(x)
+ x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww)
+
+ return x
+
+
+class SwinTransformer(nn.Module):
+ """Swin Transformer backbone.
+ A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer using Shifted Windows` -
+ https://arxiv.org/pdf/2103.14030
+ Args:
+ pretrain_img_size (int): Input image size for training the pretrained model,
+ used in absolute postion embedding. Default 224.
+ patch_size (int | tuple(int)): Patch size. Default: 4.
+ in_chans (int): Number of input image channels. Default: 3.
+ embed_dim (int): Number of linear projection output channels. Default: 96.
+ depths (tuple[int]): Depths of each Swin Transformer stage.
+ num_heads (tuple[int]): Number of attention head of each stage.
+ window_size (int): Window size. Default: 7.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim. Default: 4.
+ qkv_bias (bool): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float): Override default qk scale of head_dim ** -0.5 if set.
+ drop_rate (float): Dropout rate.
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
+ drop_path_rate (float): Stochastic depth rate. Default: 0.2.
+ norm_layer (nn.Module): Normalization layer. Default: nn.LayerNorm.
+ ape (bool): If True, add absolute position embedding to the patch embedding. Default: False.
+ patch_norm (bool): If True, add normalization after patch embedding. Default: True.
+ out_indices (Sequence[int]): Output from which stages.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters.
+ use_checkpoint (bool): Whether to use checkpointing to save memory. Default: False.
+ dilation (bool): if True, the output size if 16x downsample, ow 32x downsample.
+ """
+
+ def __init__(
+ self,
+ pretrain_img_size=224,
+ patch_size=4,
+ in_chans=3,
+ embed_dim=96,
+ depths=[2, 2, 6, 2],
+ num_heads=[3, 6, 12, 24],
+ window_size=7,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.0,
+ attn_drop_rate=0.0,
+ drop_path_rate=0.2,
+ norm_layer=nn.LayerNorm,
+ ape=False,
+ patch_norm=True,
+ out_indices=(0, 1, 2, 3),
+ frozen_stages=-1,
+ dilation=False,
+ use_checkpoint=False,
+ ):
+ super().__init__()
+
+ self.pretrain_img_size = pretrain_img_size
+ self.num_layers = len(depths)
+ self.embed_dim = embed_dim
+ self.ape = ape
+ self.patch_norm = patch_norm
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.dilation = dilation
+
+ # if use_checkpoint:
+ # print("use_checkpoint!!!!!!!!!!!!!!!!!!!!!!!!")
+
+ # split image into non-overlapping patches
+ self.patch_embed = PatchEmbed(
+ patch_size=patch_size,
+ in_chans=in_chans,
+ embed_dim=embed_dim,
+ norm_layer=norm_layer if self.patch_norm else None,
+ )
+
+ # absolute position embedding
+ if self.ape:
+ pretrain_img_size = to_2tuple(pretrain_img_size)
+ patch_size = to_2tuple(patch_size)
+ patches_resolution = [
+ pretrain_img_size[0] // patch_size[0],
+ pretrain_img_size[1] // patch_size[1],
+ ]
+
+ self.absolute_pos_embed = nn.Parameter(
+ torch.zeros(1, embed_dim, patches_resolution[0], patches_resolution[1])
+ )
+ trunc_normal_(self.absolute_pos_embed, std=0.02)
+
+ self.pos_drop = nn.Dropout(p=drop_rate)
+
+ # stochastic depth
+ dpr = [
+ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
+ ] # stochastic depth decay rule
+
+ # build layers
+ self.layers = nn.ModuleList()
+ # prepare downsample list
+ downsamplelist = [PatchMerging for i in range(self.num_layers)]
+ downsamplelist[-1] = None
+ num_features = [int(embed_dim * 2**i) for i in range(self.num_layers)]
+ if self.dilation:
+ downsamplelist[-2] = None
+ num_features[-1] = int(embed_dim * 2 ** (self.num_layers - 1)) // 2
+ for i_layer in range(self.num_layers):
+ layer = BasicLayer(
+ # dim=int(embed_dim * 2 ** i_layer),
+ dim=num_features[i_layer],
+ depth=depths[i_layer],
+ num_heads=num_heads[i_layer],
+ window_size=window_size,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop_rate,
+ attn_drop=attn_drop_rate,
+ drop_path=dpr[sum(depths[:i_layer]) : sum(depths[: i_layer + 1])],
+ norm_layer=norm_layer,
+ # downsample=PatchMerging if (i_layer < self.num_layers - 1) else None,
+ downsample=downsamplelist[i_layer],
+ use_checkpoint=use_checkpoint,
+ )
+ self.layers.append(layer)
+
+ # num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)]
+ self.num_features = num_features
+
+ # add a norm layer for each output
+ for i_layer in out_indices:
+ layer = norm_layer(num_features[i_layer])
+ layer_name = f"norm{i_layer}"
+ self.add_module(layer_name, layer)
+
+ self._freeze_stages()
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+
+ if self.frozen_stages >= 1 and self.ape:
+ self.absolute_pos_embed.requires_grad = False
+
+ if self.frozen_stages >= 2:
+ self.pos_drop.eval()
+ for i in range(0, self.frozen_stages - 1):
+ m = self.layers[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ # def init_weights(self, pretrained=None):
+ # """Initialize the weights in backbone.
+ # Args:
+ # pretrained (str, optional): Path to pre-trained weights.
+ # Defaults to None.
+ # """
+
+ # def _init_weights(m):
+ # if isinstance(m, nn.Linear):
+ # trunc_normal_(m.weight, std=.02)
+ # if isinstance(m, nn.Linear) and m.bias is not None:
+ # nn.init.constant_(m.bias, 0)
+ # elif isinstance(m, nn.LayerNorm):
+ # nn.init.constant_(m.bias, 0)
+ # nn.init.constant_(m.weight, 1.0)
+
+ # if isinstance(pretrained, str):
+ # self.apply(_init_weights)
+ # logger = get_root_logger()
+ # load_checkpoint(self, pretrained, strict=False, logger=logger)
+ # elif pretrained is None:
+ # self.apply(_init_weights)
+ # else:
+ # raise TypeError('pretrained must be a str or None')
+
+ def forward_raw(self, x):
+ """Forward function."""
+ x = self.patch_embed(x)
+
+ Wh, Ww = x.size(2), x.size(3)
+ if self.ape:
+ # interpolate the position embedding to the corresponding size
+ absolute_pos_embed = F.interpolate(
+ self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
+ )
+ x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
+ else:
+ x = x.flatten(2).transpose(1, 2)
+ x = self.pos_drop(x)
+
+ outs = []
+ for i in range(self.num_layers):
+ layer = self.layers[i]
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
+ # import ipdb; ipdb.set_trace()
+
+ if i in self.out_indices:
+ norm_layer = getattr(self, f"norm{i}")
+ x_out = norm_layer(x_out)
+
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
+ outs.append(out)
+ # in:
+ # torch.Size([2, 3, 1024, 1024])
+ # outs:
+ # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
+ # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
+ return tuple(outs)
+
+ def forward(self, tensor_list: NestedTensor):
+ x = tensor_list.tensors
+
+ """Forward function."""
+ x = self.patch_embed(x)
+
+ Wh, Ww = x.size(2), x.size(3)
+ if self.ape:
+ # interpolate the position embedding to the corresponding size
+ absolute_pos_embed = F.interpolate(
+ self.absolute_pos_embed, size=(Wh, Ww), mode="bicubic"
+ )
+ x = (x + absolute_pos_embed).flatten(2).transpose(1, 2) # B Wh*Ww C
+ else:
+ x = x.flatten(2).transpose(1, 2)
+ x = self.pos_drop(x)
+
+ outs = []
+ for i in range(self.num_layers):
+ layer = self.layers[i]
+ x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww)
+
+ if i in self.out_indices:
+ norm_layer = getattr(self, f"norm{i}")
+ x_out = norm_layer(x_out)
+
+ out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous()
+ outs.append(out)
+ # in:
+ # torch.Size([2, 3, 1024, 1024])
+ # out:
+ # [torch.Size([2, 192, 256, 256]), torch.Size([2, 384, 128, 128]), \
+ # torch.Size([2, 768, 64, 64]), torch.Size([2, 1536, 32, 32])]
+
+ # collect for nesttensors
+ outs_dict = {}
+ for idx, out_i in enumerate(outs):
+ m = tensor_list.mask
+ assert m is not None
+ mask = F.interpolate(m[None].float(), size=out_i.shape[-2:]).to(torch.bool)[0]
+ outs_dict[idx] = NestedTensor(out_i, mask)
+
+ return outs_dict
+
+ def train(self, mode=True):
+ """Convert the model into training mode while keep layers freezed."""
+ super(SwinTransformer, self).train(mode)
+ self._freeze_stages()
+
+
+def build_swin_transformer(modelname, pretrain_img_size, **kw):
+ assert modelname in [
+ "swin_T_224_1k",
+ "swin_B_224_22k",
+ "swin_B_384_22k",
+ "swin_L_224_22k",
+ "swin_L_384_22k",
+ ]
+
+ model_para_dict = {
+ "swin_T_224_1k": dict(
+ embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7
+ ),
+ "swin_B_224_22k": dict(
+ embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=7
+ ),
+ "swin_B_384_22k": dict(
+ embed_dim=128, depths=[2, 2, 18, 2], num_heads=[4, 8, 16, 32], window_size=12
+ ),
+ "swin_L_224_22k": dict(
+ embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=7
+ ),
+ "swin_L_384_22k": dict(
+ embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12
+ ),
+ }
+ kw_cgf = model_para_dict[modelname]
+ kw_cgf.update(kw)
+ model = SwinTransformer(pretrain_img_size=pretrain_img_size, **kw_cgf)
+ return model
+
+
+if __name__ == "__main__":
+ model = build_swin_transformer("swin_L_384_22k", 384, dilation=True)
+ x = torch.rand(2, 3, 1024, 1024)
+ y = model.forward_raw(x)
+ import ipdb
+
+ ipdb.set_trace()
+ x = torch.rand(2, 3, 384, 384)
+ y = model.forward_raw(x)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/bertwarper.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/bertwarper.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0cf9779b270e1aead32845006f8b881fcba37ad
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/bertwarper.py
@@ -0,0 +1,273 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import torch
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+from torch import Tensor, nn
+from torchvision.ops.boxes import nms
+from transformers import BertConfig, BertModel, BertPreTrainedModel
+from transformers.modeling_outputs import BaseModelOutputWithPoolingAndCrossAttentions
+
+
+class BertModelWarper(nn.Module):
+ def __init__(self, bert_model):
+ super().__init__()
+ # self.bert = bert_modelc
+
+ self.config = bert_model.config
+ self.embeddings = bert_model.embeddings
+ self.encoder = bert_model.encoder
+ self.pooler = bert_model.pooler
+
+ self.get_extended_attention_mask = bert_model.get_extended_attention_mask
+ self.invert_attention_mask = bert_model.invert_attention_mask
+ self.get_head_mask = bert_model.get_head_mask
+
+ def forward(
+ self,
+ input_ids=None,
+ attention_mask=None,
+ token_type_ids=None,
+ position_ids=None,
+ head_mask=None,
+ inputs_embeds=None,
+ encoder_hidden_states=None,
+ encoder_attention_mask=None,
+ past_key_values=None,
+ use_cache=None,
+ output_attentions=None,
+ output_hidden_states=None,
+ return_dict=None,
+ ):
+ r"""
+ encoder_hidden_states (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if
+ the model is configured as a decoder.
+ encoder_attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in
+ the cross-attention if the model is configured as a decoder. Mask values selected in ``[0, 1]``:
+
+ - 1 for tokens that are **not masked**,
+ - 0 for tokens that are **masked**.
+ past_key_values (:obj:`tuple(tuple(torch.FloatTensor))` of length :obj:`config.n_layers` with each tuple having 4 tensors of shape :obj:`(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
+
+ If :obj:`past_key_values` are used, the user can optionally input only the last :obj:`decoder_input_ids`
+ (those that don't have their past key value states given to this model) of shape :obj:`(batch_size, 1)`
+ instead of all :obj:`decoder_input_ids` of shape :obj:`(batch_size, sequence_length)`.
+ use_cache (:obj:`bool`, `optional`):
+ If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
+ decoding (see :obj:`past_key_values`).
+ """
+ output_attentions = (
+ output_attentions if output_attentions is not None else self.config.output_attentions
+ )
+ output_hidden_states = (
+ output_hidden_states
+ if output_hidden_states is not None
+ else self.config.output_hidden_states
+ )
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
+
+ if self.config.is_decoder:
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
+ else:
+ use_cache = False
+
+ if input_ids is not None and inputs_embeds is not None:
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
+ elif input_ids is not None:
+ input_shape = input_ids.size()
+ batch_size, seq_length = input_shape
+ elif inputs_embeds is not None:
+ input_shape = inputs_embeds.size()[:-1]
+ batch_size, seq_length = input_shape
+ else:
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
+
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
+
+ # past_key_values_length
+ past_key_values_length = (
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
+ )
+
+ if attention_mask is None:
+ attention_mask = torch.ones(
+ ((batch_size, seq_length + past_key_values_length)), device=device
+ )
+ if token_type_ids is None:
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
+
+ # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length]
+ # ourselves in which case we just need to make it broadcastable to all heads.
+ extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(
+ attention_mask, input_shape, device
+ )
+
+ # If a 2D or 3D attention mask is provided for the cross-attention
+ # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
+ if self.config.is_decoder and encoder_hidden_states is not None:
+ encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
+ encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
+ if encoder_attention_mask is None:
+ encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
+ encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask)
+ else:
+ encoder_extended_attention_mask = None
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+
+ # Prepare head mask if needed
+ # 1.0 in head_mask indicate we keep the head
+ # attention_probs has shape bsz x n_heads x N x N
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
+
+ embedding_output = self.embeddings(
+ input_ids=input_ids,
+ position_ids=position_ids,
+ token_type_ids=token_type_ids,
+ inputs_embeds=inputs_embeds,
+ past_key_values_length=past_key_values_length,
+ )
+
+ encoder_outputs = self.encoder(
+ embedding_output,
+ attention_mask=extended_attention_mask,
+ head_mask=head_mask,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_extended_attention_mask,
+ past_key_values=past_key_values,
+ use_cache=use_cache,
+ output_attentions=output_attentions,
+ output_hidden_states=output_hidden_states,
+ return_dict=return_dict,
+ )
+ sequence_output = encoder_outputs[0]
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
+
+ if not return_dict:
+ return (sequence_output, pooled_output) + encoder_outputs[1:]
+
+ return BaseModelOutputWithPoolingAndCrossAttentions(
+ last_hidden_state=sequence_output,
+ pooler_output=pooled_output,
+ past_key_values=encoder_outputs.past_key_values,
+ hidden_states=encoder_outputs.hidden_states,
+ attentions=encoder_outputs.attentions,
+ cross_attentions=encoder_outputs.cross_attentions,
+ )
+
+
+class TextEncoderShell(nn.Module):
+ def __init__(self, text_encoder):
+ super().__init__()
+ self.text_encoder = text_encoder
+ self.config = self.text_encoder.config
+
+ def forward(self, **kw):
+ # feed into text encoder
+ return self.text_encoder(**kw)
+
+
+def generate_masks_with_special_tokens(tokenized, special_tokens_list, tokenizer):
+ """Generate attention mask between each pair of special tokens
+ Args:
+ input_ids (torch.Tensor): input ids. Shape: [bs, num_token]
+ special_tokens_mask (list): special tokens mask.
+ Returns:
+ torch.Tensor: attention mask between each special tokens.
+ """
+ input_ids = tokenized["input_ids"]
+ bs, num_token = input_ids.shape
+ # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens
+ special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool()
+ for special_token in special_tokens_list:
+ special_tokens_mask |= input_ids == special_token
+
+ # idxs: each row is a list of indices of special tokens
+ idxs = torch.nonzero(special_tokens_mask)
+
+ # generate attention mask and positional ids
+ attention_mask = (
+ torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1)
+ )
+ position_ids = torch.zeros((bs, num_token), device=input_ids.device)
+ previous_col = 0
+ for i in range(idxs.shape[0]):
+ row, col = idxs[i]
+ if (col == 0) or (col == num_token - 1):
+ attention_mask[row, col, col] = True
+ position_ids[row, col] = 0
+ else:
+ attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True
+ position_ids[row, previous_col + 1 : col + 1] = torch.arange(
+ 0, col - previous_col, device=input_ids.device
+ )
+
+ previous_col = col
+
+ # # padding mask
+ # padding_mask = tokenized['attention_mask']
+ # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool()
+
+ return attention_mask, position_ids.to(torch.long)
+
+
+def generate_masks_with_special_tokens_and_transfer_map(tokenized, special_tokens_list, tokenizer):
+ """Generate attention mask between each pair of special tokens
+ Args:
+ input_ids (torch.Tensor): input ids. Shape: [bs, num_token]
+ special_tokens_mask (list): special tokens mask.
+ Returns:
+ torch.Tensor: attention mask between each special tokens.
+ """
+ input_ids = tokenized["input_ids"]
+ bs, num_token = input_ids.shape
+ # special_tokens_mask: bs, num_token. 1 for special tokens. 0 for normal tokens
+ special_tokens_mask = torch.zeros((bs, num_token), device=input_ids.device).bool()
+ for special_token in special_tokens_list:
+ special_tokens_mask |= input_ids == special_token
+
+ # idxs: each row is a list of indices of special tokens
+ idxs = torch.nonzero(special_tokens_mask)
+
+ # generate attention mask and positional ids
+ attention_mask = (
+ torch.eye(num_token, device=input_ids.device).bool().unsqueeze(0).repeat(bs, 1, 1)
+ )
+ position_ids = torch.zeros((bs, num_token), device=input_ids.device)
+ cate_to_token_mask_list = [[] for _ in range(bs)]
+ previous_col = 0
+ for i in range(idxs.shape[0]):
+ row, col = idxs[i]
+ if (col == 0) or (col == num_token - 1):
+ attention_mask[row, col, col] = True
+ position_ids[row, col] = 0
+ else:
+ attention_mask[row, previous_col + 1 : col + 1, previous_col + 1 : col + 1] = True
+ position_ids[row, previous_col + 1 : col + 1] = torch.arange(
+ 0, col - previous_col, device=input_ids.device
+ )
+ c2t_maski = torch.zeros((num_token), device=input_ids.device).bool()
+ c2t_maski[previous_col + 1 : col] = True
+ cate_to_token_mask_list[row].append(c2t_maski)
+ previous_col = col
+
+ cate_to_token_mask_list = [
+ torch.stack(cate_to_token_mask_listi, dim=0)
+ for cate_to_token_mask_listi in cate_to_token_mask_list
+ ]
+
+ # # padding mask
+ # padding_mask = tokenized['attention_mask']
+ # attention_mask = attention_mask & padding_mask.unsqueeze(1).bool() & padding_mask.unsqueeze(2).bool()
+
+ return attention_mask, position_ids.to(torch.long), cate_to_token_mask_list
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h
new file mode 100644
index 0000000000000000000000000000000000000000..c7408eba007b424194618baa63726657e36875e3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn.h
@@ -0,0 +1,64 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+
+#include "ms_deform_attn_cpu.h"
+
+#ifdef WITH_CUDA
+#include "ms_deform_attn_cuda.h"
+#endif
+
+namespace groundingdino {
+
+at::Tensor
+ms_deform_attn_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ if (value.type().is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_forward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
+
+std::vector
+ms_deform_attn_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ if (value.type().is_cuda())
+ {
+#ifdef WITH_CUDA
+ return ms_deform_attn_cuda_backward(
+ value, spatial_shapes, level_start_index, sampling_loc, attn_weight, grad_output, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..551243fdadfd1682b5dc6628623b67a79b3f6c74
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.cpp
@@ -0,0 +1,43 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+
+#include
+#include
+
+namespace groundingdino {
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+ AT_ERROR("Not implement on cpu");
+}
+
+} // namespace groundingdino
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h
new file mode 100644
index 0000000000000000000000000000000000000000..b2b88e8c46f19b6db0933163e57ccdb51180f517
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cpu.h
@@ -0,0 +1,35 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+namespace groundingdino {
+
+at::Tensor
+ms_deform_attn_cpu_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector
+ms_deform_attn_cpu_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+} // namespace groundingdino
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..d04fae8a9a45c11e4e74f3035e94762796da4096
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.cu
@@ -0,0 +1,156 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include "ms_deform_im2col_cuda.cuh"
+
+#include
+#include
+#include
+#include
+
+namespace groundingdino {
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step)
+{
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto output = at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ columns.data());
+
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads*channels});
+
+ return output;
+}
+
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step)
+{
+
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(), "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(), "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(), "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(), "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(), "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(), "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(), "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(), "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)", batch, im2col_step_);
+
+ auto grad_value = at::zeros_like(value);
+ auto grad_sampling_loc = at::zeros_like(sampling_loc);
+ auto grad_attn_weight = at::zeros_like(attn_weight);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view({batch/im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch/im2col_step_; ++n)
+ {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(at::cuda::getCurrentCUDAStream(),
+ grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(),
+ level_start_index.data(),
+ sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() + n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query, num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() + n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() + n * im2col_step_ * per_attn_weight_size);
+
+ }));
+ }
+
+ return {
+ grad_value, grad_sampling_loc, grad_attn_weight
+ };
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h
new file mode 100644
index 0000000000000000000000000000000000000000..ad1311a78f61303616504eb991aaa9c4a93d9948
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_attn_cuda.h
@@ -0,0 +1,33 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#pragma once
+#include
+
+namespace groundingdino {
+
+at::Tensor ms_deform_attn_cuda_forward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step);
+
+std::vector ms_deform_attn_cuda_backward(
+ const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const at::Tensor &grad_output,
+ const int im2col_step);
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..6bc2acb7aea0eab2e9e91e769a16861e1652c284
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/MsDeformAttn/ms_deform_im2col_cuda.cuh
@@ -0,0 +1,1327 @@
+/*!
+**************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************
+* Modified from DCN (https://github.com/msracver/Deformable-ConvNets)
+* Copyright (c) 2018 Microsoft
+**************************************************************************
+*/
+
+#include
+#include
+#include
+
+#include
+#include
+
+#include
+
+#define CUDA_KERNEL_LOOP(i, n) \
+ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \
+ i < (n); \
+ i += blockDim.x * gridDim.x)
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads)
+{
+ return (N + num_threads - 1) / num_threads;
+}
+
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(const scalar_t* &bottom_data,
+ const int &height, const int &width, const int &nheads, const int &channels,
+ const scalar_t &h, const scalar_t &w, const int &m, const int &c,
+ const scalar_t &top_grad,
+ const scalar_t &attn_weight,
+ scalar_t* &grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0)
+ {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value+ptr1, w1*top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1)
+ {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value+ptr2, w2*top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0)
+ {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value+ptr3, w3*top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1)
+ {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value+ptr4, w4*top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(const int n,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *data_col)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr = data_value + (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col) * weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockSize/2; s>0; s>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0)
+ {
+ scalar_t _grad_w=cache_grad_sampling_loc[0], _grad_h=cache_grad_sampling_loc[1], _grad_a=cache_grad_attn_weight[0];
+ int sid=2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid)
+ {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ extern __shared__ int _s[];
+ scalar_t* cache_grad_sampling_loc = (scalar_t*)_s;
+ scalar_t* cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc+(threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc+((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight+threadIdx.x)=0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc+(threadIdx.x << 1), cache_grad_attn_weight+threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s=blockDim.x/2, spre=blockDim.x; s>0; s>>=1, spre>>=1)
+ {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre)
+ {
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] += cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0)
+ {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(const int n,
+ const scalar_t *grad_col,
+ const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t *grad_value,
+ scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight)
+{
+ CUDA_KERNEL_LOOP(index, n)
+ {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col=0; l_col < num_levels; ++l_col)
+ {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset = data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col=0; p_col < num_point; ++p_col)
+ {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w)
+ {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im, w_im, m_col, c_col,
+ top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream,
+ const scalar_t* data_value,
+ const int64_t* data_spatial_shapes,
+ const int64_t* data_level_start_index,
+ const scalar_t* data_sampling_loc,
+ const scalar_t* data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* data_col)
+{
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
+
+template
+void ms_deformable_col2im_cuda(cudaStream_t stream,
+ const scalar_t* grad_col,
+ const scalar_t* data_value,
+ const int64_t * data_spatial_shapes,
+ const int64_t * data_level_start_index,
+ const scalar_t * data_sampling_loc,
+ const scalar_t * data_attn_weight,
+ const int batch_size,
+ const int spatial_size,
+ const int num_heads,
+ const int channels,
+ const int num_levels,
+ const int num_query,
+ const int num_point,
+ scalar_t* grad_value,
+ scalar_t* grad_sampling_loc,
+ scalar_t* grad_attn_weight)
+{
+ const int num_threads = (channels > CUDA_NUM_THREADS)?CUDA_NUM_THREADS:channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024)
+ {
+ if ((channels & 1023) == 0)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ else{
+ switch(channels)
+ {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ break;
+ default:
+ if (channels < 64)
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ else
+ {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels,
+ grad_col,
+ data_value,
+ data_spatial_shapes,
+ data_level_start_index,
+ data_sampling_loc,
+ data_attn_weight,
+ batch_size,
+ spatial_size,
+ num_heads,
+ channels,
+ num_levels,
+ num_query,
+ num_point,
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess)
+ {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/cuda_version.cu b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/cuda_version.cu
new file mode 100644
index 0000000000000000000000000000000000000000..64569e34ffb250964de27e33e7a53f3822270b9e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/cuda_version.cu
@@ -0,0 +1,7 @@
+#include
+
+namespace groundingdino {
+int get_cudart_version() {
+ return CUDART_VERSION;
+}
+} // namespace groundingdino
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/vision.cpp b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/vision.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..c1f2c50c82909bbd5492c163d634af77a3ba1781
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/csrc/vision.cpp
@@ -0,0 +1,58 @@
+// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+
+#include "MsDeformAttn/ms_deform_attn.h"
+
+namespace groundingdino {
+
+#ifdef WITH_CUDA
+extern int get_cudart_version();
+#endif
+
+std::string get_cuda_version() {
+#ifdef WITH_CUDA
+ std::ostringstream oss;
+
+ // copied from
+ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/cuda/detail/CUDAHooks.cpp#L231
+ auto printCudaStyleVersion = [&](int v) {
+ oss << (v / 1000) << "." << (v / 10 % 100);
+ if (v % 10 != 0) {
+ oss << "." << (v % 10);
+ }
+ };
+ printCudaStyleVersion(get_cudart_version());
+ return oss.str();
+#else
+ return std::string("not available");
+#endif
+}
+
+// similar to
+// https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Version.cpp
+std::string get_compiler_version() {
+ std::ostringstream ss;
+#if defined(__GNUC__)
+#ifndef __clang__
+ { ss << "GCC " << __GNUC__ << "." << __GNUC_MINOR__; }
+#endif
+#endif
+
+#if defined(__clang_major__)
+ {
+ ss << "clang " << __clang_major__ << "." << __clang_minor__ << "."
+ << __clang_patchlevel__;
+ }
+#endif
+
+#if defined(_MSC_VER)
+ { ss << "MSVC " << _MSC_FULL_VER; }
+#endif
+ return ss.str();
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("ms_deform_attn_forward", &ms_deform_attn_forward, "ms_deform_attn_forward");
+ m.def("ms_deform_attn_backward", &ms_deform_attn_backward, "ms_deform_attn_backward");
+}
+
+} // namespace groundingdino
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/fuse_modules.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/fuse_modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..2753b3ddee43c7a9fe28d1824db5d786e7e1ad59
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/fuse_modules.py
@@ -0,0 +1,297 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from timm.models.layers import DropPath
+
+
+class FeatureResizer(nn.Module):
+ """
+ This class takes as input a set of embeddings of dimension C1 and outputs a set of
+ embedding of dimension C2, after a linear transformation, dropout and normalization (LN).
+ """
+
+ def __init__(self, input_feat_size, output_feat_size, dropout, do_ln=True):
+ super().__init__()
+ self.do_ln = do_ln
+ # Object feature encoding
+ self.fc = nn.Linear(input_feat_size, output_feat_size, bias=True)
+ self.layer_norm = nn.LayerNorm(output_feat_size, eps=1e-12)
+ self.dropout = nn.Dropout(dropout)
+
+ def forward(self, encoder_features):
+ x = self.fc(encoder_features)
+ if self.do_ln:
+ x = self.layer_norm(x)
+ output = self.dropout(x)
+ return output
+
+
+def l1norm(X, dim, eps=1e-8):
+ """L1-normalize columns of X"""
+ norm = torch.abs(X).sum(dim=dim, keepdim=True) + eps
+ X = torch.div(X, norm)
+ return X
+
+
+def l2norm(X, dim, eps=1e-8):
+ """L2-normalize columns of X"""
+ norm = torch.pow(X, 2).sum(dim=dim, keepdim=True).sqrt() + eps
+ X = torch.div(X, norm)
+ return X
+
+
+def func_attention(query, context, smooth=1, raw_feature_norm="softmax", eps=1e-8):
+ """
+ query: (n_context, queryL, d)
+ context: (n_context, sourceL, d)
+ """
+ batch_size_q, queryL = query.size(0), query.size(1)
+ batch_size, sourceL = context.size(0), context.size(1)
+
+ # Get attention
+ # --> (batch, d, queryL)
+ queryT = torch.transpose(query, 1, 2)
+
+ # (batch, sourceL, d)(batch, d, queryL)
+ # --> (batch, sourceL, queryL)
+ attn = torch.bmm(context, queryT)
+ if raw_feature_norm == "softmax":
+ # --> (batch*sourceL, queryL)
+ attn = attn.view(batch_size * sourceL, queryL)
+ attn = nn.Softmax()(attn)
+ # --> (batch, sourceL, queryL)
+ attn = attn.view(batch_size, sourceL, queryL)
+ elif raw_feature_norm == "l2norm":
+ attn = l2norm(attn, 2)
+ elif raw_feature_norm == "clipped_l2norm":
+ attn = nn.LeakyReLU(0.1)(attn)
+ attn = l2norm(attn, 2)
+ else:
+ raise ValueError("unknown first norm type:", raw_feature_norm)
+ # --> (batch, queryL, sourceL)
+ attn = torch.transpose(attn, 1, 2).contiguous()
+ # --> (batch*queryL, sourceL)
+ attn = attn.view(batch_size * queryL, sourceL)
+ attn = nn.Softmax()(attn * smooth)
+ # --> (batch, queryL, sourceL)
+ attn = attn.view(batch_size, queryL, sourceL)
+ # --> (batch, sourceL, queryL)
+ attnT = torch.transpose(attn, 1, 2).contiguous()
+
+ # --> (batch, d, sourceL)
+ contextT = torch.transpose(context, 1, 2)
+ # (batch x d x sourceL)(batch x sourceL x queryL)
+ # --> (batch, d, queryL)
+ weightedContext = torch.bmm(contextT, attnT)
+ # --> (batch, queryL, d)
+ weightedContext = torch.transpose(weightedContext, 1, 2)
+
+ return weightedContext, attnT
+
+
+class BiMultiHeadAttention(nn.Module):
+ def __init__(self, v_dim, l_dim, embed_dim, num_heads, dropout=0.1, cfg=None):
+ super(BiMultiHeadAttention, self).__init__()
+
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.head_dim = embed_dim // num_heads
+ self.v_dim = v_dim
+ self.l_dim = l_dim
+
+ assert (
+ self.head_dim * self.num_heads == self.embed_dim
+ ), f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
+ self.scale = self.head_dim ** (-0.5)
+ self.dropout = dropout
+
+ self.v_proj = nn.Linear(self.v_dim, self.embed_dim)
+ self.l_proj = nn.Linear(self.l_dim, self.embed_dim)
+ self.values_v_proj = nn.Linear(self.v_dim, self.embed_dim)
+ self.values_l_proj = nn.Linear(self.l_dim, self.embed_dim)
+
+ self.out_v_proj = nn.Linear(self.embed_dim, self.v_dim)
+ self.out_l_proj = nn.Linear(self.embed_dim, self.l_dim)
+
+ self.stable_softmax_2d = True
+ self.clamp_min_for_underflow = True
+ self.clamp_max_for_overflow = True
+
+ self._reset_parameters()
+
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
+
+ def _reset_parameters(self):
+ nn.init.xavier_uniform_(self.v_proj.weight)
+ self.v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.l_proj.weight)
+ self.l_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.values_v_proj.weight)
+ self.values_v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.values_l_proj.weight)
+ self.values_l_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.out_v_proj.weight)
+ self.out_v_proj.bias.data.fill_(0)
+ nn.init.xavier_uniform_(self.out_l_proj.weight)
+ self.out_l_proj.bias.data.fill_(0)
+
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
+ """_summary_
+
+ Args:
+ v (_type_): bs, n_img, dim
+ l (_type_): bs, n_text, dim
+ attention_mask_v (_type_, optional): _description_. bs, n_img
+ attention_mask_l (_type_, optional): _description_. bs, n_text
+
+ Returns:
+ _type_: _description_
+ """
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ bsz, tgt_len, _ = v.size()
+
+ query_states = self.v_proj(v) * self.scale
+ key_states = self._shape(self.l_proj(l), -1, bsz)
+ value_v_states = self._shape(self.values_v_proj(v), -1, bsz)
+ value_l_states = self._shape(self.values_l_proj(l), -1, bsz)
+
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
+ key_states = key_states.view(*proj_shape)
+ value_v_states = value_v_states.view(*proj_shape)
+ value_l_states = value_l_states.view(*proj_shape)
+
+ src_len = key_states.size(1)
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) # bs*nhead, nimg, ntxt
+
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
+ raise ValueError(
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is {attn_weights.size()}"
+ )
+
+ if self.stable_softmax_2d:
+ attn_weights = attn_weights - attn_weights.max()
+
+ if self.clamp_min_for_underflow:
+ attn_weights = torch.clamp(
+ attn_weights, min=-50000
+ ) # Do not increase -50000, data type half has quite limited range
+ if self.clamp_max_for_overflow:
+ attn_weights = torch.clamp(
+ attn_weights, max=50000
+ ) # Do not increase 50000, data type half has quite limited range
+
+ attn_weights_T = attn_weights.transpose(1, 2)
+ attn_weights_l = attn_weights_T - torch.max(attn_weights_T, dim=-1, keepdim=True)[0]
+ if self.clamp_min_for_underflow:
+ attn_weights_l = torch.clamp(
+ attn_weights_l, min=-50000
+ ) # Do not increase -50000, data type half has quite limited range
+ if self.clamp_max_for_overflow:
+ attn_weights_l = torch.clamp(
+ attn_weights_l, max=50000
+ ) # Do not increase 50000, data type half has quite limited range
+
+ # mask vison for language
+ if attention_mask_v is not None:
+ attention_mask_v = (
+ attention_mask_v[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1)
+ )
+ attn_weights_l.masked_fill_(attention_mask_v, float("-inf"))
+
+ attn_weights_l = attn_weights_l.softmax(dim=-1)
+
+ # mask language for vision
+ if attention_mask_l is not None:
+ attention_mask_l = (
+ attention_mask_l[:, None, None, :].repeat(1, self.num_heads, 1, 1).flatten(0, 1)
+ )
+ attn_weights.masked_fill_(attention_mask_l, float("-inf"))
+ attn_weights_v = attn_weights.softmax(dim=-1)
+
+ attn_probs_v = F.dropout(attn_weights_v, p=self.dropout, training=self.training)
+ attn_probs_l = F.dropout(attn_weights_l, p=self.dropout, training=self.training)
+
+ attn_output_v = torch.bmm(attn_probs_v, value_l_states)
+ attn_output_l = torch.bmm(attn_probs_l, value_v_states)
+
+ if attn_output_v.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output_v` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is {attn_output_v.size()}"
+ )
+
+ if attn_output_l.size() != (bsz * self.num_heads, src_len, self.head_dim):
+ raise ValueError(
+ f"`attn_output_l` should be of size {(bsz, self.num_heads, src_len, self.head_dim)}, but is {attn_output_l.size()}"
+ )
+
+ attn_output_v = attn_output_v.view(bsz, self.num_heads, tgt_len, self.head_dim)
+ attn_output_v = attn_output_v.transpose(1, 2)
+ attn_output_v = attn_output_v.reshape(bsz, tgt_len, self.embed_dim)
+
+ attn_output_l = attn_output_l.view(bsz, self.num_heads, src_len, self.head_dim)
+ attn_output_l = attn_output_l.transpose(1, 2)
+ attn_output_l = attn_output_l.reshape(bsz, src_len, self.embed_dim)
+
+ attn_output_v = self.out_v_proj(attn_output_v)
+ attn_output_l = self.out_l_proj(attn_output_l)
+
+ return attn_output_v, attn_output_l
+
+
+# Bi-Direction MHA (text->image, image->text)
+class BiAttentionBlock(nn.Module):
+ def __init__(
+ self,
+ v_dim,
+ l_dim,
+ embed_dim,
+ num_heads,
+ dropout=0.1,
+ drop_path=0.0,
+ init_values=1e-4,
+ cfg=None,
+ ):
+ """
+ Inputs:
+ embed_dim - Dimensionality of input and attention feature vectors
+ hidden_dim - Dimensionality of hidden layer in feed-forward network
+ (usually 2-4x larger than embed_dim)
+ num_heads - Number of heads to use in the Multi-Head Attention block
+ dropout - Amount of dropout to apply in the feed-forward network
+ """
+ super(BiAttentionBlock, self).__init__()
+
+ # pre layer norm
+ self.layer_norm_v = nn.LayerNorm(v_dim)
+ self.layer_norm_l = nn.LayerNorm(l_dim)
+ self.attn = BiMultiHeadAttention(
+ v_dim=v_dim, l_dim=l_dim, embed_dim=embed_dim, num_heads=num_heads, dropout=dropout
+ )
+
+ # add layer scale for training stability
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ self.gamma_v = nn.Parameter(init_values * torch.ones((v_dim)), requires_grad=True)
+ self.gamma_l = nn.Parameter(init_values * torch.ones((l_dim)), requires_grad=True)
+
+ def forward(self, v, l, attention_mask_v=None, attention_mask_l=None):
+ v = self.layer_norm_v(v)
+ l = self.layer_norm_l(l)
+ delta_v, delta_l = self.attn(
+ v, l, attention_mask_v=attention_mask_v, attention_mask_l=attention_mask_l
+ )
+ # v, l = v + delta_v, l + delta_l
+ v = v + self.drop_path(self.gamma_v * delta_v)
+ l = l + self.drop_path(self.gamma_l * delta_l)
+ return v, l
+
+ # def forward(self, v:List[torch.Tensor], l, attention_mask_v=None, attention_mask_l=None)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py
new file mode 100644
index 0000000000000000000000000000000000000000..052df6220595a1b39b7e2aea37ca4872d113dfd2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/groundingdino.py
@@ -0,0 +1,395 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR model and criterion classes.
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Modified from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+# Modified from Deformable DETR (https://github.com/fundamentalvision/Deformable-DETR)
+# Copyright (c) 2020 SenseTime. All Rights Reserved.
+# ------------------------------------------------------------------------
+import copy
+from typing import List
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from torchvision.ops.boxes import nms
+from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
+
+from groundingdino.util import box_ops, get_tokenlizer
+from groundingdino.util.misc import (
+ NestedTensor,
+ accuracy,
+ get_world_size,
+ interpolate,
+ inverse_sigmoid,
+ is_dist_avail_and_initialized,
+ nested_tensor_from_tensor_list,
+)
+from groundingdino.util.utils import get_phrases_from_posmap
+from groundingdino.util.visualizer import COCOVisualizer
+from groundingdino.util.vl_utils import create_positive_map_from_span
+
+from ..registry import MODULE_BUILD_FUNCS
+from .backbone import build_backbone
+from .bertwarper import (
+ BertModelWarper,
+ generate_masks_with_special_tokens,
+ generate_masks_with_special_tokens_and_transfer_map,
+)
+from .transformer import build_transformer
+from .utils import MLP, ContrastiveEmbed, sigmoid_focal_loss
+
+
+class GroundingDINO(nn.Module):
+ """This is the Cross-Attention Detector module that performs object detection"""
+
+ def __init__(
+ self,
+ backbone,
+ transformer,
+ num_queries,
+ aux_loss=False,
+ iter_update=False,
+ query_dim=2,
+ num_feature_levels=1,
+ nheads=8,
+ # two stage
+ two_stage_type="no", # ['no', 'standard']
+ dec_pred_bbox_embed_share=True,
+ two_stage_class_embed_share=True,
+ two_stage_bbox_embed_share=True,
+ num_patterns=0,
+ dn_number=100,
+ dn_box_noise_scale=0.4,
+ dn_label_noise_ratio=0.5,
+ dn_labelbook_size=100,
+ text_encoder_type="bert-base-uncased",
+ sub_sentence_present=True,
+ max_text_len=256,
+ ):
+ """Initializes the model.
+ Parameters:
+ backbone: torch module of the backbone to be used. See backbone.py
+ transformer: torch module of the transformer architecture. See transformer.py
+ num_queries: number of object queries, ie detection slot. This is the maximal number of objects
+ Conditional DETR can detect in a single image. For COCO, we recommend 100 queries.
+ aux_loss: True if auxiliary decoding losses (loss at each decoder layer) are to be used.
+ """
+ super().__init__()
+ self.num_queries = num_queries
+ self.transformer = transformer
+ self.hidden_dim = hidden_dim = transformer.d_model
+ self.num_feature_levels = num_feature_levels
+ self.nheads = nheads
+ self.max_text_len = 256
+ self.sub_sentence_present = sub_sentence_present
+
+ # setting query dim
+ self.query_dim = query_dim
+ assert query_dim == 4
+
+ # for dn training
+ self.num_patterns = num_patterns
+ self.dn_number = dn_number
+ self.dn_box_noise_scale = dn_box_noise_scale
+ self.dn_label_noise_ratio = dn_label_noise_ratio
+ self.dn_labelbook_size = dn_labelbook_size
+
+ # bert
+ self.tokenizer = get_tokenlizer.get_tokenlizer(text_encoder_type)
+ self.bert = get_tokenlizer.get_pretrained_language_model(text_encoder_type)
+ self.bert.pooler.dense.weight.requires_grad_(False)
+ self.bert.pooler.dense.bias.requires_grad_(False)
+ self.bert = BertModelWarper(bert_model=self.bert)
+
+ self.feat_map = nn.Linear(self.bert.config.hidden_size, self.hidden_dim, bias=True)
+ nn.init.constant_(self.feat_map.bias.data, 0)
+ nn.init.xavier_uniform_(self.feat_map.weight.data)
+ # freeze
+
+ # special tokens
+ self.specical_tokens = self.tokenizer.convert_tokens_to_ids(["[CLS]", "[SEP]", ".", "?"])
+
+ # prepare input projection layers
+ if num_feature_levels > 1:
+ num_backbone_outs = len(backbone.num_channels)
+ input_proj_list = []
+ for _ in range(num_backbone_outs):
+ in_channels = backbone.num_channels[_]
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ )
+ for _ in range(num_feature_levels - num_backbone_outs):
+ input_proj_list.append(
+ nn.Sequential(
+ nn.Conv2d(in_channels, hidden_dim, kernel_size=3, stride=2, padding=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ )
+ in_channels = hidden_dim
+ self.input_proj = nn.ModuleList(input_proj_list)
+ else:
+ assert two_stage_type == "no", "two_stage_type should be no if num_feature_levels=1 !!!"
+ self.input_proj = nn.ModuleList(
+ [
+ nn.Sequential(
+ nn.Conv2d(backbone.num_channels[-1], hidden_dim, kernel_size=1),
+ nn.GroupNorm(32, hidden_dim),
+ )
+ ]
+ )
+
+ self.backbone = backbone
+ self.aux_loss = aux_loss
+ self.box_pred_damping = box_pred_damping = None
+
+ self.iter_update = iter_update
+ assert iter_update, "Why not iter_update?"
+
+ # prepare pred layers
+ self.dec_pred_bbox_embed_share = dec_pred_bbox_embed_share
+ # prepare class & box embed
+ _class_embed = ContrastiveEmbed()
+
+ _bbox_embed = MLP(hidden_dim, hidden_dim, 4, 3)
+ nn.init.constant_(_bbox_embed.layers[-1].weight.data, 0)
+ nn.init.constant_(_bbox_embed.layers[-1].bias.data, 0)
+
+ if dec_pred_bbox_embed_share:
+ box_embed_layerlist = [_bbox_embed for i in range(transformer.num_decoder_layers)]
+ else:
+ box_embed_layerlist = [
+ copy.deepcopy(_bbox_embed) for i in range(transformer.num_decoder_layers)
+ ]
+ class_embed_layerlist = [_class_embed for i in range(transformer.num_decoder_layers)]
+ self.bbox_embed = nn.ModuleList(box_embed_layerlist)
+ self.class_embed = nn.ModuleList(class_embed_layerlist)
+ self.transformer.decoder.bbox_embed = self.bbox_embed
+ self.transformer.decoder.class_embed = self.class_embed
+
+ # two stage
+ self.two_stage_type = two_stage_type
+ assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format(
+ two_stage_type
+ )
+ if two_stage_type != "no":
+ if two_stage_bbox_embed_share:
+ assert dec_pred_bbox_embed_share
+ self.transformer.enc_out_bbox_embed = _bbox_embed
+ else:
+ self.transformer.enc_out_bbox_embed = copy.deepcopy(_bbox_embed)
+
+ if two_stage_class_embed_share:
+ assert dec_pred_bbox_embed_share
+ self.transformer.enc_out_class_embed = _class_embed
+ else:
+ self.transformer.enc_out_class_embed = copy.deepcopy(_class_embed)
+
+ self.refpoint_embed = None
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ # init input_proj
+ for proj in self.input_proj:
+ nn.init.xavier_uniform_(proj[0].weight, gain=1)
+ nn.init.constant_(proj[0].bias, 0)
+
+ def init_ref_points(self, use_num_queries):
+ self.refpoint_embed = nn.Embedding(use_num_queries, self.query_dim)
+
+ def forward(self, samples: NestedTensor, targets: List = None, **kw):
+ """The forward expects a NestedTensor, which consists of:
+ - samples.tensor: batched images, of shape [batch_size x 3 x H x W]
+ - samples.mask: a binary mask of shape [batch_size x H x W], containing 1 on padded pixels
+
+ It returns a dict with the following elements:
+ - "pred_logits": the classification logits (including no-object) for all queries.
+ Shape= [batch_size x num_queries x num_classes]
+ - "pred_boxes": The normalized boxes coordinates for all queries, represented as
+ (center_x, center_y, width, height). These values are normalized in [0, 1],
+ relative to the size of each individual image (disregarding possible padding).
+ See PostProcess for information on how to retrieve the unnormalized bounding box.
+ - "aux_outputs": Optional, only returned when auxilary losses are activated. It is a list of
+ dictionnaries containing the two above keys for each decoder layer.
+ """
+ if targets is None:
+ captions = kw["captions"]
+ else:
+ captions = [t["caption"] for t in targets]
+ len(captions)
+
+ # encoder texts
+ tokenized = self.tokenizer(captions, padding="longest", return_tensors="pt").to(
+ samples.device
+ )
+ (
+ text_self_attention_masks,
+ position_ids,
+ cate_to_token_mask_list,
+ ) = generate_masks_with_special_tokens_and_transfer_map(
+ tokenized, self.specical_tokens, self.tokenizer
+ )
+
+ if text_self_attention_masks.shape[1] > self.max_text_len:
+ text_self_attention_masks = text_self_attention_masks[
+ :, : self.max_text_len, : self.max_text_len
+ ]
+ position_ids = position_ids[:, : self.max_text_len]
+ tokenized["input_ids"] = tokenized["input_ids"][:, : self.max_text_len]
+ tokenized["attention_mask"] = tokenized["attention_mask"][:, : self.max_text_len]
+ tokenized["token_type_ids"] = tokenized["token_type_ids"][:, : self.max_text_len]
+
+ # extract text embeddings
+ if self.sub_sentence_present:
+ tokenized_for_encoder = {k: v for k, v in tokenized.items() if k != "attention_mask"}
+ tokenized_for_encoder["attention_mask"] = text_self_attention_masks
+ tokenized_for_encoder["position_ids"] = position_ids
+ else:
+ # import ipdb; ipdb.set_trace()
+ tokenized_for_encoder = tokenized
+
+ bert_output = self.bert(**tokenized_for_encoder) # bs, 195, 768
+
+ encoded_text = self.feat_map(bert_output["last_hidden_state"]) # bs, 195, d_model
+ text_token_mask = tokenized.attention_mask.bool() # bs, 195
+ # text_token_mask: True for nomask, False for mask
+ # text_self_attention_masks: True for nomask, False for mask
+
+ if encoded_text.shape[1] > self.max_text_len:
+ encoded_text = encoded_text[:, : self.max_text_len, :]
+ text_token_mask = text_token_mask[:, : self.max_text_len]
+ position_ids = position_ids[:, : self.max_text_len]
+ text_self_attention_masks = text_self_attention_masks[
+ :, : self.max_text_len, : self.max_text_len
+ ]
+
+ text_dict = {
+ "encoded_text": encoded_text, # bs, 195, d_model
+ "text_token_mask": text_token_mask, # bs, 195
+ "position_ids": position_ids, # bs, 195
+ "text_self_attention_masks": text_self_attention_masks, # bs, 195,195
+ }
+
+ # import ipdb; ipdb.set_trace()
+
+ if isinstance(samples, (list, torch.Tensor)):
+ samples = nested_tensor_from_tensor_list(samples)
+ features, poss = self.backbone(samples)
+
+ srcs = []
+ masks = []
+ for l, feat in enumerate(features):
+ src, mask = feat.decompose()
+ srcs.append(self.input_proj[l](src))
+ masks.append(mask)
+ assert mask is not None
+ if self.num_feature_levels > len(srcs):
+ _len_srcs = len(srcs)
+ for l in range(_len_srcs, self.num_feature_levels):
+ if l == _len_srcs:
+ src = self.input_proj[l](features[-1].tensors)
+ else:
+ src = self.input_proj[l](srcs[-1])
+ m = samples.mask
+ mask = F.interpolate(m[None].float(), size=src.shape[-2:]).to(torch.bool)[0]
+ pos_l = self.backbone[1](NestedTensor(src, mask)).to(src.dtype)
+ srcs.append(src)
+ masks.append(mask)
+ poss.append(pos_l)
+
+ input_query_bbox = input_query_label = attn_mask = dn_meta = None
+ hs, reference, hs_enc, ref_enc, init_box_proposal = self.transformer(
+ srcs, masks, input_query_bbox, poss, input_query_label, attn_mask, text_dict
+ )
+
+ # deformable-detr-like anchor update
+ outputs_coord_list = []
+ for dec_lid, (layer_ref_sig, layer_bbox_embed, layer_hs) in enumerate(
+ zip(reference[:-1], self.bbox_embed, hs)
+ ):
+ layer_delta_unsig = layer_bbox_embed(layer_hs)
+ layer_outputs_unsig = layer_delta_unsig + inverse_sigmoid(layer_ref_sig)
+ layer_outputs_unsig = layer_outputs_unsig.sigmoid()
+ outputs_coord_list.append(layer_outputs_unsig)
+ outputs_coord_list = torch.stack(outputs_coord_list)
+
+ # output
+ outputs_class = torch.stack(
+ [
+ layer_cls_embed(layer_hs, text_dict)
+ for layer_cls_embed, layer_hs in zip(self.class_embed, hs)
+ ]
+ )
+ out = {"pred_logits": outputs_class[-1], "pred_boxes": outputs_coord_list[-1]}
+
+ # # for intermediate outputs
+ # if self.aux_loss:
+ # out['aux_outputs'] = self._set_aux_loss(outputs_class, outputs_coord_list)
+
+ # # for encoder output
+ # if hs_enc is not None:
+ # # prepare intermediate outputs
+ # interm_coord = ref_enc[-1]
+ # interm_class = self.transformer.enc_out_class_embed(hs_enc[-1], text_dict)
+ # out['interm_outputs'] = {'pred_logits': interm_class, 'pred_boxes': interm_coord}
+ # out['interm_outputs_for_matching_pre'] = {'pred_logits': interm_class, 'pred_boxes': init_box_proposal}
+
+ return out
+
+ @torch.jit.unused
+ def _set_aux_loss(self, outputs_class, outputs_coord):
+ # this is a workaround to make torchscript happy, as torchscript
+ # doesn't support dictionary with non-homogeneous values, such
+ # as a dict having both a Tensor and a list.
+ return [
+ {"pred_logits": a, "pred_boxes": b}
+ for a, b in zip(outputs_class[:-1], outputs_coord[:-1])
+ ]
+
+
+@MODULE_BUILD_FUNCS.registe_with_name(module_name="groundingdino")
+def build_groundingdino(args):
+
+ backbone = build_backbone(args)
+ transformer = build_transformer(args)
+
+ dn_labelbook_size = args.dn_labelbook_size
+ dec_pred_bbox_embed_share = args.dec_pred_bbox_embed_share
+ sub_sentence_present = args.sub_sentence_present
+
+ model = GroundingDINO(
+ backbone,
+ transformer,
+ num_queries=args.num_queries,
+ aux_loss=True,
+ iter_update=True,
+ query_dim=4,
+ num_feature_levels=args.num_feature_levels,
+ nheads=args.nheads,
+ dec_pred_bbox_embed_share=dec_pred_bbox_embed_share,
+ two_stage_type=args.two_stage_type,
+ two_stage_bbox_embed_share=args.two_stage_bbox_embed_share,
+ two_stage_class_embed_share=args.two_stage_class_embed_share,
+ num_patterns=args.num_patterns,
+ dn_number=0,
+ dn_box_noise_scale=args.dn_box_noise_scale,
+ dn_label_noise_ratio=args.dn_label_noise_ratio,
+ dn_labelbook_size=dn_labelbook_size,
+ text_encoder_type=args.text_encoder_type,
+ sub_sentence_present=sub_sentence_present,
+ max_text_len=args.max_text_len,
+ )
+
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/ms_deform_attn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/ms_deform_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..489d501bef364020212306d81e9b85c8daa27491
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/ms_deform_attn.py
@@ -0,0 +1,413 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Deformable DETR
+# Copyright (c) 2020 SenseTime. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------------------------------
+# Modified from:
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/functions/ms_deform_attn_func.py
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/modules/ms_deform_attn.py
+# https://github.com/open-mmlab/mmcv/blob/master/mmcv/ops/multi_scale_deform_attn.py
+# ------------------------------------------------------------------------------------------------
+
+import math
+import warnings
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd import Function
+from torch.autograd.function import once_differentiable
+from torch.nn.init import constant_, xavier_uniform_
+
+try:
+ from groundingdino import _C
+except:
+ warnings.warn("Failed to load custom C++ ops. Running on CPU mode Only!")
+
+
+# helpers
+def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError("invalid input for _is_power_of_2: {} (type: {})".format(n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+
+class MultiScaleDeformableAttnFunction(Function):
+ @staticmethod
+ def forward(
+ ctx,
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ im2col_step,
+ ):
+ ctx.im2col_step = im2col_step
+ output = _C.ms_deform_attn_forward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ ctx.im2col_step,
+ )
+ ctx.save_for_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ )
+ return output
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_output):
+ (
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ ) = ctx.saved_tensors
+ grad_value, grad_sampling_loc, grad_attn_weight = _C.ms_deform_attn_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ grad_output,
+ ctx.im2col_step,
+ )
+
+ return grad_value, None, None, grad_sampling_loc, grad_attn_weight, None
+
+
+def multi_scale_deformable_attn_pytorch(
+ value: torch.Tensor,
+ value_spatial_shapes: torch.Tensor,
+ sampling_locations: torch.Tensor,
+ attention_weights: torch.Tensor,
+) -> torch.Tensor:
+
+ bs, _, num_heads, embed_dims = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ = sampling_locations.shape
+ value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes], dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level, (H_, W_) in enumerate(value_spatial_shapes):
+ # bs, H_*W_, num_heads, embed_dims ->
+ # bs, H_*W_, num_heads*embed_dims ->
+ # bs, num_heads*embed_dims, H_*W_ ->
+ # bs*num_heads, embed_dims, H_, W_
+ value_l_ = (
+ value_list[level].flatten(2).transpose(1, 2).reshape(bs * num_heads, embed_dims, H_, W_)
+ )
+ # bs, num_queries, num_heads, num_points, 2 ->
+ # bs, num_heads, num_queries, num_points, 2 ->
+ # bs*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :, level].transpose(1, 2).flatten(0, 1)
+ # bs*num_heads, embed_dims, num_queries, num_points
+ sampling_value_l_ = F.grid_sample(
+ value_l_, sampling_grid_l_, mode="bilinear", padding_mode="zeros", align_corners=False
+ )
+ sampling_value_list.append(sampling_value_l_)
+ # (bs, num_queries, num_heads, num_levels, num_points) ->
+ # (bs, num_heads, num_queries, num_levels, num_points) ->
+ # (bs, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ bs * num_heads, 1, num_queries, num_levels * num_points
+ )
+ output = (
+ (torch.stack(sampling_value_list, dim=-2).flatten(-2) * attention_weights)
+ .sum(-1)
+ .view(bs, num_heads * embed_dims, num_queries)
+ )
+ return output.transpose(1, 2).contiguous()
+
+
+class MultiScaleDeformableAttention(nn.Module):
+ """Multi-Scale Deformable Attention Module used in Deformable-DETR
+
+ `Deformable DETR: Deformable Transformers for End-to-End Object Detection.
+ `_.
+
+ Args:
+ embed_dim (int): The embedding dimension of Attention. Default: 256.
+ num_heads (int): The number of attention heads. Default: 8.
+ num_levels (int): The number of feature map used in Attention. Default: 4.
+ num_points (int): The number of sampling points for each query
+ in each head. Default: 4.
+ img2col_steps (int): The step used in image_to_column. Defualt: 64.
+ dropout (float): Dropout layer used in output. Default: 0.1.
+ batch_first (bool): if ``True``, then the input and output tensor will be
+ provided as `(bs, n, embed_dim)`. Default: False. `(n, bs, embed_dim)`
+ """
+
+ def __init__(
+ self,
+ embed_dim: int = 256,
+ num_heads: int = 8,
+ num_levels: int = 4,
+ num_points: int = 4,
+ img2col_step: int = 64,
+ batch_first: bool = False,
+ ):
+ super().__init__()
+ if embed_dim % num_heads != 0:
+ raise ValueError(
+ "embed_dim must be divisible by num_heads, but got {} and {}".format(
+ embed_dim, num_heads
+ )
+ )
+ head_dim = embed_dim // num_heads
+
+ self.batch_first = batch_first
+
+ if not _is_power_of_2(head_dim):
+ warnings.warn(
+ """
+ You'd better set d_model in MSDeformAttn to make sure that
+ each dim of the attention head a power of 2, which is more efficient.
+ """
+ )
+
+ self.im2col_step = img2col_step
+ self.embed_dim = embed_dim
+ self.num_heads = num_heads
+ self.num_levels = num_levels
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(embed_dim, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dim, num_heads * num_levels * num_points)
+ self.value_proj = nn.Linear(embed_dim, embed_dim)
+ self.output_proj = nn.Linear(embed_dim, embed_dim)
+
+ self.init_weights()
+
+ def _reset_parameters(self):
+ return self.init_weights()
+
+ def init_weights(self):
+ """
+ Default initialization for Parameters of Module.
+ """
+ constant_(self.sampling_offsets.weight.data, 0.0)
+ thetas = torch.arange(self.num_heads, dtype=torch.float32) * (
+ 2.0 * math.pi / self.num_heads
+ )
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (
+ (grid_init / grid_init.abs().max(-1, keepdim=True)[0])
+ .view(self.num_heads, 1, 1, 2)
+ .repeat(1, self.num_levels, self.num_points, 1)
+ )
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+ with torch.no_grad():
+ self.sampling_offsets.bias = nn.Parameter(grid_init.view(-1))
+ constant_(self.attention_weights.weight.data, 0.0)
+ constant_(self.attention_weights.bias.data, 0.0)
+ xavier_uniform_(self.value_proj.weight.data)
+ constant_(self.value_proj.bias.data, 0.0)
+ xavier_uniform_(self.output_proj.weight.data)
+ constant_(self.output_proj.bias.data, 0.0)
+
+ def freeze_sampling_offsets(self):
+ print("Freeze sampling offsets")
+ self.sampling_offsets.weight.requires_grad = False
+ self.sampling_offsets.bias.requires_grad = False
+
+ def freeze_attention_weights(self):
+ print("Freeze attention weights")
+ self.attention_weights.weight.requires_grad = False
+ self.attention_weights.bias.requires_grad = False
+
+ def forward(
+ self,
+ query: torch.Tensor,
+ key: Optional[torch.Tensor] = None,
+ value: Optional[torch.Tensor] = None,
+ query_pos: Optional[torch.Tensor] = None,
+ key_padding_mask: Optional[torch.Tensor] = None,
+ reference_points: Optional[torch.Tensor] = None,
+ spatial_shapes: Optional[torch.Tensor] = None,
+ level_start_index: Optional[torch.Tensor] = None,
+ **kwargs
+ ) -> torch.Tensor:
+
+ """Forward Function of MultiScaleDeformableAttention
+
+ Args:
+ query (torch.Tensor): Query embeddings with shape
+ `(num_query, bs, embed_dim)`
+ key (torch.Tensor): Key embeddings with shape
+ `(num_key, bs, embed_dim)`
+ value (torch.Tensor): Value embeddings with shape
+ `(num_key, bs, embed_dim)`
+ query_pos (torch.Tensor): The position embedding for `query`. Default: None.
+ key_padding_mask (torch.Tensor): ByteTensor for `query`, with shape `(bs, num_key)`,
+ indicating which elements within `key` to be ignored in attention.
+ reference_points (torch.Tensor): The normalized reference points
+ with shape `(bs, num_query, num_levels, 2)`,
+ all elements is range in [0, 1], top-left (0, 0),
+ bottom-right (1, 1), including padding are.
+ or `(N, Length_{query}, num_levels, 4)`, add additional
+ two dimensions `(h, w)` to form reference boxes.
+ spatial_shapes (torch.Tensor): Spatial shape of features in different levels.
+ With shape `(num_levels, 2)`, last dimension represents `(h, w)`.
+ level_start_index (torch.Tensor): The start index of each level. A tensor with
+ shape `(num_levels, )` which can be represented as
+ `[0, h_0 * w_0, h_0 * w_0 + h_1 * w_1, ...]`.
+
+ Returns:
+ torch.Tensor: forward results with shape `(num_query, bs, embed_dim)`
+ """
+
+ if value is None:
+ value = query
+
+ if query_pos is not None:
+ query = query + query_pos
+
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], float(0))
+ value = value.view(bs, num_value, self.num_heads, -1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2
+ )
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points
+ )
+ attention_weights = attention_weights.softmax(-1)
+ attention_weights = attention_weights.view(
+ bs,
+ num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points,
+ )
+
+ # bs, num_query, num_heads, num_levels, num_points, 2
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack([spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :]
+ + sampling_offsets / offset_normalizer[None, None, None, :, None, :]
+ )
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = (
+ reference_points[:, :, None, :, None, :2]
+ + sampling_offsets
+ / self.num_points
+ * reference_points[:, :, None, :, None, 2:]
+ * 0.5
+ )
+ else:
+ raise ValueError(
+ "Last dim of reference_points must be 2 or 4, but get {} instead.".format(
+ reference_points.shape[-1]
+ )
+ )
+
+ if torch.cuda.is_available() and value.is_cuda:
+ halffloat = False
+ if value.dtype == torch.float16:
+ halffloat = True
+ value = value.float()
+ sampling_locations = sampling_locations.float()
+ attention_weights = attention_weights.float()
+
+ output = MultiScaleDeformableAttnFunction.apply(
+ value,
+ spatial_shapes,
+ level_start_index,
+ sampling_locations,
+ attention_weights,
+ self.im2col_step,
+ )
+
+ if halffloat:
+ output = output.half()
+ else:
+ output = multi_scale_deformable_attn_pytorch(
+ value, spatial_shapes, sampling_locations, attention_weights
+ )
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ output = output.permute(1, 0, 2)
+
+ return output
+
+
+def create_dummy_class(klass, dependency, message=""):
+ """
+ When a dependency of a class is not available, create a dummy class which throws ImportError
+ when used.
+
+ Args:
+ klass (str): name of the class.
+ dependency (str): name of the dependency.
+ message: extra message to print
+ Returns:
+ class: a class object
+ """
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, klass)
+ if message:
+ err = err + " " + message
+
+ class _DummyMetaClass(type):
+ # throw error on class attribute access
+ def __getattr__(_, __): # noqa: B902
+ raise ImportError(err)
+
+ class _Dummy(object, metaclass=_DummyMetaClass):
+ # throw error on constructor
+ def __init__(self, *args, **kwargs):
+ raise ImportError(err)
+
+ return _Dummy
+
+
+def create_dummy_func(func, dependency, message=""):
+ """
+ When a dependency of a function is not available, create a dummy function which throws
+ ImportError when used.
+
+ Args:
+ func (str): name of the function.
+ dependency (str or list[str]): name(s) of the dependency.
+ message: extra message to print
+ Returns:
+ function: a function object
+ """
+ err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func)
+ if message:
+ err = err + " " + message
+
+ if isinstance(dependency, (list, tuple)):
+ dependency = ",".join(dependency)
+
+ def _dummy(*args, **kwargs):
+ raise ImportError(err)
+
+ return _dummy
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..fcb8742dbdde6e80fd38b11d064211f6935aae76
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer.py
@@ -0,0 +1,959 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# DINO
+# Copyright (c) 2022 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Conditional DETR Transformer class.
+# Copyright (c) 2021 Microsoft. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Modified from DETR (https://github.com/facebookresearch/detr)
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+# ------------------------------------------------------------------------
+
+from typing import Optional
+
+import torch
+import torch.utils.checkpoint as checkpoint
+from torch import Tensor, nn
+
+from groundingdino.util.misc import inverse_sigmoid
+
+from .fuse_modules import BiAttentionBlock
+from .ms_deform_attn import MultiScaleDeformableAttention as MSDeformAttn
+from .transformer_vanilla import TransformerEncoderLayer
+from .utils import (
+ MLP,
+ _get_activation_fn,
+ _get_clones,
+ gen_encoder_output_proposals,
+ gen_sineembed_for_position,
+ get_sine_pos_embed,
+)
+
+
+class Transformer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ nhead=8,
+ num_queries=300,
+ num_encoder_layers=6,
+ num_unicoder_layers=0,
+ num_decoder_layers=6,
+ dim_feedforward=2048,
+ dropout=0.0,
+ activation="relu",
+ normalize_before=False,
+ return_intermediate_dec=False,
+ query_dim=4,
+ num_patterns=0,
+ # for deformable encoder
+ num_feature_levels=1,
+ enc_n_points=4,
+ dec_n_points=4,
+ # init query
+ learnable_tgt_init=False,
+ # two stage
+ two_stage_type="no", # ['no', 'standard', 'early', 'combine', 'enceachlayer', 'enclayer1']
+ embed_init_tgt=False,
+ # for text
+ use_text_enhancer=False,
+ use_fusion_layer=False,
+ use_checkpoint=False,
+ use_transformer_ckpt=False,
+ use_text_cross_attention=False,
+ text_dropout=0.1,
+ fusion_dropout=0.1,
+ fusion_droppath=0.0,
+ ):
+ super().__init__()
+ self.num_feature_levels = num_feature_levels
+ self.num_encoder_layers = num_encoder_layers
+ self.num_unicoder_layers = num_unicoder_layers
+ self.num_decoder_layers = num_decoder_layers
+ self.num_queries = num_queries
+ assert query_dim == 4
+
+ # choose encoder layer type
+ encoder_layer = DeformableTransformerEncoderLayer(
+ d_model, dim_feedforward, dropout, activation, num_feature_levels, nhead, enc_n_points
+ )
+
+ if use_text_enhancer:
+ text_enhance_layer = TransformerEncoderLayer(
+ d_model=d_model,
+ nhead=nhead // 2,
+ dim_feedforward=dim_feedforward // 2,
+ dropout=text_dropout,
+ )
+ else:
+ text_enhance_layer = None
+
+ if use_fusion_layer:
+ feature_fusion_layer = BiAttentionBlock(
+ v_dim=d_model,
+ l_dim=d_model,
+ embed_dim=dim_feedforward // 2,
+ num_heads=nhead // 2,
+ dropout=fusion_dropout,
+ drop_path=fusion_droppath,
+ )
+ else:
+ feature_fusion_layer = None
+
+ encoder_norm = nn.LayerNorm(d_model) if normalize_before else None
+ assert encoder_norm is None
+ self.encoder = TransformerEncoder(
+ encoder_layer,
+ num_encoder_layers,
+ d_model=d_model,
+ num_queries=num_queries,
+ text_enhance_layer=text_enhance_layer,
+ feature_fusion_layer=feature_fusion_layer,
+ use_checkpoint=use_checkpoint,
+ use_transformer_ckpt=use_transformer_ckpt,
+ )
+
+ # choose decoder layer type
+ decoder_layer = DeformableTransformerDecoderLayer(
+ d_model,
+ dim_feedforward,
+ dropout,
+ activation,
+ num_feature_levels,
+ nhead,
+ dec_n_points,
+ use_text_cross_attention=use_text_cross_attention,
+ )
+
+ decoder_norm = nn.LayerNorm(d_model)
+ self.decoder = TransformerDecoder(
+ decoder_layer,
+ num_decoder_layers,
+ decoder_norm,
+ return_intermediate=return_intermediate_dec,
+ d_model=d_model,
+ query_dim=query_dim,
+ num_feature_levels=num_feature_levels,
+ )
+
+ self.d_model = d_model
+ self.nhead = nhead
+ self.dec_layers = num_decoder_layers
+ self.num_queries = num_queries # useful for single stage model only
+ self.num_patterns = num_patterns
+ if not isinstance(num_patterns, int):
+ Warning("num_patterns should be int but {}".format(type(num_patterns)))
+ self.num_patterns = 0
+
+ if num_feature_levels > 1:
+ if self.num_encoder_layers > 0:
+ self.level_embed = nn.Parameter(torch.Tensor(num_feature_levels, d_model))
+ else:
+ self.level_embed = None
+
+ self.learnable_tgt_init = learnable_tgt_init
+ assert learnable_tgt_init, "why not learnable_tgt_init"
+ self.embed_init_tgt = embed_init_tgt
+ if (two_stage_type != "no" and embed_init_tgt) or (two_stage_type == "no"):
+ self.tgt_embed = nn.Embedding(self.num_queries, d_model)
+ nn.init.normal_(self.tgt_embed.weight.data)
+ else:
+ self.tgt_embed = None
+
+ # for two stage
+ self.two_stage_type = two_stage_type
+ assert two_stage_type in ["no", "standard"], "unknown param {} of two_stage_type".format(
+ two_stage_type
+ )
+ if two_stage_type == "standard":
+ # anchor selection at the output of encoder
+ self.enc_output = nn.Linear(d_model, d_model)
+ self.enc_output_norm = nn.LayerNorm(d_model)
+ self.two_stage_wh_embedding = None
+
+ if two_stage_type == "no":
+ self.init_ref_points(num_queries) # init self.refpoint_embed
+
+ self.enc_out_class_embed = None
+ self.enc_out_bbox_embed = None
+
+ self._reset_parameters()
+
+ def _reset_parameters(self):
+ for p in self.parameters():
+ if p.dim() > 1:
+ nn.init.xavier_uniform_(p)
+ for m in self.modules():
+ if isinstance(m, MSDeformAttn):
+ m._reset_parameters()
+ if self.num_feature_levels > 1 and self.level_embed is not None:
+ nn.init.normal_(self.level_embed)
+
+ def get_valid_ratio(self, mask):
+ _, H, W = mask.shape
+ valid_H = torch.sum(~mask[:, :, 0], 1)
+ valid_W = torch.sum(~mask[:, 0, :], 1)
+ valid_ratio_h = valid_H.float() / H
+ valid_ratio_w = valid_W.float() / W
+ valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
+ return valid_ratio
+
+ def init_ref_points(self, use_num_queries):
+ self.refpoint_embed = nn.Embedding(use_num_queries, 4)
+
+ def forward(self, srcs, masks, refpoint_embed, pos_embeds, tgt, attn_mask=None, text_dict=None):
+ """
+ Input:
+ - srcs: List of multi features [bs, ci, hi, wi]
+ - masks: List of multi masks [bs, hi, wi]
+ - refpoint_embed: [bs, num_dn, 4]. None in infer
+ - pos_embeds: List of multi pos embeds [bs, ci, hi, wi]
+ - tgt: [bs, num_dn, d_model]. None in infer
+
+ """
+ # prepare input for encoder
+ src_flatten = []
+ mask_flatten = []
+ lvl_pos_embed_flatten = []
+ spatial_shapes = []
+ for lvl, (src, mask, pos_embed) in enumerate(zip(srcs, masks, pos_embeds)):
+ bs, c, h, w = src.shape
+ spatial_shape = (h, w)
+ spatial_shapes.append(spatial_shape)
+
+ src = src.flatten(2).transpose(1, 2) # bs, hw, c
+ mask = mask.flatten(1) # bs, hw
+ pos_embed = pos_embed.flatten(2).transpose(1, 2) # bs, hw, c
+ if self.num_feature_levels > 1 and self.level_embed is not None:
+ lvl_pos_embed = pos_embed + self.level_embed[lvl].view(1, 1, -1)
+ else:
+ lvl_pos_embed = pos_embed
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
+ src_flatten.append(src)
+ mask_flatten.append(mask)
+ src_flatten = torch.cat(src_flatten, 1) # bs, \sum{hxw}, c
+ mask_flatten = torch.cat(mask_flatten, 1) # bs, \sum{hxw}
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1) # bs, \sum{hxw}, c
+ spatial_shapes = torch.as_tensor(
+ spatial_shapes, dtype=torch.long, device=src_flatten.device
+ )
+ level_start_index = torch.cat(
+ (spatial_shapes.new_zeros((1,)), spatial_shapes.prod(1).cumsum(0)[:-1])
+ )
+ valid_ratios = torch.stack([self.get_valid_ratio(m) for m in masks], 1)
+
+ # two stage
+ enc_topk_proposals = enc_refpoint_embed = None
+
+ #########################################################
+ # Begin Encoder
+ #########################################################
+ memory, memory_text = self.encoder(
+ src_flatten,
+ pos=lvl_pos_embed_flatten,
+ level_start_index=level_start_index,
+ spatial_shapes=spatial_shapes,
+ valid_ratios=valid_ratios,
+ key_padding_mask=mask_flatten,
+ memory_text=text_dict["encoded_text"],
+ text_attention_mask=~text_dict["text_token_mask"],
+ # we ~ the mask . False means use the token; True means pad the token
+ position_ids=text_dict["position_ids"],
+ text_self_attention_masks=text_dict["text_self_attention_masks"],
+ )
+ #########################################################
+ # End Encoder
+ # - memory: bs, \sum{hw}, c
+ # - mask_flatten: bs, \sum{hw}
+ # - lvl_pos_embed_flatten: bs, \sum{hw}, c
+ # - enc_intermediate_output: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c)
+ # - enc_intermediate_refpoints: None or (nenc+1, bs, nq, c) or (nenc, bs, nq, c)
+ #########################################################
+ text_dict["encoded_text"] = memory_text
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # if memory.isnan().any() | memory.isinf().any():
+ # import ipdb; ipdb.set_trace()
+
+ if self.two_stage_type == "standard":
+ output_memory, output_proposals = gen_encoder_output_proposals(
+ memory, mask_flatten, spatial_shapes
+ )
+ output_memory = self.enc_output_norm(self.enc_output(output_memory))
+
+ if text_dict is not None:
+ enc_outputs_class_unselected = self.enc_out_class_embed(output_memory, text_dict)
+ else:
+ enc_outputs_class_unselected = self.enc_out_class_embed(output_memory)
+
+ topk_logits = enc_outputs_class_unselected.max(-1)[0]
+ enc_outputs_coord_unselected = (
+ self.enc_out_bbox_embed(output_memory) + output_proposals
+ ) # (bs, \sum{hw}, 4) unsigmoid
+ topk = self.num_queries
+
+ topk_proposals = torch.topk(topk_logits, topk, dim=1)[1] # bs, nq
+
+ # gather boxes
+ refpoint_embed_undetach = torch.gather(
+ enc_outputs_coord_unselected, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)
+ ) # unsigmoid
+ refpoint_embed_ = refpoint_embed_undetach.detach()
+ init_box_proposal = torch.gather(
+ output_proposals, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, 4)
+ ).sigmoid() # sigmoid
+
+ # gather tgt
+ tgt_undetach = torch.gather(
+ output_memory, 1, topk_proposals.unsqueeze(-1).repeat(1, 1, self.d_model)
+ )
+ if self.embed_init_tgt:
+ tgt_ = (
+ self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, d_model
+ else:
+ tgt_ = tgt_undetach.detach()
+
+ if refpoint_embed is not None:
+ refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1)
+ tgt = torch.cat([tgt, tgt_], dim=1)
+ else:
+ refpoint_embed, tgt = refpoint_embed_, tgt_
+
+ elif self.two_stage_type == "no":
+ tgt_ = (
+ self.tgt_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, d_model
+ refpoint_embed_ = (
+ self.refpoint_embed.weight[:, None, :].repeat(1, bs, 1).transpose(0, 1)
+ ) # nq, bs, 4
+
+ if refpoint_embed is not None:
+ refpoint_embed = torch.cat([refpoint_embed, refpoint_embed_], dim=1)
+ tgt = torch.cat([tgt, tgt_], dim=1)
+ else:
+ refpoint_embed, tgt = refpoint_embed_, tgt_
+
+ if self.num_patterns > 0:
+ tgt_embed = tgt.repeat(1, self.num_patterns, 1)
+ refpoint_embed = refpoint_embed.repeat(1, self.num_patterns, 1)
+ tgt_pat = self.patterns.weight[None, :, :].repeat_interleave(
+ self.num_queries, 1
+ ) # 1, n_q*n_pat, d_model
+ tgt = tgt_embed + tgt_pat
+
+ init_box_proposal = refpoint_embed_.sigmoid()
+
+ else:
+ raise NotImplementedError("unknown two_stage_type {}".format(self.two_stage_type))
+ #########################################################
+ # End preparing tgt
+ # - tgt: bs, NQ, d_model
+ # - refpoint_embed(unsigmoid): bs, NQ, d_model
+ #########################################################
+
+ #########################################################
+ # Begin Decoder
+ #########################################################
+ hs, references = self.decoder(
+ tgt=tgt.transpose(0, 1),
+ memory=memory.transpose(0, 1),
+ memory_key_padding_mask=mask_flatten,
+ pos=lvl_pos_embed_flatten.transpose(0, 1),
+ refpoints_unsigmoid=refpoint_embed.transpose(0, 1),
+ level_start_index=level_start_index,
+ spatial_shapes=spatial_shapes,
+ valid_ratios=valid_ratios,
+ tgt_mask=attn_mask,
+ memory_text=text_dict["encoded_text"],
+ text_attention_mask=~text_dict["text_token_mask"],
+ # we ~ the mask . False means use the token; True means pad the token
+ )
+ #########################################################
+ # End Decoder
+ # hs: n_dec, bs, nq, d_model
+ # references: n_dec+1, bs, nq, query_dim
+ #########################################################
+
+ #########################################################
+ # Begin postprocess
+ #########################################################
+ if self.two_stage_type == "standard":
+ hs_enc = tgt_undetach.unsqueeze(0)
+ ref_enc = refpoint_embed_undetach.sigmoid().unsqueeze(0)
+ else:
+ hs_enc = ref_enc = None
+ #########################################################
+ # End postprocess
+ # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or (n_enc, bs, nq, d_model) or None
+ # ref_enc: (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or (n_enc, bs, nq, d_model) or None
+ #########################################################
+
+ return hs, references, hs_enc, ref_enc, init_box_proposal
+ # hs: (n_dec, bs, nq, d_model)
+ # references: sigmoid coordinates. (n_dec+1, bs, bq, 4)
+ # hs_enc: (n_enc+1, bs, nq, d_model) or (1, bs, nq, d_model) or None
+ # ref_enc: sigmoid coordinates. \
+ # (n_enc+1, bs, nq, query_dim) or (1, bs, nq, query_dim) or None
+
+
+class TransformerEncoder(nn.Module):
+ def __init__(
+ self,
+ encoder_layer,
+ num_layers,
+ d_model=256,
+ num_queries=300,
+ enc_layer_share=False,
+ text_enhance_layer=None,
+ feature_fusion_layer=None,
+ use_checkpoint=False,
+ use_transformer_ckpt=False,
+ ):
+ """_summary_
+
+ Args:
+ encoder_layer (_type_): _description_
+ num_layers (_type_): _description_
+ norm (_type_, optional): _description_. Defaults to None.
+ d_model (int, optional): _description_. Defaults to 256.
+ num_queries (int, optional): _description_. Defaults to 300.
+ enc_layer_share (bool, optional): _description_. Defaults to False.
+
+ """
+ super().__init__()
+ # prepare layers
+ self.layers = []
+ self.text_layers = []
+ self.fusion_layers = []
+ if num_layers > 0:
+ self.layers = _get_clones(encoder_layer, num_layers, layer_share=enc_layer_share)
+
+ if text_enhance_layer is not None:
+ self.text_layers = _get_clones(
+ text_enhance_layer, num_layers, layer_share=enc_layer_share
+ )
+ if feature_fusion_layer is not None:
+ self.fusion_layers = _get_clones(
+ feature_fusion_layer, num_layers, layer_share=enc_layer_share
+ )
+ else:
+ self.layers = []
+ del encoder_layer
+
+ if text_enhance_layer is not None:
+ self.text_layers = []
+ del text_enhance_layer
+ if feature_fusion_layer is not None:
+ self.fusion_layers = []
+ del feature_fusion_layer
+
+ self.query_scale = None
+ self.num_queries = num_queries
+ self.num_layers = num_layers
+ self.d_model = d_model
+
+ self.use_checkpoint = use_checkpoint
+ self.use_transformer_ckpt = use_transformer_ckpt
+
+ @staticmethod
+ def get_reference_points(spatial_shapes, valid_ratios, device):
+ reference_points_list = []
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
+
+ ref_y, ref_x = torch.meshgrid(
+ torch.linspace(0.5, H_ - 0.5, H_, dtype=torch.float32, device=device),
+ torch.linspace(0.5, W_ - 0.5, W_, dtype=torch.float32, device=device),
+ )
+ ref_y = ref_y.reshape(-1)[None] / (valid_ratios[:, None, lvl, 1] * H_)
+ ref_x = ref_x.reshape(-1)[None] / (valid_ratios[:, None, lvl, 0] * W_)
+ ref = torch.stack((ref_x, ref_y), -1)
+ reference_points_list.append(ref)
+ reference_points = torch.cat(reference_points_list, 1)
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
+ return reference_points
+
+ def forward(
+ self,
+ # for images
+ src: Tensor,
+ pos: Tensor,
+ spatial_shapes: Tensor,
+ level_start_index: Tensor,
+ valid_ratios: Tensor,
+ key_padding_mask: Tensor,
+ # for texts
+ memory_text: Tensor = None,
+ text_attention_mask: Tensor = None,
+ pos_text: Tensor = None,
+ text_self_attention_masks: Tensor = None,
+ position_ids: Tensor = None,
+ ):
+ """
+ Input:
+ - src: [bs, sum(hi*wi), 256]
+ - pos: pos embed for src. [bs, sum(hi*wi), 256]
+ - spatial_shapes: h,w of each level [num_level, 2]
+ - level_start_index: [num_level] start point of level in sum(hi*wi).
+ - valid_ratios: [bs, num_level, 2]
+ - key_padding_mask: [bs, sum(hi*wi)]
+
+ - memory_text: bs, n_text, 256
+ - text_attention_mask: bs, n_text
+ False for no padding; True for padding
+ - pos_text: bs, n_text, 256
+
+ - position_ids: bs, n_text
+ Intermedia:
+ - reference_points: [bs, sum(hi*wi), num_level, 2]
+ Outpus:
+ - output: [bs, sum(hi*wi), 256]
+ """
+
+ output = src
+
+ # preparation and reshape
+ if self.num_layers > 0:
+ reference_points = self.get_reference_points(
+ spatial_shapes, valid_ratios, device=src.device
+ )
+
+ if self.text_layers:
+ # generate pos_text
+ bs, n_text, text_dim = memory_text.shape
+ if pos_text is None and position_ids is None:
+ pos_text = (
+ torch.arange(n_text, device=memory_text.device)
+ .float()
+ .unsqueeze(0)
+ .unsqueeze(-1)
+ .repeat(bs, 1, 1)
+ )
+ pos_text = get_sine_pos_embed(pos_text, num_pos_feats=256, exchange_xy=False)
+ if position_ids is not None:
+ pos_text = get_sine_pos_embed(
+ position_ids[..., None], num_pos_feats=256, exchange_xy=False
+ )
+
+ # main process
+ for layer_id, layer in enumerate(self.layers):
+ # if output.isnan().any() or memory_text.isnan().any():
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ if self.fusion_layers:
+ if self.use_checkpoint:
+ output, memory_text = checkpoint.checkpoint(
+ self.fusion_layers[layer_id],
+ output,
+ memory_text,
+ key_padding_mask,
+ text_attention_mask,
+ )
+ else:
+ output, memory_text = self.fusion_layers[layer_id](
+ v=output,
+ l=memory_text,
+ attention_mask_v=key_padding_mask,
+ attention_mask_l=text_attention_mask,
+ )
+
+ if self.text_layers:
+ memory_text = self.text_layers[layer_id](
+ src=memory_text.transpose(0, 1),
+ src_mask=~text_self_attention_masks, # note we use ~ for mask here
+ src_key_padding_mask=text_attention_mask,
+ pos=(pos_text.transpose(0, 1) if pos_text is not None else None),
+ ).transpose(0, 1)
+
+ # main process
+ if self.use_transformer_ckpt:
+ output = checkpoint.checkpoint(
+ layer,
+ output,
+ pos,
+ reference_points,
+ spatial_shapes,
+ level_start_index,
+ key_padding_mask,
+ )
+ else:
+ output = layer(
+ src=output,
+ pos=pos,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ key_padding_mask=key_padding_mask,
+ )
+
+ return output, memory_text
+
+
+class TransformerDecoder(nn.Module):
+ def __init__(
+ self,
+ decoder_layer,
+ num_layers,
+ norm=None,
+ return_intermediate=False,
+ d_model=256,
+ query_dim=4,
+ num_feature_levels=1,
+ ):
+ super().__init__()
+ if num_layers > 0:
+ self.layers = _get_clones(decoder_layer, num_layers)
+ else:
+ self.layers = []
+ self.num_layers = num_layers
+ self.norm = norm
+ self.return_intermediate = return_intermediate
+ assert return_intermediate, "support return_intermediate only"
+ self.query_dim = query_dim
+ assert query_dim in [2, 4], "query_dim should be 2/4 but {}".format(query_dim)
+ self.num_feature_levels = num_feature_levels
+
+ self.ref_point_head = MLP(query_dim // 2 * d_model, d_model, d_model, 2)
+ self.query_pos_sine_scale = None
+
+ self.query_scale = None
+ self.bbox_embed = None
+ self.class_embed = None
+
+ self.d_model = d_model
+
+ self.ref_anchor_head = None
+
+ def forward(
+ self,
+ tgt,
+ memory,
+ tgt_mask: Optional[Tensor] = None,
+ memory_mask: Optional[Tensor] = None,
+ tgt_key_padding_mask: Optional[Tensor] = None,
+ memory_key_padding_mask: Optional[Tensor] = None,
+ pos: Optional[Tensor] = None,
+ refpoints_unsigmoid: Optional[Tensor] = None, # num_queries, bs, 2
+ # for memory
+ level_start_index: Optional[Tensor] = None, # num_levels
+ spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
+ valid_ratios: Optional[Tensor] = None,
+ # for text
+ memory_text: Optional[Tensor] = None,
+ text_attention_mask: Optional[Tensor] = None,
+ ):
+ """
+ Input:
+ - tgt: nq, bs, d_model
+ - memory: hw, bs, d_model
+ - pos: hw, bs, d_model
+ - refpoints_unsigmoid: nq, bs, 2/4
+ - valid_ratios/spatial_shapes: bs, nlevel, 2
+ """
+ output = tgt
+
+ intermediate = []
+ reference_points = refpoints_unsigmoid.sigmoid()
+ ref_points = [reference_points]
+
+ for layer_id, layer in enumerate(self.layers):
+
+ if reference_points.shape[-1] == 4:
+ reference_points_input = (
+ reference_points[:, :, None]
+ * torch.cat([valid_ratios, valid_ratios], -1)[None, :]
+ ) # nq, bs, nlevel, 4
+ else:
+ assert reference_points.shape[-1] == 2
+ reference_points_input = reference_points[:, :, None] * valid_ratios[None, :]
+ query_sine_embed = gen_sineembed_for_position(
+ reference_points_input[:, :, 0, :]
+ ) # nq, bs, 256*2
+
+ # conditional query
+ raw_query_pos = self.ref_point_head(query_sine_embed) # nq, bs, 256
+ pos_scale = self.query_scale(output) if self.query_scale is not None else 1
+ query_pos = pos_scale * raw_query_pos
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # if query_pos.isnan().any() | query_pos.isinf().any():
+ # import ipdb; ipdb.set_trace()
+
+ # main process
+ output = layer(
+ tgt=output,
+ tgt_query_pos=query_pos,
+ tgt_query_sine_embed=query_sine_embed,
+ tgt_key_padding_mask=tgt_key_padding_mask,
+ tgt_reference_points=reference_points_input,
+ memory_text=memory_text,
+ text_attention_mask=text_attention_mask,
+ memory=memory,
+ memory_key_padding_mask=memory_key_padding_mask,
+ memory_level_start_index=level_start_index,
+ memory_spatial_shapes=spatial_shapes,
+ memory_pos=pos,
+ self_attn_mask=tgt_mask,
+ cross_attn_mask=memory_mask,
+ )
+ if output.isnan().any() | output.isinf().any():
+ print(f"output layer_id {layer_id} is nan")
+ try:
+ num_nan = output.isnan().sum().item()
+ num_inf = output.isinf().sum().item()
+ print(f"num_nan {num_nan}, num_inf {num_inf}")
+ except Exception as e:
+ print(e)
+ # if os.environ.get("SHILONG_AMP_INFNAN_DEBUG") == '1':
+ # import ipdb; ipdb.set_trace()
+
+ # iter update
+ if self.bbox_embed is not None:
+ # box_holder = self.bbox_embed(output)
+ # box_holder[..., :self.query_dim] += inverse_sigmoid(reference_points)
+ # new_reference_points = box_holder[..., :self.query_dim].sigmoid()
+
+ reference_before_sigmoid = inverse_sigmoid(reference_points)
+ delta_unsig = self.bbox_embed[layer_id](output)
+ outputs_unsig = delta_unsig + reference_before_sigmoid
+ new_reference_points = outputs_unsig.sigmoid()
+
+ reference_points = new_reference_points.detach()
+ # if layer_id != self.num_layers - 1:
+ ref_points.append(new_reference_points)
+
+ intermediate.append(self.norm(output))
+
+ return [
+ [itm_out.transpose(0, 1) for itm_out in intermediate],
+ [itm_refpoint.transpose(0, 1) for itm_refpoint in ref_points],
+ ]
+
+
+class DeformableTransformerEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ d_ffn=1024,
+ dropout=0.1,
+ activation="relu",
+ n_levels=4,
+ n_heads=8,
+ n_points=4,
+ ):
+ super().__init__()
+
+ # self attention
+ self.self_attn = MSDeformAttn(
+ embed_dim=d_model,
+ num_levels=n_levels,
+ num_heads=n_heads,
+ num_points=n_points,
+ batch_first=True,
+ )
+ self.dropout1 = nn.Dropout(dropout)
+ self.norm1 = nn.LayerNorm(d_model)
+
+ # ffn
+ self.linear1 = nn.Linear(d_model, d_ffn)
+ self.activation = _get_activation_fn(activation, d_model=d_ffn)
+ self.dropout2 = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(d_ffn, d_model)
+ self.dropout3 = nn.Dropout(dropout)
+ self.norm2 = nn.LayerNorm(d_model)
+
+ @staticmethod
+ def with_pos_embed(tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward_ffn(self, src):
+ src2 = self.linear2(self.dropout2(self.activation(self.linear1(src))))
+ src = src + self.dropout3(src2)
+ src = self.norm2(src)
+ return src
+
+ def forward(
+ self, src, pos, reference_points, spatial_shapes, level_start_index, key_padding_mask=None
+ ):
+ # self attention
+ # import ipdb; ipdb.set_trace()
+ src2 = self.self_attn(
+ query=self.with_pos_embed(src, pos),
+ reference_points=reference_points,
+ value=src,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ key_padding_mask=key_padding_mask,
+ )
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+
+ # ffn
+ src = self.forward_ffn(src)
+
+ return src
+
+
+class DeformableTransformerDecoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model=256,
+ d_ffn=1024,
+ dropout=0.1,
+ activation="relu",
+ n_levels=4,
+ n_heads=8,
+ n_points=4,
+ use_text_feat_guide=False,
+ use_text_cross_attention=False,
+ ):
+ super().__init__()
+
+ # cross attention
+ self.cross_attn = MSDeformAttn(
+ embed_dim=d_model,
+ num_levels=n_levels,
+ num_heads=n_heads,
+ num_points=n_points,
+ batch_first=True,
+ )
+ self.dropout1 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm1 = nn.LayerNorm(d_model)
+
+ # cross attention text
+ if use_text_cross_attention:
+ self.ca_text = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
+ self.catext_dropout = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.catext_norm = nn.LayerNorm(d_model)
+
+ # self attention
+ self.self_attn = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
+ self.dropout2 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm2 = nn.LayerNorm(d_model)
+
+ # ffn
+ self.linear1 = nn.Linear(d_model, d_ffn)
+ self.activation = _get_activation_fn(activation, d_model=d_ffn, batch_dim=1)
+ self.dropout3 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.linear2 = nn.Linear(d_ffn, d_model)
+ self.dropout4 = nn.Dropout(dropout) if dropout > 0 else nn.Identity()
+ self.norm3 = nn.LayerNorm(d_model)
+
+ self.key_aware_proj = None
+ self.use_text_feat_guide = use_text_feat_guide
+ assert not use_text_feat_guide
+ self.use_text_cross_attention = use_text_cross_attention
+
+ def rm_self_attn_modules(self):
+ self.self_attn = None
+ self.dropout2 = None
+ self.norm2 = None
+
+ @staticmethod
+ def with_pos_embed(tensor, pos):
+ return tensor if pos is None else tensor + pos
+
+ def forward_ffn(self, tgt):
+ with torch.cuda.amp.autocast(enabled=False):
+ tgt2 = self.linear2(self.dropout3(self.activation(self.linear1(tgt))))
+ tgt = tgt + self.dropout4(tgt2)
+ tgt = self.norm3(tgt)
+ return tgt
+
+ def forward(
+ self,
+ # for tgt
+ tgt: Optional[Tensor], # nq, bs, d_model
+ tgt_query_pos: Optional[Tensor] = None, # pos for query. MLP(Sine(pos))
+ tgt_query_sine_embed: Optional[Tensor] = None, # pos for query. Sine(pos)
+ tgt_key_padding_mask: Optional[Tensor] = None,
+ tgt_reference_points: Optional[Tensor] = None, # nq, bs, 4
+ memory_text: Optional[Tensor] = None, # bs, num_token, d_model
+ text_attention_mask: Optional[Tensor] = None, # bs, num_token
+ # for memory
+ memory: Optional[Tensor] = None, # hw, bs, d_model
+ memory_key_padding_mask: Optional[Tensor] = None,
+ memory_level_start_index: Optional[Tensor] = None, # num_levels
+ memory_spatial_shapes: Optional[Tensor] = None, # bs, num_levels, 2
+ memory_pos: Optional[Tensor] = None, # pos for memory
+ # sa
+ self_attn_mask: Optional[Tensor] = None, # mask used for self-attention
+ cross_attn_mask: Optional[Tensor] = None, # mask used for cross-attention
+ ):
+ """
+ Input:
+ - tgt/tgt_query_pos: nq, bs, d_model
+ -
+ """
+ assert cross_attn_mask is None
+
+ # self attention
+ if self.self_attn is not None:
+ # import ipdb; ipdb.set_trace()
+ q = k = self.with_pos_embed(tgt, tgt_query_pos)
+ tgt2 = self.self_attn(q, k, tgt, attn_mask=self_attn_mask)[0]
+ tgt = tgt + self.dropout2(tgt2)
+ tgt = self.norm2(tgt)
+
+ if self.use_text_cross_attention:
+ tgt2 = self.ca_text(
+ self.with_pos_embed(tgt, tgt_query_pos),
+ memory_text.transpose(0, 1),
+ memory_text.transpose(0, 1),
+ key_padding_mask=text_attention_mask,
+ )[0]
+ tgt = tgt + self.catext_dropout(tgt2)
+ tgt = self.catext_norm(tgt)
+
+ tgt2 = self.cross_attn(
+ query=self.with_pos_embed(tgt, tgt_query_pos).transpose(0, 1),
+ reference_points=tgt_reference_points.transpose(0, 1).contiguous(),
+ value=memory.transpose(0, 1),
+ spatial_shapes=memory_spatial_shapes,
+ level_start_index=memory_level_start_index,
+ key_padding_mask=memory_key_padding_mask,
+ ).transpose(0, 1)
+ tgt = tgt + self.dropout1(tgt2)
+ tgt = self.norm1(tgt)
+
+ # ffn
+ tgt = self.forward_ffn(tgt)
+
+ return tgt
+
+
+def build_transformer(args):
+ return Transformer(
+ d_model=args.hidden_dim,
+ dropout=args.dropout,
+ nhead=args.nheads,
+ num_queries=args.num_queries,
+ dim_feedforward=args.dim_feedforward,
+ num_encoder_layers=args.enc_layers,
+ num_decoder_layers=args.dec_layers,
+ normalize_before=args.pre_norm,
+ return_intermediate_dec=True,
+ query_dim=args.query_dim,
+ activation=args.transformer_activation,
+ num_patterns=args.num_patterns,
+ num_feature_levels=args.num_feature_levels,
+ enc_n_points=args.enc_n_points,
+ dec_n_points=args.dec_n_points,
+ learnable_tgt_init=True,
+ # two stage
+ two_stage_type=args.two_stage_type, # ['no', 'standard', 'early']
+ embed_init_tgt=args.embed_init_tgt,
+ use_text_enhancer=args.use_text_enhancer,
+ use_fusion_layer=args.use_fusion_layer,
+ use_checkpoint=args.use_checkpoint,
+ use_transformer_ckpt=args.use_transformer_ckpt,
+ use_text_cross_attention=args.use_text_cross_attention,
+ text_dropout=args.text_dropout,
+ fusion_dropout=args.fusion_dropout,
+ fusion_droppath=args.fusion_droppath,
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py
new file mode 100644
index 0000000000000000000000000000000000000000..10c0920c1a217af5bb3e1b13077568035ab3b7b5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/transformer_vanilla.py
@@ -0,0 +1,123 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+DETR Transformer class.
+
+Copy-paste from torch.nn.Transformer with modifications:
+ * positional encodings are passed in MHattention
+ * extra LN at the end of encoder is removed
+ * decoder returns a stack of activations from all decoding layers
+"""
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+from .utils import (
+ MLP,
+ _get_activation_fn,
+ _get_clones,
+ gen_encoder_output_proposals,
+ gen_sineembed_for_position,
+ sigmoid_focal_loss,
+)
+
+
+class TextTransformer(nn.Module):
+ def __init__(self, num_layers, d_model=256, nheads=8, dim_feedforward=2048, dropout=0.1):
+ super().__init__()
+ self.num_layers = num_layers
+ self.d_model = d_model
+ self.nheads = nheads
+ self.dim_feedforward = dim_feedforward
+ self.norm = None
+
+ single_encoder_layer = TransformerEncoderLayer(
+ d_model=d_model, nhead=nheads, dim_feedforward=dim_feedforward, dropout=dropout
+ )
+ self.layers = _get_clones(single_encoder_layer, num_layers)
+
+ def forward(self, memory_text: torch.Tensor, text_attention_mask: torch.Tensor):
+ """
+
+ Args:
+ text_attention_mask: bs, num_token
+ memory_text: bs, num_token, d_model
+
+ Raises:
+ RuntimeError: _description_
+
+ Returns:
+ output: bs, num_token, d_model
+ """
+
+ output = memory_text.transpose(0, 1)
+
+ for layer in self.layers:
+ output = layer(output, src_key_padding_mask=text_attention_mask)
+
+ if self.norm is not None:
+ output = self.norm(output)
+
+ return output.transpose(0, 1)
+
+
+class TransformerEncoderLayer(nn.Module):
+ def __init__(
+ self,
+ d_model,
+ nhead,
+ dim_feedforward=2048,
+ dropout=0.1,
+ activation="relu",
+ normalize_before=False,
+ ):
+ super().__init__()
+ self.self_attn = nn.MultiheadAttention(d_model, nhead, dropout=dropout)
+ # Implementation of Feedforward model
+ self.linear1 = nn.Linear(d_model, dim_feedforward)
+ self.dropout = nn.Dropout(dropout)
+ self.linear2 = nn.Linear(dim_feedforward, d_model)
+
+ self.norm1 = nn.LayerNorm(d_model)
+ self.norm2 = nn.LayerNorm(d_model)
+ self.dropout1 = nn.Dropout(dropout)
+ self.dropout2 = nn.Dropout(dropout)
+
+ self.activation = _get_activation_fn(activation)
+ self.normalize_before = normalize_before
+ self.nhead = nhead
+
+ def with_pos_embed(self, tensor, pos: Optional[Tensor]):
+ return tensor if pos is None else tensor + pos
+
+ def forward(
+ self,
+ src,
+ src_mask: Optional[Tensor] = None,
+ src_key_padding_mask: Optional[Tensor] = None,
+ pos: Optional[Tensor] = None,
+ ):
+ # repeat attn mask
+ if src_mask.dim() == 3 and src_mask.shape[0] == src.shape[1]:
+ # bs, num_q, num_k
+ src_mask = src_mask.repeat(self.nhead, 1, 1)
+
+ q = k = self.with_pos_embed(src, pos)
+
+ src2 = self.self_attn(q, k, value=src, attn_mask=src_mask)[0]
+
+ # src2 = self.self_attn(q, k, value=src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0]
+ src = src + self.dropout1(src2)
+ src = self.norm1(src)
+ src2 = self.linear2(self.dropout(self.activation(self.linear1(src))))
+ src = src + self.dropout2(src2)
+ src = self.norm2(src)
+ return src
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5bd18f70225e12b2e27fdb4eabcde91d959f8e31
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/GroundingDINO/utils.py
@@ -0,0 +1,268 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+
+import copy
+import math
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor, nn
+
+
+def _get_clones(module, N, layer_share=False):
+ # import ipdb; ipdb.set_trace()
+ if layer_share:
+ return nn.ModuleList([module for i in range(N)])
+ else:
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+
+
+def get_sine_pos_embed(
+ pos_tensor: torch.Tensor,
+ num_pos_feats: int = 128,
+ temperature: int = 10000,
+ exchange_xy: bool = True,
+):
+ """generate sine position embedding from a position tensor
+ Args:
+ pos_tensor (torch.Tensor): shape: [..., n].
+ num_pos_feats (int): projected shape for each float in the tensor.
+ temperature (int): temperature in the sine/cosine function.
+ exchange_xy (bool, optional): exchange pos x and pos y. \
+ For example, input tensor is [x,y], the results will be [pos(y), pos(x)]. Defaults to True.
+ Returns:
+ pos_embed (torch.Tensor): shape: [..., n*num_pos_feats].
+ """
+ scale = 2 * math.pi
+ dim_t = torch.arange(num_pos_feats, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = temperature ** (2 * torch.div(dim_t, 2, rounding_mode="floor") / num_pos_feats)
+
+ def sine_func(x: torch.Tensor):
+ sin_x = x * scale / dim_t
+ sin_x = torch.stack((sin_x[..., 0::2].sin(), sin_x[..., 1::2].cos()), dim=3).flatten(2)
+ return sin_x
+
+ pos_res = [sine_func(x) for x in pos_tensor.split([1] * pos_tensor.shape[-1], dim=-1)]
+ if exchange_xy:
+ pos_res[0], pos_res[1] = pos_res[1], pos_res[0]
+ pos_res = torch.cat(pos_res, dim=-1)
+ return pos_res
+
+
+def gen_encoder_output_proposals(
+ memory: Tensor, memory_padding_mask: Tensor, spatial_shapes: Tensor, learnedwh=None
+):
+ """
+ Input:
+ - memory: bs, \sum{hw}, d_model
+ - memory_padding_mask: bs, \sum{hw}
+ - spatial_shapes: nlevel, 2
+ - learnedwh: 2
+ Output:
+ - output_memory: bs, \sum{hw}, d_model
+ - output_proposals: bs, \sum{hw}, 4
+ """
+ N_, S_, C_ = memory.shape
+ proposals = []
+ _cur = 0
+ for lvl, (H_, W_) in enumerate(spatial_shapes):
+ mask_flatten_ = memory_padding_mask[:, _cur : (_cur + H_ * W_)].view(N_, H_, W_, 1)
+ valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1)
+ valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
+
+ # import ipdb; ipdb.set_trace()
+
+ grid_y, grid_x = torch.meshgrid(
+ torch.linspace(0, H_ - 1, H_, dtype=torch.float32, device=memory.device),
+ torch.linspace(0, W_ - 1, W_, dtype=torch.float32, device=memory.device),
+ )
+ grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1) # H_, W_, 2
+
+ scale = torch.cat([valid_W.unsqueeze(-1), valid_H.unsqueeze(-1)], 1).view(N_, 1, 1, 2)
+ grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
+
+ if learnedwh is not None:
+ # import ipdb; ipdb.set_trace()
+ wh = torch.ones_like(grid) * learnedwh.sigmoid() * (2.0**lvl)
+ else:
+ wh = torch.ones_like(grid) * 0.05 * (2.0**lvl)
+
+ # scale = torch.cat([W_[None].unsqueeze(-1), H_[None].unsqueeze(-1)], 1).view(1, 1, 1, 2).repeat(N_, 1, 1, 1)
+ # grid = (grid.unsqueeze(0).expand(N_, -1, -1, -1) + 0.5) / scale
+ # wh = torch.ones_like(grid) / scale
+ proposal = torch.cat((grid, wh), -1).view(N_, -1, 4)
+ proposals.append(proposal)
+ _cur += H_ * W_
+ # import ipdb; ipdb.set_trace()
+ output_proposals = torch.cat(proposals, 1)
+ output_proposals_valid = ((output_proposals > 0.01) & (output_proposals < 0.99)).all(
+ -1, keepdim=True
+ )
+ output_proposals = torch.log(output_proposals / (1 - output_proposals)) # unsigmoid
+ output_proposals = output_proposals.masked_fill(memory_padding_mask.unsqueeze(-1), float("inf"))
+ output_proposals = output_proposals.masked_fill(~output_proposals_valid, float("inf"))
+
+ output_memory = memory
+ output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float(0))
+ output_memory = output_memory.masked_fill(~output_proposals_valid, float(0))
+
+ # output_memory = output_memory.masked_fill(memory_padding_mask.unsqueeze(-1), float('inf'))
+ # output_memory = output_memory.masked_fill(~output_proposals_valid, float('inf'))
+
+ return output_memory, output_proposals
+
+
+class RandomBoxPerturber:
+ def __init__(
+ self, x_noise_scale=0.2, y_noise_scale=0.2, w_noise_scale=0.2, h_noise_scale=0.2
+ ) -> None:
+ self.noise_scale = torch.Tensor(
+ [x_noise_scale, y_noise_scale, w_noise_scale, h_noise_scale]
+ )
+
+ def __call__(self, refanchors: Tensor) -> Tensor:
+ nq, bs, query_dim = refanchors.shape
+ device = refanchors.device
+
+ noise_raw = torch.rand_like(refanchors)
+ noise_scale = self.noise_scale.to(device)[:query_dim]
+
+ new_refanchors = refanchors * (1 + (noise_raw - 0.5) * noise_scale)
+ return new_refanchors.clamp_(0, 1)
+
+
+def sigmoid_focal_loss(
+ inputs, targets, num_boxes, alpha: float = 0.25, gamma: float = 2, no_reduction=False
+):
+ """
+ Loss used in RetinaNet for dense detection: https://arxiv.org/abs/1708.02002.
+ Args:
+ inputs: A float tensor of arbitrary shape.
+ The predictions for each example.
+ targets: A float tensor with the same shape as inputs. Stores the binary
+ classification label for each element in inputs
+ (0 for the negative class and 1 for the positive class).
+ alpha: (optional) Weighting factor in range (0,1) to balance
+ positive vs negative examples. Default = -1 (no weighting).
+ gamma: Exponent of the modulating factor (1 - p_t) to
+ balance easy vs hard examples.
+ Returns:
+ Loss tensor
+ """
+ prob = inputs.sigmoid()
+ ce_loss = F.binary_cross_entropy_with_logits(inputs, targets, reduction="none")
+ p_t = prob * targets + (1 - prob) * (1 - targets)
+ loss = ce_loss * ((1 - p_t) ** gamma)
+
+ if alpha >= 0:
+ alpha_t = alpha * targets + (1 - alpha) * (1 - targets)
+ loss = alpha_t * loss
+
+ if no_reduction:
+ return loss
+
+ return loss.mean(1).sum() / num_boxes
+
+
+class MLP(nn.Module):
+ """Very simple multi-layer perceptron (also called FFN)"""
+
+ def __init__(self, input_dim, hidden_dim, output_dim, num_layers):
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
+ )
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ return x
+
+
+def _get_activation_fn(activation, d_model=256, batch_dim=0):
+ """Return an activation function given a string"""
+ if activation == "relu":
+ return F.relu
+ if activation == "gelu":
+ return F.gelu
+ if activation == "glu":
+ return F.glu
+ if activation == "prelu":
+ return nn.PReLU()
+ if activation == "selu":
+ return F.selu
+
+ raise RuntimeError(f"activation should be relu/gelu, not {activation}.")
+
+
+def gen_sineembed_for_position(pos_tensor):
+ # n_query, bs, _ = pos_tensor.size()
+ # sineembed_tensor = torch.zeros(n_query, bs, 256)
+ scale = 2 * math.pi
+ dim_t = torch.arange(128, dtype=torch.float32, device=pos_tensor.device)
+ dim_t = 10000 ** (2 * (torch.div(dim_t, 2, rounding_mode='floor')) / 128)
+ x_embed = pos_tensor[:, :, 0] * scale
+ y_embed = pos_tensor[:, :, 1] * scale
+ pos_x = x_embed[:, :, None] / dim_t
+ pos_y = y_embed[:, :, None] / dim_t
+ pos_x = torch.stack((pos_x[:, :, 0::2].sin(), pos_x[:, :, 1::2].cos()), dim=3).flatten(2)
+ pos_y = torch.stack((pos_y[:, :, 0::2].sin(), pos_y[:, :, 1::2].cos()), dim=3).flatten(2)
+ if pos_tensor.size(-1) == 2:
+ pos = torch.cat((pos_y, pos_x), dim=2)
+ elif pos_tensor.size(-1) == 4:
+ w_embed = pos_tensor[:, :, 2] * scale
+ pos_w = w_embed[:, :, None] / dim_t
+ pos_w = torch.stack((pos_w[:, :, 0::2].sin(), pos_w[:, :, 1::2].cos()), dim=3).flatten(2)
+
+ h_embed = pos_tensor[:, :, 3] * scale
+ pos_h = h_embed[:, :, None] / dim_t
+ pos_h = torch.stack((pos_h[:, :, 0::2].sin(), pos_h[:, :, 1::2].cos()), dim=3).flatten(2)
+
+ pos = torch.cat((pos_y, pos_x, pos_w, pos_h), dim=2)
+ else:
+ raise ValueError("Unknown pos_tensor shape(-1):{}".format(pos_tensor.size(-1)))
+ return pos
+
+
+class ContrastiveEmbed(nn.Module):
+ def __init__(self, max_text_len=256):
+ """
+ Args:
+ max_text_len: max length of text.
+ """
+ super().__init__()
+ self.max_text_len = max_text_len
+
+ def forward(self, x, text_dict):
+ """_summary_
+
+ Args:
+ x (_type_): _description_
+ text_dict (_type_): _description_
+ {
+ 'encoded_text': encoded_text, # bs, 195, d_model
+ 'text_token_mask': text_token_mask, # bs, 195
+ # True for used tokens. False for padding tokens
+ }
+ Returns:
+ _type_: _description_
+ """
+ assert isinstance(text_dict, dict)
+
+ y = text_dict["encoded_text"]
+ text_token_mask = text_dict["text_token_mask"]
+
+ res = x @ y.transpose(-1, -2)
+ res.masked_fill_(~text_token_mask[:, None, :], float("-inf"))
+
+ # padding to max_text_len
+ new_res = torch.full((*res.shape[:-1], self.max_text_len), float("-inf"), device=res.device)
+ new_res[..., : res.shape[-1]] = res
+
+ return new_res
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3413961d1d184b99835eb1e919b052d70298bc6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/__init__.py
@@ -0,0 +1,18 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+from .GroundingDINO import build_groundingdino
+
+
+def build_model(args):
+ # we use register to maintain models from catdet6 on.
+ from .registry import MODULE_BUILD_FUNCS
+
+ assert args.modelname in MODULE_BUILD_FUNCS._module_dict
+ build_func = MODULE_BUILD_FUNCS.get(args.modelname)
+ model = build_func(args)
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/registry.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d22a59eec79a2a19b83fa1779f2adaf5753aec6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/models/registry.py
@@ -0,0 +1,66 @@
+# ------------------------------------------------------------------------
+# Grounding DINO
+# url: https://github.com/IDEA-Research/GroundingDINO
+# Copyright (c) 2023 IDEA. All Rights Reserved.
+# Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+# ------------------------------------------------------------------------
+# -*- coding: utf-8 -*-
+# @Author: Yihao Chen
+# @Date: 2021-08-16 16:03:17
+# @Last Modified by: Shilong Liu
+# @Last Modified time: 2022-01-23 15:26
+# modified from mmcv
+
+import inspect
+from functools import partial
+
+
+class Registry(object):
+ def __init__(self, name):
+ self._name = name
+ self._module_dict = dict()
+
+ def __repr__(self):
+ format_str = self.__class__.__name__ + "(name={}, items={})".format(
+ self._name, list(self._module_dict.keys())
+ )
+ return format_str
+
+ def __len__(self):
+ return len(self._module_dict)
+
+ @property
+ def name(self):
+ return self._name
+
+ @property
+ def module_dict(self):
+ return self._module_dict
+
+ def get(self, key):
+ return self._module_dict.get(key, None)
+
+ def registe_with_name(self, module_name=None, force=False):
+ return partial(self.register, module_name=module_name, force=force)
+
+ def register(self, module_build_function, module_name=None, force=False):
+ """Register a module build function.
+ Args:
+ module (:obj:`nn.Module`): Module to be registered.
+ """
+ if not inspect.isfunction(module_build_function):
+ raise TypeError(
+ "module_build_function must be a function, but got {}".format(
+ type(module_build_function)
+ )
+ )
+ if module_name is None:
+ module_name = module_build_function.__name__
+ if not force and module_name in self._module_dict:
+ raise KeyError("{} is already registered in {}".format(module_name, self.name))
+ self._module_dict[module_name] = module_build_function
+
+ return module_build_function
+
+
+MODULE_BUILD_FUNCS = Registry("model build functions")
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..168f9979a4623806934b0ff1102ac166704e7dec
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/box_ops.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/box_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..781068d294e576954edb4bd07b6e0f30e4e1bcd9
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/box_ops.py
@@ -0,0 +1,140 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Utilities for bounding box manipulation and GIoU.
+"""
+import torch
+from torchvision.ops.boxes import box_area
+
+
+def box_cxcywh_to_xyxy(x):
+ x_c, y_c, w, h = x.unbind(-1)
+ b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
+ return torch.stack(b, dim=-1)
+
+
+def box_xyxy_to_cxcywh(x):
+ x0, y0, x1, y1 = x.unbind(-1)
+ b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
+ return torch.stack(b, dim=-1)
+
+
+# modified from torchvision to also return the union
+def box_iou(boxes1, boxes2):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ # import ipdb; ipdb.set_trace()
+ lt = torch.max(boxes1[:, None, :2], boxes2[:, :2]) # [N,M,2]
+ rb = torch.min(boxes1[:, None, 2:], boxes2[:, 2:]) # [N,M,2]
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ inter = wh[:, :, 0] * wh[:, :, 1] # [N,M]
+
+ union = area1[:, None] + area2 - inter
+
+ iou = inter / (union + 1e-6)
+ return iou, union
+
+
+def generalized_box_iou(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/
+
+ The boxes should be in [x0, y0, x1, y1] format
+
+ Returns a [N, M] pairwise matrix, where N = len(boxes1)
+ and M = len(boxes2)
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
+ # except:
+ # import ipdb; ipdb.set_trace()
+ iou, union = box_iou(boxes1, boxes2)
+
+ lt = torch.min(boxes1[:, None, :2], boxes2[:, :2])
+ rb = torch.max(boxes1[:, None, 2:], boxes2[:, 2:])
+
+ wh = (rb - lt).clamp(min=0) # [N,M,2]
+ area = wh[:, :, 0] * wh[:, :, 1]
+
+ return iou - (area - union) / (area + 1e-6)
+
+
+# modified from torchvision to also return the union
+def box_iou_pairwise(boxes1, boxes2):
+ area1 = box_area(boxes1)
+ area2 = box_area(boxes2)
+
+ lt = torch.max(boxes1[:, :2], boxes2[:, :2]) # [N,2]
+ rb = torch.min(boxes1[:, 2:], boxes2[:, 2:]) # [N,2]
+
+ wh = (rb - lt).clamp(min=0) # [N,2]
+ inter = wh[:, 0] * wh[:, 1] # [N]
+
+ union = area1 + area2 - inter
+
+ iou = inter / union
+ return iou, union
+
+
+def generalized_box_iou_pairwise(boxes1, boxes2):
+ """
+ Generalized IoU from https://giou.stanford.edu/
+
+ Input:
+ - boxes1, boxes2: N,4
+ Output:
+ - giou: N, 4
+ """
+ # degenerate boxes gives inf / nan results
+ # so do an early check
+ assert (boxes1[:, 2:] >= boxes1[:, :2]).all()
+ assert (boxes2[:, 2:] >= boxes2[:, :2]).all()
+ assert boxes1.shape == boxes2.shape
+ iou, union = box_iou_pairwise(boxes1, boxes2) # N, 4
+
+ lt = torch.min(boxes1[:, :2], boxes2[:, :2])
+ rb = torch.max(boxes1[:, 2:], boxes2[:, 2:])
+
+ wh = (rb - lt).clamp(min=0) # [N,2]
+ area = wh[:, 0] * wh[:, 1]
+
+ return iou - (area - union) / area
+
+
+def masks_to_boxes(masks):
+ """Compute the bounding boxes around the provided masks
+
+ The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
+
+ Returns a [N, 4] tensors, with the boxes in xyxy format
+ """
+ if masks.numel() == 0:
+ return torch.zeros((0, 4), device=masks.device)
+
+ h, w = masks.shape[-2:]
+
+ y = torch.arange(0, h, dtype=torch.float)
+ x = torch.arange(0, w, dtype=torch.float)
+ y, x = torch.meshgrid(y, x)
+
+ x_mask = masks * x.unsqueeze(0)
+ x_max = x_mask.flatten(1).max(-1)[0]
+ x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ y_mask = masks * y.unsqueeze(0)
+ y_max = y_mask.flatten(1).max(-1)[0]
+ y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
+
+ return torch.stack([x_min, y_min, x_max, y_max], 1)
+
+
+if __name__ == "__main__":
+ x = torch.rand(5, 4)
+ y = torch.rand(3, 4)
+ iou, union = box_iou(x, y)
+ import ipdb
+
+ ipdb.set_trace()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/get_tokenlizer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/get_tokenlizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7dcf7e95f03f95b20546b26442a94225924618b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/get_tokenlizer.py
@@ -0,0 +1,26 @@
+from transformers import AutoTokenizer, BertModel, BertTokenizer, RobertaModel, RobertaTokenizerFast
+
+
+def get_tokenlizer(text_encoder_type):
+ if not isinstance(text_encoder_type, str):
+ # print("text_encoder_type is not a str")
+ if hasattr(text_encoder_type, "text_encoder_type"):
+ text_encoder_type = text_encoder_type.text_encoder_type
+ elif text_encoder_type.get("text_encoder_type", False):
+ text_encoder_type = text_encoder_type.get("text_encoder_type")
+ else:
+ raise ValueError(
+ "Unknown type of text_encoder_type: {}".format(type(text_encoder_type))
+ )
+ print("final text_encoder_type: {}".format(text_encoder_type))
+
+ tokenizer = AutoTokenizer.from_pretrained(text_encoder_type)
+ return tokenizer
+
+
+def get_pretrained_language_model(text_encoder_type):
+ if text_encoder_type == "bert-base-uncased":
+ return BertModel.from_pretrained(text_encoder_type)
+ if text_encoder_type == "roberta-base":
+ return RobertaModel.from_pretrained(text_encoder_type)
+ raise ValueError("Unknown text_encoder_type {}".format(text_encoder_type))
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/inference.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/inference.py
new file mode 100644
index 0000000000000000000000000000000000000000..8168b96ca51e6e494c7c675c2f4a610e21b095d6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/inference.py
@@ -0,0 +1,98 @@
+from typing import Tuple, List
+
+import cv2
+import numpy as np
+import supervision as sv
+import torch
+from PIL import Image
+from torchvision.ops import box_convert
+
+import groundingdino.datasets.transforms as T
+from groundingdino.models import build_model
+from groundingdino.util.misc import clean_state_dict
+from groundingdino.util.slconfig import SLConfig
+from groundingdino.util.utils import get_phrases_from_posmap
+
+
+def preprocess_caption(caption: str) -> str:
+ result = caption.lower().strip()
+ if result.endswith("."):
+ return result
+ return result + "."
+
+
+def load_model(model_config_path: str, model_checkpoint_path: str, device: str = "cuda"):
+ args = SLConfig.fromfile(model_config_path)
+ args.device = device
+ model = build_model(args)
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
+ model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
+ model.eval()
+ return model
+
+
+def load_image(image_path: str) -> Tuple[np.array, torch.Tensor]:
+ transform = T.Compose(
+ [
+ T.RandomResize([800], max_size=1333),
+ T.ToTensor(),
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
+ ]
+ )
+ image_source = Image.open(image_path).convert("RGB")
+ image = np.asarray(image_source)
+ image_transformed, _ = transform(image_source, None)
+ return image, image_transformed
+
+
+def predict(
+ model,
+ image: torch.Tensor,
+ caption: str,
+ box_threshold: float,
+ text_threshold: float,
+ device: str = "cuda"
+) -> Tuple[torch.Tensor, torch.Tensor, List[str]]:
+ caption = preprocess_caption(caption=caption)
+
+ model = model.to(device)
+ image = image.to(device)
+
+ with torch.no_grad():
+ outputs = model(image[None], captions=[caption])
+
+ prediction_logits = outputs["pred_logits"].cpu().sigmoid()[0] # prediction_logits.shape = (nq, 256)
+ prediction_boxes = outputs["pred_boxes"].cpu()[0] # prediction_boxes.shape = (nq, 4)
+
+ mask = prediction_logits.max(dim=1)[0] > box_threshold
+ logits = prediction_logits[mask] # logits.shape = (n, 256)
+ boxes = prediction_boxes[mask] # boxes.shape = (n, 4)
+
+ tokenizer = model.tokenizer
+ tokenized = tokenizer(caption)
+
+ phrases = [
+ get_phrases_from_posmap(logit > text_threshold, tokenized, tokenizer).replace('.', '')
+ for logit
+ in logits
+ ]
+
+ return boxes, logits.max(dim=1)[0], phrases
+
+
+def annotate(image_source: np.ndarray, boxes: torch.Tensor, logits: torch.Tensor, phrases: List[str]) -> np.ndarray:
+ h, w, _ = image_source.shape
+ boxes = boxes * torch.Tensor([w, h, w, h])
+ xyxy = box_convert(boxes=boxes, in_fmt="cxcywh", out_fmt="xyxy").numpy()
+ detections = sv.Detections(xyxy=xyxy)
+
+ labels = [
+ f"{phrase} {logit:.2f}"
+ for phrase, logit
+ in zip(phrases, logits)
+ ]
+
+ box_annotator = sv.BoxAnnotator()
+ annotated_frame = cv2.cvtColor(image_source, cv2.COLOR_RGB2BGR)
+ annotated_frame = box_annotator.annotate(scene=annotated_frame, detections=detections, labels=labels)
+ return annotated_frame
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/logger.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..18145f54c927abd59b95f3fa6e6da8002bc2ce97
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/logger.py
@@ -0,0 +1,93 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+import functools
+import logging
+import os
+import sys
+
+from termcolor import colored
+
+
+class _ColorfulFormatter(logging.Formatter):
+ def __init__(self, *args, **kwargs):
+ self._root_name = kwargs.pop("root_name") + "."
+ self._abbrev_name = kwargs.pop("abbrev_name", "")
+ if len(self._abbrev_name):
+ self._abbrev_name = self._abbrev_name + "."
+ super(_ColorfulFormatter, self).__init__(*args, **kwargs)
+
+ def formatMessage(self, record):
+ record.name = record.name.replace(self._root_name, self._abbrev_name)
+ log = super(_ColorfulFormatter, self).formatMessage(record)
+ if record.levelno == logging.WARNING:
+ prefix = colored("WARNING", "red", attrs=["blink"])
+ elif record.levelno == logging.ERROR or record.levelno == logging.CRITICAL:
+ prefix = colored("ERROR", "red", attrs=["blink", "underline"])
+ else:
+ return log
+ return prefix + " " + log
+
+
+# so that calling setup_logger multiple times won't add many handlers
+@functools.lru_cache()
+def setup_logger(output=None, distributed_rank=0, *, color=True, name="imagenet", abbrev_name=None):
+ """
+ Initialize the detectron2 logger and set its verbosity level to "INFO".
+
+ Args:
+ output (str): a file name or a directory to save log. If None, will not save log file.
+ If ends with ".txt" or ".log", assumed to be a file name.
+ Otherwise, logs will be saved to `output/log.txt`.
+ name (str): the root module name of this logger
+
+ Returns:
+ logging.Logger: a logger
+ """
+ logger = logging.getLogger(name)
+ logger.setLevel(logging.DEBUG)
+ logger.propagate = False
+
+ if abbrev_name is None:
+ abbrev_name = name
+
+ plain_formatter = logging.Formatter(
+ "[%(asctime)s.%(msecs)03d]: %(message)s", datefmt="%m/%d %H:%M:%S"
+ )
+ # stdout logging: master only
+ if distributed_rank == 0:
+ ch = logging.StreamHandler(stream=sys.stdout)
+ ch.setLevel(logging.DEBUG)
+ if color:
+ formatter = _ColorfulFormatter(
+ colored("[%(asctime)s.%(msecs)03d]: ", "green") + "%(message)s",
+ datefmt="%m/%d %H:%M:%S",
+ root_name=name,
+ abbrev_name=str(abbrev_name),
+ )
+ else:
+ formatter = plain_formatter
+ ch.setFormatter(formatter)
+ logger.addHandler(ch)
+
+ # file logging: all workers
+ if output is not None:
+ if output.endswith(".txt") or output.endswith(".log"):
+ filename = output
+ else:
+ filename = os.path.join(output, "log.txt")
+ if distributed_rank > 0:
+ filename = filename + f".rank{distributed_rank}"
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
+
+ fh = logging.StreamHandler(_cached_log_stream(filename))
+ fh.setLevel(logging.DEBUG)
+ fh.setFormatter(plain_formatter)
+ logger.addHandler(fh)
+
+ return logger
+
+
+# cache the opened file object, so that different calls to `setup_logger`
+# with the same file name can safely write to the same file.
+@functools.lru_cache(maxsize=None)
+def _cached_log_stream(filename):
+ return open(filename, "a")
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/misc.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..d64b84ef24bea0c98e76824feb1903f6bfebe7a5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/misc.py
@@ -0,0 +1,717 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
+"""
+Misc functions, including distributed helpers.
+
+Mostly copy-paste from torchvision references.
+"""
+import colorsys
+import datetime
+import functools
+import io
+import json
+import os
+import pickle
+import subprocess
+import time
+from collections import OrderedDict, defaultdict, deque
+from typing import List, Optional
+
+import numpy as np
+import torch
+import torch.distributed as dist
+
+# needed due to empty tensor bug in pytorch and torchvision 0.5
+import torchvision
+from torch import Tensor
+
+__torchvision_need_compat_flag = float(torchvision.__version__.split(".")[1]) < 7
+if __torchvision_need_compat_flag:
+ from torchvision.ops import _new_empty_tensor
+ from torchvision.ops.misc import _output_size
+
+
+class SmoothedValue(object):
+ """Track a series of values and provide access to smoothed values over a
+ window or the global series average.
+ """
+
+ def __init__(self, window_size=20, fmt=None):
+ if fmt is None:
+ fmt = "{median:.4f} ({global_avg:.4f})"
+ self.deque = deque(maxlen=window_size)
+ self.total = 0.0
+ self.count = 0
+ self.fmt = fmt
+
+ def update(self, value, n=1):
+ self.deque.append(value)
+ self.count += n
+ self.total += value * n
+
+ def synchronize_between_processes(self):
+ """
+ Warning: does not synchronize the deque!
+ """
+ if not is_dist_avail_and_initialized():
+ return
+ t = torch.tensor([self.count, self.total], dtype=torch.float64, device="cuda")
+ dist.barrier()
+ dist.all_reduce(t)
+ t = t.tolist()
+ self.count = int(t[0])
+ self.total = t[1]
+
+ @property
+ def median(self):
+ d = torch.tensor(list(self.deque))
+ if d.shape[0] == 0:
+ return 0
+ return d.median().item()
+
+ @property
+ def avg(self):
+ d = torch.tensor(list(self.deque), dtype=torch.float32)
+ return d.mean().item()
+
+ @property
+ def global_avg(self):
+ if os.environ.get("SHILONG_AMP", None) == "1":
+ eps = 1e-4
+ else:
+ eps = 1e-6
+ return self.total / (self.count + eps)
+
+ @property
+ def max(self):
+ return max(self.deque)
+
+ @property
+ def value(self):
+ return self.deque[-1]
+
+ def __str__(self):
+ return self.fmt.format(
+ median=self.median,
+ avg=self.avg,
+ global_avg=self.global_avg,
+ max=self.max,
+ value=self.value,
+ )
+
+
+@functools.lru_cache()
+def _get_global_gloo_group():
+ """
+ Return a process group based on gloo backend, containing all the ranks
+ The result is cached.
+ """
+
+ if dist.get_backend() == "nccl":
+ return dist.new_group(backend="gloo")
+
+ return dist.group.WORLD
+
+
+def all_gather_cpu(data):
+ """
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
+ Args:
+ data: any picklable object
+ Returns:
+ list[data]: list of data gathered from each rank
+ """
+
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ cpu_group = _get_global_gloo_group()
+
+ buffer = io.BytesIO()
+ torch.save(data, buffer)
+ data_view = buffer.getbuffer()
+ device = "cuda" if cpu_group is None else "cpu"
+ tensor = torch.ByteTensor(data_view).to(device)
+
+ # obtain Tensor size of each rank
+ local_size = torch.tensor([tensor.numel()], device=device, dtype=torch.long)
+ size_list = [torch.tensor([0], device=device, dtype=torch.long) for _ in range(world_size)]
+ if cpu_group is None:
+ dist.all_gather(size_list, local_size)
+ else:
+ print("gathering on cpu")
+ dist.all_gather(size_list, local_size, group=cpu_group)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+ assert isinstance(local_size.item(), int)
+ local_size = int(local_size.item())
+
+ # receiving Tensor from all ranks
+ # we pad the tensor because torch all_gather does not support
+ # gathering tensors of different shapes
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device=device))
+ if local_size != max_size:
+ padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device=device)
+ tensor = torch.cat((tensor, padding), dim=0)
+ if cpu_group is None:
+ dist.all_gather(tensor_list, tensor)
+ else:
+ dist.all_gather(tensor_list, tensor, group=cpu_group)
+
+ data_list = []
+ for size, tensor in zip(size_list, tensor_list):
+ tensor = torch.split(tensor, [size, max_size - size], dim=0)[0]
+ buffer = io.BytesIO(tensor.cpu().numpy())
+ obj = torch.load(buffer)
+ data_list.append(obj)
+
+ return data_list
+
+
+def all_gather(data):
+ """
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
+ Args:
+ data: any picklable object
+ Returns:
+ list[data]: list of data gathered from each rank
+ """
+
+ if os.getenv("CPU_REDUCE") == "1":
+ return all_gather_cpu(data)
+
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ # serialized to a Tensor
+ buffer = pickle.dumps(data)
+ storage = torch.ByteStorage.from_buffer(buffer)
+ tensor = torch.ByteTensor(storage).to("cuda")
+
+ # obtain Tensor size of each rank
+ local_size = torch.tensor([tensor.numel()], device="cuda")
+ size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)]
+ dist.all_gather(size_list, local_size)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+
+ # receiving Tensor from all ranks
+ # we pad the tensor because torch all_gather does not support
+ # gathering tensors of different shapes
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda"))
+ if local_size != max_size:
+ padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda")
+ tensor = torch.cat((tensor, padding), dim=0)
+ dist.all_gather(tensor_list, tensor)
+
+ data_list = []
+ for size, tensor in zip(size_list, tensor_list):
+ buffer = tensor.cpu().numpy().tobytes()[:size]
+ data_list.append(pickle.loads(buffer))
+
+ return data_list
+
+
+def reduce_dict(input_dict, average=True):
+ """
+ Args:
+ input_dict (dict): all the values will be reduced
+ average (bool): whether to do average or sum
+ Reduce the values in the dictionary from all processes so that all processes
+ have the averaged results. Returns a dict with the same fields as
+ input_dict, after reduction.
+ """
+ world_size = get_world_size()
+ if world_size < 2:
+ return input_dict
+ with torch.no_grad():
+ names = []
+ values = []
+ # sort the keys so that they are consistent across processes
+ for k in sorted(input_dict.keys()):
+ names.append(k)
+ values.append(input_dict[k])
+ values = torch.stack(values, dim=0)
+ dist.all_reduce(values)
+ if average:
+ values /= world_size
+ reduced_dict = {k: v for k, v in zip(names, values)}
+ return reduced_dict
+
+
+class MetricLogger(object):
+ def __init__(self, delimiter="\t"):
+ self.meters = defaultdict(SmoothedValue)
+ self.delimiter = delimiter
+
+ def update(self, **kwargs):
+ for k, v in kwargs.items():
+ if isinstance(v, torch.Tensor):
+ v = v.item()
+ assert isinstance(v, (float, int))
+ self.meters[k].update(v)
+
+ def __getattr__(self, attr):
+ if attr in self.meters:
+ return self.meters[attr]
+ if attr in self.__dict__:
+ return self.__dict__[attr]
+ raise AttributeError("'{}' object has no attribute '{}'".format(type(self).__name__, attr))
+
+ def __str__(self):
+ loss_str = []
+ for name, meter in self.meters.items():
+ # print(name, str(meter))
+ # import ipdb;ipdb.set_trace()
+ if meter.count > 0:
+ loss_str.append("{}: {}".format(name, str(meter)))
+ return self.delimiter.join(loss_str)
+
+ def synchronize_between_processes(self):
+ for meter in self.meters.values():
+ meter.synchronize_between_processes()
+
+ def add_meter(self, name, meter):
+ self.meters[name] = meter
+
+ def log_every(self, iterable, print_freq, header=None, logger=None):
+ if logger is None:
+ print_func = print
+ else:
+ print_func = logger.info
+
+ i = 0
+ if not header:
+ header = ""
+ start_time = time.time()
+ end = time.time()
+ iter_time = SmoothedValue(fmt="{avg:.4f}")
+ data_time = SmoothedValue(fmt="{avg:.4f}")
+ space_fmt = ":" + str(len(str(len(iterable)))) + "d"
+ if torch.cuda.is_available():
+ log_msg = self.delimiter.join(
+ [
+ header,
+ "[{0" + space_fmt + "}/{1}]",
+ "eta: {eta}",
+ "{meters}",
+ "time: {time}",
+ "data: {data}",
+ "max mem: {memory:.0f}",
+ ]
+ )
+ else:
+ log_msg = self.delimiter.join(
+ [
+ header,
+ "[{0" + space_fmt + "}/{1}]",
+ "eta: {eta}",
+ "{meters}",
+ "time: {time}",
+ "data: {data}",
+ ]
+ )
+ MB = 1024.0 * 1024.0
+ for obj in iterable:
+ data_time.update(time.time() - end)
+ yield obj
+ # import ipdb; ipdb.set_trace()
+ iter_time.update(time.time() - end)
+ if i % print_freq == 0 or i == len(iterable) - 1:
+ eta_seconds = iter_time.global_avg * (len(iterable) - i)
+ eta_string = str(datetime.timedelta(seconds=int(eta_seconds)))
+ if torch.cuda.is_available():
+ print_func(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ memory=torch.cuda.max_memory_allocated() / MB,
+ )
+ )
+ else:
+ print_func(
+ log_msg.format(
+ i,
+ len(iterable),
+ eta=eta_string,
+ meters=str(self),
+ time=str(iter_time),
+ data=str(data_time),
+ )
+ )
+ i += 1
+ end = time.time()
+ total_time = time.time() - start_time
+ total_time_str = str(datetime.timedelta(seconds=int(total_time)))
+ print_func(
+ "{} Total time: {} ({:.4f} s / it)".format(
+ header, total_time_str, total_time / len(iterable)
+ )
+ )
+
+
+def get_sha():
+ cwd = os.path.dirname(os.path.abspath(__file__))
+
+ def _run(command):
+ return subprocess.check_output(command, cwd=cwd).decode("ascii").strip()
+
+ sha = "N/A"
+ diff = "clean"
+ branch = "N/A"
+ try:
+ sha = _run(["git", "rev-parse", "HEAD"])
+ subprocess.check_output(["git", "diff"], cwd=cwd)
+ diff = _run(["git", "diff-index", "HEAD"])
+ diff = "has uncommited changes" if diff else "clean"
+ branch = _run(["git", "rev-parse", "--abbrev-ref", "HEAD"])
+ except Exception:
+ pass
+ message = f"sha: {sha}, status: {diff}, branch: {branch}"
+ return message
+
+
+def collate_fn(batch):
+ # import ipdb; ipdb.set_trace()
+ batch = list(zip(*batch))
+ batch[0] = nested_tensor_from_tensor_list(batch[0])
+ return tuple(batch)
+
+
+def _max_by_axis(the_list):
+ # type: (List[List[int]]) -> List[int]
+ maxes = the_list[0]
+ for sublist in the_list[1:]:
+ for index, item in enumerate(sublist):
+ maxes[index] = max(maxes[index], item)
+ return maxes
+
+
+class NestedTensor(object):
+ def __init__(self, tensors, mask: Optional[Tensor]):
+ self.tensors = tensors
+ self.mask = mask
+ if mask == "auto":
+ self.mask = torch.zeros_like(tensors).to(tensors.device)
+ if self.mask.dim() == 3:
+ self.mask = self.mask.sum(0).to(bool)
+ elif self.mask.dim() == 4:
+ self.mask = self.mask.sum(1).to(bool)
+ else:
+ raise ValueError(
+ "tensors dim must be 3 or 4 but {}({})".format(
+ self.tensors.dim(), self.tensors.shape
+ )
+ )
+
+ def imgsize(self):
+ res = []
+ for i in range(self.tensors.shape[0]):
+ mask = self.mask[i]
+ maxH = (~mask).sum(0).max()
+ maxW = (~mask).sum(1).max()
+ res.append(torch.Tensor([maxH, maxW]))
+ return res
+
+ def to(self, device):
+ # type: (Device) -> NestedTensor # noqa
+ cast_tensor = self.tensors.to(device)
+ mask = self.mask
+ if mask is not None:
+ assert mask is not None
+ cast_mask = mask.to(device)
+ else:
+ cast_mask = None
+ return NestedTensor(cast_tensor, cast_mask)
+
+ def to_img_list_single(self, tensor, mask):
+ assert tensor.dim() == 3, "dim of tensor should be 3 but {}".format(tensor.dim())
+ maxH = (~mask).sum(0).max()
+ maxW = (~mask).sum(1).max()
+ img = tensor[:, :maxH, :maxW]
+ return img
+
+ def to_img_list(self):
+ """remove the padding and convert to img list
+
+ Returns:
+ [type]: [description]
+ """
+ if self.tensors.dim() == 3:
+ return self.to_img_list_single(self.tensors, self.mask)
+ else:
+ res = []
+ for i in range(self.tensors.shape[0]):
+ tensor_i = self.tensors[i]
+ mask_i = self.mask[i]
+ res.append(self.to_img_list_single(tensor_i, mask_i))
+ return res
+
+ @property
+ def device(self):
+ return self.tensors.device
+
+ def decompose(self):
+ return self.tensors, self.mask
+
+ def __repr__(self):
+ return str(self.tensors)
+
+ @property
+ def shape(self):
+ return {"tensors.shape": self.tensors.shape, "mask.shape": self.mask.shape}
+
+
+def nested_tensor_from_tensor_list(tensor_list: List[Tensor]):
+ # TODO make this more general
+ if tensor_list[0].ndim == 3:
+ if torchvision._is_tracing():
+ # nested_tensor_from_tensor_list() does not export well to ONNX
+ # call _onnx_nested_tensor_from_tensor_list() instead
+ return _onnx_nested_tensor_from_tensor_list(tensor_list)
+
+ # TODO make it support different-sized images
+ max_size = _max_by_axis([list(img.shape) for img in tensor_list])
+ # min_size = tuple(min(s) for s in zip(*[img.shape for img in tensor_list]))
+ batch_shape = [len(tensor_list)] + max_size
+ b, c, h, w = batch_shape
+ dtype = tensor_list[0].dtype
+ device = tensor_list[0].device
+ tensor = torch.zeros(batch_shape, dtype=dtype, device=device)
+ mask = torch.ones((b, h, w), dtype=torch.bool, device=device)
+ for img, pad_img, m in zip(tensor_list, tensor, mask):
+ pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
+ m[: img.shape[1], : img.shape[2]] = False
+ else:
+ raise ValueError("not supported")
+ return NestedTensor(tensor, mask)
+
+
+# _onnx_nested_tensor_from_tensor_list() is an implementation of
+# nested_tensor_from_tensor_list() that is supported by ONNX tracing.
+@torch.jit.unused
+def _onnx_nested_tensor_from_tensor_list(tensor_list: List[Tensor]) -> NestedTensor:
+ max_size = []
+ for i in range(tensor_list[0].dim()):
+ max_size_i = torch.max(
+ torch.stack([img.shape[i] for img in tensor_list]).to(torch.float32)
+ ).to(torch.int64)
+ max_size.append(max_size_i)
+ max_size = tuple(max_size)
+
+ # work around for
+ # pad_img[: img.shape[0], : img.shape[1], : img.shape[2]].copy_(img)
+ # m[: img.shape[1], :img.shape[2]] = False
+ # which is not yet supported in onnx
+ padded_imgs = []
+ padded_masks = []
+ for img in tensor_list:
+ padding = [(s1 - s2) for s1, s2 in zip(max_size, tuple(img.shape))]
+ padded_img = torch.nn.functional.pad(img, (0, padding[2], 0, padding[1], 0, padding[0]))
+ padded_imgs.append(padded_img)
+
+ m = torch.zeros_like(img[0], dtype=torch.int, device=img.device)
+ padded_mask = torch.nn.functional.pad(m, (0, padding[2], 0, padding[1]), "constant", 1)
+ padded_masks.append(padded_mask.to(torch.bool))
+
+ tensor = torch.stack(padded_imgs)
+ mask = torch.stack(padded_masks)
+
+ return NestedTensor(tensor, mask=mask)
+
+
+def setup_for_distributed(is_master):
+ """
+ This function disables printing when not in master process
+ """
+ import builtins as __builtin__
+
+ builtin_print = __builtin__.print
+
+ def print(*args, **kwargs):
+ force = kwargs.pop("force", False)
+ if is_master or force:
+ builtin_print(*args, **kwargs)
+
+ __builtin__.print = print
+
+
+def is_dist_avail_and_initialized():
+ if not dist.is_available():
+ return False
+ if not dist.is_initialized():
+ return False
+ return True
+
+
+def get_world_size():
+ if not is_dist_avail_and_initialized():
+ return 1
+ return dist.get_world_size()
+
+
+def get_rank():
+ if not is_dist_avail_and_initialized():
+ return 0
+ return dist.get_rank()
+
+
+def is_main_process():
+ return get_rank() == 0
+
+
+def save_on_master(*args, **kwargs):
+ if is_main_process():
+ torch.save(*args, **kwargs)
+
+
+def init_distributed_mode(args):
+ if "WORLD_SIZE" in os.environ and os.environ["WORLD_SIZE"] != "": # 'RANK' in os.environ and
+ args.rank = int(os.environ["RANK"])
+ args.world_size = int(os.environ["WORLD_SIZE"])
+ args.gpu = args.local_rank = int(os.environ["LOCAL_RANK"])
+
+ # launch by torch.distributed.launch
+ # Single node
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 1 --rank 0 ...
+ # Multi nodes
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 0 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
+ # python -m torch.distributed.launch --nproc_per_node=8 main.py --world-size 2 --rank 1 --dist-url 'tcp://IP_OF_NODE0:FREEPORT' ...
+ # args.rank = int(os.environ.get('OMPI_COMM_WORLD_RANK'))
+ # local_world_size = int(os.environ['GPU_PER_NODE_COUNT'])
+ # args.world_size = args.world_size * local_world_size
+ # args.gpu = args.local_rank = int(os.environ['LOCAL_RANK'])
+ # args.rank = args.rank * local_world_size + args.local_rank
+ print(
+ "world size: {}, rank: {}, local rank: {}".format(
+ args.world_size, args.rank, args.local_rank
+ )
+ )
+ print(json.dumps(dict(os.environ), indent=2))
+ elif "SLURM_PROCID" in os.environ:
+ args.rank = int(os.environ["SLURM_PROCID"])
+ args.gpu = args.local_rank = int(os.environ["SLURM_LOCALID"])
+ args.world_size = int(os.environ["SLURM_NPROCS"])
+
+ print(
+ "world size: {}, world rank: {}, local rank: {}, device_count: {}".format(
+ args.world_size, args.rank, args.local_rank, torch.cuda.device_count()
+ )
+ )
+ else:
+ print("Not using distributed mode")
+ args.distributed = False
+ args.world_size = 1
+ args.rank = 0
+ args.local_rank = 0
+ return
+
+ print("world_size:{} rank:{} local_rank:{}".format(args.world_size, args.rank, args.local_rank))
+ args.distributed = True
+ torch.cuda.set_device(args.local_rank)
+ args.dist_backend = "nccl"
+ print("| distributed init (rank {}): {}".format(args.rank, args.dist_url), flush=True)
+
+ torch.distributed.init_process_group(
+ backend=args.dist_backend,
+ world_size=args.world_size,
+ rank=args.rank,
+ init_method=args.dist_url,
+ )
+
+ print("Before torch.distributed.barrier()")
+ torch.distributed.barrier()
+ print("End torch.distributed.barrier()")
+ setup_for_distributed(args.rank == 0)
+
+
+@torch.no_grad()
+def accuracy(output, target, topk=(1,)):
+ """Computes the precision@k for the specified values of k"""
+ if target.numel() == 0:
+ return [torch.zeros([], device=output.device)]
+ maxk = max(topk)
+ batch_size = target.size(0)
+
+ _, pred = output.topk(maxk, 1, True, True)
+ pred = pred.t()
+ correct = pred.eq(target.view(1, -1).expand_as(pred))
+
+ res = []
+ for k in topk:
+ correct_k = correct[:k].view(-1).float().sum(0)
+ res.append(correct_k.mul_(100.0 / batch_size))
+ return res
+
+
+@torch.no_grad()
+def accuracy_onehot(pred, gt):
+ """_summary_
+
+ Args:
+ pred (_type_): n, c
+ gt (_type_): n, c
+ """
+ tp = ((pred - gt).abs().sum(-1) < 1e-4).float().sum()
+ acc = tp / gt.shape[0] * 100
+ return acc
+
+
+def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
+ # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
+ """
+ Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
+ This will eventually be supported natively by PyTorch, and this
+ class can go away.
+ """
+ if __torchvision_need_compat_flag < 0.7:
+ if input.numel() > 0:
+ return torch.nn.functional.interpolate(input, size, scale_factor, mode, align_corners)
+
+ output_shape = _output_size(2, input, size, scale_factor)
+ output_shape = list(input.shape[:-2]) + list(output_shape)
+ return _new_empty_tensor(input, output_shape)
+ else:
+ return torchvision.ops.misc.interpolate(input, size, scale_factor, mode, align_corners)
+
+
+class color_sys:
+ def __init__(self, num_colors) -> None:
+ self.num_colors = num_colors
+ colors = []
+ for i in np.arange(0.0, 360.0, 360.0 / num_colors):
+ hue = i / 360.0
+ lightness = (50 + np.random.rand() * 10) / 100.0
+ saturation = (90 + np.random.rand() * 10) / 100.0
+ colors.append(
+ tuple([int(j * 255) for j in colorsys.hls_to_rgb(hue, lightness, saturation)])
+ )
+ self.colors = colors
+
+ def __call__(self, idx):
+ return self.colors[idx]
+
+
+def inverse_sigmoid(x, eps=1e-3):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+def clean_state_dict(state_dict):
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k[:7] == "module.":
+ k = k[7:] # remove `module.`
+ new_state_dict[k] = v
+ return new_state_dict
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slconfig.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slconfig.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f293e3aff215a3c7c2f7d21d27853493b6ebfbc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slconfig.py
@@ -0,0 +1,427 @@
+# ==========================================================
+# Modified from mmcv
+# ==========================================================
+import ast
+import os.path as osp
+import shutil
+import sys
+import tempfile
+from argparse import Action
+from importlib import import_module
+import platform
+
+from addict import Dict
+from yapf.yapflib.yapf_api import FormatCode
+
+BASE_KEY = "_base_"
+DELETE_KEY = "_delete_"
+RESERVED_KEYS = ["filename", "text", "pretty_text", "get", "dump", "merge_from_dict"]
+
+
+def check_file_exist(filename, msg_tmpl='file "{}" does not exist'):
+ if not osp.isfile(filename):
+ raise FileNotFoundError(msg_tmpl.format(filename))
+
+
+class ConfigDict(Dict):
+ def __missing__(self, name):
+ raise KeyError(name)
+
+ def __getattr__(self, name):
+ try:
+ value = super(ConfigDict, self).__getattr__(name)
+ except KeyError:
+ ex = AttributeError(f"'{self.__class__.__name__}' object has no " f"attribute '{name}'")
+ except Exception as e:
+ ex = e
+ else:
+ return value
+ raise ex
+
+
+class SLConfig(object):
+ """
+ config files.
+ only support .py file as config now.
+
+ ref: mmcv.utils.config
+
+ Example:
+ >>> cfg = Config(dict(a=1, b=dict(b1=[0, 1])))
+ >>> cfg.a
+ 1
+ >>> cfg.b
+ {'b1': [0, 1]}
+ >>> cfg.b.b1
+ [0, 1]
+ >>> cfg = Config.fromfile('tests/data/config/a.py')
+ >>> cfg.filename
+ "/home/kchen/projects/mmcv/tests/data/config/a.py"
+ >>> cfg.item4
+ 'test'
+ >>> cfg
+ "Config [path: /home/kchen/projects/mmcv/tests/data/config/a.py]: "
+ "{'item1': [1, 2], 'item2': {'a': 0}, 'item3': True, 'item4': 'test'}"
+ """
+
+ @staticmethod
+ def _validate_py_syntax(filename):
+ with open(filename) as f:
+ content = f.read()
+ try:
+ ast.parse(content)
+ except SyntaxError:
+ raise SyntaxError("There are syntax errors in config " f"file {filename}")
+
+ @staticmethod
+ def _file2dict(filename):
+ filename = osp.abspath(osp.expanduser(filename))
+ check_file_exist(filename)
+ if filename.lower().endswith(".py"):
+ with tempfile.TemporaryDirectory() as temp_config_dir:
+ temp_config_file = tempfile.NamedTemporaryFile(dir=temp_config_dir, suffix=".py")
+ temp_config_name = osp.basename(temp_config_file.name)
+ if platform.system() == 'Windows':
+ temp_config_file.close()
+ shutil.copyfile(filename, osp.join(temp_config_dir, temp_config_name))
+ temp_module_name = osp.splitext(temp_config_name)[0]
+ sys.path.insert(0, temp_config_dir)
+ SLConfig._validate_py_syntax(filename)
+ mod = import_module(temp_module_name)
+ sys.path.pop(0)
+ cfg_dict = {
+ name: value for name, value in mod.__dict__.items() if not name.startswith("__")
+ }
+ # delete imported module
+ del sys.modules[temp_module_name]
+ # close temp file
+ temp_config_file.close()
+ elif filename.lower().endswith((".yml", ".yaml", ".json")):
+ from .slio import slload
+
+ cfg_dict = slload(filename)
+ else:
+ raise IOError("Only py/yml/yaml/json type are supported now!")
+
+ cfg_text = filename + "\n"
+ with open(filename, "r") as f:
+ cfg_text += f.read()
+
+ # parse the base file
+ if BASE_KEY in cfg_dict:
+ cfg_dir = osp.dirname(filename)
+ base_filename = cfg_dict.pop(BASE_KEY)
+ base_filename = base_filename if isinstance(base_filename, list) else [base_filename]
+
+ cfg_dict_list = list()
+ cfg_text_list = list()
+ for f in base_filename:
+ _cfg_dict, _cfg_text = SLConfig._file2dict(osp.join(cfg_dir, f))
+ cfg_dict_list.append(_cfg_dict)
+ cfg_text_list.append(_cfg_text)
+
+ base_cfg_dict = dict()
+ for c in cfg_dict_list:
+ if len(base_cfg_dict.keys() & c.keys()) > 0:
+ raise KeyError("Duplicate key is not allowed among bases")
+ # TODO Allow the duplicate key while warnning user
+ base_cfg_dict.update(c)
+
+ base_cfg_dict = SLConfig._merge_a_into_b(cfg_dict, base_cfg_dict)
+ cfg_dict = base_cfg_dict
+
+ # merge cfg_text
+ cfg_text_list.append(cfg_text)
+ cfg_text = "\n".join(cfg_text_list)
+
+ return cfg_dict, cfg_text
+
+ @staticmethod
+ def _merge_a_into_b(a, b):
+ """merge dict `a` into dict `b` (non-inplace).
+ values in `a` will overwrite `b`.
+ copy first to avoid inplace modification
+
+ Args:
+ a ([type]): [description]
+ b ([type]): [description]
+
+ Returns:
+ [dict]: [description]
+ """
+ # import ipdb; ipdb.set_trace()
+ if not isinstance(a, dict):
+ return a
+
+ b = b.copy()
+ for k, v in a.items():
+ if isinstance(v, dict) and k in b and not v.pop(DELETE_KEY, False):
+
+ if not isinstance(b[k], dict) and not isinstance(b[k], list):
+ # if :
+ # import ipdb; ipdb.set_trace()
+ raise TypeError(
+ f"{k}={v} in child config cannot inherit from base "
+ f"because {k} is a dict in the child config but is of "
+ f"type {type(b[k])} in base config. You may set "
+ f"`{DELETE_KEY}=True` to ignore the base config"
+ )
+ b[k] = SLConfig._merge_a_into_b(v, b[k])
+ elif isinstance(b, list):
+ try:
+ _ = int(k)
+ except:
+ raise TypeError(
+ f"b is a list, " f"index {k} should be an int when input but {type(k)}"
+ )
+ b[int(k)] = SLConfig._merge_a_into_b(v, b[int(k)])
+ else:
+ b[k] = v
+
+ return b
+
+ @staticmethod
+ def fromfile(filename):
+ cfg_dict, cfg_text = SLConfig._file2dict(filename)
+ return SLConfig(cfg_dict, cfg_text=cfg_text, filename=filename)
+
+ def __init__(self, cfg_dict=None, cfg_text=None, filename=None):
+ if cfg_dict is None:
+ cfg_dict = dict()
+ elif not isinstance(cfg_dict, dict):
+ raise TypeError("cfg_dict must be a dict, but " f"got {type(cfg_dict)}")
+ for key in cfg_dict:
+ if key in RESERVED_KEYS:
+ raise KeyError(f"{key} is reserved for config file")
+
+ super(SLConfig, self).__setattr__("_cfg_dict", ConfigDict(cfg_dict))
+ super(SLConfig, self).__setattr__("_filename", filename)
+ if cfg_text:
+ text = cfg_text
+ elif filename:
+ with open(filename, "r") as f:
+ text = f.read()
+ else:
+ text = ""
+ super(SLConfig, self).__setattr__("_text", text)
+
+ @property
+ def filename(self):
+ return self._filename
+
+ @property
+ def text(self):
+ return self._text
+
+ @property
+ def pretty_text(self):
+
+ indent = 4
+
+ def _indent(s_, num_spaces):
+ s = s_.split("\n")
+ if len(s) == 1:
+ return s_
+ first = s.pop(0)
+ s = [(num_spaces * " ") + line for line in s]
+ s = "\n".join(s)
+ s = first + "\n" + s
+ return s
+
+ def _format_basic_types(k, v, use_mapping=False):
+ if isinstance(v, str):
+ v_str = f"'{v}'"
+ else:
+ v_str = str(v)
+
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: {v_str}"
+ else:
+ attr_str = f"{str(k)}={v_str}"
+ attr_str = _indent(attr_str, indent)
+
+ return attr_str
+
+ def _format_list(k, v, use_mapping=False):
+ # check if all items in the list are dict
+ if all(isinstance(_, dict) for _ in v):
+ v_str = "[\n"
+ v_str += "\n".join(
+ f"dict({_indent(_format_dict(v_), indent)})," for v_ in v
+ ).rstrip(",")
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: {v_str}"
+ else:
+ attr_str = f"{str(k)}={v_str}"
+ attr_str = _indent(attr_str, indent) + "]"
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping)
+ return attr_str
+
+ def _contain_invalid_identifier(dict_str):
+ contain_invalid_identifier = False
+ for key_name in dict_str:
+ contain_invalid_identifier |= not str(key_name).isidentifier()
+ return contain_invalid_identifier
+
+ def _format_dict(input_dict, outest_level=False):
+ r = ""
+ s = []
+
+ use_mapping = _contain_invalid_identifier(input_dict)
+ if use_mapping:
+ r += "{"
+ for idx, (k, v) in enumerate(input_dict.items()):
+ is_last = idx >= len(input_dict) - 1
+ end = "" if outest_level or is_last else ","
+ if isinstance(v, dict):
+ v_str = "\n" + _format_dict(v)
+ if use_mapping:
+ k_str = f"'{k}'" if isinstance(k, str) else str(k)
+ attr_str = f"{k_str}: dict({v_str}"
+ else:
+ attr_str = f"{str(k)}=dict({v_str}"
+ attr_str = _indent(attr_str, indent) + ")" + end
+ elif isinstance(v, list):
+ attr_str = _format_list(k, v, use_mapping) + end
+ else:
+ attr_str = _format_basic_types(k, v, use_mapping) + end
+
+ s.append(attr_str)
+ r += "\n".join(s)
+ if use_mapping:
+ r += "}"
+ return r
+
+ cfg_dict = self._cfg_dict.to_dict()
+ text = _format_dict(cfg_dict, outest_level=True)
+ # copied from setup.cfg
+ yapf_style = dict(
+ based_on_style="pep8",
+ blank_line_before_nested_class_or_def=True,
+ split_before_expression_after_opening_paren=True,
+ )
+ text, _ = FormatCode(text, style_config=yapf_style, verify=True)
+
+ return text
+
+ def __repr__(self):
+ return f"Config (path: {self.filename}): {self._cfg_dict.__repr__()}"
+
+ def __len__(self):
+ return len(self._cfg_dict)
+
+ def __getattr__(self, name):
+ # # debug
+ # print('+'*15)
+ # print('name=%s' % name)
+ # print("addr:", id(self))
+ # # print('type(self):', type(self))
+ # print(self.__dict__)
+ # print('+'*15)
+ # if self.__dict__ == {}:
+ # raise ValueError
+
+ return getattr(self._cfg_dict, name)
+
+ def __getitem__(self, name):
+ return self._cfg_dict.__getitem__(name)
+
+ def __setattr__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setattr__(name, value)
+
+ def __setitem__(self, name, value):
+ if isinstance(value, dict):
+ value = ConfigDict(value)
+ self._cfg_dict.__setitem__(name, value)
+
+ def __iter__(self):
+ return iter(self._cfg_dict)
+
+ def dump(self, file=None):
+ # import ipdb; ipdb.set_trace()
+ if file is None:
+ return self.pretty_text
+ else:
+ with open(file, "w") as f:
+ f.write(self.pretty_text)
+
+ def merge_from_dict(self, options):
+ """Merge list into cfg_dict
+
+ Merge the dict parsed by MultipleKVAction into this cfg.
+
+ Examples:
+ >>> options = {'model.backbone.depth': 50,
+ ... 'model.backbone.with_cp':True}
+ >>> cfg = Config(dict(model=dict(backbone=dict(type='ResNet'))))
+ >>> cfg.merge_from_dict(options)
+ >>> cfg_dict = super(Config, self).__getattribute__('_cfg_dict')
+ >>> assert cfg_dict == dict(
+ ... model=dict(backbone=dict(depth=50, with_cp=True)))
+
+ Args:
+ options (dict): dict of configs to merge from.
+ """
+ option_cfg_dict = {}
+ for full_key, v in options.items():
+ d = option_cfg_dict
+ key_list = full_key.split(".")
+ for subkey in key_list[:-1]:
+ d.setdefault(subkey, ConfigDict())
+ d = d[subkey]
+ subkey = key_list[-1]
+ d[subkey] = v
+
+ cfg_dict = super(SLConfig, self).__getattribute__("_cfg_dict")
+ super(SLConfig, self).__setattr__(
+ "_cfg_dict", SLConfig._merge_a_into_b(option_cfg_dict, cfg_dict)
+ )
+
+ # for multiprocess
+ def __setstate__(self, state):
+ self.__init__(state)
+
+ def copy(self):
+ return SLConfig(self._cfg_dict.copy())
+
+ def deepcopy(self):
+ return SLConfig(self._cfg_dict.deepcopy())
+
+
+class DictAction(Action):
+ """
+ argparse action to split an argument into KEY=VALUE form
+ on the first = and append to a dictionary. List options should
+ be passed as comma separated values, i.e KEY=V1,V2,V3
+ """
+
+ @staticmethod
+ def _parse_int_float_bool(val):
+ try:
+ return int(val)
+ except ValueError:
+ pass
+ try:
+ return float(val)
+ except ValueError:
+ pass
+ if val.lower() in ["true", "false"]:
+ return True if val.lower() == "true" else False
+ if val.lower() in ["none", "null"]:
+ return None
+ return val
+
+ def __call__(self, parser, namespace, values, option_string=None):
+ options = {}
+ for kv in values:
+ key, val = kv.split("=", maxsplit=1)
+ val = [self._parse_int_float_bool(v) for v in val.split(",")]
+ if len(val) == 1:
+ val = val[0]
+ options[key] = val
+ setattr(namespace, self.dest, options)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slio.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slio.py
new file mode 100644
index 0000000000000000000000000000000000000000..72c1f0f7b82cdc931d381feef64fe15815ba657e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/slio.py
@@ -0,0 +1,177 @@
+# ==========================================================
+# Modified from mmcv
+# ==========================================================
+
+import json
+import pickle
+from abc import ABCMeta, abstractmethod
+from pathlib import Path
+
+import yaml
+
+try:
+ from yaml import CLoader as Loader, CDumper as Dumper
+except ImportError:
+ from yaml import Loader, Dumper
+
+
+# ===========================
+# Rigister handler
+# ===========================
+
+
+class BaseFileHandler(metaclass=ABCMeta):
+ @abstractmethod
+ def load_from_fileobj(self, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ pass
+
+ @abstractmethod
+ def dump_to_str(self, obj, **kwargs):
+ pass
+
+ def load_from_path(self, filepath, mode="r", **kwargs):
+ with open(filepath, mode) as f:
+ return self.load_from_fileobj(f, **kwargs)
+
+ def dump_to_path(self, obj, filepath, mode="w", **kwargs):
+ with open(filepath, mode) as f:
+ self.dump_to_fileobj(obj, f, **kwargs)
+
+
+class JsonHandler(BaseFileHandler):
+ def load_from_fileobj(self, file):
+ return json.load(file)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ json.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ return json.dumps(obj, **kwargs)
+
+
+class PickleHandler(BaseFileHandler):
+ def load_from_fileobj(self, file, **kwargs):
+ return pickle.load(file, **kwargs)
+
+ def load_from_path(self, filepath, **kwargs):
+ return super(PickleHandler, self).load_from_path(filepath, mode="rb", **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault("protocol", 2)
+ return pickle.dumps(obj, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault("protocol", 2)
+ pickle.dump(obj, file, **kwargs)
+
+ def dump_to_path(self, obj, filepath, **kwargs):
+ super(PickleHandler, self).dump_to_path(obj, filepath, mode="wb", **kwargs)
+
+
+class YamlHandler(BaseFileHandler):
+ def load_from_fileobj(self, file, **kwargs):
+ kwargs.setdefault("Loader", Loader)
+ return yaml.load(file, **kwargs)
+
+ def dump_to_fileobj(self, obj, file, **kwargs):
+ kwargs.setdefault("Dumper", Dumper)
+ yaml.dump(obj, file, **kwargs)
+
+ def dump_to_str(self, obj, **kwargs):
+ kwargs.setdefault("Dumper", Dumper)
+ return yaml.dump(obj, **kwargs)
+
+
+file_handlers = {
+ "json": JsonHandler(),
+ "yaml": YamlHandler(),
+ "yml": YamlHandler(),
+ "pickle": PickleHandler(),
+ "pkl": PickleHandler(),
+}
+
+# ===========================
+# load and dump
+# ===========================
+
+
+def is_str(x):
+ """Whether the input is an string instance.
+
+ Note: This method is deprecated since python 2 is no longer supported.
+ """
+ return isinstance(x, str)
+
+
+def slload(file, file_format=None, **kwargs):
+ """Load data from json/yaml/pickle files.
+
+ This method provides a unified api for loading data from serialized files.
+
+ Args:
+ file (str or :obj:`Path` or file-like object): Filename or a file-like
+ object.
+ file_format (str, optional): If not specified, the file format will be
+ inferred from the file extension, otherwise use the specified one.
+ Currently supported formats include "json", "yaml/yml" and
+ "pickle/pkl".
+
+ Returns:
+ The content from the file.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None and is_str(file):
+ file_format = file.split(".")[-1]
+ if file_format not in file_handlers:
+ raise TypeError(f"Unsupported format: {file_format}")
+
+ handler = file_handlers[file_format]
+ if is_str(file):
+ obj = handler.load_from_path(file, **kwargs)
+ elif hasattr(file, "read"):
+ obj = handler.load_from_fileobj(file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filepath str or a file-object')
+ return obj
+
+
+def sldump(obj, file=None, file_format=None, **kwargs):
+ """Dump data to json/yaml/pickle strings or files.
+
+ This method provides a unified api for dumping data as strings or to files,
+ and also supports custom arguments for each file format.
+
+ Args:
+ obj (any): The python object to be dumped.
+ file (str or :obj:`Path` or file-like object, optional): If not
+ specified, then the object is dump to a str, otherwise to a file
+ specified by the filename or file-like object.
+ file_format (str, optional): Same as :func:`load`.
+
+ Returns:
+ bool: True for success, False otherwise.
+ """
+ if isinstance(file, Path):
+ file = str(file)
+ if file_format is None:
+ if is_str(file):
+ file_format = file.split(".")[-1]
+ elif file is None:
+ raise ValueError("file_format must be specified since file is None")
+ if file_format not in file_handlers:
+ raise TypeError(f"Unsupported format: {file_format}")
+
+ handler = file_handlers[file_format]
+ if file is None:
+ return handler.dump_to_str(obj, **kwargs)
+ elif is_str(file):
+ handler.dump_to_path(obj, file, **kwargs)
+ elif hasattr(file, "write"):
+ handler.dump_to_fileobj(obj, file, **kwargs)
+ else:
+ raise TypeError('"file" must be a filename str or a file-object')
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/time_counter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/time_counter.py
new file mode 100644
index 0000000000000000000000000000000000000000..0aedb2e4d61bfbe7571dca9d50053f0fedaa1359
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/time_counter.py
@@ -0,0 +1,62 @@
+import json
+import time
+
+
+class TimeCounter:
+ def __init__(self) -> None:
+ pass
+
+ def clear(self):
+ self.timedict = {}
+ self.basetime = time.perf_counter()
+
+ def timeit(self, name):
+ nowtime = time.perf_counter() - self.basetime
+ self.timedict[name] = nowtime
+ self.basetime = time.perf_counter()
+
+
+class TimeHolder:
+ def __init__(self) -> None:
+ self.timedict = {}
+
+ def update(self, _timedict: dict):
+ for k, v in _timedict.items():
+ if k not in self.timedict:
+ self.timedict[k] = AverageMeter(name=k, val_only=True)
+ self.timedict[k].update(val=v)
+
+ def final_res(self):
+ return {k: v.avg for k, v in self.timedict.items()}
+
+ def __str__(self):
+ return json.dumps(self.final_res(), indent=2)
+
+
+class AverageMeter(object):
+ """Computes and stores the average and current value"""
+
+ def __init__(self, name, fmt=":f", val_only=False):
+ self.name = name
+ self.fmt = fmt
+ self.val_only = val_only
+ self.reset()
+
+ def reset(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+
+ def update(self, val, n=1):
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
+
+ def __str__(self):
+ if self.val_only:
+ fmtstr = "{name} {val" + self.fmt + "}"
+ else:
+ fmtstr = "{name} {val" + self.fmt + "} ({avg" + self.fmt + "})"
+ return fmtstr.format(**self.__dict__)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9f0318e306fa04bff0ada70486b41aaa69b07c8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/utils.py
@@ -0,0 +1,608 @@
+import argparse
+import json
+import warnings
+from collections import OrderedDict
+from copy import deepcopy
+from typing import Any, Dict, List
+
+import numpy as np
+import torch
+from transformers import AutoTokenizer
+
+from groundingdino.util.slconfig import SLConfig
+
+
+def slprint(x, name="x"):
+ if isinstance(x, (torch.Tensor, np.ndarray)):
+ print(f"{name}.shape:", x.shape)
+ elif isinstance(x, (tuple, list)):
+ print("type x:", type(x))
+ for i in range(min(10, len(x))):
+ slprint(x[i], f"{name}[{i}]")
+ elif isinstance(x, dict):
+ for k, v in x.items():
+ slprint(v, f"{name}[{k}]")
+ else:
+ print(f"{name}.type:", type(x))
+
+
+def clean_state_dict(state_dict):
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k[:7] == "module.":
+ k = k[7:] # remove `module.`
+ new_state_dict[k] = v
+ return new_state_dict
+
+
+def renorm(
+ img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
+) -> torch.FloatTensor:
+ # img: tensor(3,H,W) or tensor(B,3,H,W)
+ # return: same as img
+ assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim()
+ if img.dim() == 3:
+ assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (
+ img.size(0),
+ str(img.size()),
+ )
+ img_perm = img.permute(1, 2, 0)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(2, 0, 1)
+ else: # img.dim() == 4
+ assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (
+ img.size(1),
+ str(img.size()),
+ )
+ img_perm = img.permute(0, 2, 3, 1)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(0, 3, 1, 2)
+
+
+class CocoClassMapper:
+ def __init__(self) -> None:
+ self.category_map_str = {
+ "1": 1,
+ "2": 2,
+ "3": 3,
+ "4": 4,
+ "5": 5,
+ "6": 6,
+ "7": 7,
+ "8": 8,
+ "9": 9,
+ "10": 10,
+ "11": 11,
+ "13": 12,
+ "14": 13,
+ "15": 14,
+ "16": 15,
+ "17": 16,
+ "18": 17,
+ "19": 18,
+ "20": 19,
+ "21": 20,
+ "22": 21,
+ "23": 22,
+ "24": 23,
+ "25": 24,
+ "27": 25,
+ "28": 26,
+ "31": 27,
+ "32": 28,
+ "33": 29,
+ "34": 30,
+ "35": 31,
+ "36": 32,
+ "37": 33,
+ "38": 34,
+ "39": 35,
+ "40": 36,
+ "41": 37,
+ "42": 38,
+ "43": 39,
+ "44": 40,
+ "46": 41,
+ "47": 42,
+ "48": 43,
+ "49": 44,
+ "50": 45,
+ "51": 46,
+ "52": 47,
+ "53": 48,
+ "54": 49,
+ "55": 50,
+ "56": 51,
+ "57": 52,
+ "58": 53,
+ "59": 54,
+ "60": 55,
+ "61": 56,
+ "62": 57,
+ "63": 58,
+ "64": 59,
+ "65": 60,
+ "67": 61,
+ "70": 62,
+ "72": 63,
+ "73": 64,
+ "74": 65,
+ "75": 66,
+ "76": 67,
+ "77": 68,
+ "78": 69,
+ "79": 70,
+ "80": 71,
+ "81": 72,
+ "82": 73,
+ "84": 74,
+ "85": 75,
+ "86": 76,
+ "87": 77,
+ "88": 78,
+ "89": 79,
+ "90": 80,
+ }
+ self.origin2compact_mapper = {int(k): v - 1 for k, v in self.category_map_str.items()}
+ self.compact2origin_mapper = {int(v - 1): int(k) for k, v in self.category_map_str.items()}
+
+ def origin2compact(self, idx):
+ return self.origin2compact_mapper[int(idx)]
+
+ def compact2origin(self, idx):
+ return self.compact2origin_mapper[int(idx)]
+
+
+def to_device(item, device):
+ if isinstance(item, torch.Tensor):
+ return item.to(device)
+ elif isinstance(item, list):
+ return [to_device(i, device) for i in item]
+ elif isinstance(item, dict):
+ return {k: to_device(v, device) for k, v in item.items()}
+ else:
+ raise NotImplementedError(
+ "Call Shilong if you use other containers! type: {}".format(type(item))
+ )
+
+
+#
+def get_gaussian_mean(x, axis, other_axis, softmax=True):
+ """
+
+ Args:
+ x (float): Input images(BxCxHxW)
+ axis (int): The index for weighted mean
+ other_axis (int): The other index
+
+ Returns: weighted index for axis, BxC
+
+ """
+ mat2line = torch.sum(x, axis=other_axis)
+ # mat2line = mat2line / mat2line.mean() * 10
+ if softmax:
+ u = torch.softmax(mat2line, axis=2)
+ else:
+ u = mat2line / (mat2line.sum(2, keepdim=True) + 1e-6)
+ size = x.shape[axis]
+ ind = torch.linspace(0, 1, size).to(x.device)
+ batch = x.shape[0]
+ channel = x.shape[1]
+ index = ind.repeat([batch, channel, 1])
+ mean_position = torch.sum(index * u, dim=2)
+ return mean_position
+
+
+def get_expected_points_from_map(hm, softmax=True):
+ """get_gaussian_map_from_points
+ B,C,H,W -> B,N,2 float(0, 1) float(0, 1)
+ softargmax function
+
+ Args:
+ hm (float): Input images(BxCxHxW)
+
+ Returns:
+ weighted index for axis, BxCx2. float between 0 and 1.
+
+ """
+ # hm = 10*hm
+ B, C, H, W = hm.shape
+ y_mean = get_gaussian_mean(hm, 2, 3, softmax=softmax) # B,C
+ x_mean = get_gaussian_mean(hm, 3, 2, softmax=softmax) # B,C
+ # return torch.cat((x_mean.unsqueeze(-1), y_mean.unsqueeze(-1)), 2)
+ return torch.stack([x_mean, y_mean], dim=2)
+
+
+# Positional encoding (section 5.1)
+# borrow from nerf
+class Embedder:
+ def __init__(self, **kwargs):
+ self.kwargs = kwargs
+ self.create_embedding_fn()
+
+ def create_embedding_fn(self):
+ embed_fns = []
+ d = self.kwargs["input_dims"]
+ out_dim = 0
+ if self.kwargs["include_input"]:
+ embed_fns.append(lambda x: x)
+ out_dim += d
+
+ max_freq = self.kwargs["max_freq_log2"]
+ N_freqs = self.kwargs["num_freqs"]
+
+ if self.kwargs["log_sampling"]:
+ freq_bands = 2.0 ** torch.linspace(0.0, max_freq, steps=N_freqs)
+ else:
+ freq_bands = torch.linspace(2.0**0.0, 2.0**max_freq, steps=N_freqs)
+
+ for freq in freq_bands:
+ for p_fn in self.kwargs["periodic_fns"]:
+ embed_fns.append(lambda x, p_fn=p_fn, freq=freq: p_fn(x * freq))
+ out_dim += d
+
+ self.embed_fns = embed_fns
+ self.out_dim = out_dim
+
+ def embed(self, inputs):
+ return torch.cat([fn(inputs) for fn in self.embed_fns], -1)
+
+
+def get_embedder(multires, i=0):
+ import torch.nn as nn
+
+ if i == -1:
+ return nn.Identity(), 3
+
+ embed_kwargs = {
+ "include_input": True,
+ "input_dims": 3,
+ "max_freq_log2": multires - 1,
+ "num_freqs": multires,
+ "log_sampling": True,
+ "periodic_fns": [torch.sin, torch.cos],
+ }
+
+ embedder_obj = Embedder(**embed_kwargs)
+ embed = lambda x, eo=embedder_obj: eo.embed(x)
+ return embed, embedder_obj.out_dim
+
+
+class APOPMeter:
+ def __init__(self) -> None:
+ self.tp = 0
+ self.fp = 0
+ self.tn = 0
+ self.fn = 0
+
+ def update(self, pred, gt):
+ """
+ Input:
+ pred, gt: Tensor()
+ """
+ assert pred.shape == gt.shape
+ self.tp += torch.logical_and(pred == 1, gt == 1).sum().item()
+ self.fp += torch.logical_and(pred == 1, gt == 0).sum().item()
+ self.tn += torch.logical_and(pred == 0, gt == 0).sum().item()
+ self.tn += torch.logical_and(pred == 1, gt == 0).sum().item()
+
+ def update_cm(self, tp, fp, tn, fn):
+ self.tp += tp
+ self.fp += fp
+ self.tn += tn
+ self.tn += fn
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+def get_raw_dict(args):
+ """
+ return the dicf contained in args.
+
+ e.g:
+ >>> with open(path, 'w') as f:
+ json.dump(get_raw_dict(args), f, indent=2)
+ """
+ if isinstance(args, argparse.Namespace):
+ return vars(args)
+ elif isinstance(args, dict):
+ return args
+ elif isinstance(args, SLConfig):
+ return args._cfg_dict
+ else:
+ raise NotImplementedError("Unknown type {}".format(type(args)))
+
+
+def stat_tensors(tensor):
+ assert tensor.dim() == 1
+ tensor_sm = tensor.softmax(0)
+ entropy = (tensor_sm * torch.log(tensor_sm + 1e-9)).sum()
+
+ return {
+ "max": tensor.max(),
+ "min": tensor.min(),
+ "mean": tensor.mean(),
+ "var": tensor.var(),
+ "std": tensor.var() ** 0.5,
+ "entropy": entropy,
+ }
+
+
+class NiceRepr:
+ """Inherit from this class and define ``__nice__`` to "nicely" print your
+ objects.
+
+ Defines ``__str__`` and ``__repr__`` in terms of ``__nice__`` function
+ Classes that inherit from :class:`NiceRepr` should redefine ``__nice__``.
+ If the inheriting class has a ``__len__``, method then the default
+ ``__nice__`` method will return its length.
+
+ Example:
+ >>> class Foo(NiceRepr):
+ ... def __nice__(self):
+ ... return 'info'
+ >>> foo = Foo()
+ >>> assert str(foo) == ''
+ >>> assert repr(foo).startswith('>> class Bar(NiceRepr):
+ ... pass
+ >>> bar = Bar()
+ >>> import pytest
+ >>> with pytest.warns(None) as record:
+ >>> assert 'object at' in str(bar)
+ >>> assert 'object at' in repr(bar)
+
+ Example:
+ >>> class Baz(NiceRepr):
+ ... def __len__(self):
+ ... return 5
+ >>> baz = Baz()
+ >>> assert str(baz) == ''
+ """
+
+ def __nice__(self):
+ """str: a "nice" summary string describing this module"""
+ if hasattr(self, "__len__"):
+ # It is a common pattern for objects to use __len__ in __nice__
+ # As a convenience we define a default __nice__ for these objects
+ return str(len(self))
+ else:
+ # In all other cases force the subclass to overload __nice__
+ raise NotImplementedError(f"Define the __nice__ method for {self.__class__!r}")
+
+ def __repr__(self):
+ """str: the string of the module"""
+ try:
+ nice = self.__nice__()
+ classname = self.__class__.__name__
+ return f"<{classname}({nice}) at {hex(id(self))}>"
+ except NotImplementedError as ex:
+ warnings.warn(str(ex), category=RuntimeWarning)
+ return object.__repr__(self)
+
+ def __str__(self):
+ """str: the string of the module"""
+ try:
+ classname = self.__class__.__name__
+ nice = self.__nice__()
+ return f"<{classname}({nice})>"
+ except NotImplementedError as ex:
+ warnings.warn(str(ex), category=RuntimeWarning)
+ return object.__repr__(self)
+
+
+def ensure_rng(rng=None):
+ """Coerces input into a random number generator.
+
+ If the input is None, then a global random state is returned.
+
+ If the input is a numeric value, then that is used as a seed to construct a
+ random state. Otherwise the input is returned as-is.
+
+ Adapted from [1]_.
+
+ Args:
+ rng (int | numpy.random.RandomState | None):
+ if None, then defaults to the global rng. Otherwise this can be an
+ integer or a RandomState class
+ Returns:
+ (numpy.random.RandomState) : rng -
+ a numpy random number generator
+
+ References:
+ .. [1] https://gitlab.kitware.com/computer-vision/kwarray/blob/master/kwarray/util_random.py#L270 # noqa: E501
+ """
+
+ if rng is None:
+ rng = np.random.mtrand._rand
+ elif isinstance(rng, int):
+ rng = np.random.RandomState(rng)
+ else:
+ rng = rng
+ return rng
+
+
+def random_boxes(num=1, scale=1, rng=None):
+ """Simple version of ``kwimage.Boxes.random``
+
+ Returns:
+ Tensor: shape (n, 4) in x1, y1, x2, y2 format.
+
+ References:
+ https://gitlab.kitware.com/computer-vision/kwimage/blob/master/kwimage/structs/boxes.py#L1390
+
+ Example:
+ >>> num = 3
+ >>> scale = 512
+ >>> rng = 0
+ >>> boxes = random_boxes(num, scale, rng)
+ >>> print(boxes)
+ tensor([[280.9925, 278.9802, 308.6148, 366.1769],
+ [216.9113, 330.6978, 224.0446, 456.5878],
+ [405.3632, 196.3221, 493.3953, 270.7942]])
+ """
+ rng = ensure_rng(rng)
+
+ tlbr = rng.rand(num, 4).astype(np.float32)
+
+ tl_x = np.minimum(tlbr[:, 0], tlbr[:, 2])
+ tl_y = np.minimum(tlbr[:, 1], tlbr[:, 3])
+ br_x = np.maximum(tlbr[:, 0], tlbr[:, 2])
+ br_y = np.maximum(tlbr[:, 1], tlbr[:, 3])
+
+ tlbr[:, 0] = tl_x * scale
+ tlbr[:, 1] = tl_y * scale
+ tlbr[:, 2] = br_x * scale
+ tlbr[:, 3] = br_y * scale
+
+ boxes = torch.from_numpy(tlbr)
+ return boxes
+
+
+class ModelEma(torch.nn.Module):
+ def __init__(self, model, decay=0.9997, device=None):
+ super(ModelEma, self).__init__()
+ # make a copy of the model for accumulating moving average of weights
+ self.module = deepcopy(model)
+ self.module.eval()
+
+ # import ipdb; ipdb.set_trace()
+
+ self.decay = decay
+ self.device = device # perform ema on different device from model if set
+ if self.device is not None:
+ self.module.to(device=device)
+
+ def _update(self, model, update_fn):
+ with torch.no_grad():
+ for ema_v, model_v in zip(
+ self.module.state_dict().values(), model.state_dict().values()
+ ):
+ if self.device is not None:
+ model_v = model_v.to(device=self.device)
+ ema_v.copy_(update_fn(ema_v, model_v))
+
+ def update(self, model):
+ self._update(model, update_fn=lambda e, m: self.decay * e + (1.0 - self.decay) * m)
+
+ def set(self, model):
+ self._update(model, update_fn=lambda e, m: m)
+
+
+class BestMetricSingle:
+ def __init__(self, init_res=0.0, better="large") -> None:
+ self.init_res = init_res
+ self.best_res = init_res
+ self.best_ep = -1
+
+ self.better = better
+ assert better in ["large", "small"]
+
+ def isbetter(self, new_res, old_res):
+ if self.better == "large":
+ return new_res > old_res
+ if self.better == "small":
+ return new_res < old_res
+
+ def update(self, new_res, ep):
+ if self.isbetter(new_res, self.best_res):
+ self.best_res = new_res
+ self.best_ep = ep
+ return True
+ return False
+
+ def __str__(self) -> str:
+ return "best_res: {}\t best_ep: {}".format(self.best_res, self.best_ep)
+
+ def __repr__(self) -> str:
+ return self.__str__()
+
+ def summary(self) -> dict:
+ return {
+ "best_res": self.best_res,
+ "best_ep": self.best_ep,
+ }
+
+
+class BestMetricHolder:
+ def __init__(self, init_res=0.0, better="large", use_ema=False) -> None:
+ self.best_all = BestMetricSingle(init_res, better)
+ self.use_ema = use_ema
+ if use_ema:
+ self.best_ema = BestMetricSingle(init_res, better)
+ self.best_regular = BestMetricSingle(init_res, better)
+
+ def update(self, new_res, epoch, is_ema=False):
+ """
+ return if the results is the best.
+ """
+ if not self.use_ema:
+ return self.best_all.update(new_res, epoch)
+ else:
+ if is_ema:
+ self.best_ema.update(new_res, epoch)
+ return self.best_all.update(new_res, epoch)
+ else:
+ self.best_regular.update(new_res, epoch)
+ return self.best_all.update(new_res, epoch)
+
+ def summary(self):
+ if not self.use_ema:
+ return self.best_all.summary()
+
+ res = {}
+ res.update({f"all_{k}": v for k, v in self.best_all.summary().items()})
+ res.update({f"regular_{k}": v for k, v in self.best_regular.summary().items()})
+ res.update({f"ema_{k}": v for k, v in self.best_ema.summary().items()})
+ return res
+
+ def __repr__(self) -> str:
+ return json.dumps(self.summary(), indent=2)
+
+ def __str__(self) -> str:
+ return self.__repr__()
+
+
+def targets_to(targets: List[Dict[str, Any]], device):
+ """Moves the target dicts to the given device."""
+ excluded_keys = [
+ "questionId",
+ "tokens_positive",
+ "strings_positive",
+ "tokens",
+ "dataset_name",
+ "sentence_id",
+ "original_img_id",
+ "nb_eval",
+ "task_id",
+ "original_id",
+ "token_span",
+ "caption",
+ "dataset_type",
+ ]
+ return [
+ {k: v.to(device) if k not in excluded_keys else v for k, v in t.items()} for t in targets
+ ]
+
+
+def get_phrases_from_posmap(
+ posmap: torch.BoolTensor, tokenized: Dict, tokenizer: AutoTokenizer
+):
+ assert isinstance(posmap, torch.Tensor), "posmap must be torch.Tensor"
+ if posmap.dim() == 1:
+ non_zero_idx = posmap.nonzero(as_tuple=True)[0].tolist()
+ token_ids = [tokenized["input_ids"][i] for i in non_zero_idx]
+ return tokenizer.decode(token_ids)
+ else:
+ raise NotImplementedError("posmap must be 1-dim")
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/visualizer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/visualizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a1b7b101e9b73f75f9136bc67f2063c7c1cf1c1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/visualizer.py
@@ -0,0 +1,318 @@
+# -*- coding: utf-8 -*-
+"""
+@File : visualizer.py
+@Time : 2022/04/05 11:39:33
+@Author : Shilong Liu
+@Contact : slongliu86@gmail.com
+"""
+
+import datetime
+import os
+
+import cv2
+import matplotlib.pyplot as plt
+import numpy as np
+import torch
+from matplotlib import transforms
+from matplotlib.collections import PatchCollection
+from matplotlib.patches import Polygon
+from pycocotools import mask as maskUtils
+
+
+def renorm(
+ img: torch.FloatTensor, mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]
+) -> torch.FloatTensor:
+ # img: tensor(3,H,W) or tensor(B,3,H,W)
+ # return: same as img
+ assert img.dim() == 3 or img.dim() == 4, "img.dim() should be 3 or 4 but %d" % img.dim()
+ if img.dim() == 3:
+ assert img.size(0) == 3, 'img.size(0) shoule be 3 but "%d". (%s)' % (
+ img.size(0),
+ str(img.size()),
+ )
+ img_perm = img.permute(1, 2, 0)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(2, 0, 1)
+ else: # img.dim() == 4
+ assert img.size(1) == 3, 'img.size(1) shoule be 3 but "%d". (%s)' % (
+ img.size(1),
+ str(img.size()),
+ )
+ img_perm = img.permute(0, 2, 3, 1)
+ mean = torch.Tensor(mean)
+ std = torch.Tensor(std)
+ img_res = img_perm * std + mean
+ return img_res.permute(0, 3, 1, 2)
+
+
+class ColorMap:
+ def __init__(self, basergb=[255, 255, 0]):
+ self.basergb = np.array(basergb)
+
+ def __call__(self, attnmap):
+ # attnmap: h, w. np.uint8.
+ # return: h, w, 4. np.uint8.
+ assert attnmap.dtype == np.uint8
+ h, w = attnmap.shape
+ res = self.basergb.copy()
+ res = res[None][None].repeat(h, 0).repeat(w, 1) # h, w, 3
+ attn1 = attnmap.copy()[..., None] # h, w, 1
+ res = np.concatenate((res, attn1), axis=-1).astype(np.uint8)
+ return res
+
+
+def rainbow_text(x, y, ls, lc, **kw):
+ """
+ Take a list of strings ``ls`` and colors ``lc`` and place them next to each
+ other, with text ls[i] being shown in color lc[i].
+
+ This example shows how to do both vertical and horizontal text, and will
+ pass all keyword arguments to plt.text, so you can set the font size,
+ family, etc.
+ """
+ t = plt.gca().transData
+ fig = plt.gcf()
+ plt.show()
+
+ # horizontal version
+ for s, c in zip(ls, lc):
+ text = plt.text(x, y, " " + s + " ", color=c, transform=t, **kw)
+ text.draw(fig.canvas.get_renderer())
+ ex = text.get_window_extent()
+ t = transforms.offset_copy(text._transform, x=ex.width, units="dots")
+
+ # #vertical version
+ # for s,c in zip(ls,lc):
+ # text = plt.text(x,y," "+s+" ",color=c, transform=t,
+ # rotation=90,va='bottom',ha='center',**kw)
+ # text.draw(fig.canvas.get_renderer())
+ # ex = text.get_window_extent()
+ # t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
+
+
+class COCOVisualizer:
+ def __init__(self, coco=None, tokenlizer=None) -> None:
+ self.coco = coco
+
+ def visualize(self, img, tgt, caption=None, dpi=180, savedir="vis"):
+ """
+ img: tensor(3, H, W)
+ tgt: make sure they are all on cpu.
+ must have items: 'image_id', 'boxes', 'size'
+ """
+ plt.figure(dpi=dpi)
+ plt.rcParams["font.size"] = "5"
+ ax = plt.gca()
+ img = renorm(img).permute(1, 2, 0)
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ ax.imshow(img)
+
+ self.addtgt(tgt)
+
+ if tgt is None:
+ image_id = 0
+ elif "image_id" not in tgt:
+ image_id = 0
+ else:
+ image_id = tgt["image_id"]
+
+ if caption is None:
+ savename = "{}/{}-{}.png".format(
+ savedir, int(image_id), str(datetime.datetime.now()).replace(" ", "-")
+ )
+ else:
+ savename = "{}/{}-{}-{}.png".format(
+ savedir, caption, int(image_id), str(datetime.datetime.now()).replace(" ", "-")
+ )
+ print("savename: {}".format(savename))
+ os.makedirs(os.path.dirname(savename), exist_ok=True)
+ plt.savefig(savename)
+ plt.close()
+
+ def addtgt(self, tgt):
+ """ """
+ if tgt is None or not "boxes" in tgt:
+ ax = plt.gca()
+
+ if "caption" in tgt:
+ ax.set_title(tgt["caption"], wrap=True)
+
+ ax.set_axis_off()
+ return
+
+ ax = plt.gca()
+ H, W = tgt["size"]
+ numbox = tgt["boxes"].shape[0]
+
+ color = []
+ polygons = []
+ boxes = []
+ for box in tgt["boxes"].cpu():
+ unnormbbox = box * torch.Tensor([W, H, W, H])
+ unnormbbox[:2] -= unnormbbox[2:] / 2
+ [bbox_x, bbox_y, bbox_w, bbox_h] = unnormbbox.tolist()
+ boxes.append([bbox_x, bbox_y, bbox_w, bbox_h])
+ poly = [
+ [bbox_x, bbox_y],
+ [bbox_x, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y],
+ ]
+ np_poly = np.array(poly).reshape((4, 2))
+ polygons.append(Polygon(np_poly))
+ c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]
+ color.append(c)
+
+ p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.1)
+ ax.add_collection(p)
+ p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
+ ax.add_collection(p)
+
+ if "strings_positive" in tgt and len(tgt["strings_positive"]) > 0:
+ assert (
+ len(tgt["strings_positive"]) == numbox
+ ), f"{len(tgt['strings_positive'])} = {numbox}, "
+ for idx, strlist in enumerate(tgt["strings_positive"]):
+ cate_id = int(tgt["labels"][idx])
+ _string = str(cate_id) + ":" + " ".join(strlist)
+ bbox_x, bbox_y, bbox_w, bbox_h = boxes[idx]
+ # ax.text(bbox_x, bbox_y, _string, color='black', bbox={'facecolor': 'yellow', 'alpha': 1.0, 'pad': 1})
+ ax.text(
+ bbox_x,
+ bbox_y,
+ _string,
+ color="black",
+ bbox={"facecolor": color[idx], "alpha": 0.6, "pad": 1},
+ )
+
+ if "box_label" in tgt:
+ assert len(tgt["box_label"]) == numbox, f"{len(tgt['box_label'])} = {numbox}, "
+ for idx, bl in enumerate(tgt["box_label"]):
+ _string = str(bl)
+ bbox_x, bbox_y, bbox_w, bbox_h = boxes[idx]
+ # ax.text(bbox_x, bbox_y, _string, color='black', bbox={'facecolor': 'yellow', 'alpha': 1.0, 'pad': 1})
+ ax.text(
+ bbox_x,
+ bbox_y,
+ _string,
+ color="black",
+ bbox={"facecolor": color[idx], "alpha": 0.6, "pad": 1},
+ )
+
+ if "caption" in tgt:
+ ax.set_title(tgt["caption"], wrap=True)
+ # plt.figure()
+ # rainbow_text(0.0,0.0,"all unicorns poop rainbows ! ! !".split(),
+ # ['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'])
+
+ if "attn" in tgt:
+ # if os.environ.get('IPDB_SHILONG_DEBUG', None) == 'INFO':
+ # import ipdb; ipdb.set_trace()
+ if isinstance(tgt["attn"], tuple):
+ tgt["attn"] = [tgt["attn"]]
+ for item in tgt["attn"]:
+ attn_map, basergb = item
+ attn_map = (attn_map - attn_map.min()) / (attn_map.max() - attn_map.min() + 1e-3)
+ attn_map = (attn_map * 255).astype(np.uint8)
+ cm = ColorMap(basergb)
+ heatmap = cm(attn_map)
+ ax.imshow(heatmap)
+ ax.set_axis_off()
+
+ def showAnns(self, anns, draw_bbox=False):
+ """
+ Display the specified annotations.
+ :param anns (array of object): annotations to display
+ :return: None
+ """
+ if len(anns) == 0:
+ return 0
+ if "segmentation" in anns[0] or "keypoints" in anns[0]:
+ datasetType = "instances"
+ elif "caption" in anns[0]:
+ datasetType = "captions"
+ else:
+ raise Exception("datasetType not supported")
+ if datasetType == "instances":
+ ax = plt.gca()
+ ax.set_autoscale_on(False)
+ polygons = []
+ color = []
+ for ann in anns:
+ c = (np.random.random((1, 3)) * 0.6 + 0.4).tolist()[0]
+ if "segmentation" in ann:
+ if type(ann["segmentation"]) == list:
+ # polygon
+ for seg in ann["segmentation"]:
+ poly = np.array(seg).reshape((int(len(seg) / 2), 2))
+ polygons.append(Polygon(poly))
+ color.append(c)
+ else:
+ # mask
+ t = self.imgs[ann["image_id"]]
+ if type(ann["segmentation"]["counts"]) == list:
+ rle = maskUtils.frPyObjects(
+ [ann["segmentation"]], t["height"], t["width"]
+ )
+ else:
+ rle = [ann["segmentation"]]
+ m = maskUtils.decode(rle)
+ img = np.ones((m.shape[0], m.shape[1], 3))
+ if ann["iscrowd"] == 1:
+ color_mask = np.array([2.0, 166.0, 101.0]) / 255
+ if ann["iscrowd"] == 0:
+ color_mask = np.random.random((1, 3)).tolist()[0]
+ for i in range(3):
+ img[:, :, i] = color_mask[i]
+ ax.imshow(np.dstack((img, m * 0.5)))
+ if "keypoints" in ann and type(ann["keypoints"]) == list:
+ # turn skeleton into zero-based index
+ sks = np.array(self.loadCats(ann["category_id"])[0]["skeleton"]) - 1
+ kp = np.array(ann["keypoints"])
+ x = kp[0::3]
+ y = kp[1::3]
+ v = kp[2::3]
+ for sk in sks:
+ if np.all(v[sk] > 0):
+ plt.plot(x[sk], y[sk], linewidth=3, color=c)
+ plt.plot(
+ x[v > 0],
+ y[v > 0],
+ "o",
+ markersize=8,
+ markerfacecolor=c,
+ markeredgecolor="k",
+ markeredgewidth=2,
+ )
+ plt.plot(
+ x[v > 1],
+ y[v > 1],
+ "o",
+ markersize=8,
+ markerfacecolor=c,
+ markeredgecolor=c,
+ markeredgewidth=2,
+ )
+
+ if draw_bbox:
+ [bbox_x, bbox_y, bbox_w, bbox_h] = ann["bbox"]
+ poly = [
+ [bbox_x, bbox_y],
+ [bbox_x, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y + bbox_h],
+ [bbox_x + bbox_w, bbox_y],
+ ]
+ np_poly = np.array(poly).reshape((4, 2))
+ polygons.append(Polygon(np_poly))
+ color.append(c)
+
+ # p = PatchCollection(polygons, facecolor=color, linewidths=0, alpha=0.4)
+ # ax.add_collection(p)
+ p = PatchCollection(polygons, facecolor="none", edgecolors=color, linewidths=2)
+ ax.add_collection(p)
+ elif datasetType == "captions":
+ for ann in anns:
+ print(ann["caption"])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/vl_utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/vl_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c91bb02f584398f08a28e6b7719e2b99f6e28616
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/util/vl_utils.py
@@ -0,0 +1,100 @@
+import os
+import random
+from typing import List
+
+import torch
+
+
+def create_positive_map_from_span(tokenized, token_span, max_text_len=256):
+ """construct a map such that positive_map[i,j] = True iff box i is associated to token j
+ Input:
+ - tokenized:
+ - input_ids: Tensor[1, ntokens]
+ - attention_mask: Tensor[1, ntokens]
+ - token_span: list with length num_boxes.
+ - each item: [start_idx, end_idx]
+ """
+ positive_map = torch.zeros((len(token_span), max_text_len), dtype=torch.float)
+ for j, tok_list in enumerate(token_span):
+ for (beg, end) in tok_list:
+ beg_pos = tokenized.char_to_token(beg)
+ end_pos = tokenized.char_to_token(end - 1)
+ if beg_pos is None:
+ try:
+ beg_pos = tokenized.char_to_token(beg + 1)
+ if beg_pos is None:
+ beg_pos = tokenized.char_to_token(beg + 2)
+ except:
+ beg_pos = None
+ if end_pos is None:
+ try:
+ end_pos = tokenized.char_to_token(end - 2)
+ if end_pos is None:
+ end_pos = tokenized.char_to_token(end - 3)
+ except:
+ end_pos = None
+ if beg_pos is None or end_pos is None:
+ continue
+
+ assert beg_pos is not None and end_pos is not None
+ if os.environ.get("SHILONG_DEBUG_ONLY_ONE_POS", None) == "TRUE":
+ positive_map[j, beg_pos] = 1
+ break
+ else:
+ positive_map[j, beg_pos : end_pos + 1].fill_(1)
+
+ return positive_map / (positive_map.sum(-1)[:, None] + 1e-6)
+
+
+def build_captions_and_token_span(cat_list, force_lowercase):
+ """
+ Return:
+ captions: str
+ cat2tokenspan: dict
+ {
+ 'dog': [[0, 2]],
+ ...
+ }
+ """
+
+ cat2tokenspan = {}
+ captions = ""
+ for catname in cat_list:
+ class_name = catname
+ if force_lowercase:
+ class_name = class_name.lower()
+ if "/" in class_name:
+ class_name_list: List = class_name.strip().split("/")
+ class_name_list.append(class_name)
+ class_name: str = random.choice(class_name_list)
+
+ tokens_positive_i = []
+ subnamelist = [i.strip() for i in class_name.strip().split(" ")]
+ for subname in subnamelist:
+ if len(subname) == 0:
+ continue
+ if len(captions) > 0:
+ captions = captions + " "
+ strat_idx = len(captions)
+ end_idx = strat_idx + len(subname)
+ tokens_positive_i.append([strat_idx, end_idx])
+ captions = captions + subname
+
+ if len(tokens_positive_i) > 0:
+ captions = captions + " ."
+ cat2tokenspan[class_name] = tokens_positive_i
+
+ return captions, cat2tokenspan
+
+
+def build_id2posspan_and_caption(category_dict: dict):
+ """Build id2pos_span and caption from category_dict
+
+ Args:
+ category_dict (dict): category_dict
+ """
+ cat_list = [item["name"].lower() for item in category_dict]
+ id2catname = {item["id"]: item["name"].lower() for item in category_dict}
+ caption, cat2posspan = build_captions_and_token_span(cat_list, force_lowercase=True)
+ id2posspan = {catid: cat2posspan[catname] for catid, catname in id2catname.items()}
+ return id2posspan, caption
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/version.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..b794fd409a5e3b3b65ad76a43d6a01a318877640
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/groundingdino/version.py
@@ -0,0 +1 @@
+__version__ = '0.1.0'
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/requirements.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f52ed0acc1fa8a6812b5e966de649b79d1164aa5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/requirements.txt
@@ -0,0 +1,10 @@
+torch
+torchvision
+transformers
+addict
+yapf
+timm
+numpy
+opencv-python
+supervision==0.3.2
+pycocotools
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/setup.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..a045b763fb4a4f61bac23b735544a18ffc68d20a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/GroundingDINO/setup.py
@@ -0,0 +1,208 @@
+# coding=utf-8
+# Copyright 2022 The IDEA Authors. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+# ------------------------------------------------------------------------------------------------
+# Modified from
+# https://github.com/fundamentalvision/Deformable-DETR/blob/main/models/ops/setup.py
+# https://github.com/facebookresearch/detectron2/blob/main/setup.py
+# https://github.com/open-mmlab/mmdetection/blob/master/setup.py
+# https://github.com/Oneflow-Inc/libai/blob/main/setup.py
+# ------------------------------------------------------------------------------------------------
+
+import glob
+import os
+import subprocess
+
+import torch
+from setuptools import find_packages, setup
+from torch.utils.cpp_extension import CUDA_HOME, CppExtension, CUDAExtension
+
+# groundingdino version info
+version = "0.1.0"
+package_name = "groundingdino"
+cwd = os.path.dirname(os.path.abspath(__file__))
+
+
+sha = "Unknown"
+try:
+ sha = subprocess.check_output(["git", "rev-parse", "HEAD"], cwd=cwd).decode("ascii").strip()
+except Exception:
+ pass
+
+
+def write_version_file():
+ version_path = os.path.join(cwd, "groundingdino", "version.py")
+ with open(version_path, "w") as f:
+ f.write(f"__version__ = '{version}'\n")
+ # f.write(f"git_version = {repr(sha)}\n")
+
+
+requirements = ["torch", "torchvision"]
+
+torch_ver = [int(x) for x in torch.__version__.split(".")[:2]]
+
+
+def get_extensions():
+ this_dir = os.path.dirname(os.path.abspath(__file__))
+ extensions_dir = os.path.join(this_dir, "groundingdino", "models", "GroundingDINO", "csrc")
+
+ main_source = os.path.join(extensions_dir, "vision.cpp")
+ sources = glob.glob(os.path.join(extensions_dir, "**", "*.cpp"))
+ source_cuda = glob.glob(os.path.join(extensions_dir, "**", "*.cu")) + glob.glob(
+ os.path.join(extensions_dir, "*.cu")
+ )
+
+ sources = [main_source] + sources
+
+ extension = CppExtension
+
+ extra_compile_args = {"cxx": []}
+ define_macros = []
+
+ if torch.cuda.is_available() and CUDA_HOME is not None:
+ print("Compiling with CUDA")
+ extension = CUDAExtension
+ sources += source_cuda
+ define_macros += [("WITH_CUDA", None)]
+ extra_compile_args["nvcc"] = [
+ "-DCUDA_HAS_FP16=1",
+ "-D__CUDA_NO_HALF_OPERATORS__",
+ "-D__CUDA_NO_HALF_CONVERSIONS__",
+ "-D__CUDA_NO_HALF2_OPERATORS__",
+ ]
+ else:
+ print("Compiling without CUDA")
+ define_macros += [("WITH_HIP", None)]
+ extra_compile_args["nvcc"] = []
+ return None
+
+ sources = [os.path.join(extensions_dir, s) for s in sources]
+ include_dirs = [extensions_dir]
+
+ ext_modules = [
+ extension(
+ "groundingdino._C",
+ sources,
+ include_dirs=include_dirs,
+ define_macros=define_macros,
+ extra_compile_args=extra_compile_args,
+ )
+ ]
+
+ return ext_modules
+
+
+def parse_requirements(fname="requirements.txt", with_version=True):
+ """Parse the package dependencies listed in a requirements file but strips
+ specific versioning information.
+
+ Args:
+ fname (str): path to requirements file
+ with_version (bool, default=False): if True include version specs
+
+ Returns:
+ List[str]: list of requirements items
+
+ CommandLine:
+ python -c "import setup; print(setup.parse_requirements())"
+ """
+ import re
+ import sys
+ from os.path import exists
+
+ require_fpath = fname
+
+ def parse_line(line):
+ """Parse information from a line in a requirements text file."""
+ if line.startswith("-r "):
+ # Allow specifying requirements in other files
+ target = line.split(" ")[1]
+ for info in parse_require_file(target):
+ yield info
+ else:
+ info = {"line": line}
+ if line.startswith("-e "):
+ info["package"] = line.split("#egg=")[1]
+ elif "@git+" in line:
+ info["package"] = line
+ else:
+ # Remove versioning from the package
+ pat = "(" + "|".join([">=", "==", ">"]) + ")"
+ parts = re.split(pat, line, maxsplit=1)
+ parts = [p.strip() for p in parts]
+
+ info["package"] = parts[0]
+ if len(parts) > 1:
+ op, rest = parts[1:]
+ if ";" in rest:
+ # Handle platform specific dependencies
+ # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
+ version, platform_deps = map(str.strip, rest.split(";"))
+ info["platform_deps"] = platform_deps
+ else:
+ version = rest # NOQA
+ info["version"] = (op, version)
+ yield info
+
+ def parse_require_file(fpath):
+ with open(fpath, "r") as f:
+ for line in f.readlines():
+ line = line.strip()
+ if line and not line.startswith("#"):
+ for info in parse_line(line):
+ yield info
+
+ def gen_packages_items():
+ if exists(require_fpath):
+ for info in parse_require_file(require_fpath):
+ parts = [info["package"]]
+ if with_version and "version" in info:
+ parts.extend(info["version"])
+ if not sys.version.startswith("3.4"):
+ # apparently package_deps are broken in 3.4
+ platform_deps = info.get("platform_deps")
+ if platform_deps is not None:
+ parts.append(";" + platform_deps)
+ item = "".join(parts)
+ yield item
+
+ packages = list(gen_packages_items())
+ return packages
+
+
+if __name__ == "__main__":
+ print(f"Building wheel {package_name}-{version}")
+
+ with open("LICENSE", "r", encoding="utf-8") as f:
+ license = f.read()
+
+ write_version_file()
+
+ setup(
+ name="groundingdino",
+ version="0.1.0",
+ author="International Digital Economy Academy, Shilong Liu",
+ url="https://github.com/IDEA-Research/GroundingDINO",
+ description="open-set object detector",
+ license=license,
+ install_requires=parse_requirements("requirements.txt"),
+ packages=find_packages(
+ exclude=(
+ "configs",
+ "tests",
+ )
+ ),
+ ext_modules=get_extensions(),
+ cmdclass={"build_ext": torch.utils.cpp_extension.BuildExtension},
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b1395e94b016dd1b95b4c7e3ed493e1d0b342917
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2020 - present, Facebook, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Makefile b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..604a6334ab380f42b6bcdb1793c51cc8ca7b6940
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/Makefile
@@ -0,0 +1,10 @@
+build-image:
+ docker build -t=gsa:v0 .
+
+run: build-image
+ nvidia-docker run --gpus all -it --rm --net=host --privileged \
+ -v /tmp/.X11-unix:/tmp/.X11-unix \
+ -e DISPLAY=$DISPLAY \
+ -v ${PWD}:/home/appuser \
+ --name=gsa \
+ --ipc=host -it gsa:v0
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..e955e8b0efa1c07a9faf4bbe5e55a9f53c3dd9e9
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/README.md
@@ -0,0 +1,441 @@
+
+
+# Grounded-Segment-Anything
+[](https://www.youtube.com/watch?v=GuEDDBWrN24&t=521s) [](https://github.com/camenduru/grounded-segment-anything-colab) [](https://huggingface.co/spaces/IDEA-Research/Grounded-SAM) [](https://modelscope.cn/studios/tuofeilunhifi/Grounded-Segment-Anything/summary) [](https://huggingface.co/spaces/yizhangliu/Grounded-Segment-Anything) [](https://github.com/continue-revolution/sd-webui-segment-anything) [](./grounded_sam.ipynb)
+
+We plan to create a very interesting demo by combining [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) and [Segment Anything](https://github.com/facebookresearch/segment-anything) which aims to detect and segment Anything with text inputs! And we will continue to improve it and create more interesting demos based on this foundation.
+
+We are very willing to **help everyone share and promote new projects** based on Segment-Anything, Please checkout here for more amazing demos and works in the community: [Highlight Extension Projects](#bulb-highlight-extension-projects). You can submit a new issue (with `project` tag) or a new pull request to add new project's links.
+
+**🍄 Why Building this Project?**
+
+The **core idea** behind this project is to **combine the strengths of different models in order to build a very powerful pipeline for solving complex problems**. And it's worth mentioning that this is a workflow for combining strong expert models, where **all parts can be used separately or in combination, and can be replaced with any similar but different models (like replacing Grounding DINO with GLIP or other detectors / replacing Stable-Diffusion with ControlNet or GLIGEN/ Combining with ChatGPT)**.
+
+**🍊 Preliminary Works**
+- [Segment Anything](https://github.com/facebookresearch/segment-anything) is a strong segmentation model. But it needs prompts (like boxes/points) to generate masks.
+- [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO) is a strong zero-shot detector which is capable of to generate high quality boxes and labels with free-form text.
+- [OSX](https://osx-ubody.github.io/) is a strong and efficient one-stage motion capture method to generate high quality 3D human mesh from monucular image. We also release a large-scale upper-body dataset UBody for a more accurate reconstrution in the upper-body scene.
+- [Stable-Diffusion](https://github.com/CompVis/stable-diffusion) is an amazing strong text-to-image diffusion model.
+- [BLIP](https://github.com/salesforce/lavis) is a wonderful language-vision model for image understanding.
+- [Visual ChatGPT](https://github.com/microsoft/visual-chatgpt) is a wonderful tool that connects ChatGPT and a series of Visual Foundation Models to enable sending and receiving images during chatting.
+
+
+**🔥 Highlighted Projects**
+
+- Checkout the [Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once) demo! It supports segmenting with various types of prompts (text, point, scribble, referring image, etc.) and any combination of prompts.
+- Checkout the [OpenSeeD](https://github.com/IDEA-Research/OpenSeeD) for the interactive segmentation with box input to generate mask.
+
+**🍉 The Supported Amazing Demos in this Project**
+
+- [GroundingDINO: Detect Everything with Text Prompt](#runner-run-grounding-dino-demo)
+- [GroundingDINO + Segment-Anything: Detect and Segment Everything with Text Prompt](#runningman-run-grounded-segment-anything-demo)
+- [GroundingDINO + Segment-Anything + Stable-Diffusion: Detect, Segment and Generate Anything with Text Prompts](#skier-run-grounded-segment-anything--inpainting-demo)
+- [Grounded-SAM + Stable-Diffusion Gradio APP](#golfing-run-grounded-segment-anything--inpainting-gradio-app)
+- [Grounded-SAM + BLIP: Automatically Labeling System!](#robot-run-grounded-segment-anything--blip-demo)
+- [Whisper + Grounded-SAM: Detect and Segment Everything with Speech!](#openmouth-run-grounded-segment-anything--whisper-demo)
+- [Grounded-SAM + Visual ChatGPT: Automatically Label & Generate Everything with ChatBot!](#speechballoon-run-chatbot-demo)
+- [Grounded-SAM + OSX: Text to 3D Whole-Body Mesh Recovery, Detect Anyone and Reconstruct his 3D Humen Mesh!](#mandancing-run-grounded-segment-anything--osx-demo)
+- [Interactive Fashion-Edit Playground: Click for Segmentation And Editing!](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace)
+- [Interactive Human-face Editing Playground: Click And Editing Human Face!](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace)
+
+
+
+
+## The Amazing Demo Preview (Continual Updating)
+
+**🔥 ChatBot for our project is built**
+
+https://user-images.githubusercontent.com/24236723/231955561-2ae4ec1a-c75f-4cc5-9b7b-517aa1432123.mp4
+
+**🔥 🔈Speak to edit🎨: Whisper + ChatGPT + Grounded-SAM + SD**
+
+
+
+**🔥 Grounded-SAM: Semi-automatic Labeling System**
+
+
+**Tips**
+- If you want to detect multiple objects in one sentence with [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO), we suggest seperating each name with `.` . An example: `cat . dog . chair .`
+
+**🔥 Grounded-SAM + Stable-Diffusion Inpainting: Data-Factory, Generating New Data**
+
+
+**🔥 BLIP + Grounded-SAM: Automatic Label System**
+
+Using BLIP to generate caption, extracting tags with ChatGPT, and using Grounded-SAM for box and mask generating. Here's the demo output:
+
+
+
+**🔥 Grounded-SAM+OSX: Promptable 3D Whole-Body Human Mesh Recovery**
+
+Using Grounded-SAM for box and mask generating, using [OSX](https://github.com/IDEA-Research/OSX) to estimate the SMPLX parameters and reconstruct 3D whole-body (body, face and hand) human mesh. Here's a demo:
+
+
+
+
+
+
+**🔥 Interactive Editing**
+- Release the interactive fashion-edit playground in [here](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace). Run in the notebook, just click for annotating points for further segmentation. Enjoy it!
+
+
+ 
+
+- Release human-face-edit branch [here](https://github.com/IDEA-Research/Grounded-Segment-Anything/tree/humanFace). We'll keep updating this branch with more interesting features. Here are some examples:
+
+ 
+
+
+
+## :bulb: Highlight Extension Projects
+- [Segment Everything Everywhere All at Once](https://github.com/UX-Decoder/Segment-Everything-Everywhere-All-At-Once) Support various types of prompts and any combination of prompts.
+- [Computer Vision in the Wild (CVinW) Readings](https://github.com/Computer-Vision-in-the-Wild/CVinW_Readings) for those who are interested in open-set tasks in computer vision.
+- [OpenSeeD](https://github.com/IDEA-Research/OpenSeeD): interactive segmentation with box input to generate mask.
+- [Zero-Shot Anomaly Detection](https://github.com/caoyunkang/GroundedSAM-zero-shot-anomaly-detection) by Yunkang Cao
+- [EditAnything: ControlNet + StableDiffusion based on the SAM segmentation mask](https://github.com/sail-sg/EditAnything) by Shanghua Gao and Pan Zhou
+- [IEA: Image Editing Anything](https://github.com/feizc/IEA) by Zhengcong Fei
+- [SAM-MMRorate: Combining Rotated Object Detector and SAM](https://github.com/Li-Qingyun/sam-mmrotate) by Qingyun Li and Xue Yang
+- [Awesome-Anything](https://github.com/VainF/Awesome-Anything) by Gongfan Fang
+- [Prompt-Segment-Anything](https://github.com/RockeyCoss/Prompt-Segment-Anything) by Rockey
+- [WebUI for Segment-Anything and Grounded-SAM](https://github.com/continue-revolution/sd-webui-segment-anything) by Chengsong Zhang
+- [Inpainting Anything: Inpaint Anything with SAM + Inpainting models](https://github.com/geekyutao/Inpaint-Anything) by Tao Yu
+- [Grounded Segment Anything From Objects to Parts: Combining Segment-Anything with VLPart & GLIP & Visual ChatGPT](https://github.com/Cheems-Seminar/segment-anything-and-name-it) by Peize Sun and Shoufa Chen
+- [Narapi-SAM: Integration of Segment Anything into Narapi (A nice viewer for SAM)](https://github.com/MIC-DKFZ/napari-sam) by MIC-DKFZ
+- [Grounded Segment Anything Colab](https://github.com/camenduru/grounded-segment-anything-colab) by camenduru
+- [Optical Character Recognition with Segment Anything](https://github.com/yeungchenwa/OCR-SAM) by Zhenhua Yang
+- [Transform Image into Unique Paragraph with ChatGPT, BLIP2, OFA, GRIT, Segment Anything, ControlNet](https://github.com/showlab/Image2Paragraph) by showlab
+- [Lang-Segment-Anything: Another awesome demo for combining GroundingDINO with Segment-Anything](https://github.com/luca-medeiros/lang-segment-anything) by Luca Medeiros
+- [🥳 🚀 **Playground: Integrate SAM and OpenMMLab!**](https://github.com/open-mmlab/playground)
+- [3D-object via Segment Anything](https://github.com/dvlab-research/3D-Box-Segment-Anything) by Yukang Chen
+- [Image2Paragraph: Transform Image Into Unique Paragraph](https://github.com/showlab/Image2Paragraph) by Show Lab
+- [Zero-shot Scene Graph Generate with Grounded-SAM](https://github.com/showlab/Image2Paragraph) by JackWhite-rwx
+- [CLIP Surgery for Better Explainability with Enhancement in Open-Vocabulary Tasks](https://github.com/xmed-lab/CLIP_Surgery) by Eli-YiLi
+- [Panoptic-Segment-Anything: Zero-shot panoptic segmentation using SAM](https://github.com/segments-ai/panoptic-segment-anything) by segments-ai
+
+## :open_book: Notebook Demo
+See our [notebook file](grounded_sam.ipynb) as an example.
+
+## :hammer_and_wrench: Installation
+The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.
+
+### Install with Docker
+
+Open one terminal:
+
+```
+make run
+```
+
+That's it.
+
+If you would like to allow visualization across docker container, open another terminal and type:
+
+```
+xhost +
+```
+
+
+### Install without Docker
+
+Install Segment Anything:
+
+```bash
+python -m pip install -e segment_anything
+```
+
+Install Grounding DINO:
+
+```bash
+python -m pip install -e GroundingDINO
+```
+
+
+Install diffusers:
+
+```bash
+pip install --upgrade diffusers[torch]
+```
+
+Install osx:
+
+```bash
+git submodule update --init --recursive
+cd grounded-sam-osx && bash install.sh
+```
+
+The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. `jupyter` is also required to run the example notebooks.
+
+```
+pip install opencv-python pycocotools matplotlib onnxruntime onnx ipykernel
+```
+
+More details can be found in [install segment anything](https://github.com/facebookresearch/segment-anything#installation) and [install GroundingDINO](https://github.com/IDEA-Research/GroundingDINO#install) and [install OSX](https://github.com/IDEA-Research/OSX)
+
+
+## :runner: Run Grounding DINO Demo
+- Download the checkpoint for Grounding Dino:
+```bash
+cd Grounded-Segment-Anything
+
+wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
+```
+
+- Run demo
+```bash
+export CUDA_VISIBLE_DEVICES=0
+python grounding_dino_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --input_image assets/demo1.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --text_prompt "bear" \
+ --device "cuda"
+```
+- The model prediction visualization will be saved in `output_dir` as follow:
+
+
+
+## :running_man: Run Grounded-Segment-Anything Demo
+- Download the checkpoint for Segment Anything and Grounding Dino:
+```bash
+cd Grounded-Segment-Anything
+
+wget https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth
+wget https://github.com/IDEA-Research/GroundingDINO/releases/download/v0.1.0-alpha/groundingdino_swint_ogc.pth
+```
+
+- Run Demo
+```bash
+export CUDA_VISIBLE_DEVICES=0
+python grounded_sam_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/demo1.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --text_prompt "bear" \
+ --device "cuda"
+```
+
+- The model prediction visualization will be saved in `output_dir` as follow:
+
+
+
+**More Examples**
+
+
+## :skier: Run Grounded-Segment-Anything + Inpainting Demo
+
+```bash
+CUDA_VISIBLE_DEVICES=0
+python grounded_sam_inpainting_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/inpaint_demo.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --det_prompt "bench" \
+ --inpaint_prompt "A sofa, high quality, detailed" \
+ --device "cuda"
+```
+
+## :golfing: Run Grounded-Segment-Anything + Inpainting Gradio APP
+
+```bash
+python gradio_app.py
+```
+
+- The gradio_app visualization as follow:
+
+
+
+
+## :robot: Run Grounded-Segment-Anything + BLIP Demo
+It is easy to generate pseudo labels automatically as follows:
+1. Use BLIP (or other caption models) to generate a caption.
+2. Extract tags from the caption. We use ChatGPT to handle the potential complicated sentences.
+3. Use Grounded-Segment-Anything to generate the boxes and masks.
+
+- Run Demo
+```bash
+export CUDA_VISIBLE_DEVICES=0
+python automatic_label_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/demo3.jpg \
+ --output_dir "outputs" \
+ --openai_key your_openai_key \
+ --box_threshold 0.25 \
+ --text_threshold 0.2 \
+ --iou_threshold 0.5 \
+ --device "cuda"
+```
+
+- The pseudo labels and model prediction visualization will be saved in `output_dir` as follows:
+
+
+
+
+## :open_mouth: Run Grounded-Segment-Anything + Whisper Demo
+Detect and segment anything with speech!
+
+**Install Whisper**
+```bash
+pip install -U openai-whisper
+```
+See the [whisper official page](https://github.com/openai/whisper#setup) if you have other questions for the installation.
+
+**Run Voice-to-Label Demo**
+
+Optional: Download the demo audio file
+
+```bash
+wget https://huggingface.co/ShilongLiu/GroundingDINO/resolve/main/demo_audio.mp3
+```
+
+
+```bash
+export CUDA_VISIBLE_DEVICES=0
+python grounded_sam_whisper_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/demo4.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --speech_file "demo_audio.mp3" \
+ --device "cuda"
+```
+
+
+
+**Run Voice-to-inpaint Demo**
+
+You can enable chatgpt to help you automatically detect the object and inpainting order with `--enable_chatgpt`.
+
+Or you can specify the object you want to inpaint [stored in `args.det_speech_file`] and the text you want to inpaint with [stored in `args.inpaint_speech_file`].
+
+```bash
+# Example: enable chatgpt
+export CUDA_VISIBLE_DEVICES=0
+export OPENAI_KEY=your_openai_key
+python grounded_sam_whisper_inpainting_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/inpaint_demo.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --prompt_speech_file assets/acoustics/prompt_speech_file.mp3 \
+ --enable_chatgpt \
+ --openai_key $OPENAI_KEY \
+ --device "cuda"
+```
+
+```bash
+# Example: without chatgpt
+export CUDA_VISIBLE_DEVICES=0
+python grounded_sam_whisper_inpainting_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image assets/inpaint_demo.jpg \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --det_speech_file "assets/acoustics/det_voice.mp3" \
+ --inpaint_speech_file "assets/acoustics/inpaint_voice.mp3" \
+ --device "cuda"
+```
+
+
+
+## :speech_balloon: Run ChatBot Demo
+Following [Visual ChatGPT](https://github.com/microsoft/visual-chatgpt), we add a ChatBot for our project. Currently, it supports:
+1. "Descripe the image."
+2. "Detect the dog (and the cat) in the image."
+3. "Segment anything in the image."
+4. "Segment the dog (and the cat) in the image."
+5. "Help me label the image."
+6. "Replace the dog with a cat in the image."
+
+To use the ChatBot:
+- Install whisper if you want to use audio as input.
+- Set the default model setting in the tool `Grounded_dino_sam_inpainting`.
+- Run Demo
+```bash
+export CUDA_VISIBLE_DEVICES=0
+python chatbot.py
+```
+
+## :man_dancing: Run Grounded-Segment-Anything + OSX Demo
+
+- Download the checkpoint `osx_l_wo_decoder.pth.tar` from [here](https://drive.google.com/drive/folders/1x7MZbB6eAlrq5PKC9MaeIm4GqkBpokow?usp=share_link) for OSX:
+- Download the human model files and place it into `grounded-sam-osx/utils/human_model_files` following the instruction of [OSX](https://github.com/IDEA-Research/OSX).
+
+- Run Demo
+
+```shell
+export CUDA_VISIBLE_DEVICES=0
+python grounded_sam_osx_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --osx_checkpoint osx_l_wo_decoder.pth.tar \
+ --input_image assets/osx/grounded_sam_osx_demo.png \
+ --output_dir "outputs" \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --text_prompt "humans, chairs" \
+ --device "cuda"
+```
+
+- The model prediction visualization will be saved in `output_dir` as follow:
+
+
+
+- We also support promptable 3D whole-body mesh recovery. For example, you can track someone with with a text prompt and estimate his 3D pose and shape :
+
+|  |
+| :---------------------------------------------------: |
+| *A person with pink clothes* |
+
+|  |
+| :---------------------------------------------------: |
+| *A man with a sunglasses* |
+
+## :cupid: Acknowledgements
+
+- [Segment Anything](https://github.com/facebookresearch/segment-anything)
+- [Grounding DINO](https://github.com/IDEA-Research/GroundingDINO)
+
+## Citation
+If you find this project helpful for your research, please consider citing the following BibTeX entry.
+```BibTex
+@article{kirillov2023segany,
+ title={Segment Anything},
+ author={Kirillov, Alexander and Mintun, Eric and Ravi, Nikhila and Mao, Hanzi and Rolland, Chloe and Gustafson, Laura and Xiao, Tete and Whitehead, Spencer and Berg, Alexander C. and Lo, Wan-Yen and Doll{\'a}r, Piotr and Girshick, Ross},
+ journal={arXiv:2304.02643},
+ year={2023}
+}
+
+@inproceedings{ShilongLiu2023GroundingDM,
+ title={Grounding DINO: Marrying DINO with Grounded Pre-Training for Open-Set Object Detection},
+ author={Shilong Liu and Zhaoyang Zeng and Tianhe Ren and Feng Li and Hao Zhang and Jie Yang and Chunyuan Li and Jianwei Yang and Hang Su and Jun Zhu and Lei Zhang},
+ year={2023}
+}
+```
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..b1395e94b016dd1b95b4c7e3ed493e1d0b342917
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2020 - present, Facebook, Inc
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..8e9261c9992bbe8e70e9099c7b5062e428fc83ce
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/README.md
@@ -0,0 +1,2 @@
+# grounded-sam-osx
+This is a submodule of [Grounded-SAM](https://github.com/IDEA-Research/Grounded-Segment-Anything). It can estimate full-body pose and shape from a monuculor image. The combined of Grounded-SAM and OSX supports promptable 3D whole-body mesh recovery.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/300w.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/300w.py
new file mode 100644
index 0000000000000000000000000000000000000000..10c343a2adf84947159f2651b3e918d1fc32ea90
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/300w.py
@@ -0,0 +1,384 @@
+dataset_info = dict(
+ dataset_name='300w',
+ paper_info=dict(
+ author='Sagonas, Christos and Antonakos, Epameinondas '
+ 'and Tzimiropoulos, Georgios and Zafeiriou, Stefanos '
+ 'and Pantic, Maja',
+ title='300 faces in-the-wild challenge: '
+ 'Database and results',
+ container='Image and vision computing',
+ year='2016',
+ homepage='https://ibug.doc.ic.ac.uk/resources/300-W/',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='kpt-0', id=0, color=[255, 255, 255], type='', swap='kpt-16'),
+ 1:
+ dict(
+ name='kpt-1', id=1, color=[255, 255, 255], type='', swap='kpt-15'),
+ 2:
+ dict(
+ name='kpt-2', id=2, color=[255, 255, 255], type='', swap='kpt-14'),
+ 3:
+ dict(
+ name='kpt-3', id=3, color=[255, 255, 255], type='', swap='kpt-13'),
+ 4:
+ dict(
+ name='kpt-4', id=4, color=[255, 255, 255], type='', swap='kpt-12'),
+ 5:
+ dict(
+ name='kpt-5', id=5, color=[255, 255, 255], type='', swap='kpt-11'),
+ 6:
+ dict(
+ name='kpt-6', id=6, color=[255, 255, 255], type='', swap='kpt-10'),
+ 7:
+ dict(name='kpt-7', id=7, color=[255, 255, 255], type='', swap='kpt-9'),
+ 8:
+ dict(name='kpt-8', id=8, color=[255, 255, 255], type='', swap=''),
+ 9:
+ dict(name='kpt-9', id=9, color=[255, 255, 255], type='', swap='kpt-7'),
+ 10:
+ dict(
+ name='kpt-10', id=10, color=[255, 255, 255], type='',
+ swap='kpt-6'),
+ 11:
+ dict(
+ name='kpt-11', id=11, color=[255, 255, 255], type='',
+ swap='kpt-5'),
+ 12:
+ dict(
+ name='kpt-12', id=12, color=[255, 255, 255], type='',
+ swap='kpt-4'),
+ 13:
+ dict(
+ name='kpt-13', id=13, color=[255, 255, 255], type='',
+ swap='kpt-3'),
+ 14:
+ dict(
+ name='kpt-14', id=14, color=[255, 255, 255], type='',
+ swap='kpt-2'),
+ 15:
+ dict(
+ name='kpt-15', id=15, color=[255, 255, 255], type='',
+ swap='kpt-1'),
+ 16:
+ dict(
+ name='kpt-16', id=16, color=[255, 255, 255], type='',
+ swap='kpt-0'),
+ 17:
+ dict(
+ name='kpt-17',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-26'),
+ 18:
+ dict(
+ name='kpt-18',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-25'),
+ 19:
+ dict(
+ name='kpt-19',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-24'),
+ 20:
+ dict(
+ name='kpt-20',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-23'),
+ 21:
+ dict(
+ name='kpt-21',
+ id=21,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-22'),
+ 22:
+ dict(
+ name='kpt-22',
+ id=22,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-21'),
+ 23:
+ dict(
+ name='kpt-23',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-20'),
+ 24:
+ dict(
+ name='kpt-24',
+ id=24,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-19'),
+ 25:
+ dict(
+ name='kpt-25',
+ id=25,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-18'),
+ 26:
+ dict(
+ name='kpt-26',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-17'),
+ 27:
+ dict(name='kpt-27', id=27, color=[255, 255, 255], type='', swap=''),
+ 28:
+ dict(name='kpt-28', id=28, color=[255, 255, 255], type='', swap=''),
+ 29:
+ dict(name='kpt-29', id=29, color=[255, 255, 255], type='', swap=''),
+ 30:
+ dict(name='kpt-30', id=30, color=[255, 255, 255], type='', swap=''),
+ 31:
+ dict(
+ name='kpt-31',
+ id=31,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-35'),
+ 32:
+ dict(
+ name='kpt-32',
+ id=32,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-34'),
+ 33:
+ dict(name='kpt-33', id=33, color=[255, 255, 255], type='', swap=''),
+ 34:
+ dict(
+ name='kpt-34',
+ id=34,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-32'),
+ 35:
+ dict(
+ name='kpt-35',
+ id=35,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-31'),
+ 36:
+ dict(
+ name='kpt-36',
+ id=36,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-45'),
+ 37:
+ dict(
+ name='kpt-37',
+ id=37,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-44'),
+ 38:
+ dict(
+ name='kpt-38',
+ id=38,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-43'),
+ 39:
+ dict(
+ name='kpt-39',
+ id=39,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-42'),
+ 40:
+ dict(
+ name='kpt-40',
+ id=40,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-47'),
+ 41:
+ dict(
+ name='kpt-41',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-46'),
+ 42:
+ dict(
+ name='kpt-42',
+ id=42,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-39'),
+ 43:
+ dict(
+ name='kpt-43',
+ id=43,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-38'),
+ 44:
+ dict(
+ name='kpt-44',
+ id=44,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-37'),
+ 45:
+ dict(
+ name='kpt-45',
+ id=45,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-36'),
+ 46:
+ dict(
+ name='kpt-46',
+ id=46,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-41'),
+ 47:
+ dict(
+ name='kpt-47',
+ id=47,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-40'),
+ 48:
+ dict(
+ name='kpt-48',
+ id=48,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-54'),
+ 49:
+ dict(
+ name='kpt-49',
+ id=49,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-53'),
+ 50:
+ dict(
+ name='kpt-50',
+ id=50,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-52'),
+ 51:
+ dict(name='kpt-51', id=51, color=[255, 255, 255], type='', swap=''),
+ 52:
+ dict(
+ name='kpt-52',
+ id=52,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-50'),
+ 53:
+ dict(
+ name='kpt-53',
+ id=53,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-49'),
+ 54:
+ dict(
+ name='kpt-54',
+ id=54,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-48'),
+ 55:
+ dict(
+ name='kpt-55',
+ id=55,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-59'),
+ 56:
+ dict(
+ name='kpt-56',
+ id=56,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-58'),
+ 57:
+ dict(name='kpt-57', id=57, color=[255, 255, 255], type='', swap=''),
+ 58:
+ dict(
+ name='kpt-58',
+ id=58,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-56'),
+ 59:
+ dict(
+ name='kpt-59',
+ id=59,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-55'),
+ 60:
+ dict(
+ name='kpt-60',
+ id=60,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-64'),
+ 61:
+ dict(
+ name='kpt-61',
+ id=61,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-63'),
+ 62:
+ dict(name='kpt-62', id=62, color=[255, 255, 255], type='', swap=''),
+ 63:
+ dict(
+ name='kpt-63',
+ id=63,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-61'),
+ 64:
+ dict(
+ name='kpt-64',
+ id=64,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-60'),
+ 65:
+ dict(
+ name='kpt-65',
+ id=65,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-67'),
+ 66:
+ dict(name='kpt-66', id=66, color=[255, 255, 255], type='', swap=''),
+ 67:
+ dict(
+ name='kpt-67',
+ id=67,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-65'),
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 68,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aflw.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aflw.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf534cbb756e8c514c2f5e2a7fceedd55afb637e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aflw.py
@@ -0,0 +1,83 @@
+dataset_info = dict(
+ dataset_name='aflw',
+ paper_info=dict(
+ author='Koestinger, Martin and Wohlhart, Paul and '
+ 'Roth, Peter M and Bischof, Horst',
+ title='Annotated facial landmarks in the wild: '
+ 'A large-scale, real-world database for facial '
+ 'landmark localization',
+ container='2011 IEEE international conference on computer '
+ 'vision workshops (ICCV workshops)',
+ year='2011',
+ homepage='https://www.tugraz.at/institute/icg/research/'
+ 'team-bischof/lrs/downloads/aflw/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='kpt-0', id=0, color=[255, 255, 255], type='', swap='kpt-5'),
+ 1:
+ dict(name='kpt-1', id=1, color=[255, 255, 255], type='', swap='kpt-4'),
+ 2:
+ dict(name='kpt-2', id=2, color=[255, 255, 255], type='', swap='kpt-3'),
+ 3:
+ dict(name='kpt-3', id=3, color=[255, 255, 255], type='', swap='kpt-2'),
+ 4:
+ dict(name='kpt-4', id=4, color=[255, 255, 255], type='', swap='kpt-1'),
+ 5:
+ dict(name='kpt-5', id=5, color=[255, 255, 255], type='', swap='kpt-0'),
+ 6:
+ dict(
+ name='kpt-6', id=6, color=[255, 255, 255], type='', swap='kpt-11'),
+ 7:
+ dict(
+ name='kpt-7', id=7, color=[255, 255, 255], type='', swap='kpt-10'),
+ 8:
+ dict(name='kpt-8', id=8, color=[255, 255, 255], type='', swap='kpt-9'),
+ 9:
+ dict(name='kpt-9', id=9, color=[255, 255, 255], type='', swap='kpt-8'),
+ 10:
+ dict(
+ name='kpt-10', id=10, color=[255, 255, 255], type='',
+ swap='kpt-7'),
+ 11:
+ dict(
+ name='kpt-11', id=11, color=[255, 255, 255], type='',
+ swap='kpt-6'),
+ 12:
+ dict(
+ name='kpt-12',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-14'),
+ 13:
+ dict(name='kpt-13', id=13, color=[255, 255, 255], type='', swap=''),
+ 14:
+ dict(
+ name='kpt-14',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-12'),
+ 15:
+ dict(
+ name='kpt-15',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-17'),
+ 16:
+ dict(name='kpt-16', id=16, color=[255, 255, 255], type='', swap=''),
+ 17:
+ dict(
+ name='kpt-17',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-15'),
+ 18:
+ dict(name='kpt-18', id=18, color=[255, 255, 255], type='', swap='')
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 19,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aic.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aic.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ecdbe3f0afeb19dbb7aed42653ce5efd85cfda3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/aic.py
@@ -0,0 +1,140 @@
+dataset_info = dict(
+ dataset_name='aic',
+ paper_info=dict(
+ author='Wu, Jiahong and Zheng, He and Zhao, Bo and '
+ 'Li, Yixin and Yan, Baoming and Liang, Rui and '
+ 'Wang, Wenjia and Zhou, Shipei and Lin, Guosen and '
+ 'Fu, Yanwei and others',
+ title='Ai challenger: A large-scale dataset for going '
+ 'deeper in image understanding',
+ container='arXiv',
+ year='2017',
+ homepage='https://github.com/AIChallenger/AI_Challenger_2017',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_shoulder',
+ id=0,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 1:
+ dict(
+ name='right_elbow',
+ id=1,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 2:
+ dict(
+ name='right_wrist',
+ id=2,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 3:
+ dict(
+ name='left_shoulder',
+ id=3,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 4:
+ dict(
+ name='left_elbow',
+ id=4,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 5:
+ dict(
+ name='left_wrist',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 6:
+ dict(
+ name='right_hip',
+ id=6,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 7:
+ dict(
+ name='right_knee',
+ id=7,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 8:
+ dict(
+ name='right_ankle',
+ id=8,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 9:
+ dict(
+ name='left_hip',
+ id=9,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 10:
+ dict(
+ name='left_knee',
+ id=10,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 11:
+ dict(
+ name='left_ankle',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 12:
+ dict(
+ name='head_top',
+ id=12,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 13:
+ dict(name='neck', id=13, color=[51, 153, 255], type='upper', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_wrist', 'right_elbow'), id=0, color=[255, 128, 0]),
+ 1: dict(
+ link=('right_elbow', 'right_shoulder'), id=1, color=[255, 128, 0]),
+ 2: dict(link=('right_shoulder', 'neck'), id=2, color=[51, 153, 255]),
+ 3: dict(link=('neck', 'left_shoulder'), id=3, color=[51, 153, 255]),
+ 4: dict(link=('left_shoulder', 'left_elbow'), id=4, color=[0, 255, 0]),
+ 5: dict(link=('left_elbow', 'left_wrist'), id=5, color=[0, 255, 0]),
+ 6: dict(link=('right_ankle', 'right_knee'), id=6, color=[255, 128, 0]),
+ 7: dict(link=('right_knee', 'right_hip'), id=7, color=[255, 128, 0]),
+ 8: dict(link=('right_hip', 'left_hip'), id=8, color=[51, 153, 255]),
+ 9: dict(link=('left_hip', 'left_knee'), id=9, color=[0, 255, 0]),
+ 10: dict(link=('left_knee', 'left_ankle'), id=10, color=[0, 255, 0]),
+ 11: dict(link=('head_top', 'neck'), id=11, color=[51, 153, 255]),
+ 12: dict(
+ link=('right_shoulder', 'right_hip'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('left_shoulder', 'left_hip'), id=13, color=[51, 153, 255])
+ },
+ joint_weights=[
+ 1., 1.2, 1.5, 1., 1.2, 1.5, 1., 1.2, 1.5, 1., 1.2, 1.5, 1., 1.
+ ],
+
+ # 'https://github.com/AIChallenger/AI_Challenger_2017/blob/master/'
+ # 'Evaluation/keypoint_eval/keypoint_eval.py#L50'
+ # delta = 2 x sigma
+ sigmas=[
+ 0.01388152, 0.01515228, 0.01057665, 0.01417709, 0.01497891, 0.01402144,
+ 0.03909642, 0.03686941, 0.01981803, 0.03843971, 0.03412318, 0.02415081,
+ 0.01291456, 0.01236173
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/animalpose.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/animalpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5bb62d951b71da25e679bd755fe566216dc3f6f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/animalpose.py
@@ -0,0 +1,166 @@
+dataset_info = dict(
+ dataset_name='animalpose',
+ paper_info=dict(
+ author='Cao, Jinkun and Tang, Hongyang and Fang, Hao-Shu and '
+ 'Shen, Xiaoyong and Lu, Cewu and Tai, Yu-Wing',
+ title='Cross-Domain Adaptation for Animal Pose Estimation',
+ container='The IEEE International Conference on '
+ 'Computer Vision (ICCV)',
+ year='2019',
+ homepage='https://sites.google.com/view/animal-pose/',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='L_Eye', id=0, color=[0, 255, 0], type='upper', swap='R_Eye'),
+ 1:
+ dict(
+ name='R_Eye',
+ id=1,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_Eye'),
+ 2:
+ dict(
+ name='L_EarBase',
+ id=2,
+ color=[0, 255, 0],
+ type='upper',
+ swap='R_EarBase'),
+ 3:
+ dict(
+ name='R_EarBase',
+ id=3,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_EarBase'),
+ 4:
+ dict(name='Nose', id=4, color=[51, 153, 255], type='upper', swap=''),
+ 5:
+ dict(name='Throat', id=5, color=[51, 153, 255], type='upper', swap=''),
+ 6:
+ dict(
+ name='TailBase', id=6, color=[51, 153, 255], type='lower',
+ swap=''),
+ 7:
+ dict(
+ name='Withers', id=7, color=[51, 153, 255], type='upper', swap=''),
+ 8:
+ dict(
+ name='L_F_Elbow',
+ id=8,
+ color=[0, 255, 0],
+ type='upper',
+ swap='R_F_Elbow'),
+ 9:
+ dict(
+ name='R_F_Elbow',
+ id=9,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_F_Elbow'),
+ 10:
+ dict(
+ name='L_B_Elbow',
+ id=10,
+ color=[0, 255, 0],
+ type='lower',
+ swap='R_B_Elbow'),
+ 11:
+ dict(
+ name='R_B_Elbow',
+ id=11,
+ color=[255, 128, 0],
+ type='lower',
+ swap='L_B_Elbow'),
+ 12:
+ dict(
+ name='L_F_Knee',
+ id=12,
+ color=[0, 255, 0],
+ type='upper',
+ swap='R_F_Knee'),
+ 13:
+ dict(
+ name='R_F_Knee',
+ id=13,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_F_Knee'),
+ 14:
+ dict(
+ name='L_B_Knee',
+ id=14,
+ color=[0, 255, 0],
+ type='lower',
+ swap='R_B_Knee'),
+ 15:
+ dict(
+ name='R_B_Knee',
+ id=15,
+ color=[255, 128, 0],
+ type='lower',
+ swap='L_B_Knee'),
+ 16:
+ dict(
+ name='L_F_Paw',
+ id=16,
+ color=[0, 255, 0],
+ type='upper',
+ swap='R_F_Paw'),
+ 17:
+ dict(
+ name='R_F_Paw',
+ id=17,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_F_Paw'),
+ 18:
+ dict(
+ name='L_B_Paw',
+ id=18,
+ color=[0, 255, 0],
+ type='lower',
+ swap='R_B_Paw'),
+ 19:
+ dict(
+ name='R_B_Paw',
+ id=19,
+ color=[255, 128, 0],
+ type='lower',
+ swap='L_B_Paw')
+ },
+ skeleton_info={
+ 0: dict(link=('L_Eye', 'R_Eye'), id=0, color=[51, 153, 255]),
+ 1: dict(link=('L_Eye', 'L_EarBase'), id=1, color=[0, 255, 0]),
+ 2: dict(link=('R_Eye', 'R_EarBase'), id=2, color=[255, 128, 0]),
+ 3: dict(link=('L_Eye', 'Nose'), id=3, color=[0, 255, 0]),
+ 4: dict(link=('R_Eye', 'Nose'), id=4, color=[255, 128, 0]),
+ 5: dict(link=('Nose', 'Throat'), id=5, color=[51, 153, 255]),
+ 6: dict(link=('Throat', 'Withers'), id=6, color=[51, 153, 255]),
+ 7: dict(link=('TailBase', 'Withers'), id=7, color=[51, 153, 255]),
+ 8: dict(link=('Throat', 'L_F_Elbow'), id=8, color=[0, 255, 0]),
+ 9: dict(link=('L_F_Elbow', 'L_F_Knee'), id=9, color=[0, 255, 0]),
+ 10: dict(link=('L_F_Knee', 'L_F_Paw'), id=10, color=[0, 255, 0]),
+ 11: dict(link=('Throat', 'R_F_Elbow'), id=11, color=[255, 128, 0]),
+ 12: dict(link=('R_F_Elbow', 'R_F_Knee'), id=12, color=[255, 128, 0]),
+ 13: dict(link=('R_F_Knee', 'R_F_Paw'), id=13, color=[255, 128, 0]),
+ 14: dict(link=('TailBase', 'L_B_Elbow'), id=14, color=[0, 255, 0]),
+ 15: dict(link=('L_B_Elbow', 'L_B_Knee'), id=15, color=[0, 255, 0]),
+ 16: dict(link=('L_B_Knee', 'L_B_Paw'), id=16, color=[0, 255, 0]),
+ 17: dict(link=('TailBase', 'R_B_Elbow'), id=17, color=[255, 128, 0]),
+ 18: dict(link=('R_B_Elbow', 'R_B_Knee'), id=18, color=[255, 128, 0]),
+ 19: dict(link=('R_B_Knee', 'R_B_Paw'), id=19, color=[255, 128, 0])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.2, 1.2,
+ 1.5, 1.5, 1.5, 1.5
+ ],
+
+ # Note: The original paper did not provide enough information about
+ # the sigmas. We modified from 'https://github.com/cocodataset/'
+ # 'cocoapi/blob/master/PythonAPI/pycocotools/cocoeval.py#L523'
+ sigmas=[
+ 0.025, 0.025, 0.026, 0.035, 0.035, 0.10, 0.10, 0.10, 0.107, 0.107,
+ 0.107, 0.107, 0.087, 0.087, 0.087, 0.087, 0.089, 0.089, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ap10k.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ap10k.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0df579acbb8cf0de1ef62412ba865ee8710f0aa
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ap10k.py
@@ -0,0 +1,142 @@
+dataset_info = dict(
+ dataset_name='ap10k',
+ paper_info=dict(
+ author='Yu, Hang and Xu, Yufei and Zhang, Jing and '
+ 'Zhao, Wei and Guan, Ziyu and Tao, Dacheng',
+ title='AP-10K: A Benchmark for Animal Pose Estimation in the Wild',
+ container='35th Conference on Neural Information Processing Systems '
+ '(NeurIPS 2021) Track on Datasets and Bench-marks.',
+ year='2021',
+ homepage='https://github.com/AlexTheBad/AP-10K',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='L_Eye', id=0, color=[0, 255, 0], type='upper', swap='R_Eye'),
+ 1:
+ dict(
+ name='R_Eye',
+ id=1,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_Eye'),
+ 2:
+ dict(name='Nose', id=2, color=[51, 153, 255], type='upper', swap=''),
+ 3:
+ dict(name='Neck', id=3, color=[51, 153, 255], type='upper', swap=''),
+ 4:
+ dict(
+ name='Root of tail',
+ id=4,
+ color=[51, 153, 255],
+ type='lower',
+ swap=''),
+ 5:
+ dict(
+ name='L_Shoulder',
+ id=5,
+ color=[51, 153, 255],
+ type='upper',
+ swap='R_Shoulder'),
+ 6:
+ dict(
+ name='L_Elbow',
+ id=6,
+ color=[51, 153, 255],
+ type='upper',
+ swap='R_Elbow'),
+ 7:
+ dict(
+ name='L_F_Paw',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='R_F_Paw'),
+ 8:
+ dict(
+ name='R_Shoulder',
+ id=8,
+ color=[0, 255, 0],
+ type='upper',
+ swap='L_Shoulder'),
+ 9:
+ dict(
+ name='R_Elbow',
+ id=9,
+ color=[255, 128, 0],
+ type='upper',
+ swap='L_Elbow'),
+ 10:
+ dict(
+ name='R_F_Paw',
+ id=10,
+ color=[0, 255, 0],
+ type='lower',
+ swap='L_F_Paw'),
+ 11:
+ dict(
+ name='L_Hip',
+ id=11,
+ color=[255, 128, 0],
+ type='lower',
+ swap='R_Hip'),
+ 12:
+ dict(
+ name='L_Knee',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='R_Knee'),
+ 13:
+ dict(
+ name='L_B_Paw',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='R_B_Paw'),
+ 14:
+ dict(
+ name='R_Hip', id=14, color=[0, 255, 0], type='lower',
+ swap='L_Hip'),
+ 15:
+ dict(
+ name='R_Knee',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='L_Knee'),
+ 16:
+ dict(
+ name='R_B_Paw',
+ id=16,
+ color=[0, 255, 0],
+ type='lower',
+ swap='L_B_Paw'),
+ },
+ skeleton_info={
+ 0: dict(link=('L_Eye', 'R_Eye'), id=0, color=[0, 0, 255]),
+ 1: dict(link=('L_Eye', 'Nose'), id=1, color=[0, 0, 255]),
+ 2: dict(link=('R_Eye', 'Nose'), id=2, color=[0, 0, 255]),
+ 3: dict(link=('Nose', 'Neck'), id=3, color=[0, 255, 0]),
+ 4: dict(link=('Neck', 'Root of tail'), id=4, color=[0, 255, 0]),
+ 5: dict(link=('Neck', 'L_Shoulder'), id=5, color=[0, 255, 255]),
+ 6: dict(link=('L_Shoulder', 'L_Elbow'), id=6, color=[0, 255, 255]),
+ 7: dict(link=('L_Elbow', 'L_F_Paw'), id=6, color=[0, 255, 255]),
+ 8: dict(link=('Neck', 'R_Shoulder'), id=7, color=[6, 156, 250]),
+ 9: dict(link=('R_Shoulder', 'R_Elbow'), id=8, color=[6, 156, 250]),
+ 10: dict(link=('R_Elbow', 'R_F_Paw'), id=9, color=[6, 156, 250]),
+ 11: dict(link=('Root of tail', 'L_Hip'), id=10, color=[0, 255, 255]),
+ 12: dict(link=('L_Hip', 'L_Knee'), id=11, color=[0, 255, 255]),
+ 13: dict(link=('L_Knee', 'L_B_Paw'), id=12, color=[0, 255, 255]),
+ 14: dict(link=('Root of tail', 'R_Hip'), id=13, color=[6, 156, 250]),
+ 15: dict(link=('R_Hip', 'R_Knee'), id=14, color=[6, 156, 250]),
+ 16: dict(link=('R_Knee', 'R_B_Paw'), id=15, color=[6, 156, 250]),
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5,
+ 1.5
+ ],
+ sigmas=[
+ 0.025, 0.025, 0.026, 0.035, 0.035, 0.079, 0.072, 0.062, 0.079, 0.072,
+ 0.062, 0.107, 0.087, 0.089, 0.107, 0.087, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/atrw.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/atrw.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ec71c8c508a0340139371a651ca2dd56eeae3cf
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/atrw.py
@@ -0,0 +1,144 @@
+dataset_info = dict(
+ dataset_name='atrw',
+ paper_info=dict(
+ author='Li, Shuyuan and Li, Jianguo and Tang, Hanlin '
+ 'and Qian, Rui and Lin, Weiyao',
+ title='ATRW: A Benchmark for Amur Tiger '
+ 'Re-identification in the Wild',
+ container='Proceedings of the 28th ACM '
+ 'International Conference on Multimedia',
+ year='2020',
+ homepage='https://cvwc2019.github.io/challenge.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left_ear',
+ id=0,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 1:
+ dict(
+ name='right_ear',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 2:
+ dict(name='nose', id=2, color=[51, 153, 255], type='upper', swap=''),
+ 3:
+ dict(
+ name='right_shoulder',
+ id=3,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 4:
+ dict(
+ name='right_front_paw',
+ id=4,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_front_paw'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='left_front_paw',
+ id=6,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_front_paw'),
+ 7:
+ dict(
+ name='right_hip',
+ id=7,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 8:
+ dict(
+ name='right_knee',
+ id=8,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 9:
+ dict(
+ name='right_back_paw',
+ id=9,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_back_paw'),
+ 10:
+ dict(
+ name='left_hip',
+ id=10,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 11:
+ dict(
+ name='left_knee',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 12:
+ dict(
+ name='left_back_paw',
+ id=12,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_back_paw'),
+ 13:
+ dict(name='tail', id=13, color=[51, 153, 255], type='lower', swap=''),
+ 14:
+ dict(
+ name='center', id=14, color=[51, 153, 255], type='lower', swap=''),
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ear', 'nose'), id=0, color=[51, 153, 255]),
+ 1:
+ dict(link=('right_ear', 'nose'), id=1, color=[51, 153, 255]),
+ 2:
+ dict(link=('nose', 'center'), id=2, color=[51, 153, 255]),
+ 3:
+ dict(
+ link=('left_shoulder', 'left_front_paw'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(link=('left_shoulder', 'center'), id=4, color=[0, 255, 0]),
+ 5:
+ dict(
+ link=('right_shoulder', 'right_front_paw'),
+ id=5,
+ color=[255, 128, 0]),
+ 6:
+ dict(link=('right_shoulder', 'center'), id=6, color=[255, 128, 0]),
+ 7:
+ dict(link=('tail', 'center'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('right_back_paw', 'right_knee'), id=8, color=[255, 128, 0]),
+ 9:
+ dict(link=('right_knee', 'right_hip'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('right_hip', 'tail'), id=10, color=[255, 128, 0]),
+ 11:
+ dict(link=('left_back_paw', 'left_knee'), id=11, color=[0, 255, 0]),
+ 12:
+ dict(link=('left_knee', 'left_hip'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('left_hip', 'tail'), id=13, color=[0, 255, 0]),
+ },
+ joint_weights=[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.],
+ sigmas=[
+ 0.0277, 0.0823, 0.0831, 0.0202, 0.0716, 0.0263, 0.0646, 0.0302, 0.0440,
+ 0.0316, 0.0333, 0.0547, 0.0263, 0.0683, 0.0539
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/campus.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/campus.py
new file mode 100644
index 0000000000000000000000000000000000000000..334316e9c25282508767158d3fae30578ab3949d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/campus.py
@@ -0,0 +1,151 @@
+dataset_info = dict(
+ dataset_name='campus',
+ paper_info=dict(
+ author='Belagiannis, Vasileios and Amin, Sikandar and Andriluka, '
+ 'Mykhaylo and Schiele, Bernt and Navab, Nassir and Ilic, Slobodan',
+ title='3D Pictorial Structures for Multiple Human Pose Estimation',
+ container='IEEE Computer Society Conference on Computer Vision and '
+ 'Pattern Recognition (CVPR)',
+ year='2014',
+ homepage='http://campar.in.tum.de/Chair/MultiHumanPose',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_ankle',
+ id=0,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 1:
+ dict(
+ name='right_knee',
+ id=1,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 2:
+ dict(
+ name='right_hip',
+ id=2,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 3:
+ dict(
+ name='left_hip',
+ id=3,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 4:
+ dict(
+ name='left_knee',
+ id=4,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 5:
+ dict(
+ name='left_ankle',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 6:
+ dict(
+ name='right_wrist',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 7:
+ dict(
+ name='right_elbow',
+ id=7,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 8:
+ dict(
+ name='right_shoulder',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 9:
+ dict(
+ name='left_shoulder',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 10:
+ dict(
+ name='left_elbow',
+ id=10,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 11:
+ dict(
+ name='left_wrist',
+ id=11,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 12:
+ dict(
+ name='bottom_head',
+ id=12,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 13:
+ dict(
+ name='top_head',
+ id=13,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_ankle', 'right_knee'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('right_knee', 'right_hip'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('left_hip', 'left_knee'), id=2, color=[0, 255, 0]),
+ 3:
+ dict(link=('left_knee', 'left_ankle'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(link=('right_hip', 'left_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('right_wrist', 'right_elbow'), id=5, color=[255, 128, 0]),
+ 6:
+ dict(
+ link=('right_elbow', 'right_shoulder'), id=6, color=[255, 128, 0]),
+ 7:
+ dict(link=('left_shoulder', 'left_elbow'), id=7, color=[0, 255, 0]),
+ 8:
+ dict(link=('left_elbow', 'left_wrist'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(link=('right_hip', 'right_shoulder'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_hip', 'left_shoulder'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(
+ link=('right_shoulder', 'bottom_head'), id=11, color=[255, 128,
+ 0]),
+ 12:
+ dict(link=('left_shoulder', 'bottom_head'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('bottom_head', 'top_head'), id=13, color=[51, 153, 255]),
+ },
+ joint_weights=[
+ 1.5, 1.2, 1.0, 1.0, 1.2, 1.5, 1.5, 1.2, 1.0, 1.0, 1.2, 1.5, 1.0, 1.0
+ ],
+ sigmas=[
+ 0.089, 0.087, 0.107, 0.107, 0.087, 0.089, 0.062, 0.072, 0.079, 0.079,
+ 0.072, 0.062, 0.026, 0.026
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco.py
new file mode 100644
index 0000000000000000000000000000000000000000..865a95bc02fedd318f32d2e7aa8397147d78fdb5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco.py
@@ -0,0 +1,181 @@
+dataset_info = dict(
+ dataset_name='coco',
+ paper_info=dict(
+ author='Lin, Tsung-Yi and Maire, Michael and '
+ 'Belongie, Serge and Hays, James and '
+ 'Perona, Pietro and Ramanan, Deva and '
+ r'Doll{\'a}r, Piotr and Zitnick, C Lawrence',
+ title='Microsoft coco: Common objects in context',
+ container='European conference on computer vision',
+ year='2014',
+ homepage='http://cocodataset.org/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='left_eye',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 2:
+ dict(
+ name='right_eye',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('left_eye', 'right_eye'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('nose', 'left_eye'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(link=('nose', 'right_eye'), id=14, color=[51, 153, 255]),
+ 15:
+ dict(link=('left_eye', 'left_ear'), id=15, color=[51, 153, 255]),
+ 16:
+ dict(link=('right_eye', 'right_ear'), id=16, color=[51, 153, 255]),
+ 17:
+ dict(link=('left_ear', 'left_shoulder'), id=17, color=[51, 153, 255]),
+ 18:
+ dict(
+ link=('right_ear', 'right_shoulder'), id=18, color=[51, 153, 255])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5,
+ 1.5
+ ],
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef9b707017a24a1a133bb28566d212c618fee694
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody.py
@@ -0,0 +1,1154 @@
+dataset_info = dict(
+ dataset_name='coco_wholebody',
+ paper_info=dict(
+ author='Jin, Sheng and Xu, Lumin and Xu, Jin and '
+ 'Wang, Can and Liu, Wentao and '
+ 'Qian, Chen and Ouyang, Wanli and Luo, Ping',
+ title='Whole-Body Human Pose Estimation in the Wild',
+ container='Proceedings of the European '
+ 'Conference on Computer Vision (ECCV)',
+ year='2020',
+ homepage='https://github.com/jin-s13/COCO-WholeBody/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='left_eye',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 2:
+ dict(
+ name='right_eye',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 17:
+ dict(
+ name='left_big_toe',
+ id=17,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_big_toe'),
+ 18:
+ dict(
+ name='left_small_toe',
+ id=18,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_small_toe'),
+ 19:
+ dict(
+ name='left_heel',
+ id=19,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_heel'),
+ 20:
+ dict(
+ name='right_big_toe',
+ id=20,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_big_toe'),
+ 21:
+ dict(
+ name='right_small_toe',
+ id=21,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_small_toe'),
+ 22:
+ dict(
+ name='right_heel',
+ id=22,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_heel'),
+ 23:
+ dict(
+ name='face-0',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='face-16'),
+ 24:
+ dict(
+ name='face-1',
+ id=24,
+ color=[255, 255, 255],
+ type='',
+ swap='face-15'),
+ 25:
+ dict(
+ name='face-2',
+ id=25,
+ color=[255, 255, 255],
+ type='',
+ swap='face-14'),
+ 26:
+ dict(
+ name='face-3',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='face-13'),
+ 27:
+ dict(
+ name='face-4',
+ id=27,
+ color=[255, 255, 255],
+ type='',
+ swap='face-12'),
+ 28:
+ dict(
+ name='face-5',
+ id=28,
+ color=[255, 255, 255],
+ type='',
+ swap='face-11'),
+ 29:
+ dict(
+ name='face-6',
+ id=29,
+ color=[255, 255, 255],
+ type='',
+ swap='face-10'),
+ 30:
+ dict(
+ name='face-7',
+ id=30,
+ color=[255, 255, 255],
+ type='',
+ swap='face-9'),
+ 31:
+ dict(name='face-8', id=31, color=[255, 255, 255], type='', swap=''),
+ 32:
+ dict(
+ name='face-9',
+ id=32,
+ color=[255, 255, 255],
+ type='',
+ swap='face-7'),
+ 33:
+ dict(
+ name='face-10',
+ id=33,
+ color=[255, 255, 255],
+ type='',
+ swap='face-6'),
+ 34:
+ dict(
+ name='face-11',
+ id=34,
+ color=[255, 255, 255],
+ type='',
+ swap='face-5'),
+ 35:
+ dict(
+ name='face-12',
+ id=35,
+ color=[255, 255, 255],
+ type='',
+ swap='face-4'),
+ 36:
+ dict(
+ name='face-13',
+ id=36,
+ color=[255, 255, 255],
+ type='',
+ swap='face-3'),
+ 37:
+ dict(
+ name='face-14',
+ id=37,
+ color=[255, 255, 255],
+ type='',
+ swap='face-2'),
+ 38:
+ dict(
+ name='face-15',
+ id=38,
+ color=[255, 255, 255],
+ type='',
+ swap='face-1'),
+ 39:
+ dict(
+ name='face-16',
+ id=39,
+ color=[255, 255, 255],
+ type='',
+ swap='face-0'),
+ 40:
+ dict(
+ name='face-17',
+ id=40,
+ color=[255, 255, 255],
+ type='',
+ swap='face-26'),
+ 41:
+ dict(
+ name='face-18',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='face-25'),
+ 42:
+ dict(
+ name='face-19',
+ id=42,
+ color=[255, 255, 255],
+ type='',
+ swap='face-24'),
+ 43:
+ dict(
+ name='face-20',
+ id=43,
+ color=[255, 255, 255],
+ type='',
+ swap='face-23'),
+ 44:
+ dict(
+ name='face-21',
+ id=44,
+ color=[255, 255, 255],
+ type='',
+ swap='face-22'),
+ 45:
+ dict(
+ name='face-22',
+ id=45,
+ color=[255, 255, 255],
+ type='',
+ swap='face-21'),
+ 46:
+ dict(
+ name='face-23',
+ id=46,
+ color=[255, 255, 255],
+ type='',
+ swap='face-20'),
+ 47:
+ dict(
+ name='face-24',
+ id=47,
+ color=[255, 255, 255],
+ type='',
+ swap='face-19'),
+ 48:
+ dict(
+ name='face-25',
+ id=48,
+ color=[255, 255, 255],
+ type='',
+ swap='face-18'),
+ 49:
+ dict(
+ name='face-26',
+ id=49,
+ color=[255, 255, 255],
+ type='',
+ swap='face-17'),
+ 50:
+ dict(name='face-27', id=50, color=[255, 255, 255], type='', swap=''),
+ 51:
+ dict(name='face-28', id=51, color=[255, 255, 255], type='', swap=''),
+ 52:
+ dict(name='face-29', id=52, color=[255, 255, 255], type='', swap=''),
+ 53:
+ dict(name='face-30', id=53, color=[255, 255, 255], type='', swap=''),
+ 54:
+ dict(
+ name='face-31',
+ id=54,
+ color=[255, 255, 255],
+ type='',
+ swap='face-35'),
+ 55:
+ dict(
+ name='face-32',
+ id=55,
+ color=[255, 255, 255],
+ type='',
+ swap='face-34'),
+ 56:
+ dict(name='face-33', id=56, color=[255, 255, 255], type='', swap=''),
+ 57:
+ dict(
+ name='face-34',
+ id=57,
+ color=[255, 255, 255],
+ type='',
+ swap='face-32'),
+ 58:
+ dict(
+ name='face-35',
+ id=58,
+ color=[255, 255, 255],
+ type='',
+ swap='face-31'),
+ 59:
+ dict(
+ name='face-36',
+ id=59,
+ color=[255, 255, 255],
+ type='',
+ swap='face-45'),
+ 60:
+ dict(
+ name='face-37',
+ id=60,
+ color=[255, 255, 255],
+ type='',
+ swap='face-44'),
+ 61:
+ dict(
+ name='face-38',
+ id=61,
+ color=[255, 255, 255],
+ type='',
+ swap='face-43'),
+ 62:
+ dict(
+ name='face-39',
+ id=62,
+ color=[255, 255, 255],
+ type='',
+ swap='face-42'),
+ 63:
+ dict(
+ name='face-40',
+ id=63,
+ color=[255, 255, 255],
+ type='',
+ swap='face-47'),
+ 64:
+ dict(
+ name='face-41',
+ id=64,
+ color=[255, 255, 255],
+ type='',
+ swap='face-46'),
+ 65:
+ dict(
+ name='face-42',
+ id=65,
+ color=[255, 255, 255],
+ type='',
+ swap='face-39'),
+ 66:
+ dict(
+ name='face-43',
+ id=66,
+ color=[255, 255, 255],
+ type='',
+ swap='face-38'),
+ 67:
+ dict(
+ name='face-44',
+ id=67,
+ color=[255, 255, 255],
+ type='',
+ swap='face-37'),
+ 68:
+ dict(
+ name='face-45',
+ id=68,
+ color=[255, 255, 255],
+ type='',
+ swap='face-36'),
+ 69:
+ dict(
+ name='face-46',
+ id=69,
+ color=[255, 255, 255],
+ type='',
+ swap='face-41'),
+ 70:
+ dict(
+ name='face-47',
+ id=70,
+ color=[255, 255, 255],
+ type='',
+ swap='face-40'),
+ 71:
+ dict(
+ name='face-48',
+ id=71,
+ color=[255, 255, 255],
+ type='',
+ swap='face-54'),
+ 72:
+ dict(
+ name='face-49',
+ id=72,
+ color=[255, 255, 255],
+ type='',
+ swap='face-53'),
+ 73:
+ dict(
+ name='face-50',
+ id=73,
+ color=[255, 255, 255],
+ type='',
+ swap='face-52'),
+ 74:
+ dict(name='face-51', id=74, color=[255, 255, 255], type='', swap=''),
+ 75:
+ dict(
+ name='face-52',
+ id=75,
+ color=[255, 255, 255],
+ type='',
+ swap='face-50'),
+ 76:
+ dict(
+ name='face-53',
+ id=76,
+ color=[255, 255, 255],
+ type='',
+ swap='face-49'),
+ 77:
+ dict(
+ name='face-54',
+ id=77,
+ color=[255, 255, 255],
+ type='',
+ swap='face-48'),
+ 78:
+ dict(
+ name='face-55',
+ id=78,
+ color=[255, 255, 255],
+ type='',
+ swap='face-59'),
+ 79:
+ dict(
+ name='face-56',
+ id=79,
+ color=[255, 255, 255],
+ type='',
+ swap='face-58'),
+ 80:
+ dict(name='face-57', id=80, color=[255, 255, 255], type='', swap=''),
+ 81:
+ dict(
+ name='face-58',
+ id=81,
+ color=[255, 255, 255],
+ type='',
+ swap='face-56'),
+ 82:
+ dict(
+ name='face-59',
+ id=82,
+ color=[255, 255, 255],
+ type='',
+ swap='face-55'),
+ 83:
+ dict(
+ name='face-60',
+ id=83,
+ color=[255, 255, 255],
+ type='',
+ swap='face-64'),
+ 84:
+ dict(
+ name='face-61',
+ id=84,
+ color=[255, 255, 255],
+ type='',
+ swap='face-63'),
+ 85:
+ dict(name='face-62', id=85, color=[255, 255, 255], type='', swap=''),
+ 86:
+ dict(
+ name='face-63',
+ id=86,
+ color=[255, 255, 255],
+ type='',
+ swap='face-61'),
+ 87:
+ dict(
+ name='face-64',
+ id=87,
+ color=[255, 255, 255],
+ type='',
+ swap='face-60'),
+ 88:
+ dict(
+ name='face-65',
+ id=88,
+ color=[255, 255, 255],
+ type='',
+ swap='face-67'),
+ 89:
+ dict(name='face-66', id=89, color=[255, 255, 255], type='', swap=''),
+ 90:
+ dict(
+ name='face-67',
+ id=90,
+ color=[255, 255, 255],
+ type='',
+ swap='face-65'),
+ 91:
+ dict(
+ name='left_hand_root',
+ id=91,
+ color=[255, 255, 255],
+ type='',
+ swap='right_hand_root'),
+ 92:
+ dict(
+ name='left_thumb1',
+ id=92,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb1'),
+ 93:
+ dict(
+ name='left_thumb2',
+ id=93,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb2'),
+ 94:
+ dict(
+ name='left_thumb3',
+ id=94,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb3'),
+ 95:
+ dict(
+ name='left_thumb4',
+ id=95,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb4'),
+ 96:
+ dict(
+ name='left_forefinger1',
+ id=96,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger1'),
+ 97:
+ dict(
+ name='left_forefinger2',
+ id=97,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger2'),
+ 98:
+ dict(
+ name='left_forefinger3',
+ id=98,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger3'),
+ 99:
+ dict(
+ name='left_forefinger4',
+ id=99,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger4'),
+ 100:
+ dict(
+ name='left_middle_finger1',
+ id=100,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger1'),
+ 101:
+ dict(
+ name='left_middle_finger2',
+ id=101,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger2'),
+ 102:
+ dict(
+ name='left_middle_finger3',
+ id=102,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger3'),
+ 103:
+ dict(
+ name='left_middle_finger4',
+ id=103,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger4'),
+ 104:
+ dict(
+ name='left_ring_finger1',
+ id=104,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger1'),
+ 105:
+ dict(
+ name='left_ring_finger2',
+ id=105,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger2'),
+ 106:
+ dict(
+ name='left_ring_finger3',
+ id=106,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger3'),
+ 107:
+ dict(
+ name='left_ring_finger4',
+ id=107,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger4'),
+ 108:
+ dict(
+ name='left_pinky_finger1',
+ id=108,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger1'),
+ 109:
+ dict(
+ name='left_pinky_finger2',
+ id=109,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger2'),
+ 110:
+ dict(
+ name='left_pinky_finger3',
+ id=110,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger3'),
+ 111:
+ dict(
+ name='left_pinky_finger4',
+ id=111,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger4'),
+ 112:
+ dict(
+ name='right_hand_root',
+ id=112,
+ color=[255, 255, 255],
+ type='',
+ swap='left_hand_root'),
+ 113:
+ dict(
+ name='right_thumb1',
+ id=113,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb1'),
+ 114:
+ dict(
+ name='right_thumb2',
+ id=114,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb2'),
+ 115:
+ dict(
+ name='right_thumb3',
+ id=115,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb3'),
+ 116:
+ dict(
+ name='right_thumb4',
+ id=116,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb4'),
+ 117:
+ dict(
+ name='right_forefinger1',
+ id=117,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger1'),
+ 118:
+ dict(
+ name='right_forefinger2',
+ id=118,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger2'),
+ 119:
+ dict(
+ name='right_forefinger3',
+ id=119,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger3'),
+ 120:
+ dict(
+ name='right_forefinger4',
+ id=120,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger4'),
+ 121:
+ dict(
+ name='right_middle_finger1',
+ id=121,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger1'),
+ 122:
+ dict(
+ name='right_middle_finger2',
+ id=122,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger2'),
+ 123:
+ dict(
+ name='right_middle_finger3',
+ id=123,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger3'),
+ 124:
+ dict(
+ name='right_middle_finger4',
+ id=124,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger4'),
+ 125:
+ dict(
+ name='right_ring_finger1',
+ id=125,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger1'),
+ 126:
+ dict(
+ name='right_ring_finger2',
+ id=126,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger2'),
+ 127:
+ dict(
+ name='right_ring_finger3',
+ id=127,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger3'),
+ 128:
+ dict(
+ name='right_ring_finger4',
+ id=128,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger4'),
+ 129:
+ dict(
+ name='right_pinky_finger1',
+ id=129,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger1'),
+ 130:
+ dict(
+ name='right_pinky_finger2',
+ id=130,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger2'),
+ 131:
+ dict(
+ name='right_pinky_finger3',
+ id=131,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger3'),
+ 132:
+ dict(
+ name='right_pinky_finger4',
+ id=132,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger4')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('left_eye', 'right_eye'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('nose', 'left_eye'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(link=('nose', 'right_eye'), id=14, color=[51, 153, 255]),
+ 15:
+ dict(link=('left_eye', 'left_ear'), id=15, color=[51, 153, 255]),
+ 16:
+ dict(link=('right_eye', 'right_ear'), id=16, color=[51, 153, 255]),
+ 17:
+ dict(link=('left_ear', 'left_shoulder'), id=17, color=[51, 153, 255]),
+ 18:
+ dict(
+ link=('right_ear', 'right_shoulder'), id=18, color=[51, 153, 255]),
+ 19:
+ dict(link=('left_ankle', 'left_big_toe'), id=19, color=[0, 255, 0]),
+ 20:
+ dict(link=('left_ankle', 'left_small_toe'), id=20, color=[0, 255, 0]),
+ 21:
+ dict(link=('left_ankle', 'left_heel'), id=21, color=[0, 255, 0]),
+ 22:
+ dict(
+ link=('right_ankle', 'right_big_toe'), id=22, color=[255, 128, 0]),
+ 23:
+ dict(
+ link=('right_ankle', 'right_small_toe'),
+ id=23,
+ color=[255, 128, 0]),
+ 24:
+ dict(link=('right_ankle', 'right_heel'), id=24, color=[255, 128, 0]),
+ 25:
+ dict(
+ link=('left_hand_root', 'left_thumb1'), id=25, color=[255, 128,
+ 0]),
+ 26:
+ dict(link=('left_thumb1', 'left_thumb2'), id=26, color=[255, 128, 0]),
+ 27:
+ dict(link=('left_thumb2', 'left_thumb3'), id=27, color=[255, 128, 0]),
+ 28:
+ dict(link=('left_thumb3', 'left_thumb4'), id=28, color=[255, 128, 0]),
+ 29:
+ dict(
+ link=('left_hand_root', 'left_forefinger1'),
+ id=29,
+ color=[255, 153, 255]),
+ 30:
+ dict(
+ link=('left_forefinger1', 'left_forefinger2'),
+ id=30,
+ color=[255, 153, 255]),
+ 31:
+ dict(
+ link=('left_forefinger2', 'left_forefinger3'),
+ id=31,
+ color=[255, 153, 255]),
+ 32:
+ dict(
+ link=('left_forefinger3', 'left_forefinger4'),
+ id=32,
+ color=[255, 153, 255]),
+ 33:
+ dict(
+ link=('left_hand_root', 'left_middle_finger1'),
+ id=33,
+ color=[102, 178, 255]),
+ 34:
+ dict(
+ link=('left_middle_finger1', 'left_middle_finger2'),
+ id=34,
+ color=[102, 178, 255]),
+ 35:
+ dict(
+ link=('left_middle_finger2', 'left_middle_finger3'),
+ id=35,
+ color=[102, 178, 255]),
+ 36:
+ dict(
+ link=('left_middle_finger3', 'left_middle_finger4'),
+ id=36,
+ color=[102, 178, 255]),
+ 37:
+ dict(
+ link=('left_hand_root', 'left_ring_finger1'),
+ id=37,
+ color=[255, 51, 51]),
+ 38:
+ dict(
+ link=('left_ring_finger1', 'left_ring_finger2'),
+ id=38,
+ color=[255, 51, 51]),
+ 39:
+ dict(
+ link=('left_ring_finger2', 'left_ring_finger3'),
+ id=39,
+ color=[255, 51, 51]),
+ 40:
+ dict(
+ link=('left_ring_finger3', 'left_ring_finger4'),
+ id=40,
+ color=[255, 51, 51]),
+ 41:
+ dict(
+ link=('left_hand_root', 'left_pinky_finger1'),
+ id=41,
+ color=[0, 255, 0]),
+ 42:
+ dict(
+ link=('left_pinky_finger1', 'left_pinky_finger2'),
+ id=42,
+ color=[0, 255, 0]),
+ 43:
+ dict(
+ link=('left_pinky_finger2', 'left_pinky_finger3'),
+ id=43,
+ color=[0, 255, 0]),
+ 44:
+ dict(
+ link=('left_pinky_finger3', 'left_pinky_finger4'),
+ id=44,
+ color=[0, 255, 0]),
+ 45:
+ dict(
+ link=('right_hand_root', 'right_thumb1'),
+ id=45,
+ color=[255, 128, 0]),
+ 46:
+ dict(
+ link=('right_thumb1', 'right_thumb2'), id=46, color=[255, 128, 0]),
+ 47:
+ dict(
+ link=('right_thumb2', 'right_thumb3'), id=47, color=[255, 128, 0]),
+ 48:
+ dict(
+ link=('right_thumb3', 'right_thumb4'), id=48, color=[255, 128, 0]),
+ 49:
+ dict(
+ link=('right_hand_root', 'right_forefinger1'),
+ id=49,
+ color=[255, 153, 255]),
+ 50:
+ dict(
+ link=('right_forefinger1', 'right_forefinger2'),
+ id=50,
+ color=[255, 153, 255]),
+ 51:
+ dict(
+ link=('right_forefinger2', 'right_forefinger3'),
+ id=51,
+ color=[255, 153, 255]),
+ 52:
+ dict(
+ link=('right_forefinger3', 'right_forefinger4'),
+ id=52,
+ color=[255, 153, 255]),
+ 53:
+ dict(
+ link=('right_hand_root', 'right_middle_finger1'),
+ id=53,
+ color=[102, 178, 255]),
+ 54:
+ dict(
+ link=('right_middle_finger1', 'right_middle_finger2'),
+ id=54,
+ color=[102, 178, 255]),
+ 55:
+ dict(
+ link=('right_middle_finger2', 'right_middle_finger3'),
+ id=55,
+ color=[102, 178, 255]),
+ 56:
+ dict(
+ link=('right_middle_finger3', 'right_middle_finger4'),
+ id=56,
+ color=[102, 178, 255]),
+ 57:
+ dict(
+ link=('right_hand_root', 'right_ring_finger1'),
+ id=57,
+ color=[255, 51, 51]),
+ 58:
+ dict(
+ link=('right_ring_finger1', 'right_ring_finger2'),
+ id=58,
+ color=[255, 51, 51]),
+ 59:
+ dict(
+ link=('right_ring_finger2', 'right_ring_finger3'),
+ id=59,
+ color=[255, 51, 51]),
+ 60:
+ dict(
+ link=('right_ring_finger3', 'right_ring_finger4'),
+ id=60,
+ color=[255, 51, 51]),
+ 61:
+ dict(
+ link=('right_hand_root', 'right_pinky_finger1'),
+ id=61,
+ color=[0, 255, 0]),
+ 62:
+ dict(
+ link=('right_pinky_finger1', 'right_pinky_finger2'),
+ id=62,
+ color=[0, 255, 0]),
+ 63:
+ dict(
+ link=('right_pinky_finger2', 'right_pinky_finger3'),
+ id=63,
+ color=[0, 255, 0]),
+ 64:
+ dict(
+ link=('right_pinky_finger3', 'right_pinky_finger4'),
+ id=64,
+ color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 133,
+ # 'https://github.com/jin-s13/COCO-WholeBody/blob/master/'
+ # 'evaluation/myeval_wholebody.py#L175'
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089, 0.068, 0.066, 0.066,
+ 0.092, 0.094, 0.094, 0.042, 0.043, 0.044, 0.043, 0.040, 0.035, 0.031,
+ 0.025, 0.020, 0.023, 0.029, 0.032, 0.037, 0.038, 0.043, 0.041, 0.045,
+ 0.013, 0.012, 0.011, 0.011, 0.012, 0.012, 0.011, 0.011, 0.013, 0.015,
+ 0.009, 0.007, 0.007, 0.007, 0.012, 0.009, 0.008, 0.016, 0.010, 0.017,
+ 0.011, 0.009, 0.011, 0.009, 0.007, 0.013, 0.008, 0.011, 0.012, 0.010,
+ 0.034, 0.008, 0.008, 0.009, 0.008, 0.008, 0.007, 0.010, 0.008, 0.009,
+ 0.009, 0.009, 0.007, 0.007, 0.008, 0.011, 0.008, 0.008, 0.008, 0.01,
+ 0.008, 0.029, 0.022, 0.035, 0.037, 0.047, 0.026, 0.025, 0.024, 0.035,
+ 0.018, 0.024, 0.022, 0.026, 0.017, 0.021, 0.021, 0.032, 0.02, 0.019,
+ 0.022, 0.031, 0.029, 0.022, 0.035, 0.037, 0.047, 0.026, 0.025, 0.024,
+ 0.035, 0.018, 0.024, 0.022, 0.026, 0.017, 0.021, 0.021, 0.032, 0.02,
+ 0.019, 0.022, 0.031
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_face.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_face.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c9ee3350e3bd67ab1825344849487834c71c82b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_face.py
@@ -0,0 +1,448 @@
+dataset_info = dict(
+ dataset_name='coco_wholebody_face',
+ paper_info=dict(
+ author='Jin, Sheng and Xu, Lumin and Xu, Jin and '
+ 'Wang, Can and Liu, Wentao and '
+ 'Qian, Chen and Ouyang, Wanli and Luo, Ping',
+ title='Whole-Body Human Pose Estimation in the Wild',
+ container='Proceedings of the European '
+ 'Conference on Computer Vision (ECCV)',
+ year='2020',
+ homepage='https://github.com/jin-s13/COCO-WholeBody/',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='face-0',
+ id=0,
+ color=[255, 255, 255],
+ type='',
+ swap='face-16'),
+ 1:
+ dict(
+ name='face-1',
+ id=1,
+ color=[255, 255, 255],
+ type='',
+ swap='face-15'),
+ 2:
+ dict(
+ name='face-2',
+ id=2,
+ color=[255, 255, 255],
+ type='',
+ swap='face-14'),
+ 3:
+ dict(
+ name='face-3',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='face-13'),
+ 4:
+ dict(
+ name='face-4',
+ id=4,
+ color=[255, 255, 255],
+ type='',
+ swap='face-12'),
+ 5:
+ dict(
+ name='face-5',
+ id=5,
+ color=[255, 255, 255],
+ type='',
+ swap='face-11'),
+ 6:
+ dict(
+ name='face-6',
+ id=6,
+ color=[255, 255, 255],
+ type='',
+ swap='face-10'),
+ 7:
+ dict(
+ name='face-7', id=7, color=[255, 255, 255], type='',
+ swap='face-9'),
+ 8:
+ dict(name='face-8', id=8, color=[255, 255, 255], type='', swap=''),
+ 9:
+ dict(
+ name='face-9', id=9, color=[255, 255, 255], type='',
+ swap='face-7'),
+ 10:
+ dict(
+ name='face-10',
+ id=10,
+ color=[255, 255, 255],
+ type='',
+ swap='face-6'),
+ 11:
+ dict(
+ name='face-11',
+ id=11,
+ color=[255, 255, 255],
+ type='',
+ swap='face-5'),
+ 12:
+ dict(
+ name='face-12',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='face-4'),
+ 13:
+ dict(
+ name='face-13',
+ id=13,
+ color=[255, 255, 255],
+ type='',
+ swap='face-3'),
+ 14:
+ dict(
+ name='face-14',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='face-2'),
+ 15:
+ dict(
+ name='face-15',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='face-1'),
+ 16:
+ dict(
+ name='face-16',
+ id=16,
+ color=[255, 255, 255],
+ type='',
+ swap='face-0'),
+ 17:
+ dict(
+ name='face-17',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='face-26'),
+ 18:
+ dict(
+ name='face-18',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='face-25'),
+ 19:
+ dict(
+ name='face-19',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='face-24'),
+ 20:
+ dict(
+ name='face-20',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='face-23'),
+ 21:
+ dict(
+ name='face-21',
+ id=21,
+ color=[255, 255, 255],
+ type='',
+ swap='face-22'),
+ 22:
+ dict(
+ name='face-22',
+ id=22,
+ color=[255, 255, 255],
+ type='',
+ swap='face-21'),
+ 23:
+ dict(
+ name='face-23',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='face-20'),
+ 24:
+ dict(
+ name='face-24',
+ id=24,
+ color=[255, 255, 255],
+ type='',
+ swap='face-19'),
+ 25:
+ dict(
+ name='face-25',
+ id=25,
+ color=[255, 255, 255],
+ type='',
+ swap='face-18'),
+ 26:
+ dict(
+ name='face-26',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='face-17'),
+ 27:
+ dict(name='face-27', id=27, color=[255, 255, 255], type='', swap=''),
+ 28:
+ dict(name='face-28', id=28, color=[255, 255, 255], type='', swap=''),
+ 29:
+ dict(name='face-29', id=29, color=[255, 255, 255], type='', swap=''),
+ 30:
+ dict(name='face-30', id=30, color=[255, 255, 255], type='', swap=''),
+ 31:
+ dict(
+ name='face-31',
+ id=31,
+ color=[255, 255, 255],
+ type='',
+ swap='face-35'),
+ 32:
+ dict(
+ name='face-32',
+ id=32,
+ color=[255, 255, 255],
+ type='',
+ swap='face-34'),
+ 33:
+ dict(name='face-33', id=33, color=[255, 255, 255], type='', swap=''),
+ 34:
+ dict(
+ name='face-34',
+ id=34,
+ color=[255, 255, 255],
+ type='',
+ swap='face-32'),
+ 35:
+ dict(
+ name='face-35',
+ id=35,
+ color=[255, 255, 255],
+ type='',
+ swap='face-31'),
+ 36:
+ dict(
+ name='face-36',
+ id=36,
+ color=[255, 255, 255],
+ type='',
+ swap='face-45'),
+ 37:
+ dict(
+ name='face-37',
+ id=37,
+ color=[255, 255, 255],
+ type='',
+ swap='face-44'),
+ 38:
+ dict(
+ name='face-38',
+ id=38,
+ color=[255, 255, 255],
+ type='',
+ swap='face-43'),
+ 39:
+ dict(
+ name='face-39',
+ id=39,
+ color=[255, 255, 255],
+ type='',
+ swap='face-42'),
+ 40:
+ dict(
+ name='face-40',
+ id=40,
+ color=[255, 255, 255],
+ type='',
+ swap='face-47'),
+ 41:
+ dict(
+ name='face-41',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='face-46'),
+ 42:
+ dict(
+ name='face-42',
+ id=42,
+ color=[255, 255, 255],
+ type='',
+ swap='face-39'),
+ 43:
+ dict(
+ name='face-43',
+ id=43,
+ color=[255, 255, 255],
+ type='',
+ swap='face-38'),
+ 44:
+ dict(
+ name='face-44',
+ id=44,
+ color=[255, 255, 255],
+ type='',
+ swap='face-37'),
+ 45:
+ dict(
+ name='face-45',
+ id=45,
+ color=[255, 255, 255],
+ type='',
+ swap='face-36'),
+ 46:
+ dict(
+ name='face-46',
+ id=46,
+ color=[255, 255, 255],
+ type='',
+ swap='face-41'),
+ 47:
+ dict(
+ name='face-47',
+ id=47,
+ color=[255, 255, 255],
+ type='',
+ swap='face-40'),
+ 48:
+ dict(
+ name='face-48',
+ id=48,
+ color=[255, 255, 255],
+ type='',
+ swap='face-54'),
+ 49:
+ dict(
+ name='face-49',
+ id=49,
+ color=[255, 255, 255],
+ type='',
+ swap='face-53'),
+ 50:
+ dict(
+ name='face-50',
+ id=50,
+ color=[255, 255, 255],
+ type='',
+ swap='face-52'),
+ 51:
+ dict(name='face-51', id=52, color=[255, 255, 255], type='', swap=''),
+ 52:
+ dict(
+ name='face-52',
+ id=52,
+ color=[255, 255, 255],
+ type='',
+ swap='face-50'),
+ 53:
+ dict(
+ name='face-53',
+ id=53,
+ color=[255, 255, 255],
+ type='',
+ swap='face-49'),
+ 54:
+ dict(
+ name='face-54',
+ id=54,
+ color=[255, 255, 255],
+ type='',
+ swap='face-48'),
+ 55:
+ dict(
+ name='face-55',
+ id=55,
+ color=[255, 255, 255],
+ type='',
+ swap='face-59'),
+ 56:
+ dict(
+ name='face-56',
+ id=56,
+ color=[255, 255, 255],
+ type='',
+ swap='face-58'),
+ 57:
+ dict(name='face-57', id=57, color=[255, 255, 255], type='', swap=''),
+ 58:
+ dict(
+ name='face-58',
+ id=58,
+ color=[255, 255, 255],
+ type='',
+ swap='face-56'),
+ 59:
+ dict(
+ name='face-59',
+ id=59,
+ color=[255, 255, 255],
+ type='',
+ swap='face-55'),
+ 60:
+ dict(
+ name='face-60',
+ id=60,
+ color=[255, 255, 255],
+ type='',
+ swap='face-64'),
+ 61:
+ dict(
+ name='face-61',
+ id=61,
+ color=[255, 255, 255],
+ type='',
+ swap='face-63'),
+ 62:
+ dict(name='face-62', id=62, color=[255, 255, 255], type='', swap=''),
+ 63:
+ dict(
+ name='face-63',
+ id=63,
+ color=[255, 255, 255],
+ type='',
+ swap='face-61'),
+ 64:
+ dict(
+ name='face-64',
+ id=64,
+ color=[255, 255, 255],
+ type='',
+ swap='face-60'),
+ 65:
+ dict(
+ name='face-65',
+ id=65,
+ color=[255, 255, 255],
+ type='',
+ swap='face-67'),
+ 66:
+ dict(name='face-66', id=66, color=[255, 255, 255], type='', swap=''),
+ 67:
+ dict(
+ name='face-67',
+ id=67,
+ color=[255, 255, 255],
+ type='',
+ swap='face-65')
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 68,
+
+ # 'https://github.com/jin-s13/COCO-WholeBody/blob/master/'
+ # 'evaluation/myeval_wholebody.py#L177'
+ sigmas=[
+ 0.042, 0.043, 0.044, 0.043, 0.040, 0.035, 0.031, 0.025, 0.020, 0.023,
+ 0.029, 0.032, 0.037, 0.038, 0.043, 0.041, 0.045, 0.013, 0.012, 0.011,
+ 0.011, 0.012, 0.012, 0.011, 0.011, 0.013, 0.015, 0.009, 0.007, 0.007,
+ 0.007, 0.012, 0.009, 0.008, 0.016, 0.010, 0.017, 0.011, 0.009, 0.011,
+ 0.009, 0.007, 0.013, 0.008, 0.011, 0.012, 0.010, 0.034, 0.008, 0.008,
+ 0.009, 0.008, 0.008, 0.007, 0.010, 0.008, 0.009, 0.009, 0.009, 0.007,
+ 0.007, 0.008, 0.011, 0.008, 0.008, 0.008, 0.01, 0.008
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_hand.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_hand.py
new file mode 100644
index 0000000000000000000000000000000000000000..1910b2ced5a8b31cd6f83911e41cae9f1a580222
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/coco_wholebody_hand.py
@@ -0,0 +1,147 @@
+dataset_info = dict(
+ dataset_name='coco_wholebody_hand',
+ paper_info=dict(
+ author='Jin, Sheng and Xu, Lumin and Xu, Jin and '
+ 'Wang, Can and Liu, Wentao and '
+ 'Qian, Chen and Ouyang, Wanli and Luo, Ping',
+ title='Whole-Body Human Pose Estimation in the Wild',
+ container='Proceedings of the European '
+ 'Conference on Computer Vision (ECCV)',
+ year='2020',
+ homepage='https://github.com/jin-s13/COCO-WholeBody/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='wrist', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='thumb1', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb2', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb3', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(name='thumb4', id=4, color=[255, 128, 0], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger1', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger2', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger3', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='forefinger4', id=8, color=[255, 153, 255], type='', swap=''),
+ 9:
+ dict(
+ name='middle_finger1',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger3',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='middle_finger4',
+ id=12,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 13:
+ dict(
+ name='ring_finger1', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger2', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger3', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(
+ name='ring_finger4', id=16, color=[255, 51, 51], type='', swap=''),
+ 17:
+ dict(name='pinky_finger1', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger2', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger3', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='pinky_finger4', id=20, color=[0, 255, 0], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[
+ 0.029, 0.022, 0.035, 0.037, 0.047, 0.026, 0.025, 0.024, 0.035, 0.018,
+ 0.024, 0.022, 0.026, 0.017, 0.021, 0.021, 0.032, 0.02, 0.019, 0.022,
+ 0.031
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/cofw.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/cofw.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fb7ad2f8d1fdbe868b3691858a370e26b59a105
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/cofw.py
@@ -0,0 +1,134 @@
+dataset_info = dict(
+ dataset_name='cofw',
+ paper_info=dict(
+ author='Burgos-Artizzu, Xavier P and Perona, '
+ r'Pietro and Doll{\'a}r, Piotr',
+ title='Robust face landmark estimation under occlusion',
+ container='Proceedings of the IEEE international '
+ 'conference on computer vision',
+ year='2013',
+ homepage='http://www.vision.caltech.edu/xpburgos/ICCV13/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='kpt-0', id=0, color=[255, 255, 255], type='', swap='kpt-1'),
+ 1:
+ dict(name='kpt-1', id=1, color=[255, 255, 255], type='', swap='kpt-0'),
+ 2:
+ dict(name='kpt-2', id=2, color=[255, 255, 255], type='', swap='kpt-3'),
+ 3:
+ dict(name='kpt-3', id=3, color=[255, 255, 255], type='', swap='kpt-2'),
+ 4:
+ dict(name='kpt-4', id=4, color=[255, 255, 255], type='', swap='kpt-6'),
+ 5:
+ dict(name='kpt-5', id=5, color=[255, 255, 255], type='', swap='kpt-7'),
+ 6:
+ dict(name='kpt-6', id=6, color=[255, 255, 255], type='', swap='kpt-4'),
+ 7:
+ dict(name='kpt-7', id=7, color=[255, 255, 255], type='', swap='kpt-5'),
+ 8:
+ dict(name='kpt-8', id=8, color=[255, 255, 255], type='', swap='kpt-9'),
+ 9:
+ dict(name='kpt-9', id=9, color=[255, 255, 255], type='', swap='kpt-8'),
+ 10:
+ dict(
+ name='kpt-10',
+ id=10,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-11'),
+ 11:
+ dict(
+ name='kpt-11',
+ id=11,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-10'),
+ 12:
+ dict(
+ name='kpt-12',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-14'),
+ 13:
+ dict(
+ name='kpt-13',
+ id=13,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-15'),
+ 14:
+ dict(
+ name='kpt-14',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-12'),
+ 15:
+ dict(
+ name='kpt-15',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-13'),
+ 16:
+ dict(
+ name='kpt-16',
+ id=16,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-17'),
+ 17:
+ dict(
+ name='kpt-17',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-16'),
+ 18:
+ dict(
+ name='kpt-18',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-19'),
+ 19:
+ dict(
+ name='kpt-19',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-18'),
+ 20:
+ dict(name='kpt-20', id=20, color=[255, 255, 255], type='', swap=''),
+ 21:
+ dict(name='kpt-21', id=21, color=[255, 255, 255], type='', swap=''),
+ 22:
+ dict(
+ name='kpt-22',
+ id=22,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-23'),
+ 23:
+ dict(
+ name='kpt-23',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-22'),
+ 24:
+ dict(name='kpt-24', id=24, color=[255, 255, 255], type='', swap=''),
+ 25:
+ dict(name='kpt-25', id=25, color=[255, 255, 255], type='', swap=''),
+ 26:
+ dict(name='kpt-26', id=26, color=[255, 255, 255], type='', swap=''),
+ 27:
+ dict(name='kpt-27', id=27, color=[255, 255, 255], type='', swap=''),
+ 28:
+ dict(name='kpt-28', id=28, color=[255, 255, 255], type='', swap='')
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 29,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/crowdpose.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/crowdpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..45086531a601870716eed15a32c5413c0e24b7ae
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/crowdpose.py
@@ -0,0 +1,147 @@
+dataset_info = dict(
+ dataset_name='crowdpose',
+ paper_info=dict(
+ author='Li, Jiefeng and Wang, Can and Zhu, Hao and '
+ 'Mao, Yihuan and Fang, Hao-Shu and Lu, Cewu',
+ title='CrowdPose: Efficient Crowded Scenes Pose Estimation '
+ 'and A New Benchmark',
+ container='Proceedings of IEEE Conference on Computer '
+ 'Vision and Pattern Recognition (CVPR)',
+ year='2019',
+ homepage='https://github.com/Jeff-sjtu/CrowdPose',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left_shoulder',
+ id=0,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_shoulder'),
+ 1:
+ dict(
+ name='right_shoulder',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_shoulder'),
+ 2:
+ dict(
+ name='left_elbow',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_elbow'),
+ 3:
+ dict(
+ name='right_elbow',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_elbow'),
+ 4:
+ dict(
+ name='left_wrist',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_wrist'),
+ 5:
+ dict(
+ name='right_wrist',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='left_wrist'),
+ 6:
+ dict(
+ name='left_hip',
+ id=6,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_hip'),
+ 7:
+ dict(
+ name='right_hip',
+ id=7,
+ color=[0, 255, 0],
+ type='lower',
+ swap='left_hip'),
+ 8:
+ dict(
+ name='left_knee',
+ id=8,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_knee'),
+ 9:
+ dict(
+ name='right_knee',
+ id=9,
+ color=[0, 255, 0],
+ type='lower',
+ swap='left_knee'),
+ 10:
+ dict(
+ name='left_ankle',
+ id=10,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_ankle'),
+ 11:
+ dict(
+ name='right_ankle',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='left_ankle'),
+ 12:
+ dict(
+ name='top_head', id=12, color=[255, 128, 0], type='upper',
+ swap=''),
+ 13:
+ dict(name='neck', id=13, color=[0, 255, 0], type='upper', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('top_head', 'neck'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('right_shoulder', 'neck'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(link=('left_shoulder', 'neck'), id=14, color=[51, 153, 255])
+ },
+ joint_weights=[
+ 0.2, 0.2, 0.2, 1.3, 1.5, 0.2, 1.3, 1.5, 0.2, 0.2, 0.5, 0.2, 0.2, 0.5
+ ],
+ sigmas=[
+ 0.079, 0.079, 0.072, 0.072, 0.062, 0.062, 0.107, 0.107, 0.087, 0.087,
+ 0.089, 0.089, 0.079, 0.079
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_full.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_full.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d989069ee7253d3a5b5f01c81135b1a472cd4b2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_full.py
@@ -0,0 +1,74 @@
+dataset_info = dict(
+ dataset_name='deepfashion_full',
+ paper_info=dict(
+ author='Liu, Ziwei and Luo, Ping and Qiu, Shi '
+ 'and Wang, Xiaogang and Tang, Xiaoou',
+ title='DeepFashion: Powering Robust Clothes Recognition '
+ 'and Retrieval with Rich Annotations',
+ container='Proceedings of IEEE Conference on Computer '
+ 'Vision and Pattern Recognition (CVPR)',
+ year='2016',
+ homepage='http://mmlab.ie.cuhk.edu.hk/projects/'
+ 'DeepFashion/LandmarkDetection.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left collar',
+ id=0,
+ color=[255, 255, 255],
+ type='',
+ swap='right collar'),
+ 1:
+ dict(
+ name='right collar',
+ id=1,
+ color=[255, 255, 255],
+ type='',
+ swap='left collar'),
+ 2:
+ dict(
+ name='left sleeve',
+ id=2,
+ color=[255, 255, 255],
+ type='',
+ swap='right sleeve'),
+ 3:
+ dict(
+ name='right sleeve',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='left sleeve'),
+ 4:
+ dict(
+ name='left waistline',
+ id=0,
+ color=[255, 255, 255],
+ type='',
+ swap='right waistline'),
+ 5:
+ dict(
+ name='right waistline',
+ id=1,
+ color=[255, 255, 255],
+ type='',
+ swap='left waistline'),
+ 6:
+ dict(
+ name='left hem',
+ id=2,
+ color=[255, 255, 255],
+ type='',
+ swap='right hem'),
+ 7:
+ dict(
+ name='right hem',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='left hem'),
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 8,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_lower.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_lower.py
new file mode 100644
index 0000000000000000000000000000000000000000..db014a1747ca618f93a7d092d29027015b48ae3c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_lower.py
@@ -0,0 +1,46 @@
+dataset_info = dict(
+ dataset_name='deepfashion_lower',
+ paper_info=dict(
+ author='Liu, Ziwei and Luo, Ping and Qiu, Shi '
+ 'and Wang, Xiaogang and Tang, Xiaoou',
+ title='DeepFashion: Powering Robust Clothes Recognition '
+ 'and Retrieval with Rich Annotations',
+ container='Proceedings of IEEE Conference on Computer '
+ 'Vision and Pattern Recognition (CVPR)',
+ year='2016',
+ homepage='http://mmlab.ie.cuhk.edu.hk/projects/'
+ 'DeepFashion/LandmarkDetection.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left waistline',
+ id=0,
+ color=[255, 255, 255],
+ type='',
+ swap='right waistline'),
+ 1:
+ dict(
+ name='right waistline',
+ id=1,
+ color=[255, 255, 255],
+ type='',
+ swap='left waistline'),
+ 2:
+ dict(
+ name='left hem',
+ id=2,
+ color=[255, 255, 255],
+ type='',
+ swap='right hem'),
+ 3:
+ dict(
+ name='right hem',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='left hem'),
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 4,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_upper.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_upper.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b012fd37bee1ba5ed956a7a5465a8623bf0894
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/deepfashion_upper.py
@@ -0,0 +1,60 @@
+dataset_info = dict(
+ dataset_name='deepfashion_upper',
+ paper_info=dict(
+ author='Liu, Ziwei and Luo, Ping and Qiu, Shi '
+ 'and Wang, Xiaogang and Tang, Xiaoou',
+ title='DeepFashion: Powering Robust Clothes Recognition '
+ 'and Retrieval with Rich Annotations',
+ container='Proceedings of IEEE Conference on Computer '
+ 'Vision and Pattern Recognition (CVPR)',
+ year='2016',
+ homepage='http://mmlab.ie.cuhk.edu.hk/projects/'
+ 'DeepFashion/LandmarkDetection.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left collar',
+ id=0,
+ color=[255, 255, 255],
+ type='',
+ swap='right collar'),
+ 1:
+ dict(
+ name='right collar',
+ id=1,
+ color=[255, 255, 255],
+ type='',
+ swap='left collar'),
+ 2:
+ dict(
+ name='left sleeve',
+ id=2,
+ color=[255, 255, 255],
+ type='',
+ swap='right sleeve'),
+ 3:
+ dict(
+ name='right sleeve',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='left sleeve'),
+ 4:
+ dict(
+ name='left hem',
+ id=4,
+ color=[255, 255, 255],
+ type='',
+ swap='right hem'),
+ 5:
+ dict(
+ name='right hem',
+ id=5,
+ color=[255, 255, 255],
+ type='',
+ swap='left hem'),
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 6,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/fly.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/fly.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f94ff57ca93d8f562b6a61b9a67198abdcde217
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/fly.py
@@ -0,0 +1,237 @@
+dataset_info = dict(
+ dataset_name='fly',
+ paper_info=dict(
+ author='Pereira, Talmo D and Aldarondo, Diego E and '
+ 'Willmore, Lindsay and Kislin, Mikhail and '
+ 'Wang, Samuel S-H and Murthy, Mala and Shaevitz, Joshua W',
+ title='Fast animal pose estimation using deep neural networks',
+ container='Nature methods',
+ year='2019',
+ homepage='https://github.com/jgraving/DeepPoseKit-Data',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='head', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='eyeL', id=1, color=[255, 255, 255], type='', swap='eyeR'),
+ 2:
+ dict(name='eyeR', id=2, color=[255, 255, 255], type='', swap='eyeL'),
+ 3:
+ dict(name='neck', id=3, color=[255, 255, 255], type='', swap=''),
+ 4:
+ dict(name='thorax', id=4, color=[255, 255, 255], type='', swap=''),
+ 5:
+ dict(name='abdomen', id=5, color=[255, 255, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forelegR1',
+ id=6,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL1'),
+ 7:
+ dict(
+ name='forelegR2',
+ id=7,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL2'),
+ 8:
+ dict(
+ name='forelegR3',
+ id=8,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL3'),
+ 9:
+ dict(
+ name='forelegR4',
+ id=9,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL4'),
+ 10:
+ dict(
+ name='midlegR1',
+ id=10,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL1'),
+ 11:
+ dict(
+ name='midlegR2',
+ id=11,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL2'),
+ 12:
+ dict(
+ name='midlegR3',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL3'),
+ 13:
+ dict(
+ name='midlegR4',
+ id=13,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL4'),
+ 14:
+ dict(
+ name='hindlegR1',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL1'),
+ 15:
+ dict(
+ name='hindlegR2',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL2'),
+ 16:
+ dict(
+ name='hindlegR3',
+ id=16,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL3'),
+ 17:
+ dict(
+ name='hindlegR4',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL4'),
+ 18:
+ dict(
+ name='forelegL1',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR1'),
+ 19:
+ dict(
+ name='forelegL2',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR2'),
+ 20:
+ dict(
+ name='forelegL3',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR3'),
+ 21:
+ dict(
+ name='forelegL4',
+ id=21,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR4'),
+ 22:
+ dict(
+ name='midlegL1',
+ id=22,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR1'),
+ 23:
+ dict(
+ name='midlegL2',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR2'),
+ 24:
+ dict(
+ name='midlegL3',
+ id=24,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR3'),
+ 25:
+ dict(
+ name='midlegL4',
+ id=25,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR4'),
+ 26:
+ dict(
+ name='hindlegL1',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR1'),
+ 27:
+ dict(
+ name='hindlegL2',
+ id=27,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR2'),
+ 28:
+ dict(
+ name='hindlegL3',
+ id=28,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR3'),
+ 29:
+ dict(
+ name='hindlegL4',
+ id=29,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR4'),
+ 30:
+ dict(
+ name='wingL', id=30, color=[255, 255, 255], type='', swap='wingR'),
+ 31:
+ dict(
+ name='wingR', id=31, color=[255, 255, 255], type='', swap='wingL'),
+ },
+ skeleton_info={
+ 0: dict(link=('eyeL', 'head'), id=0, color=[255, 255, 255]),
+ 1: dict(link=('eyeR', 'head'), id=1, color=[255, 255, 255]),
+ 2: dict(link=('neck', 'head'), id=2, color=[255, 255, 255]),
+ 3: dict(link=('thorax', 'neck'), id=3, color=[255, 255, 255]),
+ 4: dict(link=('abdomen', 'thorax'), id=4, color=[255, 255, 255]),
+ 5: dict(link=('forelegR2', 'forelegR1'), id=5, color=[255, 255, 255]),
+ 6: dict(link=('forelegR3', 'forelegR2'), id=6, color=[255, 255, 255]),
+ 7: dict(link=('forelegR4', 'forelegR3'), id=7, color=[255, 255, 255]),
+ 8: dict(link=('midlegR2', 'midlegR1'), id=8, color=[255, 255, 255]),
+ 9: dict(link=('midlegR3', 'midlegR2'), id=9, color=[255, 255, 255]),
+ 10: dict(link=('midlegR4', 'midlegR3'), id=10, color=[255, 255, 255]),
+ 11:
+ dict(link=('hindlegR2', 'hindlegR1'), id=11, color=[255, 255, 255]),
+ 12:
+ dict(link=('hindlegR3', 'hindlegR2'), id=12, color=[255, 255, 255]),
+ 13:
+ dict(link=('hindlegR4', 'hindlegR3'), id=13, color=[255, 255, 255]),
+ 14:
+ dict(link=('forelegL2', 'forelegL1'), id=14, color=[255, 255, 255]),
+ 15:
+ dict(link=('forelegL3', 'forelegL2'), id=15, color=[255, 255, 255]),
+ 16:
+ dict(link=('forelegL4', 'forelegL3'), id=16, color=[255, 255, 255]),
+ 17: dict(link=('midlegL2', 'midlegL1'), id=17, color=[255, 255, 255]),
+ 18: dict(link=('midlegL3', 'midlegL2'), id=18, color=[255, 255, 255]),
+ 19: dict(link=('midlegL4', 'midlegL3'), id=19, color=[255, 255, 255]),
+ 20:
+ dict(link=('hindlegL2', 'hindlegL1'), id=20, color=[255, 255, 255]),
+ 21:
+ dict(link=('hindlegL3', 'hindlegL2'), id=21, color=[255, 255, 255]),
+ 22:
+ dict(link=('hindlegL4', 'hindlegL3'), id=22, color=[255, 255, 255]),
+ 23: dict(link=('wingL', 'neck'), id=23, color=[255, 255, 255]),
+ 24: dict(link=('wingR', 'neck'), id=24, color=[255, 255, 255])
+ },
+ joint_weights=[1.] * 32,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/freihand2d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/freihand2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b960d10f3538801531dbccdd67aeac6e73ac572
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/freihand2d.py
@@ -0,0 +1,144 @@
+dataset_info = dict(
+ dataset_name='freihand',
+ paper_info=dict(
+ author='Zimmermann, Christian and Ceylan, Duygu and '
+ 'Yang, Jimei and Russell, Bryan and '
+ 'Argus, Max and Brox, Thomas',
+ title='Freihand: A dataset for markerless capture of hand pose '
+ 'and shape from single rgb images',
+ container='Proceedings of the IEEE International '
+ 'Conference on Computer Vision',
+ year='2019',
+ homepage='https://lmb.informatik.uni-freiburg.de/projects/freihand/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='wrist', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='thumb1', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb2', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb3', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(name='thumb4', id=4, color=[255, 128, 0], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger1', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger2', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger3', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='forefinger4', id=8, color=[255, 153, 255], type='', swap=''),
+ 9:
+ dict(
+ name='middle_finger1',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger3',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='middle_finger4',
+ id=12,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 13:
+ dict(
+ name='ring_finger1', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger2', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger3', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(
+ name='ring_finger4', id=16, color=[255, 51, 51], type='', swap=''),
+ 17:
+ dict(name='pinky_finger1', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger2', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger3', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='pinky_finger4', id=20, color=[0, 255, 0], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/h36m.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/h36m.py
new file mode 100644
index 0000000000000000000000000000000000000000..00a719d8b19f9ff3c5ef98476d73216055bf9186
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/h36m.py
@@ -0,0 +1,152 @@
+dataset_info = dict(
+ dataset_name='h36m',
+ paper_info=dict(
+ author='Ionescu, Catalin and Papava, Dragos and '
+ 'Olaru, Vlad and Sminchisescu, Cristian',
+ title='Human3.6M: Large Scale Datasets and Predictive '
+ 'Methods for 3D Human Sensing in Natural Environments',
+ container='IEEE Transactions on Pattern Analysis and '
+ 'Machine Intelligence',
+ year='2014',
+ homepage='http://vision.imar.ro/human3.6m/description.php',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='root', id=0, color=[51, 153, 255], type='lower', swap=''),
+ 1:
+ dict(
+ name='right_hip',
+ id=1,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 2:
+ dict(
+ name='right_knee',
+ id=2,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 3:
+ dict(
+ name='right_foot',
+ id=3,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_foot'),
+ 4:
+ dict(
+ name='left_hip',
+ id=4,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 5:
+ dict(
+ name='left_knee',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 6:
+ dict(
+ name='left_foot',
+ id=6,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_foot'),
+ 7:
+ dict(name='spine', id=7, color=[51, 153, 255], type='upper', swap=''),
+ 8:
+ dict(name='thorax', id=8, color=[51, 153, 255], type='upper', swap=''),
+ 9:
+ dict(
+ name='neck_base',
+ id=9,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 10:
+ dict(name='head', id=10, color=[51, 153, 255], type='upper', swap=''),
+ 11:
+ dict(
+ name='left_shoulder',
+ id=11,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 12:
+ dict(
+ name='left_elbow',
+ id=12,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 13:
+ dict(
+ name='left_wrist',
+ id=13,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 14:
+ dict(
+ name='right_shoulder',
+ id=14,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 15:
+ dict(
+ name='right_elbow',
+ id=15,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 16:
+ dict(
+ name='right_wrist',
+ id=16,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('root', 'left_hip'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_hip', 'left_knee'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('left_knee', 'left_foot'), id=2, color=[0, 255, 0]),
+ 3:
+ dict(link=('root', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('right_hip', 'right_knee'), id=4, color=[255, 128, 0]),
+ 5:
+ dict(link=('right_knee', 'right_foot'), id=5, color=[255, 128, 0]),
+ 6:
+ dict(link=('root', 'spine'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(link=('spine', 'thorax'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('thorax', 'neck_base'), id=8, color=[51, 153, 255]),
+ 9:
+ dict(link=('neck_base', 'head'), id=9, color=[51, 153, 255]),
+ 10:
+ dict(link=('thorax', 'left_shoulder'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('left_shoulder', 'left_elbow'), id=11, color=[0, 255, 0]),
+ 12:
+ dict(link=('left_elbow', 'left_wrist'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('thorax', 'right_shoulder'), id=13, color=[255, 128, 0]),
+ 14:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=14, color=[255, 128,
+ 0]),
+ 15:
+ dict(link=('right_elbow', 'right_wrist'), id=15, color=[255, 128, 0])
+ },
+ joint_weights=[1.] * 17,
+ sigmas=[],
+ stats_info=dict(bbox_center=(528., 427.), bbox_scale=400.))
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/halpe.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/halpe.py
new file mode 100644
index 0000000000000000000000000000000000000000..1385fe81dc2190684f2142449c0f288f2cb74c1a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/halpe.py
@@ -0,0 +1,1157 @@
+dataset_info = dict(
+ dataset_name='halpe',
+ paper_info=dict(
+ author='Li, Yong-Lu and Xu, Liang and Liu, Xinpeng and Huang, Xijie'
+ ' and Xu, Yue and Wang, Shiyi and Fang, Hao-Shu'
+ ' and Ma, Ze and Chen, Mingyang and Lu, Cewu',
+ title='PaStaNet: Toward Human Activity Knowledge Engine',
+ container='CVPR',
+ year='2020',
+ homepage='https://github.com/Fang-Haoshu/Halpe-FullBody/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='left_eye',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 2:
+ dict(
+ name='right_eye',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 17:
+ dict(name='head', id=17, color=[255, 128, 0], type='upper', swap=''),
+ 18:
+ dict(name='neck', id=18, color=[255, 128, 0], type='upper', swap=''),
+ 19:
+ dict(name='hip', id=19, color=[255, 128, 0], type='lower', swap=''),
+ 20:
+ dict(
+ name='left_big_toe',
+ id=20,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_big_toe'),
+ 21:
+ dict(
+ name='right_big_toe',
+ id=21,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_big_toe'),
+ 22:
+ dict(
+ name='left_small_toe',
+ id=22,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_small_toe'),
+ 23:
+ dict(
+ name='right_small_toe',
+ id=23,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_small_toe'),
+ 24:
+ dict(
+ name='left_heel',
+ id=24,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_heel'),
+ 25:
+ dict(
+ name='right_heel',
+ id=25,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_heel'),
+ 26:
+ dict(
+ name='face-0',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='face-16'),
+ 27:
+ dict(
+ name='face-1',
+ id=27,
+ color=[255, 255, 255],
+ type='',
+ swap='face-15'),
+ 28:
+ dict(
+ name='face-2',
+ id=28,
+ color=[255, 255, 255],
+ type='',
+ swap='face-14'),
+ 29:
+ dict(
+ name='face-3',
+ id=29,
+ color=[255, 255, 255],
+ type='',
+ swap='face-13'),
+ 30:
+ dict(
+ name='face-4',
+ id=30,
+ color=[255, 255, 255],
+ type='',
+ swap='face-12'),
+ 31:
+ dict(
+ name='face-5',
+ id=31,
+ color=[255, 255, 255],
+ type='',
+ swap='face-11'),
+ 32:
+ dict(
+ name='face-6',
+ id=32,
+ color=[255, 255, 255],
+ type='',
+ swap='face-10'),
+ 33:
+ dict(
+ name='face-7',
+ id=33,
+ color=[255, 255, 255],
+ type='',
+ swap='face-9'),
+ 34:
+ dict(name='face-8', id=34, color=[255, 255, 255], type='', swap=''),
+ 35:
+ dict(
+ name='face-9',
+ id=35,
+ color=[255, 255, 255],
+ type='',
+ swap='face-7'),
+ 36:
+ dict(
+ name='face-10',
+ id=36,
+ color=[255, 255, 255],
+ type='',
+ swap='face-6'),
+ 37:
+ dict(
+ name='face-11',
+ id=37,
+ color=[255, 255, 255],
+ type='',
+ swap='face-5'),
+ 38:
+ dict(
+ name='face-12',
+ id=38,
+ color=[255, 255, 255],
+ type='',
+ swap='face-4'),
+ 39:
+ dict(
+ name='face-13',
+ id=39,
+ color=[255, 255, 255],
+ type='',
+ swap='face-3'),
+ 40:
+ dict(
+ name='face-14',
+ id=40,
+ color=[255, 255, 255],
+ type='',
+ swap='face-2'),
+ 41:
+ dict(
+ name='face-15',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='face-1'),
+ 42:
+ dict(
+ name='face-16',
+ id=42,
+ color=[255, 255, 255],
+ type='',
+ swap='face-0'),
+ 43:
+ dict(
+ name='face-17',
+ id=43,
+ color=[255, 255, 255],
+ type='',
+ swap='face-26'),
+ 44:
+ dict(
+ name='face-18',
+ id=44,
+ color=[255, 255, 255],
+ type='',
+ swap='face-25'),
+ 45:
+ dict(
+ name='face-19',
+ id=45,
+ color=[255, 255, 255],
+ type='',
+ swap='face-24'),
+ 46:
+ dict(
+ name='face-20',
+ id=46,
+ color=[255, 255, 255],
+ type='',
+ swap='face-23'),
+ 47:
+ dict(
+ name='face-21',
+ id=47,
+ color=[255, 255, 255],
+ type='',
+ swap='face-22'),
+ 48:
+ dict(
+ name='face-22',
+ id=48,
+ color=[255, 255, 255],
+ type='',
+ swap='face-21'),
+ 49:
+ dict(
+ name='face-23',
+ id=49,
+ color=[255, 255, 255],
+ type='',
+ swap='face-20'),
+ 50:
+ dict(
+ name='face-24',
+ id=50,
+ color=[255, 255, 255],
+ type='',
+ swap='face-19'),
+ 51:
+ dict(
+ name='face-25',
+ id=51,
+ color=[255, 255, 255],
+ type='',
+ swap='face-18'),
+ 52:
+ dict(
+ name='face-26',
+ id=52,
+ color=[255, 255, 255],
+ type='',
+ swap='face-17'),
+ 53:
+ dict(name='face-27', id=53, color=[255, 255, 255], type='', swap=''),
+ 54:
+ dict(name='face-28', id=54, color=[255, 255, 255], type='', swap=''),
+ 55:
+ dict(name='face-29', id=55, color=[255, 255, 255], type='', swap=''),
+ 56:
+ dict(name='face-30', id=56, color=[255, 255, 255], type='', swap=''),
+ 57:
+ dict(
+ name='face-31',
+ id=57,
+ color=[255, 255, 255],
+ type='',
+ swap='face-35'),
+ 58:
+ dict(
+ name='face-32',
+ id=58,
+ color=[255, 255, 255],
+ type='',
+ swap='face-34'),
+ 59:
+ dict(name='face-33', id=59, color=[255, 255, 255], type='', swap=''),
+ 60:
+ dict(
+ name='face-34',
+ id=60,
+ color=[255, 255, 255],
+ type='',
+ swap='face-32'),
+ 61:
+ dict(
+ name='face-35',
+ id=61,
+ color=[255, 255, 255],
+ type='',
+ swap='face-31'),
+ 62:
+ dict(
+ name='face-36',
+ id=62,
+ color=[255, 255, 255],
+ type='',
+ swap='face-45'),
+ 63:
+ dict(
+ name='face-37',
+ id=63,
+ color=[255, 255, 255],
+ type='',
+ swap='face-44'),
+ 64:
+ dict(
+ name='face-38',
+ id=64,
+ color=[255, 255, 255],
+ type='',
+ swap='face-43'),
+ 65:
+ dict(
+ name='face-39',
+ id=65,
+ color=[255, 255, 255],
+ type='',
+ swap='face-42'),
+ 66:
+ dict(
+ name='face-40',
+ id=66,
+ color=[255, 255, 255],
+ type='',
+ swap='face-47'),
+ 67:
+ dict(
+ name='face-41',
+ id=67,
+ color=[255, 255, 255],
+ type='',
+ swap='face-46'),
+ 68:
+ dict(
+ name='face-42',
+ id=68,
+ color=[255, 255, 255],
+ type='',
+ swap='face-39'),
+ 69:
+ dict(
+ name='face-43',
+ id=69,
+ color=[255, 255, 255],
+ type='',
+ swap='face-38'),
+ 70:
+ dict(
+ name='face-44',
+ id=70,
+ color=[255, 255, 255],
+ type='',
+ swap='face-37'),
+ 71:
+ dict(
+ name='face-45',
+ id=71,
+ color=[255, 255, 255],
+ type='',
+ swap='face-36'),
+ 72:
+ dict(
+ name='face-46',
+ id=72,
+ color=[255, 255, 255],
+ type='',
+ swap='face-41'),
+ 73:
+ dict(
+ name='face-47',
+ id=73,
+ color=[255, 255, 255],
+ type='',
+ swap='face-40'),
+ 74:
+ dict(
+ name='face-48',
+ id=74,
+ color=[255, 255, 255],
+ type='',
+ swap='face-54'),
+ 75:
+ dict(
+ name='face-49',
+ id=75,
+ color=[255, 255, 255],
+ type='',
+ swap='face-53'),
+ 76:
+ dict(
+ name='face-50',
+ id=76,
+ color=[255, 255, 255],
+ type='',
+ swap='face-52'),
+ 77:
+ dict(name='face-51', id=77, color=[255, 255, 255], type='', swap=''),
+ 78:
+ dict(
+ name='face-52',
+ id=78,
+ color=[255, 255, 255],
+ type='',
+ swap='face-50'),
+ 79:
+ dict(
+ name='face-53',
+ id=79,
+ color=[255, 255, 255],
+ type='',
+ swap='face-49'),
+ 80:
+ dict(
+ name='face-54',
+ id=80,
+ color=[255, 255, 255],
+ type='',
+ swap='face-48'),
+ 81:
+ dict(
+ name='face-55',
+ id=81,
+ color=[255, 255, 255],
+ type='',
+ swap='face-59'),
+ 82:
+ dict(
+ name='face-56',
+ id=82,
+ color=[255, 255, 255],
+ type='',
+ swap='face-58'),
+ 83:
+ dict(name='face-57', id=83, color=[255, 255, 255], type='', swap=''),
+ 84:
+ dict(
+ name='face-58',
+ id=84,
+ color=[255, 255, 255],
+ type='',
+ swap='face-56'),
+ 85:
+ dict(
+ name='face-59',
+ id=85,
+ color=[255, 255, 255],
+ type='',
+ swap='face-55'),
+ 86:
+ dict(
+ name='face-60',
+ id=86,
+ color=[255, 255, 255],
+ type='',
+ swap='face-64'),
+ 87:
+ dict(
+ name='face-61',
+ id=87,
+ color=[255, 255, 255],
+ type='',
+ swap='face-63'),
+ 88:
+ dict(name='face-62', id=88, color=[255, 255, 255], type='', swap=''),
+ 89:
+ dict(
+ name='face-63',
+ id=89,
+ color=[255, 255, 255],
+ type='',
+ swap='face-61'),
+ 90:
+ dict(
+ name='face-64',
+ id=90,
+ color=[255, 255, 255],
+ type='',
+ swap='face-60'),
+ 91:
+ dict(
+ name='face-65',
+ id=91,
+ color=[255, 255, 255],
+ type='',
+ swap='face-67'),
+ 92:
+ dict(name='face-66', id=92, color=[255, 255, 255], type='', swap=''),
+ 93:
+ dict(
+ name='face-67',
+ id=93,
+ color=[255, 255, 255],
+ type='',
+ swap='face-65'),
+ 94:
+ dict(
+ name='left_hand_root',
+ id=94,
+ color=[255, 255, 255],
+ type='',
+ swap='right_hand_root'),
+ 95:
+ dict(
+ name='left_thumb1',
+ id=95,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb1'),
+ 96:
+ dict(
+ name='left_thumb2',
+ id=96,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb2'),
+ 97:
+ dict(
+ name='left_thumb3',
+ id=97,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb3'),
+ 98:
+ dict(
+ name='left_thumb4',
+ id=98,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb4'),
+ 99:
+ dict(
+ name='left_forefinger1',
+ id=99,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger1'),
+ 100:
+ dict(
+ name='left_forefinger2',
+ id=100,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger2'),
+ 101:
+ dict(
+ name='left_forefinger3',
+ id=101,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger3'),
+ 102:
+ dict(
+ name='left_forefinger4',
+ id=102,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger4'),
+ 103:
+ dict(
+ name='left_middle_finger1',
+ id=103,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger1'),
+ 104:
+ dict(
+ name='left_middle_finger2',
+ id=104,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger2'),
+ 105:
+ dict(
+ name='left_middle_finger3',
+ id=105,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger3'),
+ 106:
+ dict(
+ name='left_middle_finger4',
+ id=106,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger4'),
+ 107:
+ dict(
+ name='left_ring_finger1',
+ id=107,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger1'),
+ 108:
+ dict(
+ name='left_ring_finger2',
+ id=108,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger2'),
+ 109:
+ dict(
+ name='left_ring_finger3',
+ id=109,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger3'),
+ 110:
+ dict(
+ name='left_ring_finger4',
+ id=110,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger4'),
+ 111:
+ dict(
+ name='left_pinky_finger1',
+ id=111,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger1'),
+ 112:
+ dict(
+ name='left_pinky_finger2',
+ id=112,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger2'),
+ 113:
+ dict(
+ name='left_pinky_finger3',
+ id=113,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger3'),
+ 114:
+ dict(
+ name='left_pinky_finger4',
+ id=114,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger4'),
+ 115:
+ dict(
+ name='right_hand_root',
+ id=115,
+ color=[255, 255, 255],
+ type='',
+ swap='left_hand_root'),
+ 116:
+ dict(
+ name='right_thumb1',
+ id=116,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb1'),
+ 117:
+ dict(
+ name='right_thumb2',
+ id=117,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb2'),
+ 118:
+ dict(
+ name='right_thumb3',
+ id=118,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb3'),
+ 119:
+ dict(
+ name='right_thumb4',
+ id=119,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb4'),
+ 120:
+ dict(
+ name='right_forefinger1',
+ id=120,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger1'),
+ 121:
+ dict(
+ name='right_forefinger2',
+ id=121,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger2'),
+ 122:
+ dict(
+ name='right_forefinger3',
+ id=122,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger3'),
+ 123:
+ dict(
+ name='right_forefinger4',
+ id=123,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger4'),
+ 124:
+ dict(
+ name='right_middle_finger1',
+ id=124,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger1'),
+ 125:
+ dict(
+ name='right_middle_finger2',
+ id=125,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger2'),
+ 126:
+ dict(
+ name='right_middle_finger3',
+ id=126,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger3'),
+ 127:
+ dict(
+ name='right_middle_finger4',
+ id=127,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger4'),
+ 128:
+ dict(
+ name='right_ring_finger1',
+ id=128,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger1'),
+ 129:
+ dict(
+ name='right_ring_finger2',
+ id=129,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger2'),
+ 130:
+ dict(
+ name='right_ring_finger3',
+ id=130,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger3'),
+ 131:
+ dict(
+ name='right_ring_finger4',
+ id=131,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger4'),
+ 132:
+ dict(
+ name='right_pinky_finger1',
+ id=132,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger1'),
+ 133:
+ dict(
+ name='right_pinky_finger2',
+ id=133,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger2'),
+ 134:
+ dict(
+ name='right_pinky_finger3',
+ id=134,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger3'),
+ 135:
+ dict(
+ name='right_pinky_finger4',
+ id=135,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger4')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('left_hip', 'hip'), id=2, color=[0, 255, 0]),
+ 3:
+ dict(link=('right_ankle', 'right_knee'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('right_knee', 'right_hip'), id=4, color=[255, 128, 0]),
+ 5:
+ dict(link=('right_hip', 'hip'), id=5, color=[255, 128, 0]),
+ 6:
+ dict(link=('head', 'neck'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(link=('neck', 'hip'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('neck', 'left_shoulder'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(link=('left_shoulder', 'left_elbow'), id=9, color=[0, 255, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('neck', 'right_shoulder'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=12, color=[255, 128,
+ 0]),
+ 13:
+ dict(link=('right_elbow', 'right_wrist'), id=13, color=[255, 128, 0]),
+ 14:
+ dict(link=('left_eye', 'right_eye'), id=14, color=[51, 153, 255]),
+ 15:
+ dict(link=('nose', 'left_eye'), id=15, color=[51, 153, 255]),
+ 16:
+ dict(link=('nose', 'right_eye'), id=16, color=[51, 153, 255]),
+ 17:
+ dict(link=('left_eye', 'left_ear'), id=17, color=[51, 153, 255]),
+ 18:
+ dict(link=('right_eye', 'right_ear'), id=18, color=[51, 153, 255]),
+ 19:
+ dict(link=('left_ear', 'left_shoulder'), id=19, color=[51, 153, 255]),
+ 20:
+ dict(
+ link=('right_ear', 'right_shoulder'), id=20, color=[51, 153, 255]),
+ 21:
+ dict(link=('left_ankle', 'left_big_toe'), id=21, color=[0, 255, 0]),
+ 22:
+ dict(link=('left_ankle', 'left_small_toe'), id=22, color=[0, 255, 0]),
+ 23:
+ dict(link=('left_ankle', 'left_heel'), id=23, color=[0, 255, 0]),
+ 24:
+ dict(
+ link=('right_ankle', 'right_big_toe'), id=24, color=[255, 128, 0]),
+ 25:
+ dict(
+ link=('right_ankle', 'right_small_toe'),
+ id=25,
+ color=[255, 128, 0]),
+ 26:
+ dict(link=('right_ankle', 'right_heel'), id=26, color=[255, 128, 0]),
+ 27:
+ dict(link=('left_wrist', 'left_thumb1'), id=27, color=[255, 128, 0]),
+ 28:
+ dict(link=('left_thumb1', 'left_thumb2'), id=28, color=[255, 128, 0]),
+ 29:
+ dict(link=('left_thumb2', 'left_thumb3'), id=29, color=[255, 128, 0]),
+ 30:
+ dict(link=('left_thumb3', 'left_thumb4'), id=30, color=[255, 128, 0]),
+ 31:
+ dict(
+ link=('left_wrist', 'left_forefinger1'),
+ id=31,
+ color=[255, 153, 255]),
+ 32:
+ dict(
+ link=('left_forefinger1', 'left_forefinger2'),
+ id=32,
+ color=[255, 153, 255]),
+ 33:
+ dict(
+ link=('left_forefinger2', 'left_forefinger3'),
+ id=33,
+ color=[255, 153, 255]),
+ 34:
+ dict(
+ link=('left_forefinger3', 'left_forefinger4'),
+ id=34,
+ color=[255, 153, 255]),
+ 35:
+ dict(
+ link=('left_wrist', 'left_middle_finger1'),
+ id=35,
+ color=[102, 178, 255]),
+ 36:
+ dict(
+ link=('left_middle_finger1', 'left_middle_finger2'),
+ id=36,
+ color=[102, 178, 255]),
+ 37:
+ dict(
+ link=('left_middle_finger2', 'left_middle_finger3'),
+ id=37,
+ color=[102, 178, 255]),
+ 38:
+ dict(
+ link=('left_middle_finger3', 'left_middle_finger4'),
+ id=38,
+ color=[102, 178, 255]),
+ 39:
+ dict(
+ link=('left_wrist', 'left_ring_finger1'),
+ id=39,
+ color=[255, 51, 51]),
+ 40:
+ dict(
+ link=('left_ring_finger1', 'left_ring_finger2'),
+ id=40,
+ color=[255, 51, 51]),
+ 41:
+ dict(
+ link=('left_ring_finger2', 'left_ring_finger3'),
+ id=41,
+ color=[255, 51, 51]),
+ 42:
+ dict(
+ link=('left_ring_finger3', 'left_ring_finger4'),
+ id=42,
+ color=[255, 51, 51]),
+ 43:
+ dict(
+ link=('left_wrist', 'left_pinky_finger1'),
+ id=43,
+ color=[0, 255, 0]),
+ 44:
+ dict(
+ link=('left_pinky_finger1', 'left_pinky_finger2'),
+ id=44,
+ color=[0, 255, 0]),
+ 45:
+ dict(
+ link=('left_pinky_finger2', 'left_pinky_finger3'),
+ id=45,
+ color=[0, 255, 0]),
+ 46:
+ dict(
+ link=('left_pinky_finger3', 'left_pinky_finger4'),
+ id=46,
+ color=[0, 255, 0]),
+ 47:
+ dict(link=('right_wrist', 'right_thumb1'), id=47, color=[255, 128, 0]),
+ 48:
+ dict(
+ link=('right_thumb1', 'right_thumb2'), id=48, color=[255, 128, 0]),
+ 49:
+ dict(
+ link=('right_thumb2', 'right_thumb3'), id=49, color=[255, 128, 0]),
+ 50:
+ dict(
+ link=('right_thumb3', 'right_thumb4'), id=50, color=[255, 128, 0]),
+ 51:
+ dict(
+ link=('right_wrist', 'right_forefinger1'),
+ id=51,
+ color=[255, 153, 255]),
+ 52:
+ dict(
+ link=('right_forefinger1', 'right_forefinger2'),
+ id=52,
+ color=[255, 153, 255]),
+ 53:
+ dict(
+ link=('right_forefinger2', 'right_forefinger3'),
+ id=53,
+ color=[255, 153, 255]),
+ 54:
+ dict(
+ link=('right_forefinger3', 'right_forefinger4'),
+ id=54,
+ color=[255, 153, 255]),
+ 55:
+ dict(
+ link=('right_wrist', 'right_middle_finger1'),
+ id=55,
+ color=[102, 178, 255]),
+ 56:
+ dict(
+ link=('right_middle_finger1', 'right_middle_finger2'),
+ id=56,
+ color=[102, 178, 255]),
+ 57:
+ dict(
+ link=('right_middle_finger2', 'right_middle_finger3'),
+ id=57,
+ color=[102, 178, 255]),
+ 58:
+ dict(
+ link=('right_middle_finger3', 'right_middle_finger4'),
+ id=58,
+ color=[102, 178, 255]),
+ 59:
+ dict(
+ link=('right_wrist', 'right_ring_finger1'),
+ id=59,
+ color=[255, 51, 51]),
+ 60:
+ dict(
+ link=('right_ring_finger1', 'right_ring_finger2'),
+ id=60,
+ color=[255, 51, 51]),
+ 61:
+ dict(
+ link=('right_ring_finger2', 'right_ring_finger3'),
+ id=61,
+ color=[255, 51, 51]),
+ 62:
+ dict(
+ link=('right_ring_finger3', 'right_ring_finger4'),
+ id=62,
+ color=[255, 51, 51]),
+ 63:
+ dict(
+ link=('right_wrist', 'right_pinky_finger1'),
+ id=63,
+ color=[0, 255, 0]),
+ 64:
+ dict(
+ link=('right_pinky_finger1', 'right_pinky_finger2'),
+ id=64,
+ color=[0, 255, 0]),
+ 65:
+ dict(
+ link=('right_pinky_finger2', 'right_pinky_finger3'),
+ id=65,
+ color=[0, 255, 0]),
+ 66:
+ dict(
+ link=('right_pinky_finger3', 'right_pinky_finger4'),
+ id=66,
+ color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 136,
+
+ # 'https://github.com/Fang-Haoshu/Halpe-FullBody/blob/master/'
+ # 'HalpeCOCOAPI/PythonAPI/halpecocotools/cocoeval.py#L245'
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089, 0.08, 0.08, 0.08,
+ 0.089, 0.089, 0.089, 0.089, 0.089, 0.089, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015, 0.015,
+ 0.015, 0.015, 0.015, 0.015, 0.015, 0.015
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/horse10.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/horse10.py
new file mode 100644
index 0000000000000000000000000000000000000000..a485bf191bc151b0d76e48f3e55eb8e2dda6c506
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/horse10.py
@@ -0,0 +1,201 @@
+dataset_info = dict(
+ dataset_name='horse10',
+ paper_info=dict(
+ author='Mathis, Alexander and Biasi, Thomas and '
+ 'Schneider, Steffen and '
+ 'Yuksekgonul, Mert and Rogers, Byron and '
+ 'Bethge, Matthias and '
+ 'Mathis, Mackenzie W',
+ title='Pretraining boosts out-of-domain robustness '
+ 'for pose estimation',
+ container='Proceedings of the IEEE/CVF Winter Conference on '
+ 'Applications of Computer Vision',
+ year='2021',
+ homepage='http://www.mackenziemathislab.org/horse10',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='Nose', id=0, color=[255, 153, 255], type='upper', swap=''),
+ 1:
+ dict(name='Eye', id=1, color=[255, 153, 255], type='upper', swap=''),
+ 2:
+ dict(
+ name='Nearknee',
+ id=2,
+ color=[255, 102, 255],
+ type='upper',
+ swap=''),
+ 3:
+ dict(
+ name='Nearfrontfetlock',
+ id=3,
+ color=[255, 102, 255],
+ type='upper',
+ swap=''),
+ 4:
+ dict(
+ name='Nearfrontfoot',
+ id=4,
+ color=[255, 102, 255],
+ type='upper',
+ swap=''),
+ 5:
+ dict(
+ name='Offknee', id=5, color=[255, 102, 255], type='upper',
+ swap=''),
+ 6:
+ dict(
+ name='Offfrontfetlock',
+ id=6,
+ color=[255, 102, 255],
+ type='upper',
+ swap=''),
+ 7:
+ dict(
+ name='Offfrontfoot',
+ id=7,
+ color=[255, 102, 255],
+ type='upper',
+ swap=''),
+ 8:
+ dict(
+ name='Shoulder',
+ id=8,
+ color=[255, 153, 255],
+ type='upper',
+ swap=''),
+ 9:
+ dict(
+ name='Midshoulder',
+ id=9,
+ color=[255, 153, 255],
+ type='upper',
+ swap=''),
+ 10:
+ dict(
+ name='Elbow', id=10, color=[255, 153, 255], type='upper', swap=''),
+ 11:
+ dict(
+ name='Girth', id=11, color=[255, 153, 255], type='upper', swap=''),
+ 12:
+ dict(
+ name='Wither', id=12, color=[255, 153, 255], type='upper',
+ swap=''),
+ 13:
+ dict(
+ name='Nearhindhock',
+ id=13,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 14:
+ dict(
+ name='Nearhindfetlock',
+ id=14,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 15:
+ dict(
+ name='Nearhindfoot',
+ id=15,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 16:
+ dict(name='Hip', id=16, color=[255, 153, 255], type='lower', swap=''),
+ 17:
+ dict(
+ name='Stifle', id=17, color=[255, 153, 255], type='lower',
+ swap=''),
+ 18:
+ dict(
+ name='Offhindhock',
+ id=18,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 19:
+ dict(
+ name='Offhindfetlock',
+ id=19,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 20:
+ dict(
+ name='Offhindfoot',
+ id=20,
+ color=[255, 51, 255],
+ type='lower',
+ swap=''),
+ 21:
+ dict(
+ name='Ischium',
+ id=21,
+ color=[255, 153, 255],
+ type='lower',
+ swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('Nose', 'Eye'), id=0, color=[255, 153, 255]),
+ 1:
+ dict(link=('Eye', 'Wither'), id=1, color=[255, 153, 255]),
+ 2:
+ dict(link=('Wither', 'Hip'), id=2, color=[255, 153, 255]),
+ 3:
+ dict(link=('Hip', 'Ischium'), id=3, color=[255, 153, 255]),
+ 4:
+ dict(link=('Ischium', 'Stifle'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('Stifle', 'Girth'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('Girth', 'Elbow'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('Elbow', 'Shoulder'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('Shoulder', 'Midshoulder'), id=8, color=[255, 153, 255]),
+ 9:
+ dict(link=('Midshoulder', 'Wither'), id=9, color=[255, 153, 255]),
+ 10:
+ dict(
+ link=('Nearknee', 'Nearfrontfetlock'),
+ id=10,
+ color=[255, 102, 255]),
+ 11:
+ dict(
+ link=('Nearfrontfetlock', 'Nearfrontfoot'),
+ id=11,
+ color=[255, 102, 255]),
+ 12:
+ dict(
+ link=('Offknee', 'Offfrontfetlock'), id=12, color=[255, 102, 255]),
+ 13:
+ dict(
+ link=('Offfrontfetlock', 'Offfrontfoot'),
+ id=13,
+ color=[255, 102, 255]),
+ 14:
+ dict(
+ link=('Nearhindhock', 'Nearhindfetlock'),
+ id=14,
+ color=[255, 51, 255]),
+ 15:
+ dict(
+ link=('Nearhindfetlock', 'Nearhindfoot'),
+ id=15,
+ color=[255, 51, 255]),
+ 16:
+ dict(
+ link=('Offhindhock', 'Offhindfetlock'),
+ id=16,
+ color=[255, 51, 255]),
+ 17:
+ dict(
+ link=('Offhindfetlock', 'Offhindfoot'),
+ id=17,
+ color=[255, 51, 255])
+ },
+ joint_weights=[1.] * 22,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand2d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..0134f07de5bf536eaffbf71155a7e6eb33b24f0a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand2d.py
@@ -0,0 +1,142 @@
+dataset_info = dict(
+ dataset_name='interhand2d',
+ paper_info=dict(
+ author='Moon, Gyeongsik and Yu, Shoou-I and Wen, He and '
+ 'Shiratori, Takaaki and Lee, Kyoung Mu',
+ title='InterHand2.6M: A dataset and baseline for 3D '
+ 'interacting hand pose estimation from a single RGB image',
+ container='arXiv',
+ year='2020',
+ homepage='https://mks0601.github.io/InterHand2.6M/',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='thumb4', id=0, color=[255, 128, 0], type='', swap=''),
+ 1:
+ dict(name='thumb3', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb2', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb1', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(
+ name='forefinger4', id=4, color=[255, 153, 255], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger3', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger2', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger1', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='middle_finger4',
+ id=8,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 9:
+ dict(
+ name='middle_finger3',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger1',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='ring_finger4', id=12, color=[255, 51, 51], type='', swap=''),
+ 13:
+ dict(
+ name='ring_finger3', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger2', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger1', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(name='pinky_finger4', id=16, color=[0, 255, 0], type='', swap=''),
+ 17:
+ dict(name='pinky_finger3', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger2', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger1', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='wrist', id=20, color=[255, 255, 255], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand3d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..e2bd8121c281c741ec9b980c7570ebef8a632993
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/interhand3d.py
@@ -0,0 +1,487 @@
+dataset_info = dict(
+ dataset_name='interhand3d',
+ paper_info=dict(
+ author='Moon, Gyeongsik and Yu, Shoou-I and Wen, He and '
+ 'Shiratori, Takaaki and Lee, Kyoung Mu',
+ title='InterHand2.6M: A dataset and baseline for 3D '
+ 'interacting hand pose estimation from a single RGB image',
+ container='arXiv',
+ year='2020',
+ homepage='https://mks0601.github.io/InterHand2.6M/',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_thumb4',
+ id=0,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb4'),
+ 1:
+ dict(
+ name='right_thumb3',
+ id=1,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb3'),
+ 2:
+ dict(
+ name='right_thumb2',
+ id=2,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb2'),
+ 3:
+ dict(
+ name='right_thumb1',
+ id=3,
+ color=[255, 128, 0],
+ type='',
+ swap='left_thumb1'),
+ 4:
+ dict(
+ name='right_forefinger4',
+ id=4,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger4'),
+ 5:
+ dict(
+ name='right_forefinger3',
+ id=5,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger3'),
+ 6:
+ dict(
+ name='right_forefinger2',
+ id=6,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger2'),
+ 7:
+ dict(
+ name='right_forefinger1',
+ id=7,
+ color=[255, 153, 255],
+ type='',
+ swap='left_forefinger1'),
+ 8:
+ dict(
+ name='right_middle_finger4',
+ id=8,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger4'),
+ 9:
+ dict(
+ name='right_middle_finger3',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger3'),
+ 10:
+ dict(
+ name='right_middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger2'),
+ 11:
+ dict(
+ name='right_middle_finger1',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap='left_middle_finger1'),
+ 12:
+ dict(
+ name='right_ring_finger4',
+ id=12,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger4'),
+ 13:
+ dict(
+ name='right_ring_finger3',
+ id=13,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger3'),
+ 14:
+ dict(
+ name='right_ring_finger2',
+ id=14,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger2'),
+ 15:
+ dict(
+ name='right_ring_finger1',
+ id=15,
+ color=[255, 51, 51],
+ type='',
+ swap='left_ring_finger1'),
+ 16:
+ dict(
+ name='right_pinky_finger4',
+ id=16,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger4'),
+ 17:
+ dict(
+ name='right_pinky_finger3',
+ id=17,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger3'),
+ 18:
+ dict(
+ name='right_pinky_finger2',
+ id=18,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger2'),
+ 19:
+ dict(
+ name='right_pinky_finger1',
+ id=19,
+ color=[0, 255, 0],
+ type='',
+ swap='left_pinky_finger1'),
+ 20:
+ dict(
+ name='right_wrist',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='left_wrist'),
+ 21:
+ dict(
+ name='left_thumb4',
+ id=21,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb4'),
+ 22:
+ dict(
+ name='left_thumb3',
+ id=22,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb3'),
+ 23:
+ dict(
+ name='left_thumb2',
+ id=23,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb2'),
+ 24:
+ dict(
+ name='left_thumb1',
+ id=24,
+ color=[255, 128, 0],
+ type='',
+ swap='right_thumb1'),
+ 25:
+ dict(
+ name='left_forefinger4',
+ id=25,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger4'),
+ 26:
+ dict(
+ name='left_forefinger3',
+ id=26,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger3'),
+ 27:
+ dict(
+ name='left_forefinger2',
+ id=27,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger2'),
+ 28:
+ dict(
+ name='left_forefinger1',
+ id=28,
+ color=[255, 153, 255],
+ type='',
+ swap='right_forefinger1'),
+ 29:
+ dict(
+ name='left_middle_finger4',
+ id=29,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger4'),
+ 30:
+ dict(
+ name='left_middle_finger3',
+ id=30,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger3'),
+ 31:
+ dict(
+ name='left_middle_finger2',
+ id=31,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger2'),
+ 32:
+ dict(
+ name='left_middle_finger1',
+ id=32,
+ color=[102, 178, 255],
+ type='',
+ swap='right_middle_finger1'),
+ 33:
+ dict(
+ name='left_ring_finger4',
+ id=33,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger4'),
+ 34:
+ dict(
+ name='left_ring_finger3',
+ id=34,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger3'),
+ 35:
+ dict(
+ name='left_ring_finger2',
+ id=35,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger2'),
+ 36:
+ dict(
+ name='left_ring_finger1',
+ id=36,
+ color=[255, 51, 51],
+ type='',
+ swap='right_ring_finger1'),
+ 37:
+ dict(
+ name='left_pinky_finger4',
+ id=37,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger4'),
+ 38:
+ dict(
+ name='left_pinky_finger3',
+ id=38,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger3'),
+ 39:
+ dict(
+ name='left_pinky_finger2',
+ id=39,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger2'),
+ 40:
+ dict(
+ name='left_pinky_finger1',
+ id=40,
+ color=[0, 255, 0],
+ type='',
+ swap='right_pinky_finger1'),
+ 41:
+ dict(
+ name='left_wrist',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='right_wrist'),
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_wrist', 'right_thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('right_thumb1', 'right_thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('right_thumb2', 'right_thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_thumb3', 'right_thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(
+ link=('right_wrist', 'right_forefinger1'),
+ id=4,
+ color=[255, 153, 255]),
+ 5:
+ dict(
+ link=('right_forefinger1', 'right_forefinger2'),
+ id=5,
+ color=[255, 153, 255]),
+ 6:
+ dict(
+ link=('right_forefinger2', 'right_forefinger3'),
+ id=6,
+ color=[255, 153, 255]),
+ 7:
+ dict(
+ link=('right_forefinger3', 'right_forefinger4'),
+ id=7,
+ color=[255, 153, 255]),
+ 8:
+ dict(
+ link=('right_wrist', 'right_middle_finger1'),
+ id=8,
+ color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('right_middle_finger1', 'right_middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('right_middle_finger2', 'right_middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('right_middle_finger3', 'right_middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(
+ link=('right_wrist', 'right_ring_finger1'),
+ id=12,
+ color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('right_ring_finger1', 'right_ring_finger2'),
+ id=13,
+ color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('right_ring_finger2', 'right_ring_finger3'),
+ id=14,
+ color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('right_ring_finger3', 'right_ring_finger4'),
+ id=15,
+ color=[255, 51, 51]),
+ 16:
+ dict(
+ link=('right_wrist', 'right_pinky_finger1'),
+ id=16,
+ color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('right_pinky_finger1', 'right_pinky_finger2'),
+ id=17,
+ color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('right_pinky_finger2', 'right_pinky_finger3'),
+ id=18,
+ color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('right_pinky_finger3', 'right_pinky_finger4'),
+ id=19,
+ color=[0, 255, 0]),
+ 20:
+ dict(link=('left_wrist', 'left_thumb1'), id=20, color=[255, 128, 0]),
+ 21:
+ dict(link=('left_thumb1', 'left_thumb2'), id=21, color=[255, 128, 0]),
+ 22:
+ dict(link=('left_thumb2', 'left_thumb3'), id=22, color=[255, 128, 0]),
+ 23:
+ dict(link=('left_thumb3', 'left_thumb4'), id=23, color=[255, 128, 0]),
+ 24:
+ dict(
+ link=('left_wrist', 'left_forefinger1'),
+ id=24,
+ color=[255, 153, 255]),
+ 25:
+ dict(
+ link=('left_forefinger1', 'left_forefinger2'),
+ id=25,
+ color=[255, 153, 255]),
+ 26:
+ dict(
+ link=('left_forefinger2', 'left_forefinger3'),
+ id=26,
+ color=[255, 153, 255]),
+ 27:
+ dict(
+ link=('left_forefinger3', 'left_forefinger4'),
+ id=27,
+ color=[255, 153, 255]),
+ 28:
+ dict(
+ link=('left_wrist', 'left_middle_finger1'),
+ id=28,
+ color=[102, 178, 255]),
+ 29:
+ dict(
+ link=('left_middle_finger1', 'left_middle_finger2'),
+ id=29,
+ color=[102, 178, 255]),
+ 30:
+ dict(
+ link=('left_middle_finger2', 'left_middle_finger3'),
+ id=30,
+ color=[102, 178, 255]),
+ 31:
+ dict(
+ link=('left_middle_finger3', 'left_middle_finger4'),
+ id=31,
+ color=[102, 178, 255]),
+ 32:
+ dict(
+ link=('left_wrist', 'left_ring_finger1'),
+ id=32,
+ color=[255, 51, 51]),
+ 33:
+ dict(
+ link=('left_ring_finger1', 'left_ring_finger2'),
+ id=33,
+ color=[255, 51, 51]),
+ 34:
+ dict(
+ link=('left_ring_finger2', 'left_ring_finger3'),
+ id=34,
+ color=[255, 51, 51]),
+ 35:
+ dict(
+ link=('left_ring_finger3', 'left_ring_finger4'),
+ id=35,
+ color=[255, 51, 51]),
+ 36:
+ dict(
+ link=('left_wrist', 'left_pinky_finger1'),
+ id=36,
+ color=[0, 255, 0]),
+ 37:
+ dict(
+ link=('left_pinky_finger1', 'left_pinky_finger2'),
+ id=37,
+ color=[0, 255, 0]),
+ 38:
+ dict(
+ link=('left_pinky_finger2', 'left_pinky_finger3'),
+ id=38,
+ color=[0, 255, 0]),
+ 39:
+ dict(
+ link=('left_pinky_finger3', 'left_pinky_finger4'),
+ id=39,
+ color=[0, 255, 0]),
+ },
+ joint_weights=[1.] * 42,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/jhmdb.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/jhmdb.py
new file mode 100644
index 0000000000000000000000000000000000000000..1b37488498a2bade1fa6f2ff6532fcd219071803
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/jhmdb.py
@@ -0,0 +1,129 @@
+dataset_info = dict(
+ dataset_name='jhmdb',
+ paper_info=dict(
+ author='H. Jhuang and J. Gall and S. Zuffi and '
+ 'C. Schmid and M. J. Black',
+ title='Towards understanding action recognition',
+ container='International Conf. on Computer Vision (ICCV)',
+ year='2013',
+ homepage='http://jhmdb.is.tue.mpg.de/dataset',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='neck', id=0, color=[255, 128, 0], type='upper', swap=''),
+ 1:
+ dict(name='belly', id=1, color=[255, 128, 0], type='upper', swap=''),
+ 2:
+ dict(name='head', id=2, color=[255, 128, 0], type='upper', swap=''),
+ 3:
+ dict(
+ name='right_shoulder',
+ id=3,
+ color=[0, 255, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 4:
+ dict(
+ name='left_shoulder',
+ id=4,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 5:
+ dict(
+ name='right_hip',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='left_hip'),
+ 6:
+ dict(
+ name='left_hip',
+ id=6,
+ color=[51, 153, 255],
+ type='lower',
+ swap='right_hip'),
+ 7:
+ dict(
+ name='right_elbow',
+ id=7,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_elbow'),
+ 8:
+ dict(
+ name='left_elbow',
+ id=8,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_elbow'),
+ 9:
+ dict(
+ name='right_knee',
+ id=9,
+ color=[51, 153, 255],
+ type='lower',
+ swap='left_knee'),
+ 10:
+ dict(
+ name='left_knee',
+ id=10,
+ color=[255, 128, 0],
+ type='lower',
+ swap='right_knee'),
+ 11:
+ dict(
+ name='right_wrist',
+ id=11,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 12:
+ dict(
+ name='left_wrist',
+ id=12,
+ color=[255, 128, 0],
+ type='upper',
+ swap='right_wrist'),
+ 13:
+ dict(
+ name='right_ankle',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='left_ankle'),
+ 14:
+ dict(
+ name='left_ankle',
+ id=14,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle')
+ },
+ skeleton_info={
+ 0: dict(link=('right_ankle', 'right_knee'), id=0, color=[255, 128, 0]),
+ 1: dict(link=('right_knee', 'right_hip'), id=1, color=[255, 128, 0]),
+ 2: dict(link=('right_hip', 'belly'), id=2, color=[255, 128, 0]),
+ 3: dict(link=('belly', 'left_hip'), id=3, color=[0, 255, 0]),
+ 4: dict(link=('left_hip', 'left_knee'), id=4, color=[0, 255, 0]),
+ 5: dict(link=('left_knee', 'left_ankle'), id=5, color=[0, 255, 0]),
+ 6: dict(link=('belly', 'neck'), id=6, color=[51, 153, 255]),
+ 7: dict(link=('neck', 'head'), id=7, color=[51, 153, 255]),
+ 8: dict(link=('neck', 'right_shoulder'), id=8, color=[255, 128, 0]),
+ 9: dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('right_elbow', 'right_wrist'), id=10, color=[255, 128, 0]),
+ 11: dict(link=('neck', 'left_shoulder'), id=11, color=[0, 255, 0]),
+ 12:
+ dict(link=('left_shoulder', 'left_elbow'), id=12, color=[0, 255, 0]),
+ 13: dict(link=('left_elbow', 'left_wrist'), id=13, color=[0, 255, 0])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.2, 1.2, 1.5, 1.5, 1.5, 1.5
+ ],
+ # Adapted from COCO dataset.
+ sigmas=[
+ 0.025, 0.107, 0.025, 0.079, 0.079, 0.107, 0.107, 0.072, 0.072, 0.087,
+ 0.087, 0.062, 0.062, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/locust.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/locust.py
new file mode 100644
index 0000000000000000000000000000000000000000..db3fa15aa060b5806faae7a21f65460f77be2745
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/locust.py
@@ -0,0 +1,263 @@
+dataset_info = dict(
+ dataset_name='locust',
+ paper_info=dict(
+ author='Graving, Jacob M and Chae, Daniel and Naik, Hemal and '
+ 'Li, Liang and Koger, Benjamin and Costelloe, Blair R and '
+ 'Couzin, Iain D',
+ title='DeepPoseKit, a software toolkit for fast and robust '
+ 'animal pose estimation using deep learning',
+ container='Elife',
+ year='2019',
+ homepage='https://github.com/jgraving/DeepPoseKit-Data',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='head', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='neck', id=1, color=[255, 255, 255], type='', swap=''),
+ 2:
+ dict(name='thorax', id=2, color=[255, 255, 255], type='', swap=''),
+ 3:
+ dict(name='abdomen1', id=3, color=[255, 255, 255], type='', swap=''),
+ 4:
+ dict(name='abdomen2', id=4, color=[255, 255, 255], type='', swap=''),
+ 5:
+ dict(
+ name='anttipL',
+ id=5,
+ color=[255, 255, 255],
+ type='',
+ swap='anttipR'),
+ 6:
+ dict(
+ name='antbaseL',
+ id=6,
+ color=[255, 255, 255],
+ type='',
+ swap='antbaseR'),
+ 7:
+ dict(name='eyeL', id=7, color=[255, 255, 255], type='', swap='eyeR'),
+ 8:
+ dict(
+ name='forelegL1',
+ id=8,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR1'),
+ 9:
+ dict(
+ name='forelegL2',
+ id=9,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR2'),
+ 10:
+ dict(
+ name='forelegL3',
+ id=10,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR3'),
+ 11:
+ dict(
+ name='forelegL4',
+ id=11,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR4'),
+ 12:
+ dict(
+ name='midlegL1',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR1'),
+ 13:
+ dict(
+ name='midlegL2',
+ id=13,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR2'),
+ 14:
+ dict(
+ name='midlegL3',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR3'),
+ 15:
+ dict(
+ name='midlegL4',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegR4'),
+ 16:
+ dict(
+ name='hindlegL1',
+ id=16,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR1'),
+ 17:
+ dict(
+ name='hindlegL2',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR2'),
+ 18:
+ dict(
+ name='hindlegL3',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR3'),
+ 19:
+ dict(
+ name='hindlegL4',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR4'),
+ 20:
+ dict(
+ name='anttipR',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='anttipL'),
+ 21:
+ dict(
+ name='antbaseR',
+ id=21,
+ color=[255, 255, 255],
+ type='',
+ swap='antbaseL'),
+ 22:
+ dict(name='eyeR', id=22, color=[255, 255, 255], type='', swap='eyeL'),
+ 23:
+ dict(
+ name='forelegR1',
+ id=23,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL1'),
+ 24:
+ dict(
+ name='forelegR2',
+ id=24,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL2'),
+ 25:
+ dict(
+ name='forelegR3',
+ id=25,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL3'),
+ 26:
+ dict(
+ name='forelegR4',
+ id=26,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL4'),
+ 27:
+ dict(
+ name='midlegR1',
+ id=27,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL1'),
+ 28:
+ dict(
+ name='midlegR2',
+ id=28,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL2'),
+ 29:
+ dict(
+ name='midlegR3',
+ id=29,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL3'),
+ 30:
+ dict(
+ name='midlegR4',
+ id=30,
+ color=[255, 255, 255],
+ type='',
+ swap='midlegL4'),
+ 31:
+ dict(
+ name='hindlegR1',
+ id=31,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL1'),
+ 32:
+ dict(
+ name='hindlegR2',
+ id=32,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL2'),
+ 33:
+ dict(
+ name='hindlegR3',
+ id=33,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL3'),
+ 34:
+ dict(
+ name='hindlegR4',
+ id=34,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL4')
+ },
+ skeleton_info={
+ 0: dict(link=('neck', 'head'), id=0, color=[255, 255, 255]),
+ 1: dict(link=('thorax', 'neck'), id=1, color=[255, 255, 255]),
+ 2: dict(link=('abdomen1', 'thorax'), id=2, color=[255, 255, 255]),
+ 3: dict(link=('abdomen2', 'abdomen1'), id=3, color=[255, 255, 255]),
+ 4: dict(link=('antbaseL', 'anttipL'), id=4, color=[255, 255, 255]),
+ 5: dict(link=('eyeL', 'antbaseL'), id=5, color=[255, 255, 255]),
+ 6: dict(link=('forelegL2', 'forelegL1'), id=6, color=[255, 255, 255]),
+ 7: dict(link=('forelegL3', 'forelegL2'), id=7, color=[255, 255, 255]),
+ 8: dict(link=('forelegL4', 'forelegL3'), id=8, color=[255, 255, 255]),
+ 9: dict(link=('midlegL2', 'midlegL1'), id=9, color=[255, 255, 255]),
+ 10: dict(link=('midlegL3', 'midlegL2'), id=10, color=[255, 255, 255]),
+ 11: dict(link=('midlegL4', 'midlegL3'), id=11, color=[255, 255, 255]),
+ 12:
+ dict(link=('hindlegL2', 'hindlegL1'), id=12, color=[255, 255, 255]),
+ 13:
+ dict(link=('hindlegL3', 'hindlegL2'), id=13, color=[255, 255, 255]),
+ 14:
+ dict(link=('hindlegL4', 'hindlegL3'), id=14, color=[255, 255, 255]),
+ 15: dict(link=('antbaseR', 'anttipR'), id=15, color=[255, 255, 255]),
+ 16: dict(link=('eyeR', 'antbaseR'), id=16, color=[255, 255, 255]),
+ 17:
+ dict(link=('forelegR2', 'forelegR1'), id=17, color=[255, 255, 255]),
+ 18:
+ dict(link=('forelegR3', 'forelegR2'), id=18, color=[255, 255, 255]),
+ 19:
+ dict(link=('forelegR4', 'forelegR3'), id=19, color=[255, 255, 255]),
+ 20: dict(link=('midlegR2', 'midlegR1'), id=20, color=[255, 255, 255]),
+ 21: dict(link=('midlegR3', 'midlegR2'), id=21, color=[255, 255, 255]),
+ 22: dict(link=('midlegR4', 'midlegR3'), id=22, color=[255, 255, 255]),
+ 23:
+ dict(link=('hindlegR2', 'hindlegR1'), id=23, color=[255, 255, 255]),
+ 24:
+ dict(link=('hindlegR3', 'hindlegR2'), id=24, color=[255, 255, 255]),
+ 25:
+ dict(link=('hindlegR4', 'hindlegR3'), id=25, color=[255, 255, 255])
+ },
+ joint_weights=[1.] * 35,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/macaque.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/macaque.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea8dac297ea2f0e36dabccccc021d953216a6ac8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/macaque.py
@@ -0,0 +1,183 @@
+dataset_info = dict(
+ dataset_name='macaque',
+ paper_info=dict(
+ author='Labuguen, Rollyn and Matsumoto, Jumpei and '
+ 'Negrete, Salvador and Nishimaru, Hiroshi and '
+ 'Nishijo, Hisao and Takada, Masahiko and '
+ 'Go, Yasuhiro and Inoue, Ken-ichi and Shibata, Tomohiro',
+ title='MacaquePose: A novel "in the wild" macaque monkey pose dataset '
+ 'for markerless motion capture',
+ container='bioRxiv',
+ year='2020',
+ homepage='http://www.pri.kyoto-u.ac.jp/datasets/'
+ 'macaquepose/index.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='left_eye',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 2:
+ dict(
+ name='right_eye',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('left_eye', 'right_eye'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('nose', 'left_eye'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(link=('nose', 'right_eye'), id=14, color=[51, 153, 255]),
+ 15:
+ dict(link=('left_eye', 'left_ear'), id=15, color=[51, 153, 255]),
+ 16:
+ dict(link=('right_eye', 'right_ear'), id=16, color=[51, 153, 255]),
+ 17:
+ dict(link=('left_ear', 'left_shoulder'), id=17, color=[51, 153, 255]),
+ 18:
+ dict(
+ link=('right_ear', 'right_shoulder'), id=18, color=[51, 153, 255])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5,
+ 1.5
+ ],
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mhp.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mhp.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16e37c79cb63c4352c48bb4e45602b8408f534b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mhp.py
@@ -0,0 +1,156 @@
+dataset_info = dict(
+ dataset_name='mhp',
+ paper_info=dict(
+ author='Zhao, Jian and Li, Jianshu and Cheng, Yu and '
+ 'Sim, Terence and Yan, Shuicheng and Feng, Jiashi',
+ title='Understanding humans in crowded scenes: '
+ 'Deep nested adversarial learning and a '
+ 'new benchmark for multi-human parsing',
+ container='Proceedings of the 26th ACM '
+ 'international conference on Multimedia',
+ year='2018',
+ homepage='https://lv-mhp.github.io/dataset',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_ankle',
+ id=0,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 1:
+ dict(
+ name='right_knee',
+ id=1,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 2:
+ dict(
+ name='right_hip',
+ id=2,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 3:
+ dict(
+ name='left_hip',
+ id=3,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 4:
+ dict(
+ name='left_knee',
+ id=4,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 5:
+ dict(
+ name='left_ankle',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 6:
+ dict(name='pelvis', id=6, color=[51, 153, 255], type='lower', swap=''),
+ 7:
+ dict(name='thorax', id=7, color=[51, 153, 255], type='upper', swap=''),
+ 8:
+ dict(
+ name='upper_neck',
+ id=8,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 9:
+ dict(
+ name='head_top', id=9, color=[51, 153, 255], type='upper',
+ swap=''),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='right_elbow',
+ id=11,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 12:
+ dict(
+ name='right_shoulder',
+ id=12,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 13:
+ dict(
+ name='left_shoulder',
+ id=13,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 14:
+ dict(
+ name='left_elbow',
+ id=14,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 15:
+ dict(
+ name='left_wrist',
+ id=15,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_ankle', 'right_knee'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('right_knee', 'right_hip'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('right_hip', 'pelvis'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('pelvis', 'left_hip'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(link=('left_hip', 'left_knee'), id=4, color=[0, 255, 0]),
+ 5:
+ dict(link=('left_knee', 'left_ankle'), id=5, color=[0, 255, 0]),
+ 6:
+ dict(link=('pelvis', 'thorax'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(link=('thorax', 'upper_neck'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('upper_neck', 'head_top'), id=8, color=[51, 153, 255]),
+ 9:
+ dict(link=('upper_neck', 'right_shoulder'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=10, color=[255, 128,
+ 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('upper_neck', 'left_shoulder'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('left_shoulder', 'left_elbow'), id=13, color=[0, 255, 0]),
+ 14:
+ dict(link=('left_elbow', 'left_wrist'), id=14, color=[0, 255, 0])
+ },
+ joint_weights=[
+ 1.5, 1.2, 1., 1., 1.2, 1.5, 1., 1., 1., 1., 1.5, 1.2, 1., 1., 1.2, 1.5
+ ],
+ # Adapted from COCO dataset.
+ sigmas=[
+ 0.089, 0.083, 0.107, 0.107, 0.083, 0.089, 0.026, 0.026, 0.026, 0.026,
+ 0.062, 0.072, 0.179, 0.179, 0.072, 0.062
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpi_inf_3dhp.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpi_inf_3dhp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ffd0a70297b24456ea38566ac205bb585aa47e5d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpi_inf_3dhp.py
@@ -0,0 +1,132 @@
+dataset_info = dict(
+ dataset_name='mpi_inf_3dhp',
+ paper_info=dict(
+ author='ehta, Dushyant and Rhodin, Helge and Casas, Dan and '
+ 'Fua, Pascal and Sotnychenko, Oleksandr and Xu, Weipeng and '
+ 'Theobalt, Christian',
+ title='Monocular 3D Human Pose Estimation In The Wild Using Improved '
+ 'CNN Supervision',
+ container='2017 international conference on 3D vision (3DV)',
+ year='2017',
+ homepage='http://gvv.mpi-inf.mpg.de/3dhp-dataset',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='head_top', id=0, color=[51, 153, 255], type='upper',
+ swap=''),
+ 1:
+ dict(name='neck', id=1, color=[51, 153, 255], type='upper', swap=''),
+ 2:
+ dict(
+ name='right_shoulder',
+ id=2,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 3:
+ dict(
+ name='right_elbow',
+ id=3,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 4:
+ dict(
+ name='right_wrist',
+ id=4,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='left_elbow',
+ id=6,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 7:
+ dict(
+ name='left_wrist',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 8:
+ dict(
+ name='right_hip',
+ id=8,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 9:
+ dict(
+ name='right_knee',
+ id=9,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 10:
+ dict(
+ name='right_ankle',
+ id=10,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='left_knee',
+ id=12,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 13:
+ dict(
+ name='left_ankle',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 14:
+ dict(name='root', id=14, color=[51, 153, 255], type='lower', swap=''),
+ 15:
+ dict(name='spine', id=15, color=[51, 153, 255], type='upper', swap=''),
+ 16:
+ dict(name='head', id=16, color=[51, 153, 255], type='upper', swap='')
+ },
+ skeleton_info={
+ 0: dict(link=('neck', 'right_shoulder'), id=0, color=[255, 128, 0]),
+ 1: dict(
+ link=('right_shoulder', 'right_elbow'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('right_elbow', 'right_wrist'), id=2, color=[255, 128, 0]),
+ 3: dict(link=('neck', 'left_shoulder'), id=3, color=[0, 255, 0]),
+ 4: dict(link=('left_shoulder', 'left_elbow'), id=4, color=[0, 255, 0]),
+ 5: dict(link=('left_elbow', 'left_wrist'), id=5, color=[0, 255, 0]),
+ 6: dict(link=('root', 'right_hip'), id=6, color=[255, 128, 0]),
+ 7: dict(link=('right_hip', 'right_knee'), id=7, color=[255, 128, 0]),
+ 8: dict(link=('right_knee', 'right_ankle'), id=8, color=[255, 128, 0]),
+ 9: dict(link=('root', 'left_hip'), id=9, color=[0, 255, 0]),
+ 10: dict(link=('left_hip', 'left_knee'), id=10, color=[0, 255, 0]),
+ 11: dict(link=('left_knee', 'left_ankle'), id=11, color=[0, 255, 0]),
+ 12: dict(link=('head_top', 'head'), id=12, color=[51, 153, 255]),
+ 13: dict(link=('head', 'neck'), id=13, color=[51, 153, 255]),
+ 14: dict(link=('neck', 'spine'), id=14, color=[51, 153, 255]),
+ 15: dict(link=('spine', 'root'), id=15, color=[51, 153, 255])
+ },
+ joint_weights=[1.] * 17,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c2a491c7b58bc3eaa5c0056d3d7184bdd1d1cc7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii.py
@@ -0,0 +1,155 @@
+dataset_info = dict(
+ dataset_name='mpii',
+ paper_info=dict(
+ author='Mykhaylo Andriluka and Leonid Pishchulin and '
+ 'Peter Gehler and Schiele, Bernt',
+ title='2D Human Pose Estimation: New Benchmark and '
+ 'State of the Art Analysis',
+ container='IEEE Conference on Computer Vision and '
+ 'Pattern Recognition (CVPR)',
+ year='2014',
+ homepage='http://human-pose.mpi-inf.mpg.de/',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_ankle',
+ id=0,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 1:
+ dict(
+ name='right_knee',
+ id=1,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 2:
+ dict(
+ name='right_hip',
+ id=2,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 3:
+ dict(
+ name='left_hip',
+ id=3,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 4:
+ dict(
+ name='left_knee',
+ id=4,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 5:
+ dict(
+ name='left_ankle',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 6:
+ dict(name='pelvis', id=6, color=[51, 153, 255], type='lower', swap=''),
+ 7:
+ dict(name='thorax', id=7, color=[51, 153, 255], type='upper', swap=''),
+ 8:
+ dict(
+ name='upper_neck',
+ id=8,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 9:
+ dict(
+ name='head_top', id=9, color=[51, 153, 255], type='upper',
+ swap=''),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='right_elbow',
+ id=11,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 12:
+ dict(
+ name='right_shoulder',
+ id=12,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 13:
+ dict(
+ name='left_shoulder',
+ id=13,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 14:
+ dict(
+ name='left_elbow',
+ id=14,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 15:
+ dict(
+ name='left_wrist',
+ id=15,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_ankle', 'right_knee'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('right_knee', 'right_hip'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('right_hip', 'pelvis'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('pelvis', 'left_hip'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(link=('left_hip', 'left_knee'), id=4, color=[0, 255, 0]),
+ 5:
+ dict(link=('left_knee', 'left_ankle'), id=5, color=[0, 255, 0]),
+ 6:
+ dict(link=('pelvis', 'thorax'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(link=('thorax', 'upper_neck'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('upper_neck', 'head_top'), id=8, color=[51, 153, 255]),
+ 9:
+ dict(link=('upper_neck', 'right_shoulder'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=10, color=[255, 128,
+ 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('upper_neck', 'left_shoulder'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('left_shoulder', 'left_elbow'), id=13, color=[0, 255, 0]),
+ 14:
+ dict(link=('left_elbow', 'left_wrist'), id=14, color=[0, 255, 0])
+ },
+ joint_weights=[
+ 1.5, 1.2, 1., 1., 1.2, 1.5, 1., 1., 1., 1., 1.5, 1.2, 1., 1., 1.2, 1.5
+ ],
+ # Adapted from COCO dataset.
+ sigmas=[
+ 0.089, 0.083, 0.107, 0.107, 0.083, 0.089, 0.026, 0.026, 0.026, 0.026,
+ 0.062, 0.072, 0.179, 0.179, 0.072, 0.062
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii_trb.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii_trb.py
new file mode 100644
index 0000000000000000000000000000000000000000..73940d4b4827f8e08343c3b517360db788e4820d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/mpii_trb.py
@@ -0,0 +1,380 @@
+dataset_info = dict(
+ dataset_name='mpii_trb',
+ paper_info=dict(
+ author='Duan, Haodong and Lin, Kwan-Yee and Jin, Sheng and '
+ 'Liu, Wentao and Qian, Chen and Ouyang, Wanli',
+ title='TRB: A Novel Triplet Representation for '
+ 'Understanding 2D Human Body',
+ container='Proceedings of the IEEE International '
+ 'Conference on Computer Vision',
+ year='2019',
+ homepage='https://github.com/kennymckormick/'
+ 'Triplet-Representation-of-human-Body',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='left_shoulder',
+ id=0,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 1:
+ dict(
+ name='right_shoulder',
+ id=1,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 2:
+ dict(
+ name='left_elbow',
+ id=2,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 3:
+ dict(
+ name='right_elbow',
+ id=3,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 4:
+ dict(
+ name='left_wrist',
+ id=4,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 5:
+ dict(
+ name='right_wrist',
+ id=5,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 6:
+ dict(
+ name='left_hip',
+ id=6,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 7:
+ dict(
+ name='right_hip',
+ id=7,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 8:
+ dict(
+ name='left_knee',
+ id=8,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 9:
+ dict(
+ name='right_knee',
+ id=9,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 10:
+ dict(
+ name='left_ankle',
+ id=10,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 11:
+ dict(
+ name='right_ankle',
+ id=11,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 12:
+ dict(name='head', id=12, color=[51, 153, 255], type='upper', swap=''),
+ 13:
+ dict(name='neck', id=13, color=[51, 153, 255], type='upper', swap=''),
+ 14:
+ dict(
+ name='right_neck',
+ id=14,
+ color=[255, 255, 255],
+ type='upper',
+ swap='left_neck'),
+ 15:
+ dict(
+ name='left_neck',
+ id=15,
+ color=[255, 255, 255],
+ type='upper',
+ swap='right_neck'),
+ 16:
+ dict(
+ name='medial_right_shoulder',
+ id=16,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_left_shoulder'),
+ 17:
+ dict(
+ name='lateral_right_shoulder',
+ id=17,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_left_shoulder'),
+ 18:
+ dict(
+ name='medial_right_bow',
+ id=18,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_left_bow'),
+ 19:
+ dict(
+ name='lateral_right_bow',
+ id=19,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_left_bow'),
+ 20:
+ dict(
+ name='medial_right_wrist',
+ id=20,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_left_wrist'),
+ 21:
+ dict(
+ name='lateral_right_wrist',
+ id=21,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_left_wrist'),
+ 22:
+ dict(
+ name='medial_left_shoulder',
+ id=22,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_right_shoulder'),
+ 23:
+ dict(
+ name='lateral_left_shoulder',
+ id=23,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_right_shoulder'),
+ 24:
+ dict(
+ name='medial_left_bow',
+ id=24,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_right_bow'),
+ 25:
+ dict(
+ name='lateral_left_bow',
+ id=25,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_right_bow'),
+ 26:
+ dict(
+ name='medial_left_wrist',
+ id=26,
+ color=[255, 255, 255],
+ type='upper',
+ swap='medial_right_wrist'),
+ 27:
+ dict(
+ name='lateral_left_wrist',
+ id=27,
+ color=[255, 255, 255],
+ type='upper',
+ swap='lateral_right_wrist'),
+ 28:
+ dict(
+ name='medial_right_hip',
+ id=28,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_left_hip'),
+ 29:
+ dict(
+ name='lateral_right_hip',
+ id=29,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_left_hip'),
+ 30:
+ dict(
+ name='medial_right_knee',
+ id=30,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_left_knee'),
+ 31:
+ dict(
+ name='lateral_right_knee',
+ id=31,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_left_knee'),
+ 32:
+ dict(
+ name='medial_right_ankle',
+ id=32,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_left_ankle'),
+ 33:
+ dict(
+ name='lateral_right_ankle',
+ id=33,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_left_ankle'),
+ 34:
+ dict(
+ name='medial_left_hip',
+ id=34,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_right_hip'),
+ 35:
+ dict(
+ name='lateral_left_hip',
+ id=35,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_right_hip'),
+ 36:
+ dict(
+ name='medial_left_knee',
+ id=36,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_right_knee'),
+ 37:
+ dict(
+ name='lateral_left_knee',
+ id=37,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_right_knee'),
+ 38:
+ dict(
+ name='medial_left_ankle',
+ id=38,
+ color=[255, 255, 255],
+ type='lower',
+ swap='medial_right_ankle'),
+ 39:
+ dict(
+ name='lateral_left_ankle',
+ id=39,
+ color=[255, 255, 255],
+ type='lower',
+ swap='lateral_right_ankle'),
+ },
+ skeleton_info={
+ 0:
+ dict(link=('head', 'neck'), id=0, color=[51, 153, 255]),
+ 1:
+ dict(link=('neck', 'left_shoulder'), id=1, color=[51, 153, 255]),
+ 2:
+ dict(link=('neck', 'right_shoulder'), id=2, color=[51, 153, 255]),
+ 3:
+ dict(link=('left_shoulder', 'left_elbow'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=4, color=[255, 128, 0]),
+ 5:
+ dict(link=('left_elbow', 'left_wrist'), id=5, color=[0, 255, 0]),
+ 6:
+ dict(link=('right_elbow', 'right_wrist'), id=6, color=[255, 128, 0]),
+ 7:
+ dict(link=('left_shoulder', 'left_hip'), id=7, color=[51, 153, 255]),
+ 8:
+ dict(link=('right_shoulder', 'right_hip'), id=8, color=[51, 153, 255]),
+ 9:
+ dict(link=('left_hip', 'right_hip'), id=9, color=[51, 153, 255]),
+ 10:
+ dict(link=('left_hip', 'left_knee'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_hip', 'right_knee'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('left_knee', 'left_ankle'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('right_knee', 'right_ankle'), id=13, color=[255, 128, 0]),
+ 14:
+ dict(link=('right_neck', 'left_neck'), id=14, color=[255, 255, 255]),
+ 15:
+ dict(
+ link=('medial_right_shoulder', 'lateral_right_shoulder'),
+ id=15,
+ color=[255, 255, 255]),
+ 16:
+ dict(
+ link=('medial_right_bow', 'lateral_right_bow'),
+ id=16,
+ color=[255, 255, 255]),
+ 17:
+ dict(
+ link=('medial_right_wrist', 'lateral_right_wrist'),
+ id=17,
+ color=[255, 255, 255]),
+ 18:
+ dict(
+ link=('medial_left_shoulder', 'lateral_left_shoulder'),
+ id=18,
+ color=[255, 255, 255]),
+ 19:
+ dict(
+ link=('medial_left_bow', 'lateral_left_bow'),
+ id=19,
+ color=[255, 255, 255]),
+ 20:
+ dict(
+ link=('medial_left_wrist', 'lateral_left_wrist'),
+ id=20,
+ color=[255, 255, 255]),
+ 21:
+ dict(
+ link=('medial_right_hip', 'lateral_right_hip'),
+ id=21,
+ color=[255, 255, 255]),
+ 22:
+ dict(
+ link=('medial_right_knee', 'lateral_right_knee'),
+ id=22,
+ color=[255, 255, 255]),
+ 23:
+ dict(
+ link=('medial_right_ankle', 'lateral_right_ankle'),
+ id=23,
+ color=[255, 255, 255]),
+ 24:
+ dict(
+ link=('medial_left_hip', 'lateral_left_hip'),
+ id=24,
+ color=[255, 255, 255]),
+ 25:
+ dict(
+ link=('medial_left_knee', 'lateral_left_knee'),
+ id=25,
+ color=[255, 255, 255]),
+ 26:
+ dict(
+ link=('medial_left_ankle', 'lateral_left_ankle'),
+ id=26,
+ color=[255, 255, 255])
+ },
+ joint_weights=[1.] * 40,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/nvgesture.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/nvgesture.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d5a3df7b9c6ac553ff8eab9428a9a3fb96ef564
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/nvgesture.py
@@ -0,0 +1,42 @@
+dataset_info = dict(
+ dataset_name='nvgesture',
+ paper_info=dict(
+ author='Pavlo Molchanov and Xiaodong Yang and Shalini Gupta '
+ 'and Kihwan Kim and Stephen Tyree and Jan Kautz',
+ title='Online Detection and Classification of Dynamic Hand Gestures '
+ 'with Recurrent 3D Convolutional Neural Networks',
+ container='Proceedings of the IEEE Conference on '
+ 'Computer Vision and Pattern Recognition',
+ year='2016',
+ homepage='https://research.nvidia.com/publication/2016-06_online-'
+ 'detection-and-classification-dynamic-hand-gestures-recurrent-3d',
+ ),
+ category_info={
+ 0: 'five fingers move right',
+ 1: 'five fingers move left',
+ 2: 'five fingers move up',
+ 3: 'five fingers move down',
+ 4: 'two fingers move right',
+ 5: 'two fingers move left',
+ 6: 'two fingers move up',
+ 7: 'two fingers move down',
+ 8: 'click',
+ 9: 'beckoned',
+ 10: 'stretch hand',
+ 11: 'shake hand',
+ 12: 'one',
+ 13: 'two',
+ 14: 'three',
+ 15: 'lift up',
+ 16: 'press down',
+ 17: 'push',
+ 18: 'shrink',
+ 19: 'levorotation',
+ 20: 'dextrorotation',
+ 21: 'two fingers prod',
+ 22: 'grab',
+ 23: 'thumbs up',
+ 24: 'OK'
+ },
+ flip_pairs=[(0, 1), (4, 5), (19, 20)],
+ fps=30)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ochuman.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ochuman.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ef20838fe583fde133a97e688d30e91ae562746
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/ochuman.py
@@ -0,0 +1,181 @@
+dataset_info = dict(
+ dataset_name='ochuman',
+ paper_info=dict(
+ author='Zhang, Song-Hai and Li, Ruilong and Dong, Xin and '
+ 'Rosin, Paul and Cai, Zixi and Han, Xi and '
+ 'Yang, Dingcheng and Huang, Haozhi and Hu, Shi-Min',
+ title='Pose2seg: Detection free human instance segmentation',
+ container='Proceedings of the IEEE conference on computer '
+ 'vision and pattern recognition',
+ year='2019',
+ homepage='https://github.com/liruilong940607/OCHumanApi',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='left_eye',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 2:
+ dict(
+ name='right_eye',
+ id=2,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('left_eye', 'right_eye'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('nose', 'left_eye'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(link=('nose', 'right_eye'), id=14, color=[51, 153, 255]),
+ 15:
+ dict(link=('left_eye', 'left_ear'), id=15, color=[51, 153, 255]),
+ 16:
+ dict(link=('right_eye', 'right_ear'), id=16, color=[51, 153, 255]),
+ 17:
+ dict(link=('left_ear', 'left_shoulder'), id=17, color=[51, 153, 255]),
+ 18:
+ dict(
+ link=('right_ear', 'right_shoulder'), id=18, color=[51, 153, 255])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5,
+ 1.5
+ ],
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/onehand10k.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/onehand10k.py
new file mode 100644
index 0000000000000000000000000000000000000000..016770f14f3075dfa7d59389524a0c11a4feb802
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/onehand10k.py
@@ -0,0 +1,142 @@
+dataset_info = dict(
+ dataset_name='onehand10k',
+ paper_info=dict(
+ author='Wang, Yangang and Peng, Cong and Liu, Yebin',
+ title='Mask-pose cascaded cnn for 2d hand pose estimation '
+ 'from single color image',
+ container='IEEE Transactions on Circuits and Systems '
+ 'for Video Technology',
+ year='2018',
+ homepage='https://www.yangangwang.com/papers/WANG-MCC-2018-10.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='wrist', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='thumb1', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb2', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb3', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(name='thumb4', id=4, color=[255, 128, 0], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger1', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger2', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger3', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='forefinger4', id=8, color=[255, 153, 255], type='', swap=''),
+ 9:
+ dict(
+ name='middle_finger1',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger3',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='middle_finger4',
+ id=12,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 13:
+ dict(
+ name='ring_finger1', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger2', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger3', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(
+ name='ring_finger4', id=16, color=[255, 51, 51], type='', swap=''),
+ 17:
+ dict(name='pinky_finger1', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger2', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger3', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='pinky_finger4', id=20, color=[0, 255, 0], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_body3d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_body3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3b19ac462415a840ca2e0b9e214bdb35d91b5e4
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_body3d.py
@@ -0,0 +1,160 @@
+dataset_info = dict(
+ dataset_name='panoptic_pose_3d',
+ paper_info=dict(
+ author='Joo, Hanbyul and Simon, Tomas and Li, Xulong'
+ 'and Liu, Hao and Tan, Lei and Gui, Lin and Banerjee, Sean'
+ 'and Godisart, Timothy and Nabbe, Bart and Matthews, Iain'
+ 'and Kanade, Takeo and Nobuhara, Shohei and Sheikh, Yaser',
+ title='Panoptic Studio: A Massively Multiview System '
+ 'for Interaction Motion Capture',
+ container='IEEE Transactions on Pattern Analysis'
+ ' and Machine Intelligence',
+ year='2017',
+ homepage='http://domedb.perception.cs.cmu.edu',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='neck', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(name='nose', id=1, color=[51, 153, 255], type='upper', swap=''),
+ 2:
+ dict(name='mid_hip', id=2, color=[0, 255, 0], type='lower', swap=''),
+ 3:
+ dict(
+ name='left_shoulder',
+ id=3,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 4:
+ dict(
+ name='left_elbow',
+ id=4,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 5:
+ dict(
+ name='left_wrist',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 6:
+ dict(
+ name='left_hip',
+ id=6,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 7:
+ dict(
+ name='left_knee',
+ id=7,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 8:
+ dict(
+ name='left_ankle',
+ id=8,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 9:
+ dict(
+ name='right_shoulder',
+ id=9,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 10:
+ dict(
+ name='right_elbow',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 11:
+ dict(
+ name='right_wrist',
+ id=11,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='right_knee',
+ id=13,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 14:
+ dict(
+ name='right_ankle',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 15:
+ dict(
+ name='left_eye',
+ id=15,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_eye'),
+ 16:
+ dict(
+ name='left_ear',
+ id=16,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 17:
+ dict(
+ name='right_eye',
+ id=17,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_eye'),
+ 18:
+ dict(
+ name='right_ear',
+ id=18,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear')
+ },
+ skeleton_info={
+ 0: dict(link=('nose', 'neck'), id=0, color=[51, 153, 255]),
+ 1: dict(link=('neck', 'left_shoulder'), id=1, color=[0, 255, 0]),
+ 2: dict(link=('neck', 'right_shoulder'), id=2, color=[255, 128, 0]),
+ 3: dict(link=('left_shoulder', 'left_elbow'), id=3, color=[0, 255, 0]),
+ 4: dict(
+ link=('right_shoulder', 'right_elbow'), id=4, color=[255, 128, 0]),
+ 5: dict(link=('left_elbow', 'left_wrist'), id=5, color=[0, 255, 0]),
+ 6:
+ dict(link=('right_elbow', 'right_wrist'), id=6, color=[255, 128, 0]),
+ 7: dict(link=('left_ankle', 'left_knee'), id=7, color=[0, 255, 0]),
+ 8: dict(link=('left_knee', 'left_hip'), id=8, color=[0, 255, 0]),
+ 9: dict(link=('right_ankle', 'right_knee'), id=9, color=[255, 128, 0]),
+ 10: dict(link=('right_knee', 'right_hip'), id=10, color=[255, 128, 0]),
+ 11: dict(link=('mid_hip', 'left_hip'), id=11, color=[0, 255, 0]),
+ 12: dict(link=('mid_hip', 'right_hip'), id=12, color=[255, 128, 0]),
+ 13: dict(link=('mid_hip', 'neck'), id=13, color=[51, 153, 255]),
+ },
+ joint_weights=[
+ 1.0, 1.0, 1.0, 1.0, 1.2, 1.5, 1.0, 1.2, 1.5, 1.0, 1.2, 1.5, 1.0, 1.2,
+ 1.5, 1.0, 1.0, 1.0, 1.0
+ ],
+ sigmas=[
+ 0.026, 0.026, 0.107, 0.079, 0.072, 0.062, 0.107, 0.087, 0.089, 0.079,
+ 0.072, 0.062, 0.107, 0.087, 0.089, 0.025, 0.035, 0.025, 0.035
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_hand2d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_hand2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a65731ba87b155beb1b40591fd9acb232c2afc6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/panoptic_hand2d.py
@@ -0,0 +1,143 @@
+dataset_info = dict(
+ dataset_name='panoptic_hand2d',
+ paper_info=dict(
+ author='Simon, Tomas and Joo, Hanbyul and '
+ 'Matthews, Iain and Sheikh, Yaser',
+ title='Hand keypoint detection in single images using '
+ 'multiview bootstrapping',
+ container='Proceedings of the IEEE conference on '
+ 'Computer Vision and Pattern Recognition',
+ year='2017',
+ homepage='http://domedb.perception.cs.cmu.edu/handdb.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='wrist', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='thumb1', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb2', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb3', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(name='thumb4', id=4, color=[255, 128, 0], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger1', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger2', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger3', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='forefinger4', id=8, color=[255, 153, 255], type='', swap=''),
+ 9:
+ dict(
+ name='middle_finger1',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger2',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger3',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='middle_finger4',
+ id=12,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 13:
+ dict(
+ name='ring_finger1', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger2', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger3', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(
+ name='ring_finger4', id=16, color=[255, 51, 51], type='', swap=''),
+ 17:
+ dict(name='pinky_finger1', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger2', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger3', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='pinky_finger4', id=20, color=[0, 255, 0], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/posetrack18.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/posetrack18.py
new file mode 100644
index 0000000000000000000000000000000000000000..5aefd1c97fe083df35ee88bebab4f99134c27971
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/posetrack18.py
@@ -0,0 +1,176 @@
+dataset_info = dict(
+ dataset_name='posetrack18',
+ paper_info=dict(
+ author='Andriluka, Mykhaylo and Iqbal, Umar and '
+ 'Insafutdinov, Eldar and Pishchulin, Leonid and '
+ 'Milan, Anton and Gall, Juergen and Schiele, Bernt',
+ title='Posetrack: A benchmark for human pose estimation and tracking',
+ container='Proceedings of the IEEE Conference on '
+ 'Computer Vision and Pattern Recognition',
+ year='2018',
+ homepage='https://posetrack.net/users/download.php',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='nose', id=0, color=[51, 153, 255], type='upper', swap=''),
+ 1:
+ dict(
+ name='head_bottom',
+ id=1,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 2:
+ dict(
+ name='head_top', id=2, color=[51, 153, 255], type='upper',
+ swap=''),
+ 3:
+ dict(
+ name='left_ear',
+ id=3,
+ color=[51, 153, 255],
+ type='upper',
+ swap='right_ear'),
+ 4:
+ dict(
+ name='right_ear',
+ id=4,
+ color=[51, 153, 255],
+ type='upper',
+ swap='left_ear'),
+ 5:
+ dict(
+ name='left_shoulder',
+ id=5,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 6:
+ dict(
+ name='right_shoulder',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 7:
+ dict(
+ name='left_elbow',
+ id=7,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 8:
+ dict(
+ name='right_elbow',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 9:
+ dict(
+ name='left_wrist',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 10:
+ dict(
+ name='right_wrist',
+ id=10,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 11:
+ dict(
+ name='left_hip',
+ id=11,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 12:
+ dict(
+ name='right_hip',
+ id=12,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 13:
+ dict(
+ name='left_knee',
+ id=13,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 14:
+ dict(
+ name='right_knee',
+ id=14,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 15:
+ dict(
+ name='left_ankle',
+ id=15,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 16:
+ dict(
+ name='right_ankle',
+ id=16,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('left_ankle', 'left_knee'), id=0, color=[0, 255, 0]),
+ 1:
+ dict(link=('left_knee', 'left_hip'), id=1, color=[0, 255, 0]),
+ 2:
+ dict(link=('right_ankle', 'right_knee'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('right_knee', 'right_hip'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('left_hip', 'right_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('left_shoulder', 'left_hip'), id=5, color=[51, 153, 255]),
+ 6:
+ dict(link=('right_shoulder', 'right_hip'), id=6, color=[51, 153, 255]),
+ 7:
+ dict(
+ link=('left_shoulder', 'right_shoulder'),
+ id=7,
+ color=[51, 153, 255]),
+ 8:
+ dict(link=('left_shoulder', 'left_elbow'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(
+ link=('right_shoulder', 'right_elbow'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_elbow', 'left_wrist'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(link=('right_elbow', 'right_wrist'), id=11, color=[255, 128, 0]),
+ 12:
+ dict(link=('nose', 'head_bottom'), id=12, color=[51, 153, 255]),
+ 13:
+ dict(link=('nose', 'head_top'), id=13, color=[51, 153, 255]),
+ 14:
+ dict(
+ link=('head_bottom', 'left_shoulder'), id=14, color=[51, 153,
+ 255]),
+ 15:
+ dict(
+ link=('head_bottom', 'right_shoulder'),
+ id=15,
+ color=[51, 153, 255])
+ },
+ joint_weights=[
+ 1., 1., 1., 1., 1., 1., 1., 1.2, 1.2, 1.5, 1.5, 1., 1., 1.2, 1.2, 1.5,
+ 1.5
+ ],
+ sigmas=[
+ 0.026, 0.025, 0.025, 0.035, 0.035, 0.079, 0.079, 0.072, 0.072, 0.062,
+ 0.062, 0.107, 0.107, 0.087, 0.087, 0.089, 0.089
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/rhd2d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/rhd2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..4631ccd03814155b06687e0b1ba2b83404c837fc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/rhd2d.py
@@ -0,0 +1,151 @@
+dataset_info = dict(
+ dataset_name='rhd2d',
+ paper_info=dict(
+ author='Christian Zimmermann and Thomas Brox',
+ title='Learning to Estimate 3D Hand Pose from Single RGB Images',
+ container='arXiv',
+ year='2017',
+ homepage='https://lmb.informatik.uni-freiburg.de/resources/'
+ 'datasets/RenderedHandposeDataset.en.html',
+ ),
+ # In RHD, 1-4: left thumb [tip to palm], which means the finger is from
+ # tip to palm, so as other fingers. Please refer to
+ # `https://lmb.informatik.uni-freiburg.de/resources/datasets/
+ # RenderedHandpose/README` for details of keypoint definition.
+ # But in COCO-WholeBody-Hand, FreiHand, CMU Panoptic HandDB, it is in
+ # inverse order. Pay attention to this if you want to combine RHD with
+ # other hand datasets to train a single model.
+ # Also, note that 'keypoint_info' will not directly affect the order of
+ # the keypoint in the dataset. It is mostly for visualization & storing
+ # information about flip_pairs.
+ keypoint_info={
+ 0:
+ dict(name='wrist', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='thumb4', id=1, color=[255, 128, 0], type='', swap=''),
+ 2:
+ dict(name='thumb3', id=2, color=[255, 128, 0], type='', swap=''),
+ 3:
+ dict(name='thumb2', id=3, color=[255, 128, 0], type='', swap=''),
+ 4:
+ dict(name='thumb1', id=4, color=[255, 128, 0], type='', swap=''),
+ 5:
+ dict(
+ name='forefinger4', id=5, color=[255, 153, 255], type='', swap=''),
+ 6:
+ dict(
+ name='forefinger3', id=6, color=[255, 153, 255], type='', swap=''),
+ 7:
+ dict(
+ name='forefinger2', id=7, color=[255, 153, 255], type='', swap=''),
+ 8:
+ dict(
+ name='forefinger1', id=8, color=[255, 153, 255], type='', swap=''),
+ 9:
+ dict(
+ name='middle_finger4',
+ id=9,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 10:
+ dict(
+ name='middle_finger3',
+ id=10,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 11:
+ dict(
+ name='middle_finger2',
+ id=11,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 12:
+ dict(
+ name='middle_finger1',
+ id=12,
+ color=[102, 178, 255],
+ type='',
+ swap=''),
+ 13:
+ dict(
+ name='ring_finger4', id=13, color=[255, 51, 51], type='', swap=''),
+ 14:
+ dict(
+ name='ring_finger3', id=14, color=[255, 51, 51], type='', swap=''),
+ 15:
+ dict(
+ name='ring_finger2', id=15, color=[255, 51, 51], type='', swap=''),
+ 16:
+ dict(
+ name='ring_finger1', id=16, color=[255, 51, 51], type='', swap=''),
+ 17:
+ dict(name='pinky_finger4', id=17, color=[0, 255, 0], type='', swap=''),
+ 18:
+ dict(name='pinky_finger3', id=18, color=[0, 255, 0], type='', swap=''),
+ 19:
+ dict(name='pinky_finger2', id=19, color=[0, 255, 0], type='', swap=''),
+ 20:
+ dict(name='pinky_finger1', id=20, color=[0, 255, 0], type='', swap='')
+ },
+ skeleton_info={
+ 0:
+ dict(link=('wrist', 'thumb1'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('thumb1', 'thumb2'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('thumb2', 'thumb3'), id=2, color=[255, 128, 0]),
+ 3:
+ dict(link=('thumb3', 'thumb4'), id=3, color=[255, 128, 0]),
+ 4:
+ dict(link=('wrist', 'forefinger1'), id=4, color=[255, 153, 255]),
+ 5:
+ dict(link=('forefinger1', 'forefinger2'), id=5, color=[255, 153, 255]),
+ 6:
+ dict(link=('forefinger2', 'forefinger3'), id=6, color=[255, 153, 255]),
+ 7:
+ dict(link=('forefinger3', 'forefinger4'), id=7, color=[255, 153, 255]),
+ 8:
+ dict(link=('wrist', 'middle_finger1'), id=8, color=[102, 178, 255]),
+ 9:
+ dict(
+ link=('middle_finger1', 'middle_finger2'),
+ id=9,
+ color=[102, 178, 255]),
+ 10:
+ dict(
+ link=('middle_finger2', 'middle_finger3'),
+ id=10,
+ color=[102, 178, 255]),
+ 11:
+ dict(
+ link=('middle_finger3', 'middle_finger4'),
+ id=11,
+ color=[102, 178, 255]),
+ 12:
+ dict(link=('wrist', 'ring_finger1'), id=12, color=[255, 51, 51]),
+ 13:
+ dict(
+ link=('ring_finger1', 'ring_finger2'), id=13, color=[255, 51, 51]),
+ 14:
+ dict(
+ link=('ring_finger2', 'ring_finger3'), id=14, color=[255, 51, 51]),
+ 15:
+ dict(
+ link=('ring_finger3', 'ring_finger4'), id=15, color=[255, 51, 51]),
+ 16:
+ dict(link=('wrist', 'pinky_finger1'), id=16, color=[0, 255, 0]),
+ 17:
+ dict(
+ link=('pinky_finger1', 'pinky_finger2'), id=17, color=[0, 255, 0]),
+ 18:
+ dict(
+ link=('pinky_finger2', 'pinky_finger3'), id=18, color=[0, 255, 0]),
+ 19:
+ dict(
+ link=('pinky_finger3', 'pinky_finger4'), id=19, color=[0, 255, 0])
+ },
+ joint_weights=[1.] * 21,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/shelf.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/shelf.py
new file mode 100644
index 0000000000000000000000000000000000000000..5fe6e42b3b44e3f65947284efd9ffac58d41d43f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/shelf.py
@@ -0,0 +1,151 @@
+dataset_info = dict(
+ dataset_name='shelf',
+ paper_info=dict(
+ author='Belagiannis, Vasileios and Amin, Sikandar and Andriluka, '
+ 'Mykhaylo and Schiele, Bernt and Navab, Nassir and Ilic, Slobodan',
+ title='3D Pictorial Structures for Multiple Human Pose Estimation',
+ container='IEEE Computer Society Conference on Computer Vision and '
+ 'Pattern Recognition (CVPR)',
+ year='2014',
+ homepage='http://campar.in.tum.de/Chair/MultiHumanPose',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='right_ankle',
+ id=0,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_ankle'),
+ 1:
+ dict(
+ name='right_knee',
+ id=1,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_knee'),
+ 2:
+ dict(
+ name='right_hip',
+ id=2,
+ color=[255, 128, 0],
+ type='lower',
+ swap='left_hip'),
+ 3:
+ dict(
+ name='left_hip',
+ id=3,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_hip'),
+ 4:
+ dict(
+ name='left_knee',
+ id=4,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_knee'),
+ 5:
+ dict(
+ name='left_ankle',
+ id=5,
+ color=[0, 255, 0],
+ type='lower',
+ swap='right_ankle'),
+ 6:
+ dict(
+ name='right_wrist',
+ id=6,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_wrist'),
+ 7:
+ dict(
+ name='right_elbow',
+ id=7,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_elbow'),
+ 8:
+ dict(
+ name='right_shoulder',
+ id=8,
+ color=[255, 128, 0],
+ type='upper',
+ swap='left_shoulder'),
+ 9:
+ dict(
+ name='left_shoulder',
+ id=9,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_shoulder'),
+ 10:
+ dict(
+ name='left_elbow',
+ id=10,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_elbow'),
+ 11:
+ dict(
+ name='left_wrist',
+ id=11,
+ color=[0, 255, 0],
+ type='upper',
+ swap='right_wrist'),
+ 12:
+ dict(
+ name='bottom_head',
+ id=12,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ 13:
+ dict(
+ name='top_head',
+ id=13,
+ color=[51, 153, 255],
+ type='upper',
+ swap=''),
+ },
+ skeleton_info={
+ 0:
+ dict(link=('right_ankle', 'right_knee'), id=0, color=[255, 128, 0]),
+ 1:
+ dict(link=('right_knee', 'right_hip'), id=1, color=[255, 128, 0]),
+ 2:
+ dict(link=('left_hip', 'left_knee'), id=2, color=[0, 255, 0]),
+ 3:
+ dict(link=('left_knee', 'left_ankle'), id=3, color=[0, 255, 0]),
+ 4:
+ dict(link=('right_hip', 'left_hip'), id=4, color=[51, 153, 255]),
+ 5:
+ dict(link=('right_wrist', 'right_elbow'), id=5, color=[255, 128, 0]),
+ 6:
+ dict(
+ link=('right_elbow', 'right_shoulder'), id=6, color=[255, 128, 0]),
+ 7:
+ dict(link=('left_shoulder', 'left_elbow'), id=7, color=[0, 255, 0]),
+ 8:
+ dict(link=('left_elbow', 'left_wrist'), id=8, color=[0, 255, 0]),
+ 9:
+ dict(link=('right_hip', 'right_shoulder'), id=9, color=[255, 128, 0]),
+ 10:
+ dict(link=('left_hip', 'left_shoulder'), id=10, color=[0, 255, 0]),
+ 11:
+ dict(
+ link=('right_shoulder', 'bottom_head'), id=11, color=[255, 128,
+ 0]),
+ 12:
+ dict(link=('left_shoulder', 'bottom_head'), id=12, color=[0, 255, 0]),
+ 13:
+ dict(link=('bottom_head', 'top_head'), id=13, color=[51, 153, 255]),
+ },
+ joint_weights=[
+ 1.5, 1.2, 1.0, 1.0, 1.2, 1.5, 1.5, 1.2, 1.0, 1.0, 1.2, 1.5, 1.0, 1.0
+ ],
+ sigmas=[
+ 0.089, 0.087, 0.107, 0.107, 0.087, 0.089, 0.062, 0.072, 0.079, 0.079,
+ 0.072, 0.062, 0.026, 0.026
+ ])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/wflw.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/wflw.py
new file mode 100644
index 0000000000000000000000000000000000000000..bed6f56f30f7a2f093e44c5726212e2a0d4659d2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/wflw.py
@@ -0,0 +1,582 @@
+dataset_info = dict(
+ dataset_name='wflw',
+ paper_info=dict(
+ author='Wu, Wayne and Qian, Chen and Yang, Shuo and Wang, '
+ 'Quan and Cai, Yici and Zhou, Qiang',
+ title='Look at boundary: A boundary-aware face alignment algorithm',
+ container='Proceedings of the IEEE conference on computer '
+ 'vision and pattern recognition',
+ year='2018',
+ homepage='https://wywu.github.io/projects/LAB/WFLW.html',
+ ),
+ keypoint_info={
+ 0:
+ dict(
+ name='kpt-0', id=0, color=[255, 255, 255], type='', swap='kpt-32'),
+ 1:
+ dict(
+ name='kpt-1', id=1, color=[255, 255, 255], type='', swap='kpt-31'),
+ 2:
+ dict(
+ name='kpt-2', id=2, color=[255, 255, 255], type='', swap='kpt-30'),
+ 3:
+ dict(
+ name='kpt-3', id=3, color=[255, 255, 255], type='', swap='kpt-29'),
+ 4:
+ dict(
+ name='kpt-4', id=4, color=[255, 255, 255], type='', swap='kpt-28'),
+ 5:
+ dict(
+ name='kpt-5', id=5, color=[255, 255, 255], type='', swap='kpt-27'),
+ 6:
+ dict(
+ name='kpt-6', id=6, color=[255, 255, 255], type='', swap='kpt-26'),
+ 7:
+ dict(
+ name='kpt-7', id=7, color=[255, 255, 255], type='', swap='kpt-25'),
+ 8:
+ dict(
+ name='kpt-8', id=8, color=[255, 255, 255], type='', swap='kpt-24'),
+ 9:
+ dict(
+ name='kpt-9', id=9, color=[255, 255, 255], type='', swap='kpt-23'),
+ 10:
+ dict(
+ name='kpt-10',
+ id=10,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-22'),
+ 11:
+ dict(
+ name='kpt-11',
+ id=11,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-21'),
+ 12:
+ dict(
+ name='kpt-12',
+ id=12,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-20'),
+ 13:
+ dict(
+ name='kpt-13',
+ id=13,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-19'),
+ 14:
+ dict(
+ name='kpt-14',
+ id=14,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-18'),
+ 15:
+ dict(
+ name='kpt-15',
+ id=15,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-17'),
+ 16:
+ dict(name='kpt-16', id=16, color=[255, 255, 255], type='', swap=''),
+ 17:
+ dict(
+ name='kpt-17',
+ id=17,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-15'),
+ 18:
+ dict(
+ name='kpt-18',
+ id=18,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-14'),
+ 19:
+ dict(
+ name='kpt-19',
+ id=19,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-13'),
+ 20:
+ dict(
+ name='kpt-20',
+ id=20,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-12'),
+ 21:
+ dict(
+ name='kpt-21',
+ id=21,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-11'),
+ 22:
+ dict(
+ name='kpt-22',
+ id=22,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-10'),
+ 23:
+ dict(
+ name='kpt-23', id=23, color=[255, 255, 255], type='',
+ swap='kpt-9'),
+ 24:
+ dict(
+ name='kpt-24', id=24, color=[255, 255, 255], type='',
+ swap='kpt-8'),
+ 25:
+ dict(
+ name='kpt-25', id=25, color=[255, 255, 255], type='',
+ swap='kpt-7'),
+ 26:
+ dict(
+ name='kpt-26', id=26, color=[255, 255, 255], type='',
+ swap='kpt-6'),
+ 27:
+ dict(
+ name='kpt-27', id=27, color=[255, 255, 255], type='',
+ swap='kpt-5'),
+ 28:
+ dict(
+ name='kpt-28', id=28, color=[255, 255, 255], type='',
+ swap='kpt-4'),
+ 29:
+ dict(
+ name='kpt-29', id=29, color=[255, 255, 255], type='',
+ swap='kpt-3'),
+ 30:
+ dict(
+ name='kpt-30', id=30, color=[255, 255, 255], type='',
+ swap='kpt-2'),
+ 31:
+ dict(
+ name='kpt-31', id=31, color=[255, 255, 255], type='',
+ swap='kpt-1'),
+ 32:
+ dict(
+ name='kpt-32', id=32, color=[255, 255, 255], type='',
+ swap='kpt-0'),
+ 33:
+ dict(
+ name='kpt-33',
+ id=33,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-46'),
+ 34:
+ dict(
+ name='kpt-34',
+ id=34,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-45'),
+ 35:
+ dict(
+ name='kpt-35',
+ id=35,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-44'),
+ 36:
+ dict(
+ name='kpt-36',
+ id=36,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-43'),
+ 37:
+ dict(
+ name='kpt-37',
+ id=37,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-42'),
+ 38:
+ dict(
+ name='kpt-38',
+ id=38,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-50'),
+ 39:
+ dict(
+ name='kpt-39',
+ id=39,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-49'),
+ 40:
+ dict(
+ name='kpt-40',
+ id=40,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-48'),
+ 41:
+ dict(
+ name='kpt-41',
+ id=41,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-47'),
+ 42:
+ dict(
+ name='kpt-42',
+ id=42,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-37'),
+ 43:
+ dict(
+ name='kpt-43',
+ id=43,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-36'),
+ 44:
+ dict(
+ name='kpt-44',
+ id=44,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-35'),
+ 45:
+ dict(
+ name='kpt-45',
+ id=45,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-34'),
+ 46:
+ dict(
+ name='kpt-46',
+ id=46,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-33'),
+ 47:
+ dict(
+ name='kpt-47',
+ id=47,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-41'),
+ 48:
+ dict(
+ name='kpt-48',
+ id=48,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-40'),
+ 49:
+ dict(
+ name='kpt-49',
+ id=49,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-39'),
+ 50:
+ dict(
+ name='kpt-50',
+ id=50,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-38'),
+ 51:
+ dict(name='kpt-51', id=51, color=[255, 255, 255], type='', swap=''),
+ 52:
+ dict(name='kpt-52', id=52, color=[255, 255, 255], type='', swap=''),
+ 53:
+ dict(name='kpt-53', id=53, color=[255, 255, 255], type='', swap=''),
+ 54:
+ dict(name='kpt-54', id=54, color=[255, 255, 255], type='', swap=''),
+ 55:
+ dict(
+ name='kpt-55',
+ id=55,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-59'),
+ 56:
+ dict(
+ name='kpt-56',
+ id=56,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-58'),
+ 57:
+ dict(name='kpt-57', id=57, color=[255, 255, 255], type='', swap=''),
+ 58:
+ dict(
+ name='kpt-58',
+ id=58,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-56'),
+ 59:
+ dict(
+ name='kpt-59',
+ id=59,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-55'),
+ 60:
+ dict(
+ name='kpt-60',
+ id=60,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-72'),
+ 61:
+ dict(
+ name='kpt-61',
+ id=61,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-71'),
+ 62:
+ dict(
+ name='kpt-62',
+ id=62,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-70'),
+ 63:
+ dict(
+ name='kpt-63',
+ id=63,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-69'),
+ 64:
+ dict(
+ name='kpt-64',
+ id=64,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-68'),
+ 65:
+ dict(
+ name='kpt-65',
+ id=65,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-75'),
+ 66:
+ dict(
+ name='kpt-66',
+ id=66,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-74'),
+ 67:
+ dict(
+ name='kpt-67',
+ id=67,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-73'),
+ 68:
+ dict(
+ name='kpt-68',
+ id=68,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-64'),
+ 69:
+ dict(
+ name='kpt-69',
+ id=69,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-63'),
+ 70:
+ dict(
+ name='kpt-70',
+ id=70,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-62'),
+ 71:
+ dict(
+ name='kpt-71',
+ id=71,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-61'),
+ 72:
+ dict(
+ name='kpt-72',
+ id=72,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-60'),
+ 73:
+ dict(
+ name='kpt-73',
+ id=73,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-67'),
+ 74:
+ dict(
+ name='kpt-74',
+ id=74,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-66'),
+ 75:
+ dict(
+ name='kpt-75',
+ id=75,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-65'),
+ 76:
+ dict(
+ name='kpt-76',
+ id=76,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-82'),
+ 77:
+ dict(
+ name='kpt-77',
+ id=77,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-81'),
+ 78:
+ dict(
+ name='kpt-78',
+ id=78,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-80'),
+ 79:
+ dict(name='kpt-79', id=79, color=[255, 255, 255], type='', swap=''),
+ 80:
+ dict(
+ name='kpt-80',
+ id=80,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-78'),
+ 81:
+ dict(
+ name='kpt-81',
+ id=81,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-77'),
+ 82:
+ dict(
+ name='kpt-82',
+ id=82,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-76'),
+ 83:
+ dict(
+ name='kpt-83',
+ id=83,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-87'),
+ 84:
+ dict(
+ name='kpt-84',
+ id=84,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-86'),
+ 85:
+ dict(name='kpt-85', id=85, color=[255, 255, 255], type='', swap=''),
+ 86:
+ dict(
+ name='kpt-86',
+ id=86,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-84'),
+ 87:
+ dict(
+ name='kpt-87',
+ id=87,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-83'),
+ 88:
+ dict(
+ name='kpt-88',
+ id=88,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-92'),
+ 89:
+ dict(
+ name='kpt-89',
+ id=89,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-91'),
+ 90:
+ dict(name='kpt-90', id=90, color=[255, 255, 255], type='', swap=''),
+ 91:
+ dict(
+ name='kpt-91',
+ id=91,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-89'),
+ 92:
+ dict(
+ name='kpt-92',
+ id=92,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-88'),
+ 93:
+ dict(
+ name='kpt-93',
+ id=93,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-95'),
+ 94:
+ dict(name='kpt-94', id=94, color=[255, 255, 255], type='', swap=''),
+ 95:
+ dict(
+ name='kpt-95',
+ id=95,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-93'),
+ 96:
+ dict(
+ name='kpt-96',
+ id=96,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-97'),
+ 97:
+ dict(
+ name='kpt-97',
+ id=97,
+ color=[255, 255, 255],
+ type='',
+ swap='kpt-96')
+ },
+ skeleton_info={},
+ joint_weights=[1.] * 98,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/zebra.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/zebra.py
new file mode 100644
index 0000000000000000000000000000000000000000..eac71f796a761bbf87b123f8b7b8b4585df0c525
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/datasets/zebra.py
@@ -0,0 +1,64 @@
+dataset_info = dict(
+ dataset_name='zebra',
+ paper_info=dict(
+ author='Graving, Jacob M and Chae, Daniel and Naik, Hemal and '
+ 'Li, Liang and Koger, Benjamin and Costelloe, Blair R and '
+ 'Couzin, Iain D',
+ title='DeepPoseKit, a software toolkit for fast and robust '
+ 'animal pose estimation using deep learning',
+ container='Elife',
+ year='2019',
+ homepage='https://github.com/jgraving/DeepPoseKit-Data',
+ ),
+ keypoint_info={
+ 0:
+ dict(name='snout', id=0, color=[255, 255, 255], type='', swap=''),
+ 1:
+ dict(name='head', id=1, color=[255, 255, 255], type='', swap=''),
+ 2:
+ dict(name='neck', id=2, color=[255, 255, 255], type='', swap=''),
+ 3:
+ dict(
+ name='forelegL1',
+ id=3,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegR1'),
+ 4:
+ dict(
+ name='forelegR1',
+ id=4,
+ color=[255, 255, 255],
+ type='',
+ swap='forelegL1'),
+ 5:
+ dict(
+ name='hindlegL1',
+ id=5,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegR1'),
+ 6:
+ dict(
+ name='hindlegR1',
+ id=6,
+ color=[255, 255, 255],
+ type='',
+ swap='hindlegL1'),
+ 7:
+ dict(name='tailbase', id=7, color=[255, 255, 255], type='', swap=''),
+ 8:
+ dict(name='tailtip', id=8, color=[255, 255, 255], type='', swap='')
+ },
+ skeleton_info={
+ 0: dict(link=('head', 'snout'), id=0, color=[255, 255, 255]),
+ 1: dict(link=('neck', 'head'), id=1, color=[255, 255, 255]),
+ 2: dict(link=('forelegL1', 'neck'), id=2, color=[255, 255, 255]),
+ 3: dict(link=('forelegR1', 'neck'), id=3, color=[255, 255, 255]),
+ 4: dict(link=('hindlegL1', 'tailbase'), id=4, color=[255, 255, 255]),
+ 5: dict(link=('hindlegR1', 'tailbase'), id=5, color=[255, 255, 255]),
+ 6: dict(link=('tailbase', 'neck'), id=6, color=[255, 255, 255]),
+ 7: dict(link=('tailtip', 'tailbase'), id=7, color=[255, 255, 255])
+ },
+ joint_weights=[1.] * 9,
+ sigmas=[])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/default_runtime.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/default_runtime.py
new file mode 100644
index 0000000000000000000000000000000000000000..62b7ff270aae280268ea528c1fbe99c0052e20e3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/default_runtime.py
@@ -0,0 +1,20 @@
+checkpoint_config = dict(interval=10)
+
+log_config = dict(
+ interval=50,
+ hooks=[
+ dict(type='TextLoggerHook'),
+ # dict(type='TensorboardLoggerHook')
+ # dict(type='PaviLoggerHook') # for internal services
+ ])
+
+log_level = 'INFO'
+load_from = None
+resume_from = None
+dist_params = dict(backend='nccl')
+workflow = [('train', 1)]
+
+# disable opencv multithreading to avoid system being overloaded
+opencv_num_threads = 0
+# set multi-process start method as `fork` to speed up the training
+mp_start_method = 'fork'
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/gaussian.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/gaussian.py
new file mode 100644
index 0000000000000000000000000000000000000000..b855f4bde1e1adf71186b3f82f1a3e522fbc53ff
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/gaussian.py
@@ -0,0 +1,5 @@
+filter_cfg = dict(
+ type='GaussianFilter',
+ window_size=11,
+ sigma=4.0,
+)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/one_euro.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/one_euro.py
new file mode 100644
index 0000000000000000000000000000000000000000..61f797efdf9fb7a12d40b2d8eee6cb3a5e2e1ea9
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/one_euro.py
@@ -0,0 +1,5 @@
+filter_cfg = dict(
+ type='OneEuroFilter',
+ min_cutoff=0.004,
+ beta=0.7,
+)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/savizky_golay.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/savizky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..40302b004460699dfe8522c59c9a3e8cf1c35d83
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/savizky_golay.py
@@ -0,0 +1,5 @@
+filter_cfg = dict(
+ type='SavizkyGolayFilter',
+ window_size=11,
+ polyorder=2,
+)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_h36m.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_h36m.md
new file mode 100644
index 0000000000000000000000000000000000000000..0901be8fe26468b3603ef77412a4feea16a1f239
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_h36m.md
@@ -0,0 +1,45 @@
+
+
+
+SmoothNet (arXiv'2021)
+
+```bibtex
+@article{zeng2021smoothnet,
+ title={SmoothNet: A Plug-and-Play Network for Refining Human Poses in Videos},
+ author={Zeng, Ailing and Yang, Lei and Ju, Xuan and Li, Jiefeng and Wang, Jianyi and Xu, Qiang},
+ journal={arXiv preprint arXiv:2112.13715},
+ year={2021}
+}
+```
+
+
+
+
+
+
+Human3.6M (TPAMI'2014)
+
+```bibtex
+@article{h36m_pami,
+ author = {Ionescu, Catalin and Papava, Dragos and Olaru, Vlad and Sminchisescu, Cristian},
+ title = {Human3.6M: Large Scale Datasets and Predictive Methods for 3D Human Sensing in Natural Environments},
+ journal = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
+ publisher = {IEEE Computer Society},
+ volume = {36},
+ number = {7},
+ pages = {1325-1339},
+ month = {jul},
+ year = {2014}
+}
+```
+
+
+
+The following SmoothNet model checkpoints are available for pose smoothing. The table shows the the performance of [SimpleBaseline3D](https://arxiv.org/abs/1705.03098) on [Human3.6M](https://ieeexplore.ieee.org/abstract/document/6682899/) dataset without/with the SmoothNet plugin, and compares the SmoothNet models with 4 different window sizes (8, 16, 32 and 64). The metrics are MPJPE(mm), P-MEJPE(mm) and Acceleration Error (mm/frame^2).
+
+| Arch | Window Size | MPJPEw/o | MPJPEw | P-MPJPEw/o | P-MPJPEw | AC. Errw/o | AC. Errw | ckpt |
+| :----------------------------------- | :---------: | :-----------------: | :---------------: | :-------------------: | :-----------------: | :-------------------: | :-----------------: | :-----------------------------------: |
+| [smoothnet_ws8](/configs/_base_/filters/smoothnet_t8_h36m.py) | 8 | 54.48 | 53.15 | 42.20 | 41.32 | 19.18 | 1.87 | [ckpt](https://download.openmmlab.com/mmpose/plugin/smoothnet/smoothnet_ws8_h36m.pth) |
+| [smoothnet_ws16](/configs/_base_/filters/smoothnet_t16_h36m.py) | 16 | 54.48 | 52.74 | 42.20 | 41.20 | 19.18 | 1.22 | [ckpt](https://download.openmmlab.com/mmpose/plugin/smoothnet/smoothnet_ws16_h36m.pth) |
+| [smoothnet_ws32](/configs/_base_/filters/smoothnet_t32_h36m.py) | 32 | 54.48 | 52.47 | 42.20 | 40.84 | 19.18 | 0.99 | [ckpt](https://download.openmmlab.com/mmpose/plugin/smoothnet/smoothnet_ws32_h36m.pth) |
+| [smoothnet_ws64](/configs/_base_/filters/smoothnet_t64_h36m.py) | 64 | 54.48 | 53.37 | 42.20 | 40.77 | 19.18 | 0.92 | [ckpt](https://download.openmmlab.com/mmpose/plugin/smoothnet/smoothnet_ws64_h36m.pth) |
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t16_h36m.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t16_h36m.py
new file mode 100644
index 0000000000000000000000000000000000000000..0cc0c3be924b59056b6b92e1a9f97978cce4a3e2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t16_h36m.py
@@ -0,0 +1,13 @@
+# Config for SmoothNet filter trained on Human3.6M data with a window size of
+# 16. The model is trained using root-centered keypoint coordinates around the
+# pelvis (index:0), thus we set root_index=0 for the filter
+filter_cfg = dict(
+ type='SmoothNetFilter',
+ window_size=16,
+ output_size=16,
+ checkpoint='https://download.openmmlab.com/mmpose/plugin/smoothnet/'
+ 'smoothnet_ws16_h36m.pth',
+ hidden_size=512,
+ res_hidden_size=256,
+ num_blocks=3,
+ root_index=0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t32_h36m.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t32_h36m.py
new file mode 100644
index 0000000000000000000000000000000000000000..dae59f3b81e2adceec532079a3849de23772f0eb
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t32_h36m.py
@@ -0,0 +1,13 @@
+# Config for SmoothNet filter trained on Human3.6M data with a window size of
+# 32. The model is trained using root-centered keypoint coordinates around the
+# pelvis (index:0), thus we set root_index=0 for the filter
+filter_cfg = dict(
+ type='SmoothNetFilter',
+ window_size=32,
+ output_size=32,
+ checkpoint='https://download.openmmlab.com/mmpose/plugin/smoothnet/'
+ 'smoothnet_ws32_h36m.pth',
+ hidden_size=512,
+ res_hidden_size=256,
+ num_blocks=3,
+ root_index=0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t64_h36m.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t64_h36m.py
new file mode 100644
index 0000000000000000000000000000000000000000..aef2993272cef9fff1d7f8c882507781064d44b7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t64_h36m.py
@@ -0,0 +1,13 @@
+# Config for SmoothNet filter trained on Human3.6M data with a window size of
+# 64. The model is trained using root-centered keypoint coordinates around the
+# pelvis (index:0), thus we set root_index=0 for the filter
+filter_cfg = dict(
+ type='SmoothNetFilter',
+ window_size=64,
+ output_size=64,
+ checkpoint='https://download.openmmlab.com/mmpose/plugin/smoothnet/'
+ 'smoothnet_ws64_h36m.pth',
+ hidden_size=512,
+ res_hidden_size=256,
+ num_blocks=3,
+ root_index=0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t8_h36m.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t8_h36m.py
new file mode 100644
index 0000000000000000000000000000000000000000..cadd8865dc75d2247a8b4af6036131963aa4d4a5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/_base_/filters/smoothnet_t8_h36m.py
@@ -0,0 +1,13 @@
+# Config for SmoothNet filter trained on Human3.6M data with a window size of
+# 8. The model is trained using root-centered keypoint coordinates around the
+# pelvis (index:0), thus we set root_index=0 for the filter
+filter_cfg = dict(
+ type='SmoothNetFilter',
+ window_size=8,
+ output_size=8,
+ checkpoint='https://download.openmmlab.com/mmpose/plugin/smoothnet/'
+ 'smoothnet_ws8_h36m.pth',
+ hidden_size=512,
+ res_hidden_size=256,
+ num_blocks=3,
+ root_index=0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/config.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/config.py
new file mode 100644
index 0000000000000000000000000000000000000000..304cbc17d7f620f55e424855abdfb6922779a66e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/config.py
@@ -0,0 +1,47 @@
+import os
+import os.path as osp
+import sys
+
+class Config:
+
+ ## model setting
+ resnet_type = 50
+ hand_resnet_type = 50
+ face_resnet_type = 18
+
+ model_type = 'OSX'
+
+ # osx_model_settiing
+ upscale = 4
+ with_wrist = False
+ hand_pos_joint_num = 20
+ num_task_token = 24
+ feat_dim = 1024
+ encoder_config_file = 'grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_large.py'
+
+ ## input, output
+ input_img_shape = (512, 384)
+ input_body_shape = (256, 192)
+ output_hm_shape = (16, 16, 12)
+ # output_hm_shape = (8, 8, 6)
+ input_hand_shape = (256, 256)
+ # output_hand_hm_shape = (8, 8, 8)
+ output_hand_hm_shape = (16, 16, 16)
+ input_face_shape = (192, 192)
+ focal = (5000, 5000) # virtual focal lengths
+ princpt = (input_body_shape[1]/2, input_body_shape[0]/2) # virtual principal point position
+ body_3d_size = 2
+ hand_3d_size = 0.3
+ face_3d_size = 0.3
+ camera_3d_size = 2.5
+
+ ## human models
+ flame_shape_params = 100
+ flame_expression_params = 50
+
+ ## directory
+ cur_dir = osp.dirname(os.path.abspath(__file__))
+
+ human_model_path = osp.join(cur_dir, 'utils', 'human_model_files')
+
+cfg = Config()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/install.sh b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/install.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9590f3e371632cb012f459281cf8e78bec99c371
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/install.sh
@@ -0,0 +1,5 @@
+#!/bin/bash
+pip install openmim
+mim install mmcv-full==1.7.1
+pip install -r requirements.txt
+cd transformer_utils && python setup.py install
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/layer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/layer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a316ae923fd35138971786edd76b2cfd98382238
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/layer.py
@@ -0,0 +1,56 @@
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+from config import cfg
+
+def make_linear_layers(feat_dims, relu_final=True, use_bn=False):
+ layers = []
+ for i in range(len(feat_dims)-1):
+ layers.append(nn.Linear(feat_dims[i], feat_dims[i+1]))
+
+ # Do not use ReLU for final estimation
+ if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and relu_final):
+ if use_bn:
+ layers.append(nn.BatchNorm1d(feat_dims[i+1]))
+ layers.append(nn.ReLU(inplace=True))
+
+ return nn.Sequential(*layers)
+
+def make_conv_layers(feat_dims, kernel=3, stride=1, padding=1, bnrelu_final=True):
+ layers = []
+ for i in range(len(feat_dims)-1):
+ layers.append(
+ nn.Conv2d(
+ in_channels=feat_dims[i],
+ out_channels=feat_dims[i+1],
+ kernel_size=kernel,
+ stride=stride,
+ padding=padding
+ ))
+ # Do not use BN and ReLU for final estimation
+ if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and bnrelu_final):
+ layers.append(nn.BatchNorm2d(feat_dims[i+1]))
+ layers.append(nn.ReLU(inplace=True))
+
+ return nn.Sequential(*layers)
+
+def make_deconv_layers(feat_dims, bnrelu_final=True):
+ layers = []
+ for i in range(len(feat_dims)-1):
+ layers.append(
+ nn.ConvTranspose2d(
+ in_channels=feat_dims[i],
+ out_channels=feat_dims[i+1],
+ kernel_size=4,
+ stride=2,
+ padding=1,
+ output_padding=0,
+ bias=False))
+
+ # Do not use BN and ReLU for final estimation
+ if i < len(feat_dims)-2 or (i == len(feat_dims)-2 and bnrelu_final):
+ layers.append(nn.BatchNorm2d(feat_dims[i+1]))
+ layers.append(nn.ReLU(inplace=True))
+
+ return nn.Sequential(*layers)
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/module.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/module.py
new file mode 100644
index 0000000000000000000000000000000000000000..630c8d1c721879dafd3e0d436ad6f29cb4675a22
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/nets/module.py
@@ -0,0 +1,172 @@
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+from nets.layer import make_conv_layers, make_linear_layers, make_deconv_layers
+from utils.transforms import sample_joint_features, soft_argmax_2d, soft_argmax_3d
+from utils.human_models import smpl_x
+from config import cfg
+from mmcv.ops.roi_align import roi_align
+
+class PositionNet(nn.Module):
+ def __init__(self, part, feat_dim=768):
+ super(PositionNet, self).__init__()
+ if part == 'body':
+ self.joint_num = len(smpl_x.pos_joint_part['body'])
+ self.hm_shape = cfg.output_hm_shape
+ elif part == 'hand':
+ self.joint_num = len(smpl_x.pos_joint_part['rhand'])
+ self.hm_shape = cfg.output_hand_hm_shape
+ self.conv = make_conv_layers([feat_dim, self.joint_num * self.hm_shape[0]], kernel=1, stride=1, padding=0, bnrelu_final=False)
+
+ def forward(self, img_feat):
+ joint_hm = self.conv(img_feat).view(-1, self.joint_num, self.hm_shape[0], self.hm_shape[1], self.hm_shape[2])
+ joint_coord = soft_argmax_3d(joint_hm)
+ joint_hm = F.softmax(joint_hm.view(-1, self.joint_num, self.hm_shape[0] * self.hm_shape[1] * self.hm_shape[2]), 2)
+ joint_hm = joint_hm.view(-1, self.joint_num, self.hm_shape[0], self.hm_shape[1], self.hm_shape[2])
+ return joint_hm, joint_coord
+
+class HandRotationNet(nn.Module):
+ def __init__(self, part, feat_dim = 768):
+ super(HandRotationNet, self).__init__()
+ self.part = part
+ self.joint_num = len(smpl_x.pos_joint_part['rhand'])
+ self.hand_conv = make_conv_layers([feat_dim, 512], kernel=1, stride=1, padding=0)
+ self.hand_pose_out = make_linear_layers([self.joint_num * 515, len(smpl_x.orig_joint_part['rhand']) * 6], relu_final=False)
+ self.feat_dim = feat_dim
+
+ def forward(self, img_feat, joint_coord_img):
+ batch_size = img_feat.shape[0]
+ img_feat = self.hand_conv(img_feat)
+ img_feat_joints = sample_joint_features(img_feat, joint_coord_img[:, :, :2])
+ feat = torch.cat((img_feat_joints, joint_coord_img), 2) # batch_size, joint_num, 512+3
+ hand_pose = self.hand_pose_out(feat.view(batch_size, -1))
+ return hand_pose
+
+class BodyRotationNet(nn.Module):
+ def __init__(self, feat_dim = 768):
+ super(BodyRotationNet, self).__init__()
+ self.joint_num = len(smpl_x.pos_joint_part['body'])
+ self.body_conv = make_linear_layers([feat_dim, 512], relu_final=False)
+ self.root_pose_out = make_linear_layers([self.joint_num * (512+3), 6], relu_final=False)
+ self.body_pose_out = make_linear_layers(
+ [self.joint_num * (512+3), (len(smpl_x.orig_joint_part['body']) - 1) * 6], relu_final=False) # without root
+ self.shape_out = make_linear_layers([feat_dim, smpl_x.shape_param_dim], relu_final=False)
+ self.cam_out = make_linear_layers([feat_dim, 3], relu_final=False)
+ self.feat_dim = feat_dim
+
+ def forward(self, body_pose_token, shape_token, cam_token, body_joint_img):
+ batch_size = body_pose_token.shape[0]
+
+ # shape parameter
+ shape_param = self.shape_out(shape_token)
+
+ # camera parameter
+ cam_param = self.cam_out(cam_token)
+
+ # body pose parameter
+ body_pose_token = self.body_conv(body_pose_token)
+ body_pose_token = torch.cat((body_pose_token, body_joint_img), 2)
+ root_pose = self.root_pose_out(body_pose_token.view(batch_size, -1))
+ body_pose = self.body_pose_out(body_pose_token.view(batch_size, -1))
+
+ return root_pose, body_pose, shape_param, cam_param
+
+class FaceRegressor(nn.Module):
+ def __init__(self, feat_dim=768):
+ super(FaceRegressor, self).__init__()
+ self.expr_out = make_linear_layers([feat_dim, smpl_x.expr_code_dim], relu_final=False)
+ self.jaw_pose_out = make_linear_layers([feat_dim, 6], relu_final=False)
+
+ def forward(self, expr_token, jaw_pose_token):
+ expr_param = self.expr_out(expr_token) # expression parameter
+ jaw_pose = self.jaw_pose_out(jaw_pose_token) # jaw pose parameter
+ return expr_param, jaw_pose
+
+class BoxNet(nn.Module):
+ def __init__(self, feat_dim=768):
+ super(BoxNet, self).__init__()
+ self.joint_num = len(smpl_x.pos_joint_part['body'])
+ self.deconv = make_deconv_layers([feat_dim + self.joint_num * cfg.output_hm_shape[0], 256, 256, 256])
+ self.bbox_center = make_conv_layers([256, 3], kernel=1, stride=1, padding=0, bnrelu_final=False)
+ self.lhand_size = make_linear_layers([256, 256, 2], relu_final=False)
+ self.rhand_size = make_linear_layers([256, 256, 2], relu_final=False)
+ self.face_size = make_linear_layers([256, 256, 2], relu_final=False)
+
+ def forward(self, img_feat, joint_hm):
+ joint_hm = joint_hm.view(joint_hm.shape[0], joint_hm.shape[1] * cfg.output_hm_shape[0], cfg.output_hm_shape[1], cfg.output_hm_shape[2])
+ img_feat = torch.cat((img_feat, joint_hm), 1)
+ img_feat = self.deconv(img_feat)
+
+ # bbox center
+ bbox_center_hm = self.bbox_center(img_feat)
+ bbox_center = soft_argmax_2d(bbox_center_hm)
+ lhand_center, rhand_center, face_center = bbox_center[:, 0, :], bbox_center[:, 1, :], bbox_center[:, 2, :]
+
+ # bbox size
+ lhand_feat = sample_joint_features(img_feat, lhand_center[:, None, :].detach())[:, 0, :]
+ lhand_size = self.lhand_size(lhand_feat)
+ rhand_feat = sample_joint_features(img_feat, rhand_center[:, None, :].detach())[:, 0, :]
+ rhand_size = self.rhand_size(rhand_feat)
+ face_feat = sample_joint_features(img_feat, face_center[:, None, :].detach())[:, 0, :]
+ face_size = self.face_size(face_feat)
+
+ lhand_center = lhand_center / 8
+ rhand_center = rhand_center / 8
+ face_center = face_center / 8
+ return lhand_center, lhand_size, rhand_center, rhand_size, face_center, face_size
+
+class BoxSizeNet(nn.Module):
+ def __init__(self):
+ super(BoxSizeNet, self).__init__()
+ self.lhand_size = make_linear_layers([256, 256, 2], relu_final=False)
+ self.rhand_size = make_linear_layers([256, 256, 2], relu_final=False)
+ self.face_size = make_linear_layers([256, 256, 2], relu_final=False)
+
+ def forward(self, box_fea):
+ # box_fea: [bs, 3, C]
+ lhand_size = self.lhand_size(box_fea[:, 0])
+ rhand_size = self.rhand_size(box_fea[:, 1])
+ face_size = self.face_size(box_fea[:, 2])
+ return lhand_size, rhand_size, face_size
+
+class HandRoI(nn.Module):
+ def __init__(self, feat_dim=768, upscale=4):
+ super(HandRoI, self).__init__()
+ self.upscale = upscale
+ if upscale==1:
+ self.deconv = make_conv_layers([feat_dim, feat_dim], kernel=1, stride=1, padding=0, bnrelu_final=False)
+ self.conv = make_conv_layers([feat_dim, feat_dim], kernel=1, stride=1, padding=0, bnrelu_final=False)
+ elif upscale==2:
+ self.deconv = make_deconv_layers([feat_dim, feat_dim//2])
+ self.conv = make_conv_layers([feat_dim//2, feat_dim], kernel=1, stride=1, padding=0, bnrelu_final=False)
+ elif upscale==4:
+ self.deconv = make_deconv_layers([feat_dim, feat_dim//2, feat_dim//4])
+ self.conv = make_conv_layers([feat_dim//4, feat_dim], kernel=1, stride=1, padding=0, bnrelu_final=False)
+ elif upscale==8:
+ self.deconv = make_deconv_layers([feat_dim, feat_dim//2, feat_dim//4, feat_dim//8])
+ self.conv = make_conv_layers([feat_dim//8, feat_dim], kernel=1, stride=1, padding=0, bnrelu_final=False)
+
+ def forward(self, img_feat, lhand_bbox, rhand_bbox):
+ lhand_bbox = torch.cat((torch.arange(lhand_bbox.shape[0]).float().cuda()[:, None], lhand_bbox),
+ 1) # batch_idx, xmin, ymin, xmax, ymax
+ rhand_bbox = torch.cat((torch.arange(rhand_bbox.shape[0]).float().cuda()[:, None], rhand_bbox),
+ 1) # batch_idx, xmin, ymin, xmax, ymax
+ img_feat = self.deconv(img_feat)
+ lhand_bbox_roi = lhand_bbox.clone()
+ lhand_bbox_roi[:, 1] = lhand_bbox_roi[:, 1] / cfg.input_body_shape[1] * cfg.output_hm_shape[2] * self.upscale
+ lhand_bbox_roi[:, 2] = lhand_bbox_roi[:, 2] / cfg.input_body_shape[0] * cfg.output_hm_shape[1] * self.upscale
+ lhand_bbox_roi[:, 3] = lhand_bbox_roi[:, 3] / cfg.input_body_shape[1] * cfg.output_hm_shape[2] * self.upscale
+ lhand_bbox_roi[:, 4] = lhand_bbox_roi[:, 4] / cfg.input_body_shape[0] * cfg.output_hm_shape[1] * self.upscale
+ assert (cfg.output_hm_shape[1]*self.upscale, cfg.output_hm_shape[2]*self.upscale) == (img_feat.shape[2], img_feat.shape[3])
+ lhand_img_feat = roi_align(img_feat, lhand_bbox_roi, (cfg.output_hand_hm_shape[1], cfg.output_hand_hm_shape[2]), 1.0, 0, 'avg', False)
+ lhand_img_feat = torch.flip(lhand_img_feat, [3]) # flip to the right hand
+
+ rhand_bbox_roi = rhand_bbox.clone()
+ rhand_bbox_roi[:, 1] = rhand_bbox_roi[:, 1] / cfg.input_body_shape[1] * cfg.output_hm_shape[2] * self.upscale
+ rhand_bbox_roi[:, 2] = rhand_bbox_roi[:, 2] / cfg.input_body_shape[0] * cfg.output_hm_shape[1] * self.upscale
+ rhand_bbox_roi[:, 3] = rhand_bbox_roi[:, 3] / cfg.input_body_shape[1] * cfg.output_hm_shape[2] * self.upscale
+ rhand_bbox_roi[:, 4] = rhand_bbox_roi[:, 4] / cfg.input_body_shape[0] * cfg.output_hm_shape[1] * self.upscale
+ rhand_img_feat = roi_align(img_feat, rhand_bbox_roi, (cfg.output_hand_hm_shape[1], cfg.output_hand_hm_shape[2]), 1.0, 0, 'avg', False)
+ hand_img_feat = torch.cat((lhand_img_feat, rhand_img_feat)) # [bs, c, cfg.output_hand_hm_shape[2]*scale, cfg.output_hand_hm_shape[1]*scale]
+ hand_img_feat = self.conv(hand_img_feat)
+ return hand_img_feat
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/osx.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/osx.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4da24d75cdd4b3217cf9b1efc5ff286b411ae3c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/osx.py
@@ -0,0 +1,153 @@
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+from nets.module import PositionNet, HandRotationNet, FaceRegressor, BoxNet, HandRoI, BodyRotationNet
+
+from utils.human_models import smpl_x
+from utils.transforms import rot6d_to_axis_angle, restore_bbox
+from config import cfg
+import math
+import copy
+from mmpose.models import build_posenet
+from mmcv import Config
+
+class Model(nn.Module):
+ def __init__(self, encoder, body_position_net, body_rotation_net, box_net, hand_position_net, hand_roi_net,
+ hand_rotation_net, face_regressor):
+ super(Model, self).__init__()
+
+ # body
+ self.backbone = encoder
+ self.body_position_net = body_position_net
+ self.body_rotation_net = body_rotation_net
+ self.box_net = box_net
+
+ # hand
+ self.hand_roi_net = hand_roi_net
+ self.hand_position_net = hand_position_net
+ self.hand_rotation_net = hand_rotation_net
+
+ # face
+ self.face_regressor = face_regressor
+
+ self.smplx_layer = copy.deepcopy(smpl_x.layer['neutral']).cuda()
+
+ self.body_num_joints = len(smpl_x.pos_joint_part['body'])
+ self.hand_joint_num = len(smpl_x.pos_joint_part['rhand'])
+
+ def get_camera_trans(self, cam_param):
+ # camera translation
+ t_xy = cam_param[:, :2]
+ gamma = torch.sigmoid(cam_param[:, 2]) # apply sigmoid to make it positive
+ k_value = torch.FloatTensor([math.sqrt(cfg.focal[0] * cfg.focal[1] * cfg.camera_3d_size * cfg.camera_3d_size / (
+ cfg.input_body_shape[0] * cfg.input_body_shape[1]))]).cuda().view(-1)
+ t_z = k_value * gamma
+ cam_trans = torch.cat((t_xy, t_z[:, None]), 1)
+ return cam_trans
+
+ def get_coord(self, root_pose, body_pose, lhand_pose, rhand_pose, jaw_pose, shape, expr, cam_trans, mode):
+ batch_size = root_pose.shape[0]
+ zero_pose = torch.zeros((1, 3)).float().cuda().repeat(batch_size, 1) # eye poses
+ output = self.smplx_layer(betas=shape, body_pose=body_pose, global_orient=root_pose, right_hand_pose=rhand_pose,
+ left_hand_pose=lhand_pose, jaw_pose=jaw_pose, leye_pose=zero_pose,
+ reye_pose=zero_pose, expression=expr)
+ # camera-centered 3D coordinate
+ vertices = output.vertices
+ # root-relative 3D coordinates
+ mesh_cam = vertices + cam_trans[:, None, :] # for rendering
+
+ return mesh_cam
+
+ def forward(self, inputs, mode):
+
+ # backbone
+ body_img = F.interpolate(inputs['img'], cfg.input_body_shape)
+
+ # 1. Encoder
+ img_feat, task_tokens = self.backbone(body_img) # task_token:[bs, N, c]
+ shape_token, cam_token, expr_token, jaw_pose_token, hand_token, body_pose_token = \
+ task_tokens[:, 0], task_tokens[:, 1], task_tokens[:, 2], task_tokens[:, 3], task_tokens[:,
+ 4:6], task_tokens[:, 6:]
+
+ # 2. Body Regressor
+ body_joint_hm, body_joint_img = self.body_position_net(img_feat)
+ root_pose, body_pose, shape, cam_param, = self.body_rotation_net(body_pose_token, shape_token, cam_token,
+ body_joint_img.detach())
+ root_pose = rot6d_to_axis_angle(root_pose)
+ body_pose = rot6d_to_axis_angle(body_pose.reshape(-1, 6)).reshape(body_pose.shape[0], -1) # (N, J_R*3)
+ cam_trans = self.get_camera_trans(cam_param)
+
+ # 3. Hand and Face BBox Estimation
+ lhand_bbox_center, lhand_bbox_size, rhand_bbox_center, rhand_bbox_size, face_bbox_center, face_bbox_size = self.box_net(
+ img_feat, body_joint_hm.detach())
+ lhand_bbox = restore_bbox(lhand_bbox_center, lhand_bbox_size, cfg.input_hand_shape[1] / cfg.input_hand_shape[0],
+ 2.0).detach() # xyxy in (cfg.input_body_shape[1], cfg.input_body_shape[0]) space
+ rhand_bbox = restore_bbox(rhand_bbox_center, rhand_bbox_size, cfg.input_hand_shape[1] / cfg.input_hand_shape[0],
+ 2.0).detach() # xyxy in (cfg.input_body_shape[1], cfg.input_body_shape[0]) space
+
+ # 4. Differentiable Feature-level Hand Crop-Upsample
+ # hand_feat: list, [bsx2, c, cfg.output_hm_shape[1]*scale, cfg.output_hm_shape[2]*scale]
+ hand_feat = self.hand_roi_net(img_feat, lhand_bbox, rhand_bbox) # hand_feat: flipped left hand + right hand
+
+ # 5. Hand/Face Regressor
+ # hand regressor
+ _, hand_joint_img = self.hand_position_net(hand_feat) # (2N, J_P, 3)
+ hand_pose = self.hand_rotation_net(hand_feat, hand_joint_img.detach())
+ hand_pose = rot6d_to_axis_angle(hand_pose.reshape(-1, 6)).reshape(hand_feat.shape[0], -1) # (2N, J_R*3)
+ batch_size = hand_pose.shape[0] // 2
+ lhand_pose = hand_pose[:batch_size, :].reshape(-1, len(smpl_x.orig_joint_part['lhand']), 3)
+ lhand_pose = torch.cat((lhand_pose[:, :, 0:1], -lhand_pose[:, :, 1:3]), 2).view(batch_size, -1)
+ rhand_pose = hand_pose[batch_size:, :]
+
+ # hand regressor
+ expr, jaw_pose = self.face_regressor(expr_token, jaw_pose_token)
+ jaw_pose = rot6d_to_axis_angle(jaw_pose)
+
+ # final output
+ mesh_cam = self.get_coord(root_pose, body_pose, lhand_pose, rhand_pose, jaw_pose, shape,
+ expr, cam_trans, mode)
+ # test output
+ out = {}
+ out['smplx_mesh_cam'] = mesh_cam
+ return out
+
+
+def init_weights(m):
+ try:
+ if type(m) == nn.ConvTranspose2d:
+ nn.init.normal_(m.weight, std=0.001)
+ elif type(m) == nn.Conv2d:
+ nn.init.normal_(m.weight, std=0.001)
+ nn.init.constant_(m.bias, 0)
+ elif type(m) == nn.BatchNorm2d:
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+ elif type(m) == nn.Linear:
+ nn.init.normal_(m.weight, std=0.01)
+ nn.init.constant_(m.bias, 0)
+ except AttributeError:
+ pass
+
+def get_model():
+ # body
+ vit_cfg = Config.fromfile(cfg.encoder_config_file)
+ vit = build_posenet(vit_cfg.model)
+ body_position_net = PositionNet('body', feat_dim=cfg.feat_dim)
+ body_rotation_net = BodyRotationNet(feat_dim=cfg.feat_dim)
+ box_net = BoxNet(feat_dim=cfg.feat_dim)
+
+ # hand
+ hand_position_net = PositionNet('hand', feat_dim=cfg.feat_dim)
+ hand_roi_net = HandRoI(feat_dim=cfg.feat_dim, upscale=cfg.upscale)
+ hand_rotation_net = HandRotationNet('hand', feat_dim=cfg.feat_dim)
+
+ # face
+ face_regressor = FaceRegressor(feat_dim=cfg.feat_dim)
+
+ # scale
+ encoder = vit.backbone
+ model = Model(encoder, body_position_net, body_rotation_net, box_net, hand_position_net, hand_roi_net,
+ hand_rotation_net,
+ face_regressor)
+
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/requirements.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ee29e184451e8303a129ab6837a941de84f67766
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/requirements.txt
@@ -0,0 +1,28 @@
+numpy
+scikit-image
+scipy
+scikit-learn
+smplx==0.1.28
+tqdm
+yacs
+numba
+opencv-python
+tensorboardx
+filterpy
+cython
+chumpy
+Pillow
+trimesh
+pyrender
+matplotlib
+json_tricks
+torchgeometry
+einops
+joblib
+boto3
+requests
+easydict
+pycocotools
+plyfile
+timm
+pyglet==1.5.27
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/.gitignore b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/.gitignore
new file mode 100644
index 0000000000000000000000000000000000000000..e792015fe7abb9597efbe787d25d0c4d242ef42b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/.gitignore
@@ -0,0 +1,141 @@
+
+
+# Byte-compiled / optimized / DLL files
+__pycache__/
+*.py[cod]
+*$py.class
+**/*.pyc
+
+# C extensions
+*.so
+
+# Distribution / packaging
+.Python
+build/
+develop-eggs/
+dist/
+downloads/
+eggs/
+.eggs/
+lib/
+lib64/
+parts/
+sdist/
+var/
+wheels/
+*.egg-info/
+.installed.cfg
+*.egg
+MANIFEST
+
+# PyInstaller
+# Usually these files are written by a python script from a template
+# before PyInstaller builds the exe, so as to inject date/other infos into it.
+*.manifest
+*.spec
+
+# Installer logs
+pip-log.txt
+pip-delete-this-directory.txt
+
+# Unit test / coverage reports
+htmlcov/
+.tox/
+.coverage
+.coverage.*
+.cache
+nosetests.xml
+coverage.xml
+*.cover
+.hypothesis/
+.pytest_cache/
+
+# Translations
+*.mo
+*.pot
+
+# Django stuff:
+*.log
+local_settings.py
+db.sqlite3
+
+# Flask stuff:
+instance/
+.webassets-cache
+
+# Scrapy stuff:
+.scrapy
+
+# Sphinx documentation
+docs/en/_build
+docs/zh_cn/_build
+
+# PyBuilder
+target/
+
+# Jupyter Notebook
+.ipynb_checkpoints
+
+# pyenv
+.python-version
+
+# celery beat schedule file
+celerybeat-schedule
+
+# SageMath parsed files
+*.sage.py
+
+# Environments
+.env
+.venv
+env/
+venv/
+ENV/
+env.bak/
+venv.bak/
+
+# Spyder project settings
+.spyderproject
+.spyproject
+
+# Rope project settings
+.ropeproject
+
+# mkdocs documentation
+/site
+
+# mypy
+.mypy_cache/
+
+# custom
+mmpose/.mim
+/models
+/data
+.vscode
+.idea
+*.pkl
+*.pkl.json
+*.log.json
+*.npy
+work_dirs/
+docs/**/topics/
+docs/**/papers/*.md
+docs/**/datasets.md
+docs/**/modelzoo.md
+
+!tests/data/**/*.pkl
+!tests/data/**/*.pkl.json
+!tests/data/**/*.log.json
+!tests/data/**/*.pth
+!tests/data/**/*.npy
+
+# Pytorch
+*.pth
+
+*.DS_Store
+
+# checkpoints
+ckpts/
+vis_results
+vis_results_poseur
+scripts
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/CITATION.cff b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/CITATION.cff
new file mode 100644
index 0000000000000000000000000000000000000000..067f4ff996793aa8b8a5f39d35f43c0e275cfa64
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/CITATION.cff
@@ -0,0 +1,8 @@
+cff-version: 1.2.0
+message: "If you use this software, please cite it as below."
+authors:
+ - name: "Poseur Contributors"
+title: "Poseur: Direct Human Pose Regression with Transformers"
+date-released: 2022-07-21
+url: "https://github.com/aim-uofa/Poseur"
+license: 2-clause BSD
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..acab10d9e2ab392bd0839978663306846c56aca3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/LICENSE
@@ -0,0 +1,677 @@
+Poseur for non-commercial purposes
+(For commercial use, contact chhshen@gmail.com for obtaining a commerical license.)
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/MANIFEST.in b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/MANIFEST.in
new file mode 100644
index 0000000000000000000000000000000000000000..8a93c252bd38bafddc390bc9ae9b7278e3479246
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/MANIFEST.in
@@ -0,0 +1,5 @@
+include requirements/*.txt
+include mmpose/.mim/model-index.yml
+recursive-include mmpose/.mim/configs *.py *.yml
+recursive-include mmpose/.mim/tools *.py *.sh
+recursive-include mmpose/.mim/demo *.py
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_base.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..26bdb9a4350e5fd371442113db8eb009d89cb649
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_base.py
@@ -0,0 +1,169 @@
+_base_ = [
+ '../../../../_base_/default_runtime.py',
+ '../../../../_base_/datasets/coco.py'
+]
+evaluation = dict(interval=10, metric='mAP', save_best='AP')
+
+optimizer = dict(type='AdamW', lr=5e-4, betas=(0.9, 0.999), weight_decay=0.1,
+ constructor='LayerDecayOptimizerConstructor',
+ paramwise_cfg=dict(
+ num_layers=12,
+ layer_decay_rate=0.75,
+ custom_keys={
+ 'bias': dict(decay_multi=0.),
+ 'pos_embed': dict(decay_mult=0.),
+ 'relative_position_bias_table': dict(decay_mult=0.),
+ 'norm': dict(decay_mult=0.)
+ }
+ )
+ )
+
+optimizer_config = dict(grad_clip=dict(max_norm=1., norm_type=2))
+
+# learning policy
+lr_config = dict(
+ policy='step',
+ warmup='linear',
+ warmup_iters=500,
+ warmup_ratio=0.001,
+ step=[170, 200])
+total_epochs = 210
+target_type = 'GaussianHeatmap'
+channel_cfg = dict(
+ num_output_channels=17,
+ dataset_joints=17,
+ dataset_channel=[
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
+ ],
+ inference_channel=[
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
+ ])
+
+# model settings
+model = dict(
+ type='TopDown',
+ pretrained=None,
+ backbone=dict(
+ type='ViT',
+ img_size=(256, 192),
+ patch_size=16,
+ embed_dim=768,
+ depth=12,
+ num_heads=12,
+ ratio=1,
+ use_checkpoint=False,
+ mlp_ratio=4,
+ qkv_bias=True,
+ drop_path_rate=0.3,
+ ),
+ keypoint_head=dict(
+ type='TopdownHeatmapSimpleHead',
+ in_channels=768,
+ num_deconv_layers=2,
+ num_deconv_filters=(256, 256),
+ num_deconv_kernels=(4, 4),
+ extra=dict(final_conv_kernel=1, ),
+ out_channels=channel_cfg['num_output_channels'],
+ loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)),
+ train_cfg=dict(),
+ test_cfg=dict(
+ flip_test=True,
+ post_process='default',
+ shift_heatmap=False,
+ target_type=target_type,
+ modulate_kernel=11,
+ use_udp=True))
+
+data_cfg = dict(
+ image_size=[192, 256],
+ heatmap_size=[48, 64],
+ num_output_channels=channel_cfg['num_output_channels'],
+ num_joints=channel_cfg['dataset_joints'],
+ dataset_channel=channel_cfg['dataset_channel'],
+ inference_channel=channel_cfg['inference_channel'],
+ soft_nms=False,
+ nms_thr=1.0,
+ oks_thr=0.9,
+ vis_thr=0.2,
+ use_gt_bbox=False,
+ det_bbox_thr=0.0,
+ bbox_file='data/coco/person_detection_results/'
+ 'COCO_val2017_detections_AP_H_56_person.json',
+)
+
+train_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='TopDownRandomFlip', flip_prob=0.5),
+ dict(
+ type='TopDownHalfBodyTransform',
+ num_joints_half_body=8,
+ prob_half_body=0.3),
+ dict(
+ type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5),
+ dict(type='TopDownAffine', use_udp=True),
+ dict(type='ToTensor'),
+ dict(
+ type='NormalizeTensor',
+ mean=[0.485, 0.456, 0.406],
+ std=[0.229, 0.224, 0.225]),
+ dict(
+ type='TopDownGenerateTarget',
+ sigma=2,
+ encoding='UDP',
+ target_type=target_type),
+ dict(
+ type='Collect',
+ keys=['img', 'target', 'target_weight'],
+ meta_keys=[
+ 'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale',
+ 'rotation', 'bbox_score', 'flip_pairs'
+ ]),
+]
+
+val_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='TopDownAffine', use_udp=True),
+ dict(type='ToTensor'),
+ dict(
+ type='NormalizeTensor',
+ mean=[0.485, 0.456, 0.406],
+ std=[0.229, 0.224, 0.225]),
+ dict(
+ type='Collect',
+ keys=['img'],
+ meta_keys=[
+ 'image_file', 'center', 'scale', 'rotation', 'bbox_score',
+ 'flip_pairs'
+ ]),
+]
+
+test_pipeline = val_pipeline
+
+data_root = 'data/coco'
+data = dict(
+ samples_per_gpu=64,
+ workers_per_gpu=4,
+ val_dataloader=dict(samples_per_gpu=32),
+ test_dataloader=dict(samples_per_gpu=32),
+ train=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_train2017.json',
+ img_prefix=f'{data_root}/train2017/',
+ data_cfg=data_cfg,
+ pipeline=train_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+ val=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_val2017.json',
+ img_prefix=f'{data_root}/val2017/',
+ data_cfg=data_cfg,
+ pipeline=val_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+ test=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_val2017.json',
+ img_prefix=f'{data_root}/val2017/',
+ data_cfg=data_cfg,
+ pipeline=test_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_large.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_large.py
new file mode 100644
index 0000000000000000000000000000000000000000..efd95afa09d8326f2a76c55ca1eea85c6cb60dcc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/configs/osx/encoder/body_encoder_large.py
@@ -0,0 +1,169 @@
+_base_ = [
+ '../../../../_base_/default_runtime.py',
+ '../../../../_base_/datasets/coco.py'
+]
+evaluation = dict(interval=10, metric='mAP', save_best='AP')
+
+optimizer = dict(type='AdamW', lr=5e-4, betas=(0.9, 0.999), weight_decay=0.1,
+ constructor='LayerDecayOptimizerConstructor',
+ paramwise_cfg=dict(
+ num_layers=16,
+ layer_decay_rate=0.8,
+ custom_keys={
+ 'bias': dict(decay_multi=0.),
+ 'pos_embed': dict(decay_mult=0.),
+ 'relative_position_bias_table': dict(decay_mult=0.),
+ 'norm': dict(decay_mult=0.)
+ }
+ )
+ )
+
+optimizer_config = dict(grad_clip=dict(max_norm=1., norm_type=2))
+
+# learning policy
+lr_config = dict(
+ policy='step',
+ warmup='linear',
+ warmup_iters=500,
+ warmup_ratio=0.001,
+ step=[170, 200])
+total_epochs = 210
+target_type = 'GaussianHeatmap'
+channel_cfg = dict(
+ num_output_channels=17,
+ dataset_joints=17,
+ dataset_channel=[
+ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
+ ],
+ inference_channel=[
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16
+ ])
+
+# model settings
+model = dict(
+ type='TopDown',
+ pretrained=None,
+ backbone=dict(
+ type='ViT',
+ img_size=(256, 192),
+ patch_size=16,
+ embed_dim=1024,
+ depth=24,
+ num_heads=16,
+ ratio=1,
+ use_checkpoint=False,
+ mlp_ratio=4,
+ qkv_bias=True,
+ drop_path_rate=0.5,
+ ),
+ keypoint_head=dict(
+ type='TopdownHeatmapSimpleHead',
+ in_channels=1024,
+ num_deconv_layers=2,
+ num_deconv_filters=(256, 256),
+ num_deconv_kernels=(4, 4),
+ extra=dict(final_conv_kernel=1, ),
+ out_channels=channel_cfg['num_output_channels'],
+ loss_keypoint=dict(type='JointsMSELoss', use_target_weight=True)),
+ train_cfg=dict(),
+ test_cfg=dict(
+ flip_test=True,
+ post_process='default',
+ shift_heatmap=False,
+ target_type=target_type,
+ modulate_kernel=11,
+ use_udp=True))
+
+data_cfg = dict(
+ image_size=[192, 256],
+ heatmap_size=[48, 64],
+ num_output_channels=channel_cfg['num_output_channels'],
+ num_joints=channel_cfg['dataset_joints'],
+ dataset_channel=channel_cfg['dataset_channel'],
+ inference_channel=channel_cfg['inference_channel'],
+ soft_nms=False,
+ nms_thr=1.0,
+ oks_thr=0.9,
+ vis_thr=0.2,
+ use_gt_bbox=False,
+ det_bbox_thr=0.0,
+ bbox_file='data/coco/person_detection_results/'
+ 'COCO_val2017_detections_AP_H_56_person.json',
+)
+
+train_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='TopDownRandomFlip', flip_prob=0.5),
+ dict(
+ type='TopDownHalfBodyTransform',
+ num_joints_half_body=8,
+ prob_half_body=0.3),
+ dict(
+ type='TopDownGetRandomScaleRotation', rot_factor=40, scale_factor=0.5),
+ dict(type='TopDownAffine', use_udp=True),
+ dict(type='ToTensor'),
+ dict(
+ type='NormalizeTensor',
+ mean=[0.485, 0.456, 0.406],
+ std=[0.229, 0.224, 0.225]),
+ dict(
+ type='TopDownGenerateTarget',
+ sigma=2,
+ encoding='UDP',
+ target_type=target_type),
+ dict(
+ type='Collect',
+ keys=['img', 'target', 'target_weight'],
+ meta_keys=[
+ 'image_file', 'joints_3d', 'joints_3d_visible', 'center', 'scale',
+ 'rotation', 'bbox_score', 'flip_pairs'
+ ]),
+]
+
+val_pipeline = [
+ dict(type='LoadImageFromFile'),
+ dict(type='TopDownAffine', use_udp=True),
+ dict(type='ToTensor'),
+ dict(
+ type='NormalizeTensor',
+ mean=[0.485, 0.456, 0.406],
+ std=[0.229, 0.224, 0.225]),
+ dict(
+ type='Collect',
+ keys=['img'],
+ meta_keys=[
+ 'image_file', 'center', 'scale', 'rotation', 'bbox_score',
+ 'flip_pairs'
+ ]),
+]
+
+test_pipeline = val_pipeline
+
+data_root = 'data/coco'
+data = dict(
+ samples_per_gpu=64,
+ workers_per_gpu=4,
+ val_dataloader=dict(samples_per_gpu=32),
+ test_dataloader=dict(samples_per_gpu=32),
+ train=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_train2017.json',
+ img_prefix=f'{data_root}/train2017/',
+ data_cfg=data_cfg,
+ pipeline=train_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+ val=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_val2017.json',
+ img_prefix=f'{data_root}/val2017/',
+ data_cfg=data_cfg,
+ pipeline=val_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+ test=dict(
+ type='TopDownCocoDataset',
+ ann_file=f'{data_root}/annotations/person_keypoints_val2017.json',
+ img_prefix=f'{data_root}/val2017/',
+ data_cfg=data_cfg,
+ pipeline=test_pipeline,
+ dataset_info={{_base_.dataset_info}}),
+)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..abcf8693e279f59c8c80f55e1797841e593dbd72
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/__init__.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import mmcv
+import mmpose.ops
+from .version import __version__, short_version
+
+
+def digit_version(version_str):
+ digit_version = []
+ for x in version_str.split('.'):
+ if x.isdigit():
+ digit_version.append(int(x))
+ elif x.find('rc') != -1:
+ patch_version = x.split('rc')
+ digit_version.append(int(patch_version[0]) - 1)
+ digit_version.append(int(patch_version[1]))
+ return digit_version
+
+
+mmcv_minimum_version = '1.3.8'
+mmcv_maximum_version = '1.8.0'
+mmcv_version = digit_version(mmcv.__version__)
+
+
+assert (mmcv_version >= digit_version(mmcv_minimum_version)
+ and mmcv_version <= digit_version(mmcv_maximum_version)), \
+ f'MMCV=={mmcv.__version__} is used but incompatible. ' \
+ f'Please install mmcv>={mmcv_minimum_version}, <={mmcv_maximum_version}.'
+
+__all__ = ['__version__', 'short_version']
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..87f34c570a66dd58d6fb84f79b45063b89526d58
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .bbox import * # noqa: F401, F403
+from .camera import * # noqa: F401, F403
+from .evaluation import * # noqa: F401, F403
+from .fp16 import * # noqa: F401, F403
+from .optimizers import * # noqa: F401, F403
+from .post_processing import * # noqa: F401, F403
+from .utils import * # noqa: F401, F403
+from .visualization import * # noqa: F401, F403
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..557993386a6c5de8336a92514072c81b48419ba7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/__init__.py
@@ -0,0 +1,5 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .transforms import (bbox_cs2xywh, bbox_xywh2cs, bbox_xywh2xyxy,
+ bbox_xyxy2xywh)
+
+__all__ = ['bbox_xywh2xyxy', 'bbox_xyxy2xywh', 'bbox_xywh2cs', 'bbox_cs2xywh']
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/transforms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..703639443a9f327801b6e6b00ca278b2e22a0ee0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/bbox/transforms.py
@@ -0,0 +1,88 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+
+
+def bbox_xyxy2xywh(bbox_xyxy):
+ """Transform the bbox format from x1y1x2y2 to xywh.
+
+ Args:
+ bbox_xyxy (np.ndarray): Bounding boxes (with scores), shaped (n, 4) or
+ (n, 5). (left, top, right, bottom, [score])
+
+ Returns:
+ np.ndarray: Bounding boxes (with scores),
+ shaped (n, 4) or (n, 5). (left, top, width, height, [score])
+ """
+ bbox_xywh = bbox_xyxy.copy()
+ bbox_xywh[:, 2] = bbox_xywh[:, 2] - bbox_xywh[:, 0]
+ bbox_xywh[:, 3] = bbox_xywh[:, 3] - bbox_xywh[:, 1]
+
+ return bbox_xywh
+
+
+def bbox_xywh2xyxy(bbox_xywh):
+ """Transform the bbox format from xywh to x1y1x2y2.
+
+ Args:
+ bbox_xywh (ndarray): Bounding boxes (with scores),
+ shaped (n, 4) or (n, 5). (left, top, width, height, [score])
+ Returns:
+ np.ndarray: Bounding boxes (with scores), shaped (n, 4) or
+ (n, 5). (left, top, right, bottom, [score])
+ """
+ bbox_xyxy = bbox_xywh.copy()
+ bbox_xyxy[:, 2] = bbox_xyxy[:, 2] + bbox_xyxy[:, 0]
+ bbox_xyxy[:, 3] = bbox_xyxy[:, 3] + bbox_xyxy[:, 1]
+
+ return bbox_xyxy
+
+
+def bbox_xywh2cs(bbox, aspect_ratio, padding=1., pixel_std=200.):
+ """Transform the bbox format from (x,y,w,h) into (center, scale)
+
+ Args:
+ bbox (ndarray): Single bbox in (x, y, w, h)
+ aspect_ratio (float): The expected bbox aspect ratio (w over h)
+ padding (float): Bbox padding factor that will be multilied to scale.
+ Default: 1.0
+ pixel_std (float): The scale normalization factor. Default: 200.0
+
+ Returns:
+ tuple: A tuple containing center and scale.
+ - np.ndarray[float32](2,): Center of the bbox (x, y).
+ - np.ndarray[float32](2,): Scale of the bbox w & h.
+ """
+
+ x, y, w, h = bbox[:4]
+ center = np.array([x + w * 0.5, y + h * 0.5], dtype=np.float32)
+
+ if w > aspect_ratio * h:
+ h = w * 1.0 / aspect_ratio
+ elif w < aspect_ratio * h:
+ w = h * aspect_ratio
+
+ scale = np.array([w, h], dtype=np.float32) / pixel_std
+ scale = scale * padding
+
+ return center, scale
+
+
+def bbox_cs2xywh(center, scale, padding=1., pixel_std=200.):
+ """Transform the bbox format from (center, scale) to (x,y,w,h). Note that
+ this is not an exact inverse operation of ``bbox_xywh2cs`` because the
+ normalization of aspect ratio in ``bbox_xywh2cs`` is irreversible.
+
+ Args:
+ center (ndarray): Single bbox center in (x, y)
+ scale (ndarray): Single bbox scale in (scale_x, scale_y)
+ padding (float): Bbox padding factor that will be multilied to scale.
+ Default: 1.0
+ pixel_std (float): The scale normalization factor. Default: 200.0
+
+ Returns:
+ ndarray: Single bbox in (x, y, w, h)
+ """
+
+ wh = scale / padding * pixel_std
+ xy = center - 0.5 * wh
+ return np.r_[xy, wh]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4a3c5526560996791a85f0d84a72a66286486ca
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/__init__.py
@@ -0,0 +1,6 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .camera_base import CAMERAS
+from .single_camera import SimpleCamera
+from .single_camera_torch import SimpleCameraTorch
+
+__all__ = ['CAMERAS', 'SimpleCamera', 'SimpleCameraTorch']
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/camera_base.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/camera_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..28b23e7c6279e3613265a949df91f6ced0413b99
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/camera_base.py
@@ -0,0 +1,45 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+
+from mmcv.utils import Registry
+
+CAMERAS = Registry('camera')
+
+
+class SingleCameraBase(metaclass=ABCMeta):
+ """Base class for single camera model.
+
+ Args:
+ param (dict): Camera parameters
+
+ Methods:
+ world_to_camera: Project points from world coordinates to camera
+ coordinates
+ camera_to_world: Project points from camera coordinates to world
+ coordinates
+ camera_to_pixel: Project points from camera coordinates to pixel
+ coordinates
+ world_to_pixel: Project points from world coordinates to pixel
+ coordinates
+ """
+
+ @abstractmethod
+ def __init__(self, param):
+ """Load camera parameters and check validity."""
+
+ def world_to_camera(self, X):
+ """Project points from world coordinates to camera coordinates."""
+ raise NotImplementedError
+
+ def camera_to_world(self, X):
+ """Project points from camera coordinates to world coordinates."""
+ raise NotImplementedError
+
+ def camera_to_pixel(self, X):
+ """Project points from camera coordinates to pixel coordinates."""
+ raise NotImplementedError
+
+ def world_to_pixel(self, X):
+ """Project points from world coordinates to pixel coordinates."""
+ _X = self.world_to_camera(X)
+ return self.camera_to_pixel(_X)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera.py
new file mode 100644
index 0000000000000000000000000000000000000000..cabd79941af5c81110876e94ce6103cc02ea5078
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera.py
@@ -0,0 +1,123 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+
+from .camera_base import CAMERAS, SingleCameraBase
+
+
+@CAMERAS.register_module()
+class SimpleCamera(SingleCameraBase):
+ """Camera model to calculate coordinate transformation with given
+ intrinsic/extrinsic camera parameters.
+
+ Note:
+ The keypoint coordinate should be an np.ndarray with a shape of
+ [...,J, C] where J is the keypoint number of an instance, and C is
+ the coordinate dimension. For example:
+
+ [J, C]: shape of joint coordinates of a person with J joints.
+ [N, J, C]: shape of a batch of person joint coordinates.
+ [N, T, J, C]: shape of a batch of pose sequences.
+
+ Args:
+ param (dict): camera parameters including:
+ - R: 3x3, camera rotation matrix (camera-to-world)
+ - T: 3x1, camera translation (camera-to-world)
+ - K: (optional) 2x3, camera intrinsic matrix
+ - k: (optional) nx1, camera radial distortion coefficients
+ - p: (optional) mx1, camera tangential distortion coefficients
+ - f: (optional) 2x1, camera focal length
+ - c: (optional) 2x1, camera center
+ if K is not provided, it will be calculated from f and c.
+
+ Methods:
+ world_to_camera: Project points from world coordinates to camera
+ coordinates
+ camera_to_pixel: Project points from camera coordinates to pixel
+ coordinates
+ world_to_pixel: Project points from world coordinates to pixel
+ coordinates
+ """
+
+ def __init__(self, param):
+
+ self.param = {}
+ # extrinsic param
+ R = np.array(param['R'], dtype=np.float32)
+ T = np.array(param['T'], dtype=np.float32)
+ assert R.shape == (3, 3)
+ assert T.shape == (3, 1)
+ # The camera matrices are transposed in advance because the joint
+ # coordinates are stored as row vectors.
+ self.param['R_c2w'] = R.T
+ self.param['T_c2w'] = T.T
+ self.param['R_w2c'] = R
+ self.param['T_w2c'] = -self.param['T_c2w'] @ self.param['R_w2c']
+
+ # intrinsic param
+ if 'K' in param:
+ K = np.array(param['K'], dtype=np.float32)
+ assert K.shape == (2, 3)
+ self.param['K'] = K.T
+ self.param['f'] = np.array([K[0, 0], K[1, 1]])[:, np.newaxis]
+ self.param['c'] = np.array([K[0, 2], K[1, 2]])[:, np.newaxis]
+ elif 'f' in param and 'c' in param:
+ f = np.array(param['f'], dtype=np.float32)
+ c = np.array(param['c'], dtype=np.float32)
+ assert f.shape == (2, 1)
+ assert c.shape == (2, 1)
+ self.param['K'] = np.concatenate((np.diagflat(f), c), axis=-1).T
+ self.param['f'] = f
+ self.param['c'] = c
+ else:
+ raise ValueError('Camera intrinsic parameters are missing. '
+ 'Either "K" or "f"&"c" should be provided.')
+
+ # distortion param
+ if 'k' in param and 'p' in param:
+ self.undistortion = True
+ self.param['k'] = np.array(param['k'], dtype=np.float32).flatten()
+ self.param['p'] = np.array(param['p'], dtype=np.float32).flatten()
+ assert self.param['k'].size in {3, 6}
+ assert self.param['p'].size == 2
+ else:
+ self.undistortion = False
+
+ def world_to_camera(self, X):
+ assert isinstance(X, np.ndarray)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+ return X @ self.param['R_w2c'] + self.param['T_w2c']
+
+ def camera_to_world(self, X):
+ assert isinstance(X, np.ndarray)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+ return X @ self.param['R_c2w'] + self.param['T_c2w']
+
+ def camera_to_pixel(self, X):
+ assert isinstance(X, np.ndarray)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+
+ _X = X / X[..., 2:]
+
+ if self.undistortion:
+ k = self.param['k']
+ p = self.param['p']
+ _X_2d = _X[..., :2]
+ r2 = (_X_2d**2).sum(-1)
+ radial = 1 + sum(ki * r2**(i + 1) for i, ki in enumerate(k[:3]))
+ if k.size == 6:
+ radial /= 1 + sum(
+ (ki * r2**(i + 1) for i, ki in enumerate(k[3:])))
+
+ tangential = 2 * (p[1] * _X[..., 0] + p[0] * _X[..., 1])
+
+ _X[..., :2] = _X_2d * (radial + tangential)[..., None] + np.outer(
+ r2, p[::-1]).reshape(_X_2d.shape)
+ return _X @ self.param['K']
+
+ def pixel_to_camera(self, X):
+ assert isinstance(X, np.ndarray)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+ _X = X.copy()
+ _X[:, :2] = (X[:, :2] - self.param['c'].T) / self.param['f'].T * X[:,
+ [2]]
+ return _X
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera_torch.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera_torch.py
new file mode 100644
index 0000000000000000000000000000000000000000..22eb72f23d6eecf1b5c5a9b570a4f142fcf6e02a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/camera/single_camera_torch.py
@@ -0,0 +1,118 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+
+from .camera_base import CAMERAS, SingleCameraBase
+
+
+@CAMERAS.register_module()
+class SimpleCameraTorch(SingleCameraBase):
+ """Camera model to calculate coordinate transformation with given
+ intrinsic/extrinsic camera parameters.
+
+ Notes:
+ The keypoint coordinate should be an np.ndarray with a shape of
+ [...,J, C] where J is the keypoint number of an instance, and C is
+ the coordinate dimension. For example:
+
+ [J, C]: shape of joint coordinates of a person with J joints.
+ [N, J, C]: shape of a batch of person joint coordinates.
+ [N, T, J, C]: shape of a batch of pose sequences.
+
+ Args:
+ param (dict): camera parameters including:
+ - R: 3x3, camera rotation matrix (camera-to-world)
+ - T: 3x1, camera translation (camera-to-world)
+ - K: (optional) 2x3, camera intrinsic matrix
+ - k: (optional) nx1, camera radial distortion coefficients
+ - p: (optional) mx1, camera tangential distortion coefficients
+ - f: (optional) 2x1, camera focal length
+ - c: (optional) 2x1, camera center
+ if K is not provided, it will be calculated from f and c.
+
+ Methods:
+ world_to_camera: Project points from world coordinates to camera
+ coordinates
+ camera_to_pixel: Project points from camera coordinates to pixel
+ coordinates
+ world_to_pixel: Project points from world coordinates to pixel
+ coordinates
+ """
+
+ def __init__(self, param, device):
+
+ self.param = {}
+ # extrinsic param
+ R = torch.tensor(param['R'], device=device)
+ T = torch.tensor(param['T'], device=device)
+
+ assert R.shape == (3, 3)
+ assert T.shape == (3, 1)
+ # The camera matrices are transposed in advance because the joint
+ # coordinates are stored as row vectors.
+ self.param['R_c2w'] = R.T
+ self.param['T_c2w'] = T.T
+ self.param['R_w2c'] = R
+ self.param['T_w2c'] = -self.param['T_c2w'] @ self.param['R_w2c']
+
+ # intrinsic param
+ if 'K' in param:
+ K = torch.tensor(param['K'], device=device)
+ assert K.shape == (2, 3)
+ self.param['K'] = K.T
+ self.param['f'] = torch.tensor([[K[0, 0]], [K[1, 1]]],
+ device=device)
+ self.param['c'] = torch.tensor([[K[0, 2]], [K[1, 2]]],
+ device=device)
+ elif 'f' in param and 'c' in param:
+ f = torch.tensor(param['f'], device=device)
+ c = torch.tensor(param['c'], device=device)
+ assert f.shape == (2, 1)
+ assert c.shape == (2, 1)
+ self.param['K'] = torch.cat([torch.diagflat(f), c], dim=-1).T
+ self.param['f'] = f
+ self.param['c'] = c
+ else:
+ raise ValueError('Camera intrinsic parameters are missing. '
+ 'Either "K" or "f"&"c" should be provided.')
+
+ # distortion param
+ if 'k' in param and 'p' in param:
+ self.undistortion = True
+ self.param['k'] = torch.tensor(param['k'], device=device).view(-1)
+ self.param['p'] = torch.tensor(param['p'], device=device).view(-1)
+ assert len(self.param['k']) in {3, 6}
+ assert len(self.param['p']) == 2
+ else:
+ self.undistortion = False
+
+ def world_to_camera(self, X):
+ assert isinstance(X, torch.Tensor)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+ return X @ self.param['R_w2c'] + self.param['T_w2c']
+
+ def camera_to_world(self, X):
+ assert isinstance(X, torch.Tensor)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+ return X @ self.param['R_c2w'] + self.param['T_c2w']
+
+ def camera_to_pixel(self, X):
+ assert isinstance(X, torch.Tensor)
+ assert X.ndim >= 2 and X.shape[-1] == 3
+
+ _X = X / X[..., 2:]
+
+ if self.undistortion:
+ k = self.param['k']
+ p = self.param['p']
+ _X_2d = _X[..., :2]
+ r2 = (_X_2d**2).sum(-1)
+ radial = 1 + sum(ki * r2**(i + 1) for i, ki in enumerate(k[:3]))
+ if k.size == 6:
+ radial /= 1 + sum(
+ (ki * r2**(i + 1) for i, ki in enumerate(k[3:])))
+
+ tangential = 2 * (p[1] * _X[..., 0] + p[0] * _X[..., 1])
+
+ _X[..., :2] = _X_2d * (radial + tangential)[..., None] + torch.ger(
+ r2, p.flip([0])).reshape(_X_2d.shape)
+ return _X @ self.param['K']
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/distributed_wrapper.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/distributed_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c67aceec992085e9952ea70c62009e9ec1db30ca
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/distributed_wrapper.py
@@ -0,0 +1,143 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+from mmcv.parallel import MODULE_WRAPPERS as MMCV_MODULE_WRAPPERS
+from mmcv.parallel import MMDistributedDataParallel
+from mmcv.parallel.scatter_gather import scatter_kwargs
+from mmcv.utils import Registry
+from torch.cuda._utils import _get_device_index
+
+MODULE_WRAPPERS = Registry('module wrapper', parent=MMCV_MODULE_WRAPPERS)
+
+
+@MODULE_WRAPPERS.register_module()
+class DistributedDataParallelWrapper(nn.Module):
+ """A DistributedDataParallel wrapper for models in 3D mesh estimation task.
+
+ In 3D mesh estimation task, there is a need to wrap different modules in
+ the models with separate DistributedDataParallel. Otherwise, it will cause
+ errors for GAN training.
+ More specific, the GAN model, usually has two sub-modules:
+ generator and discriminator. If we wrap both of them in one
+ standard DistributedDataParallel, it will cause errors during training,
+ because when we update the parameters of the generator (or discriminator),
+ the parameters of the discriminator (or generator) is not updated, which is
+ not allowed for DistributedDataParallel.
+ So we design this wrapper to separately wrap DistributedDataParallel
+ for generator and discriminator.
+
+ In this wrapper, we perform two operations:
+ 1. Wrap the modules in the models with separate MMDistributedDataParallel.
+ Note that only modules with parameters will be wrapped.
+ 2. Do scatter operation for 'forward', 'train_step' and 'val_step'.
+
+ Note that the arguments of this wrapper is the same as those in
+ `torch.nn.parallel.distributed.DistributedDataParallel`.
+
+ Args:
+ module (nn.Module): Module that needs to be wrapped.
+ device_ids (list[int | `torch.device`]): Same as that in
+ `torch.nn.parallel.distributed.DistributedDataParallel`.
+ dim (int, optional): Same as that in the official scatter function in
+ pytorch. Defaults to 0.
+ broadcast_buffers (bool): Same as that in
+ `torch.nn.parallel.distributed.DistributedDataParallel`.
+ Defaults to False.
+ find_unused_parameters (bool, optional): Same as that in
+ `torch.nn.parallel.distributed.DistributedDataParallel`.
+ Traverse the autograd graph of all tensors contained in returned
+ value of the wrapped module’s forward function. Defaults to False.
+ kwargs (dict): Other arguments used in
+ `torch.nn.parallel.distributed.DistributedDataParallel`.
+ """
+
+ def __init__(self,
+ module,
+ device_ids,
+ dim=0,
+ broadcast_buffers=False,
+ find_unused_parameters=False,
+ **kwargs):
+ super().__init__()
+ assert len(device_ids) == 1, (
+ 'Currently, DistributedDataParallelWrapper only supports one'
+ 'single CUDA device for each process.'
+ f'The length of device_ids must be 1, but got {len(device_ids)}.')
+ self.module = module
+ self.dim = dim
+ self.to_ddp(
+ device_ids=device_ids,
+ dim=dim,
+ broadcast_buffers=broadcast_buffers,
+ find_unused_parameters=find_unused_parameters,
+ **kwargs)
+ self.output_device = _get_device_index(device_ids[0], True)
+
+ def to_ddp(self, device_ids, dim, broadcast_buffers,
+ find_unused_parameters, **kwargs):
+ """Wrap models with separate MMDistributedDataParallel.
+
+ It only wraps the modules with parameters.
+ """
+ for name, module in self.module._modules.items():
+ if next(module.parameters(), None) is None:
+ module = module.cuda()
+ elif all(not p.requires_grad for p in module.parameters()):
+ module = module.cuda()
+ else:
+ module = MMDistributedDataParallel(
+ module.cuda(),
+ device_ids=device_ids,
+ dim=dim,
+ broadcast_buffers=broadcast_buffers,
+ find_unused_parameters=find_unused_parameters,
+ **kwargs)
+ self.module._modules[name] = module
+
+ def scatter(self, inputs, kwargs, device_ids):
+ """Scatter function.
+
+ Args:
+ inputs (Tensor): Input Tensor.
+ kwargs (dict): Args for
+ ``mmcv.parallel.scatter_gather.scatter_kwargs``.
+ device_ids (int): Device id.
+ """
+ return scatter_kwargs(inputs, kwargs, device_ids, dim=self.dim)
+
+ def forward(self, *inputs, **kwargs):
+ """Forward function.
+
+ Args:
+ inputs (tuple): Input data.
+ kwargs (dict): Args for
+ ``mmcv.parallel.scatter_gather.scatter_kwargs``.
+ """
+ inputs, kwargs = self.scatter(inputs, kwargs,
+ [torch.cuda.current_device()])
+ return self.module(*inputs[0], **kwargs[0])
+
+ def train_step(self, *inputs, **kwargs):
+ """Train step function.
+
+ Args:
+ inputs (Tensor): Input Tensor.
+ kwargs (dict): Args for
+ ``mmcv.parallel.scatter_gather.scatter_kwargs``.
+ """
+ inputs, kwargs = self.scatter(inputs, kwargs,
+ [torch.cuda.current_device()])
+ output = self.module.train_step(*inputs[0], **kwargs[0])
+ return output
+
+ def val_step(self, *inputs, **kwargs):
+ """Validation step function.
+
+ Args:
+ inputs (tuple): Input data.
+ kwargs (dict): Args for ``scatter_kwargs``.
+ """
+ inputs, kwargs = self.scatter(inputs, kwargs,
+ [torch.cuda.current_device()])
+ output = self.module.val_step(*inputs[0], **kwargs[0])
+ return output
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f9378429c8ddaa15f7ac17446bc9d484987df16
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/__init__.py
@@ -0,0 +1,22 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .bottom_up_eval import (aggregate_scale, aggregate_stage_flip,
+ flip_feature_maps, get_group_preds,
+ split_ae_outputs)
+from .eval_hooks import DistEvalHook, EvalHook
+from .mesh_eval import compute_similarity_transform
+from .pose3d_eval import keypoint_3d_auc, keypoint_3d_pck, keypoint_mpjpe
+from .top_down_eval import (keypoint_auc, keypoint_epe, keypoint_pck_accuracy,
+ keypoints_from_heatmaps, keypoints_from_heatmaps3d,
+ keypoints_from_regression,
+ multilabel_classification_accuracy,
+ pose_pck_accuracy, post_dark_udp)
+
+__all__ = [
+ 'EvalHook', 'DistEvalHook', 'pose_pck_accuracy', 'keypoints_from_heatmaps',
+ 'keypoints_from_regression', 'keypoint_pck_accuracy', 'keypoint_3d_pck',
+ 'keypoint_3d_auc', 'keypoint_auc', 'keypoint_epe', 'get_group_preds',
+ 'split_ae_outputs', 'flip_feature_maps', 'aggregate_stage_flip',
+ 'aggregate_scale', 'compute_similarity_transform', 'post_dark_udp',
+ 'keypoint_mpjpe', 'keypoints_from_heatmaps3d',
+ 'multilabel_classification_accuracy'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/bottom_up_eval.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/bottom_up_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..7b37d7c98e684284e3863922e7c7d2abedce0e24
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/bottom_up_eval.py
@@ -0,0 +1,333 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+import torch
+
+from mmpose.core.post_processing import (get_warp_matrix, transform_preds,
+ warp_affine_joints)
+
+
+def split_ae_outputs(outputs, num_joints, with_heatmaps, with_ae,
+ select_output_index):
+ """Split multi-stage outputs into heatmaps & tags.
+
+ Args:
+ outputs (list(Tensor)): Outputs of network
+ num_joints (int): Number of joints
+ with_heatmaps (list[bool]): Option to output
+ heatmaps for different stages.
+ with_ae (list[bool]): Option to output
+ ae tags for different stages.
+ select_output_index (list[int]): Output keep the selected index
+
+ Returns:
+ tuple: A tuple containing multi-stage outputs.
+
+ - list[Tensor]: multi-stage heatmaps.
+ - list[Tensor]: multi-stage tags.
+ """
+
+ heatmaps = []
+ tags = []
+
+ # aggregate heatmaps from different stages
+ for i, output in enumerate(outputs):
+ if i not in select_output_index:
+ continue
+ # staring index of the associative embeddings
+ offset_feat = num_joints if with_heatmaps[i] else 0
+ if with_heatmaps[i]:
+ heatmaps.append(output[:, :num_joints])
+ if with_ae[i]:
+ tags.append(output[:, offset_feat:])
+
+ return heatmaps, tags
+
+
+def flip_feature_maps(feature_maps, flip_index=None):
+ """Flip the feature maps and swap the channels.
+
+ Args:
+ feature_maps (list[Tensor]): Feature maps.
+ flip_index (list[int] | None): Channel-flip indexes.
+ If None, do not flip channels.
+
+ Returns:
+ list[Tensor]: Flipped feature_maps.
+ """
+ flipped_feature_maps = []
+ for feature_map in feature_maps:
+ feature_map = torch.flip(feature_map, [3])
+ if flip_index is not None:
+ flipped_feature_maps.append(feature_map[:, flip_index, :, :])
+ else:
+ flipped_feature_maps.append(feature_map)
+
+ return flipped_feature_maps
+
+
+def _resize_average(feature_maps, align_corners, index=-1, resize_size=None):
+ """Resize the feature maps and compute the average.
+
+ Args:
+ feature_maps (list[Tensor]): Feature maps.
+ align_corners (bool): Align corners when performing interpolation.
+ index (int): Only used when `resize_size' is None.
+ If `resize_size' is None, the target size is the size
+ of the indexed feature maps.
+ resize_size (list[int, int]): The target size [w, h].
+
+ Returns:
+ list[Tensor]: Averaged feature_maps.
+ """
+
+ if feature_maps is None:
+ return None
+ feature_maps_avg = 0
+
+ feature_map_list = _resize_concate(
+ feature_maps, align_corners, index=index, resize_size=resize_size)
+ for feature_map in feature_map_list:
+ feature_maps_avg += feature_map
+
+ feature_maps_avg /= len(feature_map_list)
+ return [feature_maps_avg]
+
+
+def _resize_unsqueeze_concat(feature_maps,
+ align_corners,
+ index=-1,
+ resize_size=None):
+ """Resize, unsqueeze and concatenate the feature_maps.
+
+ Args:
+ feature_maps (list[Tensor]): Feature maps.
+ align_corners (bool): Align corners when performing interpolation.
+ index (int): Only used when `resize_size' is None.
+ If `resize_size' is None, the target size is the size
+ of the indexed feature maps.
+ resize_size (list[int, int]): The target size [w, h].
+
+ Returns:
+ list[Tensor]: Averaged feature_maps.
+ """
+ if feature_maps is None:
+ return None
+ feature_map_list = _resize_concate(
+ feature_maps, align_corners, index=index, resize_size=resize_size)
+
+ feat_dim = len(feature_map_list[0].shape) - 1
+ output_feature_maps = torch.cat(
+ [torch.unsqueeze(fmap, dim=feat_dim + 1) for fmap in feature_map_list],
+ dim=feat_dim + 1)
+ return [output_feature_maps]
+
+
+def _resize_concate(feature_maps, align_corners, index=-1, resize_size=None):
+ """Resize and concatenate the feature_maps.
+
+ Args:
+ feature_maps (list[Tensor]): Feature maps.
+ align_corners (bool): Align corners when performing interpolation.
+ index (int): Only used when `resize_size' is None.
+ If `resize_size' is None, the target size is the size
+ of the indexed feature maps.
+ resize_size (list[int, int]): The target size [w, h].
+
+ Returns:
+ list[Tensor]: Averaged feature_maps.
+ """
+ if feature_maps is None:
+ return None
+
+ feature_map_list = []
+
+ if index < 0:
+ index += len(feature_maps)
+
+ if resize_size is None:
+ resize_size = (feature_maps[index].size(2),
+ feature_maps[index].size(3))
+
+ for feature_map in feature_maps:
+ ori_size = (feature_map.size(2), feature_map.size(3))
+ if ori_size != resize_size:
+ feature_map = torch.nn.functional.interpolate(
+ feature_map,
+ size=resize_size,
+ mode='bilinear',
+ align_corners=align_corners)
+
+ feature_map_list.append(feature_map)
+
+ return feature_map_list
+
+
+def aggregate_stage_flip(feature_maps,
+ feature_maps_flip,
+ index=-1,
+ project2image=True,
+ size_projected=None,
+ align_corners=False,
+ aggregate_stage='concat',
+ aggregate_flip='average'):
+ """Inference the model to get multi-stage outputs (heatmaps & tags), and
+ resize them to base sizes.
+
+ Args:
+ feature_maps (list[Tensor]): feature_maps can be heatmaps,
+ tags, and pafs.
+ feature_maps_flip (list[Tensor] | None): flipped feature_maps.
+ feature maps can be heatmaps, tags, and pafs.
+ project2image (bool): Option to resize to base scale.
+ size_projected (list[int, int]): Base size of heatmaps [w, h].
+ align_corners (bool): Align corners when performing interpolation.
+ aggregate_stage (str): Methods to aggregate multi-stage feature maps.
+ Options: 'concat', 'average'. Default: 'concat.
+
+ - 'concat': Concatenate the original and the flipped feature maps.
+ - 'average': Get the average of the original and the flipped
+ feature maps.
+ aggregate_flip (str): Methods to aggregate the original and
+ the flipped feature maps. Options: 'concat', 'average', 'none'.
+ Default: 'average.
+
+ - 'concat': Concatenate the original and the flipped feature maps.
+ - 'average': Get the average of the original and the flipped
+ feature maps..
+ - 'none': no flipped feature maps.
+
+ Returns:
+ list[Tensor]: Aggregated feature maps with shape [NxKxWxH].
+ """
+
+ if feature_maps_flip is None:
+ aggregate_flip = 'none'
+
+ output_feature_maps = []
+
+ if aggregate_stage == 'average':
+ _aggregate_stage_func = _resize_average
+ elif aggregate_stage == 'concat':
+ _aggregate_stage_func = _resize_concate
+ else:
+ NotImplementedError()
+
+ if project2image and size_projected:
+ _origin = _aggregate_stage_func(
+ feature_maps,
+ align_corners,
+ index=index,
+ resize_size=(size_projected[1], size_projected[0]))
+
+ _flipped = _aggregate_stage_func(
+ feature_maps_flip,
+ align_corners,
+ index=index,
+ resize_size=(size_projected[1], size_projected[0]))
+ else:
+ _origin = _aggregate_stage_func(
+ feature_maps, align_corners, index=index, resize_size=None)
+ _flipped = _aggregate_stage_func(
+ feature_maps_flip, align_corners, index=index, resize_size=None)
+
+ if aggregate_flip == 'average':
+ assert feature_maps_flip is not None
+ for _ori, _fli in zip(_origin, _flipped):
+ output_feature_maps.append((_ori + _fli) / 2.0)
+
+ elif aggregate_flip == 'concat':
+ assert feature_maps_flip is not None
+ output_feature_maps.append(*_origin)
+ output_feature_maps.append(*_flipped)
+
+ elif aggregate_flip == 'none':
+ if isinstance(_origin, list):
+ output_feature_maps.append(*_origin)
+ else:
+ output_feature_maps.append(_origin)
+ else:
+ NotImplementedError()
+
+ return output_feature_maps
+
+
+def aggregate_scale(feature_maps_list,
+ align_corners=False,
+ aggregate_scale='average'):
+ """Aggregate multi-scale outputs.
+
+ Note:
+ batch size: N
+ keypoints num : K
+ heatmap width: W
+ heatmap height: H
+
+ Args:
+ feature_maps_list (list[Tensor]): Aggregated feature maps.
+ project2image (bool): Option to resize to base scale.
+ align_corners (bool): Align corners when performing interpolation.
+ aggregate_scale (str): Methods to aggregate multi-scale feature maps.
+ Options: 'average', 'unsqueeze_concat'.
+
+ - 'average': Get the average of the feature maps.
+ - 'unsqueeze_concat': Concatenate the feature maps along new axis.
+ Default: 'average.
+
+ Returns:
+ Tensor: Aggregated feature maps.
+ """
+
+ if aggregate_scale == 'average':
+ output_feature_maps = _resize_average(
+ feature_maps_list, align_corners, index=0, resize_size=None)
+
+ elif aggregate_scale == 'unsqueeze_concat':
+ output_feature_maps = _resize_unsqueeze_concat(
+ feature_maps_list, align_corners, index=0, resize_size=None)
+ else:
+ NotImplementedError()
+
+ return output_feature_maps[0]
+
+
+def get_group_preds(grouped_joints,
+ center,
+ scale,
+ heatmap_size,
+ use_udp=False):
+ """Transform the grouped joints back to the image.
+
+ Args:
+ grouped_joints (list): Grouped person joints.
+ center (np.ndarray[2, ]): Center of the bounding box (x, y).
+ scale (np.ndarray[2, ]): Scale of the bounding box
+ wrt [width, height].
+ heatmap_size (np.ndarray[2, ]): Size of the destination heatmaps.
+ use_udp (bool): Unbiased data processing.
+ Paper ref: Huang et al. The Devil is in the Details: Delving into
+ Unbiased Data Processing for Human Pose Estimation (CVPR'2020).
+
+ Returns:
+ list: List of the pose result for each person.
+ """
+ if len(grouped_joints) == 0:
+ return []
+
+ if use_udp:
+ if grouped_joints[0].shape[0] > 0:
+ heatmap_size_t = np.array(heatmap_size, dtype=np.float32) - 1.0
+ trans = get_warp_matrix(
+ theta=0,
+ size_input=heatmap_size_t,
+ size_dst=scale,
+ size_target=heatmap_size_t)
+ grouped_joints[0][..., :2] = \
+ warp_affine_joints(grouped_joints[0][..., :2], trans)
+ results = [person for person in grouped_joints[0]]
+ else:
+ results = []
+ for person in grouped_joints[0]:
+ joints = transform_preds(person, center, scale, heatmap_size)
+ results.append(joints)
+
+ return results
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/eval_hooks.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/eval_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b35a9c6a990c69b2beac9e73f893f97c237e4783
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/eval_hooks.py
@@ -0,0 +1,99 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+from mmcv.runner import DistEvalHook as _DistEvalHook
+from mmcv.runner import EvalHook as _EvalHook
+
+MMPOSE_GREATER_KEYS = [
+ 'acc', 'ap', 'ar', 'pck', 'auc', '3dpck', 'p-3dpck', '3dauc', 'p-3dauc',
+ 'pcp'
+]
+MMPOSE_LESS_KEYS = ['loss', 'epe', 'nme', 'mpjpe', 'p-mpjpe', 'n-mpjpe']
+
+
+class EvalHook(_EvalHook):
+
+ def __init__(self,
+ dataloader,
+ start=None,
+ interval=1,
+ by_epoch=True,
+ save_best=None,
+ rule=None,
+ test_fn=None,
+ greater_keys=MMPOSE_GREATER_KEYS,
+ less_keys=MMPOSE_LESS_KEYS,
+ **eval_kwargs):
+
+ if test_fn is None:
+ from mmpose.apis import single_gpu_test
+ test_fn = single_gpu_test
+
+ # to be compatible with the config before v0.16.0
+
+ # remove "gpu_collect" from eval_kwargs
+ if 'gpu_collect' in eval_kwargs:
+ warnings.warn(
+ '"gpu_collect" will be deprecated in EvalHook.'
+ 'Please remove it from the config.', DeprecationWarning)
+ _ = eval_kwargs.pop('gpu_collect')
+
+ # update "save_best" according to "key_indicator" and remove the
+ # latter from eval_kwargs
+ if 'key_indicator' in eval_kwargs or isinstance(save_best, bool):
+ warnings.warn(
+ '"key_indicator" will be deprecated in EvalHook.'
+ 'Please use "save_best" to specify the metric key,'
+ 'e.g., save_best="AP".', DeprecationWarning)
+
+ key_indicator = eval_kwargs.pop('key_indicator', 'AP')
+ if save_best is True and key_indicator is None:
+ raise ValueError('key_indicator should not be None, when '
+ 'save_best is set to True.')
+ save_best = key_indicator
+
+ super().__init__(dataloader, start, interval, by_epoch, save_best,
+ rule, test_fn, greater_keys, less_keys, **eval_kwargs)
+
+
+class DistEvalHook(_DistEvalHook):
+
+ def __init__(self,
+ dataloader,
+ start=None,
+ interval=1,
+ by_epoch=True,
+ save_best=None,
+ rule=None,
+ test_fn=None,
+ greater_keys=MMPOSE_GREATER_KEYS,
+ less_keys=MMPOSE_LESS_KEYS,
+ broadcast_bn_buffer=True,
+ tmpdir=None,
+ gpu_collect=False,
+ **eval_kwargs):
+
+ if test_fn is None:
+ from mmpose.apis import multi_gpu_test
+ test_fn = multi_gpu_test
+
+ # to be compatible with the config before v0.16.0
+
+ # update "save_best" according to "key_indicator" and remove the
+ # latter from eval_kwargs
+ if 'key_indicator' in eval_kwargs or isinstance(save_best, bool):
+ warnings.warn(
+ '"key_indicator" will be deprecated in EvalHook.'
+ 'Please use "save_best" to specify the metric key,'
+ 'e.g., save_best="AP".', DeprecationWarning)
+
+ key_indicator = eval_kwargs.pop('key_indicator', 'AP')
+ if save_best is True and key_indicator is None:
+ raise ValueError('key_indicator should not be None, when '
+ 'save_best is set to True.')
+ save_best = key_indicator
+
+ super().__init__(dataloader, start, interval, by_epoch, save_best,
+ rule, test_fn, greater_keys, less_keys,
+ broadcast_bn_buffer, tmpdir, gpu_collect,
+ **eval_kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/mesh_eval.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/mesh_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..683b4539b29d1829a324de424c6d9f85a7037e5d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/mesh_eval.py
@@ -0,0 +1,66 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/akanazawa/hmr
+# Original licence: Copyright (c) 2018 akanazawa, under the MIT License.
+# ------------------------------------------------------------------------------
+
+import numpy as np
+
+
+def compute_similarity_transform(source_points, target_points):
+ """Computes a similarity transform (sR, t) that takes a set of 3D points
+ source_points (N x 3) closest to a set of 3D points target_points, where R
+ is an 3x3 rotation matrix, t 3x1 translation, s scale. And return the
+ transformed 3D points source_points_hat (N x 3). i.e. solves the orthogonal
+ Procrutes problem.
+
+ Note:
+ Points number: N
+
+ Args:
+ source_points (np.ndarray): Source point set with shape [N, 3].
+ target_points (np.ndarray): Target point set with shape [N, 3].
+
+ Returns:
+ np.ndarray: Transformed source point set with shape [N, 3].
+ """
+
+ assert target_points.shape[0] == source_points.shape[0]
+ assert target_points.shape[1] == 3 and source_points.shape[1] == 3
+
+ source_points = source_points.T
+ target_points = target_points.T
+
+ # 1. Remove mean.
+ mu1 = source_points.mean(axis=1, keepdims=True)
+ mu2 = target_points.mean(axis=1, keepdims=True)
+ X1 = source_points - mu1
+ X2 = target_points - mu2
+
+ # 2. Compute variance of X1 used for scale.
+ var1 = np.sum(X1**2)
+
+ # 3. The outer product of X1 and X2.
+ K = X1.dot(X2.T)
+
+ # 4. Solution that Maximizes trace(R'K) is R=U*V', where U, V are
+ # singular vectors of K.
+ U, _, Vh = np.linalg.svd(K)
+ V = Vh.T
+ # Construct Z that fixes the orientation of R to get det(R)=1.
+ Z = np.eye(U.shape[0])
+ Z[-1, -1] *= np.sign(np.linalg.det(U.dot(V.T)))
+ # Construct R.
+ R = V.dot(Z.dot(U.T))
+
+ # 5. Recover scale.
+ scale = np.trace(R.dot(K)) / var1
+
+ # 6. Recover translation.
+ t = mu2 - scale * (R.dot(mu1))
+
+ # 7. Transform the source points:
+ source_points_hat = scale * R.dot(source_points) + t
+
+ source_points_hat = source_points_hat.T
+
+ return source_points_hat
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/pose3d_eval.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/pose3d_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..545778ca7441c2d3e8ec58449c8ca7b162322e9e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/pose3d_eval.py
@@ -0,0 +1,171 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+
+from .mesh_eval import compute_similarity_transform
+
+
+def keypoint_mpjpe(pred, gt, mask, alignment='none'):
+ """Calculate the mean per-joint position error (MPJPE) and the error after
+ rigid alignment with the ground truth (P-MPJPE).
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - keypoint_dims: C
+
+ Args:
+ pred (np.ndarray): Predicted keypoint location with shape [N, K, C].
+ gt (np.ndarray): Groundtruth keypoint location with shape [N, K, C].
+ mask (np.ndarray): Visibility of the target with shape [N, K].
+ False for invisible joints, and True for visible.
+ Invisible joints will be ignored for accuracy calculation.
+ alignment (str, optional): method to align the prediction with the
+ groundtruth. Supported options are:
+
+ - ``'none'``: no alignment will be applied
+ - ``'scale'``: align in the least-square sense in scale
+ - ``'procrustes'``: align in the least-square sense in
+ scale, rotation and translation.
+ Returns:
+ tuple: A tuple containing joint position errors
+
+ - (float | np.ndarray): mean per-joint position error (mpjpe).
+ - (float | np.ndarray): mpjpe after rigid alignment with the
+ ground truth (p-mpjpe).
+ """
+ assert mask.any()
+
+ if alignment == 'none':
+ pass
+ elif alignment == 'procrustes':
+ pred = np.stack([
+ compute_similarity_transform(pred_i, gt_i)
+ for pred_i, gt_i in zip(pred, gt)
+ ])
+ elif alignment == 'scale':
+ pred_dot_pred = np.einsum('nkc,nkc->n', pred, pred)
+ pred_dot_gt = np.einsum('nkc,nkc->n', pred, gt)
+ scale_factor = pred_dot_gt / pred_dot_pred
+ pred = pred * scale_factor[:, None, None]
+ else:
+ raise ValueError(f'Invalid value for alignment: {alignment}')
+
+ error = np.linalg.norm(pred - gt, ord=2, axis=-1)[mask].mean()
+
+ return error
+
+
+def keypoint_3d_pck(pred, gt, mask, alignment='none', threshold=0.15):
+ """Calculate the Percentage of Correct Keypoints (3DPCK) w. or w/o rigid
+ alignment.
+
+ Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved
+ CNN Supervision' 3DV'2017. `__ .
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - keypoint_dims: C
+
+ Args:
+ pred (np.ndarray[N, K, C]): Predicted keypoint location.
+ gt (np.ndarray[N, K, C]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ alignment (str, optional): method to align the prediction with the
+ groundtruth. Supported options are:
+
+ - ``'none'``: no alignment will be applied
+ - ``'scale'``: align in the least-square sense in scale
+ - ``'procrustes'``: align in the least-square sense in scale,
+ rotation and translation.
+
+ threshold: If L2 distance between the prediction and the groundtruth
+ is less then threshold, the predicted result is considered as
+ correct. Default: 0.15 (m).
+
+ Returns:
+ pck: percentage of correct keypoints.
+ """
+ assert mask.any()
+
+ if alignment == 'none':
+ pass
+ elif alignment == 'procrustes':
+ pred = np.stack([
+ compute_similarity_transform(pred_i, gt_i)
+ for pred_i, gt_i in zip(pred, gt)
+ ])
+ elif alignment == 'scale':
+ pred_dot_pred = np.einsum('nkc,nkc->n', pred, pred)
+ pred_dot_gt = np.einsum('nkc,nkc->n', pred, gt)
+ scale_factor = pred_dot_gt / pred_dot_pred
+ pred = pred * scale_factor[:, None, None]
+ else:
+ raise ValueError(f'Invalid value for alignment: {alignment}')
+
+ error = np.linalg.norm(pred - gt, ord=2, axis=-1)
+ pck = (error < threshold).astype(np.float32)[mask].mean() * 100
+
+ return pck
+
+
+def keypoint_3d_auc(pred, gt, mask, alignment='none'):
+ """Calculate the Area Under the Curve (3DAUC) computed for a range of 3DPCK
+ thresholds.
+
+ Paper ref: `Monocular 3D Human Pose Estimation In The Wild Using Improved
+ CNN Supervision' 3DV'2017. `__ .
+ This implementation is derived from mpii_compute_3d_pck.m, which is
+ provided as part of the MPI-INF-3DHP test data release.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ keypoint_dims: C
+
+ Args:
+ pred (np.ndarray[N, K, C]): Predicted keypoint location.
+ gt (np.ndarray[N, K, C]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ alignment (str, optional): method to align the prediction with the
+ groundtruth. Supported options are:
+
+ - ``'none'``: no alignment will be applied
+ - ``'scale'``: align in the least-square sense in scale
+ - ``'procrustes'``: align in the least-square sense in scale,
+ rotation and translation.
+
+ Returns:
+ auc: AUC computed for a range of 3DPCK thresholds.
+ """
+ assert mask.any()
+
+ if alignment == 'none':
+ pass
+ elif alignment == 'procrustes':
+ pred = np.stack([
+ compute_similarity_transform(pred_i, gt_i)
+ for pred_i, gt_i in zip(pred, gt)
+ ])
+ elif alignment == 'scale':
+ pred_dot_pred = np.einsum('nkc,nkc->n', pred, pred)
+ pred_dot_gt = np.einsum('nkc,nkc->n', pred, gt)
+ scale_factor = pred_dot_gt / pred_dot_pred
+ pred = pred * scale_factor[:, None, None]
+ else:
+ raise ValueError(f'Invalid value for alignment: {alignment}')
+
+ error = np.linalg.norm(pred - gt, ord=2, axis=-1)
+
+ thresholds = np.linspace(0., 0.15, 31)
+ pck_values = np.zeros(len(thresholds))
+ for i in range(len(thresholds)):
+ pck_values[i] = (error < thresholds[i]).astype(np.float32)[mask].mean()
+
+ auc = pck_values.mean() * 100
+
+ return auc
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/top_down_eval.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/top_down_eval.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee6a2501cf1eec1b16f7d58bf9fd62da0fa48ccf
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/evaluation/top_down_eval.py
@@ -0,0 +1,684 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+import cv2
+import numpy as np
+
+from mmpose.core.post_processing import transform_preds
+
+
+def _calc_distances(preds, targets, mask, normalize):
+ """Calculate the normalized distances between preds and target.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ dimension of keypoints: D (normally, D=2 or D=3)
+
+ Args:
+ preds (np.ndarray[N, K, D]): Predicted keypoint location.
+ targets (np.ndarray[N, K, D]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize (np.ndarray[N, D]): Typical value is heatmap_size
+
+ Returns:
+ np.ndarray[K, N]: The normalized distances. \
+ If target keypoints are missing, the distance is -1.
+ """
+ N, K, _ = preds.shape
+ # set mask=0 when normalize==0
+ _mask = mask.copy()
+ _mask[np.where((normalize == 0).sum(1))[0], :] = False
+ distances = np.full((N, K), -1, dtype=np.float32)
+ # handle invalid values
+ normalize[np.where(normalize <= 0)] = 1e6
+ distances[_mask] = np.linalg.norm(
+ ((preds - targets) / normalize[:, None, :])[_mask], axis=-1)
+ return distances.T
+
+
+def _distance_acc(distances, thr=0.5):
+ """Return the percentage below the distance threshold, while ignoring
+ distances values with -1.
+
+ Note:
+ batch_size: N
+ Args:
+ distances (np.ndarray[N, ]): The normalized distances.
+ thr (float): Threshold of the distances.
+
+ Returns:
+ float: Percentage of distances below the threshold. \
+ If all target keypoints are missing, return -1.
+ """
+ distance_valid = distances != -1
+ num_distance_valid = distance_valid.sum()
+ if num_distance_valid > 0:
+ return (distances[distance_valid] < thr).sum() / num_distance_valid
+ return -1
+
+
+def _get_max_preds(heatmaps):
+ """Get keypoint predictions from score maps.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+
+ Returns:
+ tuple: A tuple containing aggregated results.
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ assert isinstance(heatmaps,
+ np.ndarray), ('heatmaps should be numpy.ndarray')
+ assert heatmaps.ndim == 4, 'batch_images should be 4-ndim'
+
+ N, K, _, W = heatmaps.shape
+ heatmaps_reshaped = heatmaps.reshape((N, K, -1))
+ idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
+ maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))
+
+ preds = np.tile(idx, (1, 1, 2)).astype(np.float32)
+ preds[:, :, 0] = preds[:, :, 0] % W
+ preds[:, :, 1] = preds[:, :, 1] // W
+
+ preds = np.where(np.tile(maxvals, (1, 1, 2)) > 0.0, preds, -1)
+ return preds, maxvals
+
+
+def _get_max_preds_3d(heatmaps):
+ """Get keypoint predictions from 3D score maps.
+
+ Note:
+ batch size: N
+ num keypoints: K
+ heatmap depth size: D
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, D, H, W]): model predicted heatmaps.
+
+ Returns:
+ tuple: A tuple containing aggregated results.
+
+ - preds (np.ndarray[N, K, 3]): Predicted keypoint location.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ assert isinstance(heatmaps, np.ndarray), \
+ ('heatmaps should be numpy.ndarray')
+ assert heatmaps.ndim == 5, 'heatmaps should be 5-ndim'
+
+ N, K, D, H, W = heatmaps.shape
+ heatmaps_reshaped = heatmaps.reshape((N, K, -1))
+ idx = np.argmax(heatmaps_reshaped, 2).reshape((N, K, 1))
+ maxvals = np.amax(heatmaps_reshaped, 2).reshape((N, K, 1))
+
+ preds = np.zeros((N, K, 3), dtype=np.float32)
+ _idx = idx[..., 0]
+ preds[..., 2] = _idx // (H * W)
+ preds[..., 1] = (_idx // W) % H
+ preds[..., 0] = _idx % W
+
+ preds = np.where(maxvals > 0.0, preds, -1)
+ return preds, maxvals
+
+
+def pose_pck_accuracy(output, target, mask, thr=0.05, normalize=None):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints from heatmaps.
+
+ Note:
+ PCK metric measures accuracy of the localization of the body joints.
+ The distances between predicted positions and the ground-truth ones
+ are typically normalized by the bounding box size.
+ The threshold (thr) of the normalized distance is commonly set
+ as 0.05, 0.1 or 0.2 etc.
+
+ - batch_size: N
+ - num_keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ output (np.ndarray[N, K, H, W]): Model output heatmaps.
+ target (np.ndarray[N, K, H, W]): Groundtruth heatmaps.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ thr (float): Threshold of PCK calculation. Default 0.05.
+ normalize (np.ndarray[N, 2]): Normalization factor for H&W.
+
+ Returns:
+ tuple: A tuple containing keypoint accuracy.
+
+ - np.ndarray[K]: Accuracy of each keypoint.
+ - float: Averaged accuracy across all keypoints.
+ - int: Number of valid keypoints.
+ """
+ N, K, H, W = output.shape
+ if K == 0:
+ return None, 0, 0
+ if normalize is None:
+ normalize = np.tile(np.array([[H, W]]), (N, 1))
+
+ pred, _ = _get_max_preds(output)
+ gt, _ = _get_max_preds(target)
+ return keypoint_pck_accuracy(pred, gt, mask, thr, normalize)
+
+
+def keypoint_pck_accuracy(pred, gt, mask, thr, normalize):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints for coordinates.
+
+ Note:
+ PCK metric measures accuracy of the localization of the body joints.
+ The distances between predicted positions and the ground-truth ones
+ are typically normalized by the bounding box size.
+ The threshold (thr) of the normalized distance is commonly set
+ as 0.05, 0.1 or 0.2 etc.
+
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ thr (float): Threshold of PCK calculation.
+ normalize (np.ndarray[N, 2]): Normalization factor for H&W.
+
+ Returns:
+ tuple: A tuple containing keypoint accuracy.
+
+ - acc (np.ndarray[K]): Accuracy of each keypoint.
+ - avg_acc (float): Averaged accuracy across all keypoints.
+ - cnt (int): Number of valid keypoints.
+ """
+ distances = _calc_distances(pred, gt, mask, normalize)
+
+ acc = np.array([_distance_acc(d, thr) for d in distances])
+ valid_acc = acc[acc >= 0]
+ cnt = len(valid_acc)
+ avg_acc = valid_acc.mean() if cnt > 0 else 0
+ return acc, avg_acc, cnt
+
+
+def keypoint_auc(pred, gt, mask, normalize, num_step=20):
+ """Calculate the pose accuracy of PCK for each individual keypoint and the
+ averaged accuracy across all keypoints for coordinates.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize (float): Normalization factor.
+
+ Returns:
+ float: Area under curve.
+ """
+ nor = np.tile(np.array([[normalize, normalize]]), (pred.shape[0], 1))
+ x = [1.0 * i / num_step for i in range(num_step)]
+ y = []
+ for thr in x:
+ _, avg_acc, _ = keypoint_pck_accuracy(pred, gt, mask, thr, nor)
+ y.append(avg_acc)
+
+ auc = 0
+ for i in range(num_step):
+ auc += 1.0 / num_step * y[i]
+ return auc
+
+
+def keypoint_nme(pred, gt, mask, normalize_factor):
+ """Calculate the normalized mean error (NME).
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+ normalize_factor (np.ndarray[N, 2]): Normalization factor.
+
+ Returns:
+ float: normalized mean error
+ """
+ distances = _calc_distances(pred, gt, mask, normalize_factor)
+ distance_valid = distances[distances != -1]
+ return distance_valid.sum() / max(1, len(distance_valid))
+
+
+def keypoint_epe(pred, gt, mask):
+ """Calculate the end-point error.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ pred (np.ndarray[N, K, 2]): Predicted keypoint location.
+ gt (np.ndarray[N, K, 2]): Groundtruth keypoint location.
+ mask (np.ndarray[N, K]): Visibility of the target. False for invisible
+ joints, and True for visible. Invisible joints will be ignored for
+ accuracy calculation.
+
+ Returns:
+ float: Average end-point error.
+ """
+
+ distances = _calc_distances(
+ pred, gt, mask,
+ np.ones((pred.shape[0], pred.shape[2]), dtype=np.float32))
+ distance_valid = distances[distances != -1]
+ return distance_valid.sum() / max(1, len(distance_valid))
+
+
+def _taylor(heatmap, coord):
+ """Distribution aware coordinate decoding method.
+
+ Note:
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmap (np.ndarray[H, W]): Heatmap of a particular joint type.
+ coord (np.ndarray[2,]): Coordinates of the predicted keypoints.
+
+ Returns:
+ np.ndarray[2,]: Updated coordinates.
+ """
+ H, W = heatmap.shape[:2]
+ px, py = int(coord[0]), int(coord[1])
+ if 1 < px < W - 2 and 1 < py < H - 2:
+ dx = 0.5 * (heatmap[py][px + 1] - heatmap[py][px - 1])
+ dy = 0.5 * (heatmap[py + 1][px] - heatmap[py - 1][px])
+ dxx = 0.25 * (
+ heatmap[py][px + 2] - 2 * heatmap[py][px] + heatmap[py][px - 2])
+ dxy = 0.25 * (
+ heatmap[py + 1][px + 1] - heatmap[py - 1][px + 1] -
+ heatmap[py + 1][px - 1] + heatmap[py - 1][px - 1])
+ dyy = 0.25 * (
+ heatmap[py + 2 * 1][px] - 2 * heatmap[py][px] +
+ heatmap[py - 2 * 1][px])
+ derivative = np.array([[dx], [dy]])
+ hessian = np.array([[dxx, dxy], [dxy, dyy]])
+ if dxx * dyy - dxy**2 != 0:
+ hessianinv = np.linalg.inv(hessian)
+ offset = -hessianinv @ derivative
+ offset = np.squeeze(np.array(offset.T), axis=0)
+ coord += offset
+ return coord
+
+
+def post_dark_udp(coords, batch_heatmaps, kernel=3):
+ """DARK post-pocessing. Implemented by udp. Paper ref: Huang et al. The
+ Devil is in the Details: Delving into Unbiased Data Processing for Human
+ Pose Estimation (CVPR 2020). Zhang et al. Distribution-Aware Coordinate
+ Representation for Human Pose Estimation (CVPR 2020).
+
+ Note:
+ - batch size: B
+ - num keypoints: K
+ - num persons: N
+ - height of heatmaps: H
+ - width of heatmaps: W
+
+ B=1 for bottom_up paradigm where all persons share the same heatmap.
+ B=N for top_down paradigm where each person has its own heatmaps.
+
+ Args:
+ coords (np.ndarray[N, K, 2]): Initial coordinates of human pose.
+ batch_heatmaps (np.ndarray[B, K, H, W]): batch_heatmaps
+ kernel (int): Gaussian kernel size (K) for modulation.
+
+ Returns:
+ np.ndarray([N, K, 2]): Refined coordinates.
+ """
+ if not isinstance(batch_heatmaps, np.ndarray):
+ batch_heatmaps = batch_heatmaps.cpu().numpy()
+ B, K, H, W = batch_heatmaps.shape
+ N = coords.shape[0]
+ assert (B == 1 or B == N)
+ for heatmaps in batch_heatmaps:
+ for heatmap in heatmaps:
+ cv2.GaussianBlur(heatmap, (kernel, kernel), 0, heatmap)
+ np.clip(batch_heatmaps, 0.001, 50, batch_heatmaps)
+ np.log(batch_heatmaps, batch_heatmaps)
+
+ batch_heatmaps_pad = np.pad(
+ batch_heatmaps, ((0, 0), (0, 0), (1, 1), (1, 1)),
+ mode='edge').flatten()
+
+ index = coords[..., 0] + 1 + (coords[..., 1] + 1) * (W + 2)
+ index += (W + 2) * (H + 2) * np.arange(0, B * K).reshape(-1, K)
+ index = index.astype(int).reshape(-1, 1)
+ i_ = batch_heatmaps_pad[index]
+ ix1 = batch_heatmaps_pad[index + 1]
+ iy1 = batch_heatmaps_pad[index + W + 2]
+ ix1y1 = batch_heatmaps_pad[index + W + 3]
+ ix1_y1_ = batch_heatmaps_pad[index - W - 3]
+ ix1_ = batch_heatmaps_pad[index - 1]
+ iy1_ = batch_heatmaps_pad[index - 2 - W]
+
+ dx = 0.5 * (ix1 - ix1_)
+ dy = 0.5 * (iy1 - iy1_)
+ derivative = np.concatenate([dx, dy], axis=1)
+ derivative = derivative.reshape(N, K, 2, 1)
+ dxx = ix1 - 2 * i_ + ix1_
+ dyy = iy1 - 2 * i_ + iy1_
+ dxy = 0.5 * (ix1y1 - ix1 - iy1 + i_ + i_ - ix1_ - iy1_ + ix1_y1_)
+ hessian = np.concatenate([dxx, dxy, dxy, dyy], axis=1)
+ hessian = hessian.reshape(N, K, 2, 2)
+ hessian = np.linalg.inv(hessian + np.finfo(np.float32).eps * np.eye(2))
+ coords -= np.einsum('ijmn,ijnk->ijmk', hessian, derivative).squeeze()
+ return coords
+
+
+def _gaussian_blur(heatmaps, kernel=11):
+ """Modulate heatmap distribution with Gaussian.
+ sigma = 0.3*((kernel_size-1)*0.5-1)+0.8
+ sigma~=3 if k=17
+ sigma=2 if k=11;
+ sigma~=1.5 if k=7;
+ sigma~=1 if k=3;
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ kernel (int): Gaussian kernel size (K) for modulation, which should
+ match the heatmap gaussian sigma when training.
+ K=17 for sigma=3 and k=11 for sigma=2.
+
+ Returns:
+ np.ndarray ([N, K, H, W]): Modulated heatmap distribution.
+ """
+ assert kernel % 2 == 1
+
+ border = (kernel - 1) // 2
+ batch_size = heatmaps.shape[0]
+ num_joints = heatmaps.shape[1]
+ height = heatmaps.shape[2]
+ width = heatmaps.shape[3]
+ for i in range(batch_size):
+ for j in range(num_joints):
+ origin_max = np.max(heatmaps[i, j])
+ dr = np.zeros((height + 2 * border, width + 2 * border),
+ dtype=np.float32)
+ dr[border:-border, border:-border] = heatmaps[i, j].copy()
+ dr = cv2.GaussianBlur(dr, (kernel, kernel), 0)
+ heatmaps[i, j] = dr[border:-border, border:-border].copy()
+ heatmaps[i, j] *= origin_max / np.max(heatmaps[i, j])
+ return heatmaps
+
+
+def keypoints_from_regression(regression_preds, center, scale, img_size):
+ """Get final keypoint predictions from regression vectors and transform
+ them back to the image.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ regression_preds (np.ndarray[N, K, 2]): model prediction.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+ img_size (list(img_width, img_height)): model input image size.
+
+ Returns:
+ tuple:
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ N, K, _ = regression_preds.shape
+ preds, maxvals = regression_preds, np.ones((N, K, 1), dtype=np.float32)
+
+ preds = preds * img_size
+
+ # Transform back to the image
+ for i in range(N):
+ preds[i] = transform_preds(preds[i], center[i], scale[i], img_size)
+
+ return preds, maxvals
+
+
+def keypoints_from_heatmaps(heatmaps,
+ center,
+ scale,
+ unbiased=False,
+ post_process='default',
+ kernel=11,
+ valid_radius_factor=0.0546875,
+ use_udp=False,
+ target_type='GaussianHeatmap'):
+ """Get final keypoint predictions from heatmaps and transform them back to
+ the image.
+
+ Note:
+ - batch size: N
+ - num keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+ post_process (str/None): Choice of methods to post-process
+ heatmaps. Currently supported: None, 'default', 'unbiased',
+ 'megvii'.
+ unbiased (bool): Option to use unbiased decoding. Mutually
+ exclusive with megvii.
+ Note: this arg is deprecated and unbiased=True can be replaced
+ by post_process='unbiased'
+ Paper ref: Zhang et al. Distribution-Aware Coordinate
+ Representation for Human Pose Estimation (CVPR 2020).
+ kernel (int): Gaussian kernel size (K) for modulation, which should
+ match the heatmap gaussian sigma when training.
+ K=17 for sigma=3 and k=11 for sigma=2.
+ valid_radius_factor (float): The radius factor of the positive area
+ in classification heatmap for UDP.
+ use_udp (bool): Use unbiased data processing.
+ target_type (str): 'GaussianHeatmap' or 'CombinedTarget'.
+ GaussianHeatmap: Classification target with gaussian distribution.
+ CombinedTarget: The combination of classification target
+ (response map) and regression target (offset map).
+ Paper ref: Huang et al. The Devil is in the Details: Delving into
+ Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
+
+ Returns:
+ tuple: A tuple containing keypoint predictions and scores.
+
+ - preds (np.ndarray[N, K, 2]): Predicted keypoint location in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ # Avoid being affected
+ heatmaps = heatmaps.copy()
+
+ # detect conflicts
+ if unbiased:
+ assert post_process not in [False, None, 'megvii']
+ if post_process in ['megvii', 'unbiased']:
+ assert kernel > 0
+ if use_udp:
+ assert not post_process == 'megvii'
+
+ # normalize configs
+ if post_process is False:
+ warnings.warn(
+ 'post_process=False is deprecated, '
+ 'please use post_process=None instead', DeprecationWarning)
+ post_process = None
+ elif post_process is True:
+ if unbiased is True:
+ warnings.warn(
+ 'post_process=True, unbiased=True is deprecated,'
+ " please use post_process='unbiased' instead",
+ DeprecationWarning)
+ post_process = 'unbiased'
+ else:
+ warnings.warn(
+ 'post_process=True, unbiased=False is deprecated, '
+ "please use post_process='default' instead",
+ DeprecationWarning)
+ post_process = 'default'
+ elif post_process == 'default':
+ if unbiased is True:
+ warnings.warn(
+ 'unbiased=True is deprecated, please use '
+ "post_process='unbiased' instead", DeprecationWarning)
+ post_process = 'unbiased'
+
+ # start processing
+ if post_process == 'megvii':
+ heatmaps = _gaussian_blur(heatmaps, kernel=kernel)
+
+ N, K, H, W = heatmaps.shape
+ if use_udp:
+ if target_type.lower() == 'GaussianHeatMap'.lower():
+ preds, maxvals = _get_max_preds(heatmaps)
+ preds = post_dark_udp(preds, heatmaps, kernel=kernel)
+ elif target_type.lower() == 'CombinedTarget'.lower():
+ for person_heatmaps in heatmaps:
+ for i, heatmap in enumerate(person_heatmaps):
+ kt = 2 * kernel + 1 if i % 3 == 0 else kernel
+ cv2.GaussianBlur(heatmap, (kt, kt), 0, heatmap)
+ # valid radius is in direct proportion to the height of heatmap.
+ valid_radius = valid_radius_factor * H
+ offset_x = heatmaps[:, 1::3, :].flatten() * valid_radius
+ offset_y = heatmaps[:, 2::3, :].flatten() * valid_radius
+ heatmaps = heatmaps[:, ::3, :]
+ preds, maxvals = _get_max_preds(heatmaps)
+ index = preds[..., 0] + preds[..., 1] * W
+ index += W * H * np.arange(0, N * K / 3)
+ index = index.astype(int).reshape(N, K // 3, 1)
+ preds += np.concatenate((offset_x[index], offset_y[index]), axis=2)
+ else:
+ raise ValueError('target_type should be either '
+ "'GaussianHeatmap' or 'CombinedTarget'")
+ else:
+ preds, maxvals = _get_max_preds(heatmaps)
+ if post_process == 'unbiased': # alleviate biased coordinate
+ # apply Gaussian distribution modulation.
+ heatmaps = np.log(
+ np.maximum(_gaussian_blur(heatmaps, kernel), 1e-10))
+ for n in range(N):
+ for k in range(K):
+ preds[n][k] = _taylor(heatmaps[n][k], preds[n][k])
+ elif post_process is not None:
+ # add +/-0.25 shift to the predicted locations for higher acc.
+ for n in range(N):
+ for k in range(K):
+ heatmap = heatmaps[n][k]
+ px = int(preds[n][k][0])
+ py = int(preds[n][k][1])
+ if 1 < px < W - 1 and 1 < py < H - 1:
+ diff = np.array([
+ heatmap[py][px + 1] - heatmap[py][px - 1],
+ heatmap[py + 1][px] - heatmap[py - 1][px]
+ ])
+ preds[n][k] += np.sign(diff) * .25
+ if post_process == 'megvii':
+ preds[n][k] += 0.5
+
+ # Transform back to the image
+ for i in range(N):
+ preds[i] = transform_preds(
+ preds[i], center[i], scale[i], [W, H], use_udp=use_udp)
+
+ if post_process == 'megvii':
+ maxvals = maxvals / 255.0 + 0.5
+
+ return preds, maxvals
+
+
+def keypoints_from_heatmaps3d(heatmaps, center, scale):
+ """Get final keypoint predictions from 3d heatmaps and transform them back
+ to the image.
+
+ Note:
+ - batch size: N
+ - num keypoints: K
+ - heatmap depth size: D
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ heatmaps (np.ndarray[N, K, D, H, W]): model predicted heatmaps.
+ center (np.ndarray[N, 2]): Center of the bounding box (x, y).
+ scale (np.ndarray[N, 2]): Scale of the bounding box
+ wrt height/width.
+
+ Returns:
+ tuple: A tuple containing keypoint predictions and scores.
+
+ - preds (np.ndarray[N, K, 3]): Predicted 3d keypoint location \
+ in images.
+ - maxvals (np.ndarray[N, K, 1]): Scores (confidence) of the keypoints.
+ """
+ N, K, D, H, W = heatmaps.shape
+ preds, maxvals = _get_max_preds_3d(heatmaps)
+ # Transform back to the image
+ for i in range(N):
+ preds[i, :, :2] = transform_preds(preds[i, :, :2], center[i], scale[i],
+ [W, H])
+ return preds, maxvals
+
+
+def multilabel_classification_accuracy(pred, gt, mask, thr=0.5):
+ """Get multi-label classification accuracy.
+
+ Note:
+ - batch size: N
+ - label number: L
+
+ Args:
+ pred (np.ndarray[N, L, 2]): model predicted labels.
+ gt (np.ndarray[N, L, 2]): ground-truth labels.
+ mask (np.ndarray[N, 1] or np.ndarray[N, L] ): reliability of
+ ground-truth labels.
+
+ Returns:
+ float: multi-label classification accuracy.
+ """
+ # we only compute accuracy on the samples with ground-truth of all labels.
+ valid = (mask > 0).min(axis=1) if mask.ndim == 2 else (mask > 0)
+ pred, gt = pred[valid], gt[valid]
+
+ if pred.shape[0] == 0:
+ acc = 0.0 # when no sample is with gt labels, set acc to 0.
+ else:
+ # The classification of a sample is regarded as correct
+ # only if it's correct for all labels.
+ acc = (((pred - thr) * (gt - thr)) > 0).all(axis=1).mean()
+ return acc
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5cb054810870626496ab4145446b17cf2c2e0b5d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .decorators import auto_fp16, force_fp32
+from .hooks import Fp16OptimizerHook, wrap_fp16_model
+from .utils import cast_tensor_type
+
+__all__ = [
+ 'auto_fp16', 'force_fp32', 'Fp16OptimizerHook', 'wrap_fp16_model',
+ 'cast_tensor_type'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/decorators.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/decorators.py
new file mode 100644
index 0000000000000000000000000000000000000000..2d70ddf533c069b26f08ef3a973328790843def5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/decorators.py
@@ -0,0 +1,175 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import functools
+import warnings
+from inspect import getfullargspec
+
+import torch
+
+from .utils import cast_tensor_type
+
+
+def auto_fp16(apply_to=None, out_fp32=False):
+ """Decorator to enable fp16 training automatically.
+
+ This decorator is useful when you write custom modules and want to support
+ mixed precision training. If inputs arguments are fp32 tensors, they will
+ be converted to fp16 automatically. Arguments other than fp32 tensors are
+ ignored.
+
+ Args:
+ apply_to (Iterable, optional): The argument names to be converted.
+ `None` indicates all arguments.
+ out_fp32 (bool): Whether to convert the output back to fp32.
+
+ Example:
+
+ >>> import torch.nn as nn
+ >>> class MyModule1(nn.Module):
+ >>>
+ >>> # Convert x and y to fp16
+ >>> @auto_fp16()
+ >>> def forward(self, x, y):
+ >>> pass
+
+ >>> import torch.nn as nn
+ >>> class MyModule2(nn.Module):
+ >>>
+ >>> # convert pred to fp16
+ >>> @auto_fp16(apply_to=('pred', ))
+ >>> def do_something(self, pred, others):
+ >>> pass
+ """
+
+ warnings.warn(
+ 'auto_fp16 in mmpose will be deprecated in the next release.'
+ 'Please use mmcv.runner.auto_fp16 instead (mmcv>=1.3.1).',
+ DeprecationWarning)
+
+ def auto_fp16_wrapper(old_func):
+
+ @functools.wraps(old_func)
+ def new_func(*args, **kwargs):
+ # check if the module has set the attribute `fp16_enabled`, if not,
+ # just fallback to the original method.
+ if not isinstance(args[0], torch.nn.Module):
+ raise TypeError('@auto_fp16 can only be used to decorate the '
+ 'method of nn.Module')
+ if not (hasattr(args[0], 'fp16_enabled') and args[0].fp16_enabled):
+ return old_func(*args, **kwargs)
+ # get the arg spec of the decorated method
+ args_info = getfullargspec(old_func)
+ # get the argument names to be casted
+ args_to_cast = args_info.args if apply_to is None else apply_to
+ # convert the args that need to be processed
+ new_args = []
+ # NOTE: default args are not taken into consideration
+ if args:
+ arg_names = args_info.args[:len(args)]
+ for i, arg_name in enumerate(arg_names):
+ if arg_name in args_to_cast:
+ new_args.append(
+ cast_tensor_type(args[i], torch.float, torch.half))
+ else:
+ new_args.append(args[i])
+ # convert the kwargs that need to be processed
+ new_kwargs = {}
+ if kwargs:
+ for arg_name, arg_value in kwargs.items():
+ if arg_name in args_to_cast:
+ new_kwargs[arg_name] = cast_tensor_type(
+ arg_value, torch.float, torch.half)
+ else:
+ new_kwargs[arg_name] = arg_value
+ # apply converted arguments to the decorated method
+ output = old_func(*new_args, **new_kwargs)
+ # cast the results back to fp32 if necessary
+ if out_fp32:
+ output = cast_tensor_type(output, torch.half, torch.float)
+ return output
+
+ return new_func
+
+ return auto_fp16_wrapper
+
+
+def force_fp32(apply_to=None, out_fp16=False):
+ """Decorator to convert input arguments to fp32 in force.
+
+ This decorator is useful when you write custom modules and want to support
+ mixed precision training. If there are some inputs that must be processed
+ in fp32 mode, then this decorator can handle it. If inputs arguments are
+ fp16 tensors, they will be converted to fp32 automatically. Arguments other
+ than fp16 tensors are ignored.
+
+ Args:
+ apply_to (Iterable, optional): The argument names to be converted.
+ `None` indicates all arguments.
+ out_fp16 (bool): Whether to convert the output back to fp16.
+
+ Example:
+
+ >>> import torch.nn as nn
+ >>> class MyModule1(nn.Module):
+ >>>
+ >>> # Convert x and y to fp32
+ >>> @force_fp32()
+ >>> def loss(self, x, y):
+ >>> pass
+
+ >>> import torch.nn as nn
+ >>> class MyModule2(nn.Module):
+ >>>
+ >>> # convert pred to fp32
+ >>> @force_fp32(apply_to=('pred', ))
+ >>> def post_process(self, pred, others):
+ >>> pass
+ """
+ warnings.warn(
+ 'force_fp32 in mmpose will be deprecated in the next release.'
+ 'Please use mmcv.runner.force_fp32 instead (mmcv>=1.3.1).',
+ DeprecationWarning)
+
+ def force_fp32_wrapper(old_func):
+
+ @functools.wraps(old_func)
+ def new_func(*args, **kwargs):
+ # check if the module has set the attribute `fp16_enabled`, if not,
+ # just fallback to the original method.
+ if not isinstance(args[0], torch.nn.Module):
+ raise TypeError('@force_fp32 can only be used to decorate the '
+ 'method of nn.Module')
+ if not (hasattr(args[0], 'fp16_enabled') and args[0].fp16_enabled):
+ return old_func(*args, **kwargs)
+ # get the arg spec of the decorated method
+ args_info = getfullargspec(old_func)
+ # get the argument names to be casted
+ args_to_cast = args_info.args if apply_to is None else apply_to
+ # convert the args that need to be processed
+ new_args = []
+ if args:
+ arg_names = args_info.args[:len(args)]
+ for i, arg_name in enumerate(arg_names):
+ if arg_name in args_to_cast:
+ new_args.append(
+ cast_tensor_type(args[i], torch.half, torch.float))
+ else:
+ new_args.append(args[i])
+ # convert the kwargs that need to be processed
+ new_kwargs = dict()
+ if kwargs:
+ for arg_name, arg_value in kwargs.items():
+ if arg_name in args_to_cast:
+ new_kwargs[arg_name] = cast_tensor_type(
+ arg_value, torch.half, torch.float)
+ else:
+ new_kwargs[arg_name] = arg_value
+ # apply converted arguments to the decorated method
+ output = old_func(*new_args, **new_kwargs)
+ # cast the results back to fp32 if necessary
+ if out_fp16:
+ output = cast_tensor_type(output, torch.float, torch.half)
+ return output
+
+ return new_func
+
+ return force_fp32_wrapper
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/hooks.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..74081a9b73b95ebb20cabf07cfaeab86cc874780
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/hooks.py
@@ -0,0 +1,167 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch
+import torch.nn as nn
+from mmcv.runner import OptimizerHook
+from mmcv.utils import _BatchNorm
+
+from ..utils.dist_utils import allreduce_grads
+from .utils import cast_tensor_type
+
+
+class Fp16OptimizerHook(OptimizerHook):
+ """FP16 optimizer hook.
+
+ The steps of fp16 optimizer is as follows.
+ 1. Scale the loss value.
+ 2. BP in the fp16 model.
+ 2. Copy gradients from fp16 model to fp32 weights.
+ 3. Update fp32 weights.
+ 4. Copy updated parameters from fp32 weights to fp16 model.
+
+ Refer to https://arxiv.org/abs/1710.03740 for more details.
+
+ Args:
+ loss_scale (float): Scale factor multiplied with loss.
+ """
+
+ def __init__(self,
+ grad_clip=None,
+ coalesce=True,
+ bucket_size_mb=-1,
+ loss_scale=512.,
+ distributed=True):
+ self.grad_clip = grad_clip
+ self.coalesce = coalesce
+ self.bucket_size_mb = bucket_size_mb
+ self.loss_scale = loss_scale
+ self.distributed = distributed
+
+ def before_run(self, runner):
+ """Preparing steps before Mixed Precision Training.
+
+ 1. Make a master copy of fp32 weights for optimization.
+ 2. Convert the main model from fp32 to fp16.
+
+ Args:
+ runner (:obj:`mmcv.Runner`): The underlines training runner.
+ """
+ # keep a copy of fp32 weights
+ runner.optimizer.param_groups = copy.deepcopy(
+ runner.optimizer.param_groups)
+ # convert model to fp16
+ wrap_fp16_model(runner.model)
+
+ @staticmethod
+ def copy_grads_to_fp32(fp16_net, fp32_weights):
+ """Copy gradients from fp16 model to fp32 weight copy."""
+ for fp32_param, fp16_param in zip(fp32_weights, fp16_net.parameters()):
+ if fp16_param.grad is not None:
+ if fp32_param.grad is None:
+ fp32_param.grad = fp32_param.data.new(fp32_param.size())
+ fp32_param.grad.copy_(fp16_param.grad)
+
+ @staticmethod
+ def copy_params_to_fp16(fp16_net, fp32_weights):
+ """Copy updated params from fp32 weight copy to fp16 model."""
+ for fp16_param, fp32_param in zip(fp16_net.parameters(), fp32_weights):
+ fp16_param.data.copy_(fp32_param.data)
+
+ def after_train_iter(self, runner):
+ """Backward optimization steps for Mixed Precision Training.
+
+ 1. Scale the loss by a scale factor.
+ 2. Backward the loss to obtain the gradients (fp16).
+ 3. Copy gradients from the model to the fp32 weight copy.
+ 4. Scale the gradients back and update the fp32 weight copy.
+ 5. Copy back the params from fp32 weight copy to the fp16 model.
+
+ Args:
+ runner (:obj:`mmcv.Runner`): The underlines training runner.
+ """
+ # clear grads of last iteration
+ runner.model.zero_grad()
+ runner.optimizer.zero_grad()
+ # scale the loss value
+ scaled_loss = runner.outputs['loss'] * self.loss_scale
+ scaled_loss.backward()
+ # copy fp16 grads in the model to fp32 params in the optimizer
+ fp32_weights = []
+ for param_group in runner.optimizer.param_groups:
+ fp32_weights += param_group['params']
+ self.copy_grads_to_fp32(runner.model, fp32_weights)
+ # allreduce grads
+ if self.distributed:
+ allreduce_grads(fp32_weights, self.coalesce, self.bucket_size_mb)
+ # scale the gradients back
+ for param in fp32_weights:
+ if param.grad is not None:
+ param.grad.div_(self.loss_scale)
+ if self.grad_clip is not None:
+ self.clip_grads(fp32_weights)
+ # update fp32 params
+ runner.optimizer.step()
+ # copy fp32 params to the fp16 model
+ self.copy_params_to_fp16(runner.model, fp32_weights)
+
+
+def wrap_fp16_model(model):
+ """Wrap the FP32 model to FP16.
+
+ 1. Convert FP32 model to FP16.
+ 2. Remain some necessary layers to be FP32, e.g., normalization layers.
+
+ Args:
+ model (nn.Module): Model in FP32.
+ """
+ # convert model to fp16
+ model.half()
+ # patch the normalization layers to make it work in fp32 mode
+ patch_norm_fp32(model)
+ # set `fp16_enabled` flag
+ for m in model.modules():
+ if hasattr(m, 'fp16_enabled'):
+ m.fp16_enabled = True
+
+
+def patch_norm_fp32(module):
+ """Recursively convert normalization layers from FP16 to FP32.
+
+ Args:
+ module (nn.Module): The modules to be converted in FP16.
+
+ Returns:
+ nn.Module: The converted module, the normalization layers have been
+ converted to FP32.
+ """
+ if isinstance(module, (_BatchNorm, nn.GroupNorm)):
+ module.float()
+ module.forward = patch_forward_method(module.forward, torch.half,
+ torch.float)
+ for child in module.children():
+ patch_norm_fp32(child)
+ return module
+
+
+def patch_forward_method(func, src_type, dst_type, convert_output=True):
+ """Patch the forward method of a module.
+
+ Args:
+ func (callable): The original forward method.
+ src_type (torch.dtype): Type of input arguments to be converted from.
+ dst_type (torch.dtype): Type of input arguments to be converted to.
+ convert_output (bool): Whether to convert the output back to src_type.
+
+ Returns:
+ callable: The patched forward method.
+ """
+
+ def new_forward(*args, **kwargs):
+ output = func(*cast_tensor_type(args, src_type, dst_type),
+ **cast_tensor_type(kwargs, src_type, dst_type))
+ if convert_output:
+ output = cast_tensor_type(output, dst_type, src_type)
+ return output
+
+ return new_forward
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1ec3d328328560c7959ae5e77621feb77692068
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/fp16/utils.py
@@ -0,0 +1,34 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import abc
+
+import numpy as np
+import torch
+
+
+def cast_tensor_type(inputs, src_type, dst_type):
+ """Recursively convert Tensor in inputs from src_type to dst_type.
+
+ Args:
+ inputs: Inputs that to be casted.
+ src_type (torch.dtype): Source type.
+ dst_type (torch.dtype): Destination type.
+
+ Returns:
+ The same type with inputs, but all contained Tensors have been cast.
+ """
+ if isinstance(inputs, torch.Tensor):
+ return inputs.to(dst_type)
+ elif isinstance(inputs, str):
+ return inputs
+ elif isinstance(inputs, np.ndarray):
+ return inputs
+ elif isinstance(inputs, abc.Mapping):
+ return type(inputs)({
+ k: cast_tensor_type(v, src_type, dst_type)
+ for k, v in inputs.items()
+ })
+ elif isinstance(inputs, abc.Iterable):
+ return type(inputs)(
+ cast_tensor_type(item, src_type, dst_type) for item in inputs)
+
+ return inputs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..906f67c231d9d33faee6c15f5c9b5582af6fdb19
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .builder import (OPTIMIZER_BUILDERS, OPTIMIZERS,
+ build_optimizer_constructor, build_optimizers)
+
+__all__ = [
+ 'build_optimizers', 'build_optimizer_constructor', 'OPTIMIZERS',
+ 'OPTIMIZER_BUILDERS'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/builder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd2cf49133c57f28261b555d30a5cee18ae105af
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/builder.py
@@ -0,0 +1,70 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.runner import build_optimizer
+from mmcv.runner.optimizer import OPTIMIZER_BUILDERS as MMCV_OPTIMIZER_BUILDERS
+from mmcv.utils import Registry, build_from_cfg
+
+OPTIMIZERS = Registry('optimizers')
+OPTIMIZER_BUILDERS = Registry(
+ 'optimizer builder', parent=MMCV_OPTIMIZER_BUILDERS)
+
+
+def build_optimizer_constructor(cfg):
+ constructor_type = cfg.get('type')
+ if constructor_type in OPTIMIZER_BUILDERS:
+ return build_from_cfg(cfg, OPTIMIZER_BUILDERS)
+ elif constructor_type in MMCV_OPTIMIZER_BUILDERS:
+ return build_from_cfg(cfg, MMCV_OPTIMIZER_BUILDERS)
+ else:
+ raise KeyError(f'{constructor_type} is not registered '
+ 'in the optimizer builder registry.')
+
+
+def build_optimizers(model, cfgs):
+ """Build multiple optimizers from configs.
+
+ If `cfgs` contains several dicts for optimizers, then a dict for each
+ constructed optimizers will be returned.
+ If `cfgs` only contains one optimizer config, the constructed optimizer
+ itself will be returned.
+
+ For example,
+
+ 1) Multiple optimizer configs:
+
+ .. code-block:: python
+
+ optimizer_cfg = dict(
+ model1=dict(type='SGD', lr=lr),
+ model2=dict(type='SGD', lr=lr))
+
+ The return dict is
+ ``dict('model1': torch.optim.Optimizer, 'model2': torch.optim.Optimizer)``
+
+ 2) Single optimizer config:
+
+ .. code-block:: python
+
+ optimizer_cfg = dict(type='SGD', lr=lr)
+
+ The return is ``torch.optim.Optimizer``.
+
+ Args:
+ model (:obj:`nn.Module`): The model with parameters to be optimized.
+ cfgs (dict): The config dict of the optimizer.
+
+ Returns:
+ dict[:obj:`torch.optim.Optimizer`] | :obj:`torch.optim.Optimizer`:
+ The initialized optimizers.
+ """
+ optimizers = {}
+ if hasattr(model, 'module'):
+ model = model.module
+ # determine whether 'cfgs' has several dicts for optimizers
+ if all(isinstance(v, dict) for v in cfgs.values()):
+ for key, cfg in cfgs.items():
+ cfg_ = cfg.copy()
+ module = getattr(model, key)
+ optimizers[key] = build_optimizer(module, cfg_)
+ return optimizers
+
+ return build_optimizer(model, cfgs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/layer_decay_optimizer_constructor.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/layer_decay_optimizer_constructor.py
new file mode 100644
index 0000000000000000000000000000000000000000..1ab6a82548c046483b7c412cefa0762cdbc531f8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/optimizers/layer_decay_optimizer_constructor.py
@@ -0,0 +1,208 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import json
+import warnings
+
+from mmcv.runner import DefaultOptimizerConstructor, get_dist_info
+
+from mmpose.utils import get_root_logger
+from .builder import OPTIMIZER_BUILDERS
+
+
+def get_layer_id_for_convnext(var_name, max_layer_id):
+ """Get the layer id to set the different learning rates in ``layer_wise``
+ decay_type.
+
+ Args:
+ var_name (str): The key of the model.
+ max_layer_id (int): Maximum number of backbone layers.
+
+ Returns:
+ int: The id number corresponding to different learning rate in
+ ``LearningRateDecayOptimizerConstructor``.
+ """
+
+ if var_name in ('backbone.cls_token', 'backbone.mask_token',
+ 'backbone.pos_embed'):
+ return 0
+ elif var_name.startswith('backbone.downsample_layers'):
+ stage_id = int(var_name.split('.')[2])
+ if stage_id == 0:
+ layer_id = 0
+ elif stage_id == 1:
+ layer_id = 2
+ elif stage_id == 2:
+ layer_id = 3
+ elif stage_id == 3:
+ layer_id = max_layer_id
+ return layer_id
+ elif var_name.startswith('backbone.stages'):
+ stage_id = int(var_name.split('.')[2])
+ block_id = int(var_name.split('.')[3])
+ if stage_id == 0:
+ layer_id = 1
+ elif stage_id == 1:
+ layer_id = 2
+ elif stage_id == 2:
+ layer_id = 3 + block_id // 3
+ elif stage_id == 3:
+ layer_id = max_layer_id
+ return layer_id
+ else:
+ return max_layer_id + 1
+
+
+def get_stage_id_for_convnext(var_name, max_stage_id):
+ """Get the stage id to set the different learning rates in ``stage_wise``
+ decay_type.
+
+ Args:
+ var_name (str): The key of the model.
+ max_stage_id (int): Maximum number of backbone layers.
+
+ Returns:
+ int: The id number corresponding to different learning rate in
+ ``LearningRateDecayOptimizerConstructor``.
+ """
+
+ if var_name in ('backbone.cls_token', 'backbone.mask_token',
+ 'backbone.pos_embed'):
+ return 0
+ elif var_name.startswith('backbone.downsample_layers'):
+ return 0
+ elif var_name.startswith('backbone.stages'):
+ stage_id = int(var_name.split('.')[2])
+ return stage_id + 1
+ else:
+ return max_stage_id - 1
+
+
+def get_layer_id_for_vit(var_name, max_layer_id):
+ """Get the layer id to set the different learning rates.
+
+ Args:
+ var_name (str): The key of the model.
+ num_max_layer (int): Maximum number of backbone layers.
+
+ Returns:
+ int: Returns the layer id of the key.
+ """
+
+ if var_name in ('backbone.cls_token', 'backbone.mask_token',
+ 'backbone.pos_embed'):
+ return 0
+ elif var_name.startswith('backbone.patch_embed'):
+ return 0
+ elif var_name.startswith('backbone.layers'):
+ layer_id = int(var_name.split('.')[2])
+ return layer_id + 1
+ else:
+ return max_layer_id - 1
+
+
+@OPTIMIZER_BUILDERS.register_module()
+class LearningRateDecayOptimizerConstructor(DefaultOptimizerConstructor):
+ """Different learning rates are set for different layers of backbone.
+
+ Note: Currently, this optimizer constructor is built for ConvNeXt,
+ BEiT and MAE.
+ """
+
+ def add_params(self, params, module, **kwargs):
+ """Add all parameters of module to the params list.
+
+ The parameters of the given module will be added to the list of param
+ groups, with specific rules defined by paramwise_cfg.
+
+ Args:
+ params (list[dict]): A list of param groups, it will be modified
+ in place.
+ module (nn.Module): The module to be added.
+ """
+ logger = get_root_logger()
+
+ parameter_groups = {}
+ logger.info(f'self.paramwise_cfg is {self.paramwise_cfg}')
+ num_layers = self.paramwise_cfg.get('num_layers') + 2
+ decay_rate = self.paramwise_cfg.get('decay_rate')
+ decay_type = self.paramwise_cfg.get('decay_type', 'layer_wise')
+ logger.info('Build LearningRateDecayOptimizerConstructor '
+ f'{decay_type} {decay_rate} - {num_layers}')
+ weight_decay = self.base_wd
+ for name, param in module.named_parameters():
+ if not param.requires_grad:
+ continue # frozen weights
+ if len(param.shape) == 1 or name.endswith('.bias') or name in (
+ 'pos_embed', 'cls_token'):
+ group_name = 'no_decay'
+ this_weight_decay = 0.
+ else:
+ group_name = 'decay'
+ this_weight_decay = weight_decay
+ if 'layer_wise' in decay_type:
+ if 'ConvNeXt' in module.backbone.__class__.__name__:
+ layer_id = get_layer_id_for_convnext(
+ name, self.paramwise_cfg.get('num_layers'))
+ logger.info(f'set param {name} as id {layer_id}')
+ elif 'BEiT' in module.backbone.__class__.__name__ or \
+ 'MAE' in module.backbone.__class__.__name__:
+ layer_id = get_layer_id_for_vit(name, num_layers)
+ logger.info(f'set param {name} as id {layer_id}')
+ else:
+ raise NotImplementedError()
+ elif decay_type == 'stage_wise':
+ if 'ConvNeXt' in module.backbone.__class__.__name__:
+ layer_id = get_stage_id_for_convnext(name, num_layers)
+ logger.info(f'set param {name} as id {layer_id}')
+ else:
+ raise NotImplementedError()
+ group_name = f'layer_{layer_id}_{group_name}'
+
+ if group_name not in parameter_groups:
+ scale = decay_rate**(num_layers - layer_id - 1)
+
+ parameter_groups[group_name] = {
+ 'weight_decay': this_weight_decay,
+ 'params': [],
+ 'param_names': [],
+ 'lr_scale': scale,
+ 'group_name': group_name,
+ 'lr': scale * self.base_lr,
+ }
+
+ parameter_groups[group_name]['params'].append(param)
+ parameter_groups[group_name]['param_names'].append(name)
+ rank, _ = get_dist_info()
+ if rank == 0:
+ to_display = {}
+ for key in parameter_groups:
+ to_display[key] = {
+ 'param_names': parameter_groups[key]['param_names'],
+ 'lr_scale': parameter_groups[key]['lr_scale'],
+ 'lr': parameter_groups[key]['lr'],
+ 'weight_decay': parameter_groups[key]['weight_decay'],
+ }
+ logger.info(f'Param groups = {json.dumps(to_display, indent=2)}')
+ params.extend(parameter_groups.values())
+
+
+@OPTIMIZER_BUILDERS.register_module()
+class LayerDecayOptimizerConstructor(LearningRateDecayOptimizerConstructor):
+ """Different learning rates are set for different layers of backbone.
+
+ Note: Currently, this optimizer constructor is built for BEiT,
+ and it will be deprecated.
+ Please use ``LearningRateDecayOptimizerConstructor`` instead.
+ """
+
+ def __init__(self, optimizer_cfg, paramwise_cfg):
+ warnings.warn('DeprecationWarning: Original '
+ 'LayerDecayOptimizerConstructor of BEiT '
+ 'will be deprecated. Please use '
+ 'LearningRateDecayOptimizerConstructor instead, '
+ 'and set decay_type = layer_wise_vit in paramwise_cfg.')
+ paramwise_cfg.update({'decay_type': 'layer_wise_vit'})
+ warnings.warn('DeprecationWarning: Layer_decay_rate will '
+ 'be deleted, please use decay_rate instead.')
+ paramwise_cfg['decay_rate'] = paramwise_cfg.pop('layer_decay_rate')
+ super(LayerDecayOptimizerConstructor,
+ self).__init__(optimizer_cfg, paramwise_cfg)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8076b799b9e405e7ac5a883aa3a6d5dcb84060b5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/__init__.py
@@ -0,0 +1,16 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+from .nms import oks_iou, oks_nms, soft_oks_nms
+from .one_euro_filter import OneEuroFilter
+from .post_transforms import (affine_transform, flip_back, fliplr_joints,
+ fliplr_regression, get_affine_transform,
+ get_warp_matrix, rotate_point, transform_preds,
+ warp_affine_joints)
+from .smoother import Smoother
+
+__all__ = [
+ 'oks_nms', 'soft_oks_nms', 'affine_transform', 'rotate_point', 'flip_back',
+ 'fliplr_joints', 'fliplr_regression', 'transform_preds',
+ 'get_affine_transform', 'get_warp_matrix', 'warp_affine_joints', 'oks_iou',
+ 'OneEuroFilter', 'Smoother'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/group.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/group.py
new file mode 100644
index 0000000000000000000000000000000000000000..75499cb0bc4eb96f9255e9c02d20cf7a9c95c402
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/group.py
@@ -0,0 +1,418 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/princeton-vl/pose-ae-train/
+# Original licence: Copyright (c) 2017, umich-vl, under BSD 3-Clause License.
+# ------------------------------------------------------------------------------
+
+import numpy as np
+import torch
+from munkres import Munkres
+
+from mmpose.core.evaluation import post_dark_udp
+
+
+def _py_max_match(scores):
+ """Apply munkres algorithm to get the best match.
+
+ Args:
+ scores(np.ndarray): cost matrix.
+
+ Returns:
+ np.ndarray: best match.
+ """
+ m = Munkres()
+ tmp = m.compute(scores)
+ tmp = np.array(tmp).astype(int)
+ return tmp
+
+
+def _match_by_tag(inp, params):
+ """Match joints by tags. Use Munkres algorithm to calculate the best match
+ for keypoints grouping.
+
+ Note:
+ number of keypoints: K
+ max number of people in an image: M (M=30 by default)
+ dim of tags: L
+ If use flip testing, L=2; else L=1.
+
+ Args:
+ inp(tuple):
+ tag_k (np.ndarray[KxMxL]): tag corresponding to the
+ top k values of feature map per keypoint.
+ loc_k (np.ndarray[KxMx2]): top k locations of the
+ feature maps for keypoint.
+ val_k (np.ndarray[KxM]): top k value of the
+ feature maps per keypoint.
+ params(Params): class Params().
+
+ Returns:
+ np.ndarray: result of pose groups.
+ """
+ assert isinstance(params, _Params), 'params should be class _Params()'
+
+ tag_k, loc_k, val_k = inp
+
+ default_ = np.zeros((params.num_joints, 3 + tag_k.shape[2]),
+ dtype=np.float32)
+
+ joint_dict = {}
+ tag_dict = {}
+ for i in range(params.num_joints):
+ idx = params.joint_order[i]
+
+ tags = tag_k[idx]
+ joints = np.concatenate((loc_k[idx], val_k[idx, :, None], tags), 1)
+ mask = joints[:, 2] > params.detection_threshold
+ tags = tags[mask] # shape: [M, L]
+ joints = joints[mask] # shape: [M, 3 + L], 3: x, y, val
+
+ if joints.shape[0] == 0:
+ continue
+
+ if i == 0 or len(joint_dict) == 0:
+ for tag, joint in zip(tags, joints):
+ key = tag[0]
+ joint_dict.setdefault(key, np.copy(default_))[idx] = joint
+ tag_dict[key] = [tag]
+ else:
+ # shape: [M]
+ grouped_keys = list(joint_dict.keys())
+ if params.ignore_too_much:
+ grouped_keys = grouped_keys[:params.max_num_people]
+ # shape: [M, L]
+ grouped_tags = [np.mean(tag_dict[i], axis=0) for i in grouped_keys]
+
+ # shape: [M, M, L]
+ diff = joints[:, None, 3:] - np.array(grouped_tags)[None, :, :]
+ # shape: [M, M]
+ diff_normed = np.linalg.norm(diff, ord=2, axis=2)
+ diff_saved = np.copy(diff_normed)
+
+ if params.use_detection_val:
+ diff_normed = np.round(diff_normed) * 100 - joints[:, 2:3]
+
+ num_added = diff.shape[0]
+ num_grouped = diff.shape[1]
+
+ if num_added > num_grouped:
+ diff_normed = np.concatenate(
+ (diff_normed,
+ np.zeros((num_added, num_added - num_grouped),
+ dtype=np.float32) + 1e10),
+ axis=1)
+
+ pairs = _py_max_match(diff_normed)
+ for row, col in pairs:
+ if (row < num_added and col < num_grouped
+ and diff_saved[row][col] < params.tag_threshold):
+ key = grouped_keys[col]
+ joint_dict[key][idx] = joints[row]
+ tag_dict[key].append(tags[row])
+ else:
+ key = tags[row][0]
+ joint_dict.setdefault(key, np.copy(default_))[idx] = \
+ joints[row]
+ tag_dict[key] = [tags[row]]
+
+ joint_dict_keys = list(joint_dict.keys())
+ if params.ignore_too_much:
+ # The new person joints beyond the params.max_num_people will be
+ # ignored, for the dict is in ordered when python > 3.6 version.
+ joint_dict_keys = joint_dict_keys[:params.max_num_people]
+ results = np.array([joint_dict[i]
+ for i in joint_dict_keys]).astype(np.float32)
+ return results
+
+
+class _Params:
+ """A class of parameter.
+
+ Args:
+ cfg(Config): config.
+ """
+
+ def __init__(self, cfg):
+ self.num_joints = cfg['num_joints']
+ self.max_num_people = cfg['max_num_people']
+
+ self.detection_threshold = cfg['detection_threshold']
+ self.tag_threshold = cfg['tag_threshold']
+ self.use_detection_val = cfg['use_detection_val']
+ self.ignore_too_much = cfg['ignore_too_much']
+
+ if self.num_joints == 17:
+ self.joint_order = [
+ i - 1 for i in
+ [1, 2, 3, 4, 5, 6, 7, 12, 13, 8, 9, 10, 11, 14, 15, 16, 17]
+ ]
+ else:
+ self.joint_order = list(np.arange(self.num_joints))
+
+
+class HeatmapParser:
+ """The heatmap parser for post processing."""
+
+ def __init__(self, cfg):
+ self.params = _Params(cfg)
+ self.tag_per_joint = cfg['tag_per_joint']
+ self.pool = torch.nn.MaxPool2d(cfg['nms_kernel'], 1,
+ cfg['nms_padding'])
+ self.use_udp = cfg.get('use_udp', False)
+ self.score_per_joint = cfg.get('score_per_joint', False)
+
+ def nms(self, heatmaps):
+ """Non-Maximum Suppression for heatmaps.
+
+ Args:
+ heatmap(torch.Tensor): Heatmaps before nms.
+
+ Returns:
+ torch.Tensor: Heatmaps after nms.
+ """
+
+ maxm = self.pool(heatmaps)
+ maxm = torch.eq(maxm, heatmaps).float()
+ heatmaps = heatmaps * maxm
+
+ return heatmaps
+
+ def match(self, tag_k, loc_k, val_k):
+ """Group keypoints to human poses in a batch.
+
+ Args:
+ tag_k (np.ndarray[NxKxMxL]): tag corresponding to the
+ top k values of feature map per keypoint.
+ loc_k (np.ndarray[NxKxMx2]): top k locations of the
+ feature maps for keypoint.
+ val_k (np.ndarray[NxKxM]): top k value of the
+ feature maps per keypoint.
+
+ Returns:
+ list
+ """
+
+ def _match(x):
+ return _match_by_tag(x, self.params)
+
+ return list(map(_match, zip(tag_k, loc_k, val_k)))
+
+ def top_k(self, heatmaps, tags):
+ """Find top_k values in an image.
+
+ Note:
+ batch size: N
+ number of keypoints: K
+ heatmap height: H
+ heatmap width: W
+ max number of people: M
+ dim of tags: L
+ If use flip testing, L=2; else L=1.
+
+ Args:
+ heatmaps (torch.Tensor[NxKxHxW])
+ tags (torch.Tensor[NxKxHxWxL])
+
+ Returns:
+ dict: A dict containing top_k values.
+
+ - tag_k (np.ndarray[NxKxMxL]):
+ tag corresponding to the top k values of
+ feature map per keypoint.
+ - loc_k (np.ndarray[NxKxMx2]):
+ top k location of feature map per keypoint.
+ - val_k (np.ndarray[NxKxM]):
+ top k value of feature map per keypoint.
+ """
+ heatmaps = self.nms(heatmaps)
+ N, K, H, W = heatmaps.size()
+ heatmaps = heatmaps.view(N, K, -1)
+ val_k, ind = heatmaps.topk(self.params.max_num_people, dim=2)
+
+ tags = tags.view(tags.size(0), tags.size(1), W * H, -1)
+ if not self.tag_per_joint:
+ tags = tags.expand(-1, self.params.num_joints, -1, -1)
+
+ tag_k = torch.stack(
+ [torch.gather(tags[..., i], 2, ind) for i in range(tags.size(3))],
+ dim=3)
+
+ x = ind % W
+ y = ind // W
+
+ ind_k = torch.stack((x, y), dim=3)
+
+ results = {
+ 'tag_k': tag_k.cpu().numpy(),
+ 'loc_k': ind_k.cpu().numpy(),
+ 'val_k': val_k.cpu().numpy()
+ }
+
+ return results
+
+ @staticmethod
+ def adjust(results, heatmaps):
+ """Adjust the coordinates for better accuracy.
+
+ Note:
+ batch size: N
+ number of keypoints: K
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ results (list(np.ndarray)): Keypoint predictions.
+ heatmaps (torch.Tensor[NxKxHxW]): Heatmaps.
+ """
+ _, _, H, W = heatmaps.shape
+ for batch_id, people in enumerate(results):
+ for people_id, people_i in enumerate(people):
+ for joint_id, joint in enumerate(people_i):
+ if joint[2] > 0:
+ x, y = joint[0:2]
+ xx, yy = int(x), int(y)
+ tmp = heatmaps[batch_id][joint_id]
+ if tmp[min(H - 1, yy + 1), xx] > tmp[max(0, yy - 1),
+ xx]:
+ y += 0.25
+ else:
+ y -= 0.25
+
+ if tmp[yy, min(W - 1, xx + 1)] > tmp[yy,
+ max(0, xx - 1)]:
+ x += 0.25
+ else:
+ x -= 0.25
+ results[batch_id][people_id, joint_id,
+ 0:2] = (x + 0.5, y + 0.5)
+ return results
+
+ @staticmethod
+ def refine(heatmap, tag, keypoints, use_udp=False):
+ """Given initial keypoint predictions, we identify missing joints.
+
+ Note:
+ number of keypoints: K
+ heatmap height: H
+ heatmap width: W
+ dim of tags: L
+ If use flip testing, L=2; else L=1.
+
+ Args:
+ heatmap: np.ndarray(K, H, W).
+ tag: np.ndarray(K, H, W) | np.ndarray(K, H, W, L)
+ keypoints: np.ndarray of size (K, 3 + L)
+ last dim is (x, y, score, tag).
+ use_udp: bool-unbiased data processing
+
+ Returns:
+ np.ndarray: The refined keypoints.
+ """
+
+ K, H, W = heatmap.shape
+ if len(tag.shape) == 3:
+ tag = tag[..., None]
+
+ tags = []
+ for i in range(K):
+ if keypoints[i, 2] > 0:
+ # save tag value of detected keypoint
+ x, y = keypoints[i][:2].astype(int)
+ x = np.clip(x, 0, W - 1)
+ y = np.clip(y, 0, H - 1)
+ tags.append(tag[i, y, x])
+
+ # mean tag of current detected people
+ prev_tag = np.mean(tags, axis=0)
+ results = []
+
+ for _heatmap, _tag in zip(heatmap, tag):
+ # distance of all tag values with mean tag of
+ # current detected people
+ distance_tag = (((_tag -
+ prev_tag[None, None, :])**2).sum(axis=2)**0.5)
+ norm_heatmap = _heatmap - np.round(distance_tag)
+
+ # find maximum position
+ y, x = np.unravel_index(np.argmax(norm_heatmap), _heatmap.shape)
+ xx = x.copy()
+ yy = y.copy()
+ # detection score at maximum position
+ val = _heatmap[y, x]
+ if not use_udp:
+ # offset by 0.5
+ x += 0.5
+ y += 0.5
+
+ # add a quarter offset
+ if _heatmap[yy, min(W - 1, xx + 1)] > _heatmap[yy, max(0, xx - 1)]:
+ x += 0.25
+ else:
+ x -= 0.25
+
+ if _heatmap[min(H - 1, yy + 1), xx] > _heatmap[max(0, yy - 1), xx]:
+ y += 0.25
+ else:
+ y -= 0.25
+
+ results.append((x, y, val))
+ results = np.array(results)
+
+ if results is not None:
+ for i in range(K):
+ # add keypoint if it is not detected
+ if results[i, 2] > 0 and keypoints[i, 2] == 0:
+ keypoints[i, :3] = results[i, :3]
+
+ return keypoints
+
+ def parse(self, heatmaps, tags, adjust=True, refine=True):
+ """Group keypoints into poses given heatmap and tag.
+
+ Note:
+ batch size: N
+ number of keypoints: K
+ heatmap height: H
+ heatmap width: W
+ dim of tags: L
+ If use flip testing, L=2; else L=1.
+
+ Args:
+ heatmaps (torch.Tensor[NxKxHxW]): model output heatmaps.
+ tags (torch.Tensor[NxKxHxWxL]): model output tagmaps.
+
+ Returns:
+ tuple: A tuple containing keypoint grouping results.
+
+ - results (list(np.ndarray)): Pose results.
+ - scores (list/list(np.ndarray)): Score of people.
+ """
+ results = self.match(**self.top_k(heatmaps, tags))
+
+ if adjust:
+ if self.use_udp:
+ for i in range(len(results)):
+ if results[i].shape[0] > 0:
+ results[i][..., :2] = post_dark_udp(
+ results[i][..., :2].copy(), heatmaps[i:i + 1, :])
+ else:
+ results = self.adjust(results, heatmaps)
+
+ if self.score_per_joint:
+ scores = [i[:, 2] for i in results[0]]
+ else:
+ scores = [i[:, 2].mean() for i in results[0]]
+
+ if refine:
+ results = results[0]
+ # for every detected person
+ for i in range(len(results)):
+ heatmap_numpy = heatmaps[0].cpu().numpy()
+ tag_numpy = tags[0].cpu().numpy()
+ if not self.tag_per_joint:
+ tag_numpy = np.tile(tag_numpy,
+ (self.params.num_joints, 1, 1, 1))
+ results[i] = self.refine(
+ heatmap_numpy, tag_numpy, results[i], use_udp=self.use_udp)
+ results = [results]
+
+ return results, scores
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/nms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/nms.py
new file mode 100644
index 0000000000000000000000000000000000000000..86a0ab35e0e26d27bb0bb55071018ffc5ac9af1d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/nms.py
@@ -0,0 +1,207 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
+# Original licence: Copyright (c) Microsoft, under the MIT License.
+# ------------------------------------------------------------------------------
+
+import numpy as np
+
+
+def nms(dets, thr):
+ """Greedily select boxes with high confidence and overlap <= thr.
+
+ Args:
+ dets: [[x1, y1, x2, y2, score]].
+ thr: Retain overlap < thr.
+
+ Returns:
+ list: Indexes to keep.
+ """
+ if len(dets) == 0:
+ return []
+
+ x1 = dets[:, 0]
+ y1 = dets[:, 1]
+ x2 = dets[:, 2]
+ y2 = dets[:, 3]
+ scores = dets[:, 4]
+
+ areas = (x2 - x1 + 1) * (y2 - y1 + 1)
+ order = scores.argsort()[::-1]
+
+ keep = []
+ while len(order) > 0:
+ i = order[0]
+ keep.append(i)
+ xx1 = np.maximum(x1[i], x1[order[1:]])
+ yy1 = np.maximum(y1[i], y1[order[1:]])
+ xx2 = np.minimum(x2[i], x2[order[1:]])
+ yy2 = np.minimum(y2[i], y2[order[1:]])
+
+ w = np.maximum(0.0, xx2 - xx1 + 1)
+ h = np.maximum(0.0, yy2 - yy1 + 1)
+ inter = w * h
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
+
+ inds = np.where(ovr <= thr)[0]
+ order = order[inds + 1]
+
+ return keep
+
+
+def oks_iou(g, d, a_g, a_d, sigmas=None, vis_thr=None):
+ """Calculate oks ious.
+
+ Args:
+ g: Ground truth keypoints.
+ d: Detected keypoints.
+ a_g: Area of the ground truth object.
+ a_d: Area of the detected object.
+ sigmas: standard deviation of keypoint labelling.
+ vis_thr: threshold of the keypoint visibility.
+
+ Returns:
+ list: The oks ious.
+ """
+ if sigmas is None:
+ sigmas = np.array([
+ .26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07,
+ .87, .87, .89, .89
+ ]) / 10.0
+ vars = (sigmas * 2)**2
+ xg = g[0::3]
+ yg = g[1::3]
+ vg = g[2::3]
+ ious = np.zeros(len(d), dtype=np.float32)
+ for n_d in range(0, len(d)):
+ xd = d[n_d, 0::3]
+ yd = d[n_d, 1::3]
+ vd = d[n_d, 2::3]
+ dx = xd - xg
+ dy = yd - yg
+ e = (dx**2 + dy**2) / vars / ((a_g + a_d[n_d]) / 2 + np.spacing(1)) / 2
+ if vis_thr is not None:
+ ind = list(vg > vis_thr) and list(vd > vis_thr)
+ e = e[ind]
+ ious[n_d] = np.sum(np.exp(-e)) / len(e) if len(e) != 0 else 0.0
+ return ious
+
+
+def oks_nms(kpts_db, thr, sigmas=None, vis_thr=None, score_per_joint=False):
+ """OKS NMS implementations.
+
+ Args:
+ kpts_db: keypoints.
+ thr: Retain overlap < thr.
+ sigmas: standard deviation of keypoint labelling.
+ vis_thr: threshold of the keypoint visibility.
+ score_per_joint: the input scores (in kpts_db) are per joint scores
+
+ Returns:
+ np.ndarray: indexes to keep.
+ """
+ if len(kpts_db) == 0:
+ return []
+
+ if score_per_joint:
+ scores = np.array([k['score'].mean() for k in kpts_db])
+ else:
+ scores = np.array([k['score'] for k in kpts_db])
+
+ kpts = np.array([k['keypoints'].flatten() for k in kpts_db])
+ areas = np.array([k['area'] for k in kpts_db])
+
+ order = scores.argsort()[::-1]
+
+ keep = []
+ while len(order) > 0:
+ i = order[0]
+ keep.append(i)
+
+ oks_ovr = oks_iou(kpts[i], kpts[order[1:]], areas[i], areas[order[1:]],
+ sigmas, vis_thr)
+
+ inds = np.where(oks_ovr <= thr)[0]
+ order = order[inds + 1]
+
+ keep = np.array(keep)
+
+ return keep
+
+
+def _rescore(overlap, scores, thr, type='gaussian'):
+ """Rescoring mechanism gaussian or linear.
+
+ Args:
+ overlap: calculated ious
+ scores: target scores.
+ thr: retain oks overlap < thr.
+ type: 'gaussian' or 'linear'
+
+ Returns:
+ np.ndarray: indexes to keep
+ """
+ assert len(overlap) == len(scores)
+ assert type in ['gaussian', 'linear']
+
+ if type == 'linear':
+ inds = np.where(overlap >= thr)[0]
+ scores[inds] = scores[inds] * (1 - overlap[inds])
+ else:
+ scores = scores * np.exp(-overlap**2 / thr)
+
+ return scores
+
+
+def soft_oks_nms(kpts_db,
+ thr,
+ max_dets=20,
+ sigmas=None,
+ vis_thr=None,
+ score_per_joint=False):
+ """Soft OKS NMS implementations.
+
+ Args:
+ kpts_db
+ thr: retain oks overlap < thr.
+ max_dets: max number of detections to keep.
+ sigmas: Keypoint labelling uncertainty.
+ score_per_joint: the input scores (in kpts_db) are per joint scores
+
+ Returns:
+ np.ndarray: indexes to keep.
+ """
+ if len(kpts_db) == 0:
+ return []
+
+ if score_per_joint:
+ scores = np.array([k['score'].mean() for k in kpts_db])
+ else:
+ scores = np.array([k['score'] for k in kpts_db])
+
+ kpts = np.array([k['keypoints'].flatten() for k in kpts_db])
+ areas = np.array([k['area'] for k in kpts_db])
+
+ order = scores.argsort()[::-1]
+ scores = scores[order]
+
+ keep = np.zeros(max_dets, dtype=np.intp)
+ keep_cnt = 0
+ while len(order) > 0 and keep_cnt < max_dets:
+ i = order[0]
+
+ oks_ovr = oks_iou(kpts[i], kpts[order[1:]], areas[i], areas[order[1:]],
+ sigmas, vis_thr)
+
+ order = order[1:]
+ scores = _rescore(oks_ovr, scores[1:], thr)
+
+ tmp = scores.argsort()[::-1]
+ order = order[tmp]
+ scores = scores[tmp]
+
+ keep[keep_cnt] = i
+ keep_cnt += 1
+
+ keep = keep[:keep_cnt]
+
+ return keep
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/one_euro_filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/one_euro_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..325466522dbcbd5f2cdf85276a94269466fe741f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/one_euro_filter.py
@@ -0,0 +1,113 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/HoBeom/OneEuroFilter-Numpy
+# Original licence: Copyright (c) HoBeom Jeon, under the MIT License.
+# ------------------------------------------------------------------------------
+import warnings
+from time import time
+
+import numpy as np
+
+
+def smoothing_factor(t_e, cutoff):
+ r = 2 * np.pi * cutoff * t_e
+ return r / (r + 1)
+
+
+def exponential_smoothing(a, x, x_prev):
+ return a * x + (1 - a) * x_prev
+
+
+class OneEuroFilter:
+
+ def __init__(self,
+ x0,
+ dx0=0.0,
+ min_cutoff=1.7,
+ beta=0.3,
+ d_cutoff=30.0,
+ fps=None):
+ """One Euro Filter for keypoints smoothing.
+
+ Args:
+ x0 (np.ndarray[K, 2]): Initialize keypoints value
+ dx0 (float): 0.0
+ min_cutoff (float): parameter for one euro filter
+ beta (float): parameter for one euro filter
+ d_cutoff (float): Input data FPS
+ fps (float): Video FPS for video inference
+ """
+ warnings.warn(
+ 'OneEuroFilter from '
+ '`mmpose/core/post_processing/one_euro_filter.py` will '
+ 'be deprecated in the future. Please use Smoother'
+ '(`mmpose/core/post_processing/smoother.py`) with '
+ 'OneEuroFilter (`mmpose/core/post_processing/temporal_'
+ 'filters/one_euro_filter.py`).', DeprecationWarning)
+
+ # The parameters.
+ self.data_shape = x0.shape
+ self.min_cutoff = np.full(x0.shape, min_cutoff)
+ self.beta = np.full(x0.shape, beta)
+ self.d_cutoff = np.full(x0.shape, d_cutoff)
+ # Previous values.
+ self.x_prev = x0.astype(np.float32)
+ self.dx_prev = np.full(x0.shape, dx0)
+ self.mask_prev = np.ma.masked_where(x0 <= 0, x0)
+ self.realtime = True
+ if fps is None:
+ # Using in realtime inference
+ self.t_e = None
+ self.skip_frame_factor = d_cutoff
+ self.fps = d_cutoff
+ else:
+ # fps using video inference
+ self.realtime = False
+ self.fps = float(fps)
+ self.d_cutoff = np.full(x0.shape, self.fps)
+
+ self.t_prev = time()
+
+ def __call__(self, x, t_e=1.0):
+ """Compute the filtered signal.
+
+ Hyper-parameters (cutoff, beta) are from `VNect
+ `__ .
+
+ Realtime Camera fps (d_cutoff) default 30.0
+
+ Args:
+ x (np.ndarray[K, 2]): keypoints results in frame
+ t_e (Optional): video skip frame count for posetrack
+ evaluation
+ """
+ assert x.shape == self.data_shape
+
+ t = 0
+ if self.realtime:
+ t = time()
+ t_e = (t - self.t_prev) * self.skip_frame_factor
+ t_e = np.full(x.shape, t_e)
+
+ # missing keypoints mask
+ mask = np.ma.masked_where(x <= 0, x)
+
+ # The filtered derivative of the signal.
+ a_d = smoothing_factor(t_e / self.fps, self.d_cutoff)
+ dx = (x - self.x_prev) / t_e
+ dx_hat = exponential_smoothing(a_d, dx, self.dx_prev)
+
+ # The filtered signal.
+ cutoff = self.min_cutoff + self.beta * np.abs(dx_hat)
+ a = smoothing_factor(t_e / self.fps, cutoff)
+ x_hat = exponential_smoothing(a, x, self.x_prev)
+
+ # missing keypoints remove
+ np.copyto(x_hat, -10, where=mask.mask)
+
+ # Memorize the previous values.
+ self.x_prev = x_hat
+ self.dx_prev = dx_hat
+ self.t_prev = t
+ self.mask_prev = mask
+
+ return x_hat
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/post_transforms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/post_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..93063fb1c1a60519a527037795654b0278a880e4
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/post_transforms.py
@@ -0,0 +1,366 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
+# Original licence: Copyright (c) Microsoft, under the MIT License.
+# ------------------------------------------------------------------------------
+
+import math
+
+import cv2
+import numpy as np
+import torch
+
+
+def fliplr_joints(joints_3d, joints_3d_visible, img_width, flip_pairs):
+ """Flip human joints horizontally.
+
+ Note:
+ - num_keypoints: K
+
+ Args:
+ joints_3d (np.ndarray([K, 3])): Coordinates of keypoints.
+ joints_3d_visible (np.ndarray([K, 1])): Visibility of keypoints.
+ img_width (int): Image width.
+ flip_pairs (list[tuple]): Pairs of keypoints which are mirrored
+ (for example, left ear and right ear).
+
+ Returns:
+ tuple: Flipped human joints.
+
+ - joints_3d_flipped (np.ndarray([K, 3])): Flipped joints.
+ - joints_3d_visible_flipped (np.ndarray([K, 1])): Joint visibility.
+ """
+
+ assert len(joints_3d) == len(joints_3d_visible)
+ assert img_width > 0
+
+ joints_3d_flipped = joints_3d.copy()
+ joints_3d_visible_flipped = joints_3d_visible.copy()
+
+ # Swap left-right parts
+ for left, right in flip_pairs:
+ joints_3d_flipped[left, :] = joints_3d[right, :]
+ joints_3d_flipped[right, :] = joints_3d[left, :]
+
+ joints_3d_visible_flipped[left, :] = joints_3d_visible[right, :]
+ joints_3d_visible_flipped[right, :] = joints_3d_visible[left, :]
+
+ # Flip horizontally
+ joints_3d_flipped[:, 0] = img_width - 1 - joints_3d_flipped[:, 0]
+ joints_3d_flipped = joints_3d_flipped * joints_3d_visible_flipped
+
+ return joints_3d_flipped, joints_3d_visible_flipped
+
+
+def fliplr_regression(regression,
+ flip_pairs,
+ center_mode='static',
+ center_x=0.5,
+ center_index=0):
+ """Flip human joints horizontally.
+
+ Note:
+ - batch_size: N
+ - num_keypoint: K
+
+ Args:
+ regression (np.ndarray([..., K, C])): Coordinates of keypoints, where K
+ is the joint number and C is the dimension. Example shapes are:
+
+ - [N, K, C]: a batch of keypoints where N is the batch size.
+ - [N, T, K, C]: a batch of pose sequences, where T is the frame
+ number.
+ flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored
+ (for example, left ear -- right ear).
+ center_mode (str): The mode to set the center location on the x-axis
+ to flip around. Options are:
+
+ - static: use a static x value (see center_x also)
+ - root: use a root joint (see center_index also)
+ center_x (float): Set the x-axis location of the flip center. Only used
+ when center_mode=static.
+ center_index (int): Set the index of the root joint, whose x location
+ will be used as the flip center. Only used when center_mode=root.
+
+ Returns:
+ np.ndarray([..., K, C]): Flipped joints.
+ """
+ assert regression.ndim >= 2, f'Invalid pose shape {regression.shape}'
+
+ allowed_center_mode = {'static', 'root'}
+ assert center_mode in allowed_center_mode, 'Get invalid center_mode ' \
+ f'{center_mode}, allowed choices are {allowed_center_mode}'
+
+ if center_mode == 'static':
+ x_c = center_x
+ elif center_mode == 'root':
+ assert regression.shape[-2] > center_index
+ x_c = regression[..., center_index:center_index + 1, 0]
+
+ regression_flipped = regression.copy()
+ # Swap left-right parts
+ for left, right in flip_pairs:
+ regression_flipped[..., left, :] = regression[..., right, :]
+ regression_flipped[..., right, :] = regression[..., left, :]
+
+ # Flip horizontally
+ regression_flipped[..., 0] = x_c * 2 - regression_flipped[..., 0]
+ return regression_flipped
+
+
+def flip_back(output_flipped, flip_pairs, target_type='GaussianHeatmap'):
+ """Flip the flipped heatmaps back to the original form.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmap height: H
+ - heatmap width: W
+
+ Args:
+ output_flipped (np.ndarray[N, K, H, W]): The output heatmaps obtained
+ from the flipped images.
+ flip_pairs (list[tuple()): Pairs of keypoints which are mirrored
+ (for example, left ear -- right ear).
+ target_type (str): GaussianHeatmap or CombinedTarget
+
+ Returns:
+ np.ndarray: heatmaps that flipped back to the original image
+ """
+ assert output_flipped.ndim == 4, \
+ 'output_flipped should be [batch_size, num_keypoints, height, width]'
+ shape_ori = output_flipped.shape
+ channels = 1
+ if target_type.lower() == 'CombinedTarget'.lower():
+ channels = 3
+ output_flipped[:, 1::3, ...] = -output_flipped[:, 1::3, ...]
+ output_flipped = output_flipped.reshape(shape_ori[0], -1, channels,
+ shape_ori[2], shape_ori[3])
+ output_flipped_back = output_flipped.copy()
+
+ # Swap left-right parts
+ for left, right in flip_pairs:
+ output_flipped_back[:, left, ...] = output_flipped[:, right, ...]
+ output_flipped_back[:, right, ...] = output_flipped[:, left, ...]
+ output_flipped_back = output_flipped_back.reshape(shape_ori)
+ # Flip horizontally
+ output_flipped_back = output_flipped_back[..., ::-1]
+ return output_flipped_back
+
+
+def transform_preds(coords, center, scale, output_size, use_udp=False):
+ """Get final keypoint predictions from heatmaps and apply scaling and
+ translation to map them back to the image.
+
+ Note:
+ num_keypoints: K
+
+ Args:
+ coords (np.ndarray[K, ndims]):
+
+ * If ndims=2, corrds are predicted keypoint location.
+ * If ndims=4, corrds are composed of (x, y, scores, tags)
+ * If ndims=5, corrds are composed of (x, y, scores, tags,
+ flipped_tags)
+
+ center (np.ndarray[2, ]): Center of the bounding box (x, y).
+ scale (np.ndarray[2, ]): Scale of the bounding box
+ wrt [width, height].
+ output_size (np.ndarray[2, ] | list(2,)): Size of the
+ destination heatmaps.
+ use_udp (bool): Use unbiased data processing
+
+ Returns:
+ np.ndarray: Predicted coordinates in the images.
+ """
+ assert coords.shape[1] in (2, 4, 5)
+ assert len(center) == 2
+ assert len(scale) == 2
+ assert len(output_size) == 2
+
+ # Recover the scale which is normalized by a factor of 200.
+ scale = scale * 200.0
+
+ if use_udp:
+ scale_x = scale[0] / (output_size[0] - 1.0)
+ scale_y = scale[1] / (output_size[1] - 1.0)
+ else:
+ scale_x = scale[0] / output_size[0]
+ scale_y = scale[1] / output_size[1]
+
+ target_coords = np.ones_like(coords)
+ target_coords[:, 0] = coords[:, 0] * scale_x + center[0] - scale[0] * 0.5
+ target_coords[:, 1] = coords[:, 1] * scale_y + center[1] - scale[1] * 0.5
+
+ return target_coords
+
+
+def get_affine_transform(center,
+ scale,
+ rot,
+ output_size,
+ shift=(0., 0.),
+ inv=False):
+ """Get the affine transform matrix, given the center/scale/rot/output_size.
+
+ Args:
+ center (np.ndarray[2, ]): Center of the bounding box (x, y).
+ scale (np.ndarray[2, ]): Scale of the bounding box
+ wrt [width, height].
+ rot (float): Rotation angle (degree).
+ output_size (np.ndarray[2, ] | list(2,)): Size of the
+ destination heatmaps.
+ shift (0-100%): Shift translation ratio wrt the width/height.
+ Default (0., 0.).
+ inv (bool): Option to inverse the affine transform direction.
+ (inv=False: src->dst or inv=True: dst->src)
+
+ Returns:
+ np.ndarray: The transform matrix.
+ """
+ assert len(center) == 2
+ assert len(scale) == 2
+ assert len(output_size) == 2
+ assert len(shift) == 2
+
+ # pixel_std is 200.
+ scale_tmp = scale * 200.0
+
+ shift = np.array(shift)
+ src_w = scale_tmp[0]
+ dst_w = output_size[0]
+ dst_h = output_size[1]
+
+ rot_rad = np.pi * rot / 180
+ src_dir = rotate_point([0., src_w * -0.5], rot_rad)
+ dst_dir = np.array([0., dst_w * -0.5])
+
+ src = np.zeros((3, 2), dtype=np.float32)
+ src[0, :] = center + scale_tmp * shift
+ src[1, :] = center + src_dir + scale_tmp * shift
+ src[2, :] = _get_3rd_point(src[0, :], src[1, :])
+
+ dst = np.zeros((3, 2), dtype=np.float32)
+ dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
+ dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
+ dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
+
+ if inv:
+ trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
+ else:
+ trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
+
+ return trans
+
+
+def affine_transform(pt, trans_mat):
+ """Apply an affine transformation to the points.
+
+ Args:
+ pt (np.ndarray): a 2 dimensional point to be transformed
+ trans_mat (np.ndarray): 2x3 matrix of an affine transform
+
+ Returns:
+ np.ndarray: Transformed points.
+ """
+ assert len(pt) == 2
+ new_pt = np.array(trans_mat) @ np.array([pt[0], pt[1], 1.])
+
+ return new_pt
+
+
+def _get_3rd_point(a, b):
+ """To calculate the affine matrix, three pairs of points are required. This
+ function is used to get the 3rd point, given 2D points a & b.
+
+ The 3rd point is defined by rotating vector `a - b` by 90 degrees
+ anticlockwise, using b as the rotation center.
+
+ Args:
+ a (np.ndarray): point(x,y)
+ b (np.ndarray): point(x,y)
+
+ Returns:
+ np.ndarray: The 3rd point.
+ """
+ assert len(a) == 2
+ assert len(b) == 2
+ direction = a - b
+ third_pt = b + np.array([-direction[1], direction[0]], dtype=np.float32)
+
+ return third_pt
+
+
+def rotate_point(pt, angle_rad):
+ """Rotate a point by an angle.
+
+ Args:
+ pt (list[float]): 2 dimensional point to be rotated
+ angle_rad (float): rotation angle by radian
+
+ Returns:
+ list[float]: Rotated point.
+ """
+ assert len(pt) == 2
+ sn, cs = np.sin(angle_rad), np.cos(angle_rad)
+ new_x = pt[0] * cs - pt[1] * sn
+ new_y = pt[0] * sn + pt[1] * cs
+ rotated_pt = [new_x, new_y]
+
+ return rotated_pt
+
+
+def get_warp_matrix(theta, size_input, size_dst, size_target):
+ """Calculate the transformation matrix under the constraint of unbiased.
+ Paper ref: Huang et al. The Devil is in the Details: Delving into Unbiased
+ Data Processing for Human Pose Estimation (CVPR 2020).
+
+ Args:
+ theta (float): Rotation angle in degrees.
+ size_input (np.ndarray): Size of input image [w, h].
+ size_dst (np.ndarray): Size of output image [w, h].
+ size_target (np.ndarray): Size of ROI in input plane [w, h].
+
+ Returns:
+ np.ndarray: A matrix for transformation.
+ """
+ theta = np.deg2rad(theta)
+ matrix = np.zeros((2, 3), dtype=np.float32)
+ scale_x = size_dst[0] / size_target[0]
+ scale_y = size_dst[1] / size_target[1]
+ matrix[0, 0] = math.cos(theta) * scale_x
+ matrix[0, 1] = -math.sin(theta) * scale_x
+ matrix[0, 2] = scale_x * (-0.5 * size_input[0] * math.cos(theta) +
+ 0.5 * size_input[1] * math.sin(theta) +
+ 0.5 * size_target[0])
+ matrix[1, 0] = math.sin(theta) * scale_y
+ matrix[1, 1] = math.cos(theta) * scale_y
+ matrix[1, 2] = scale_y * (-0.5 * size_input[0] * math.sin(theta) -
+ 0.5 * size_input[1] * math.cos(theta) +
+ 0.5 * size_target[1])
+ return matrix
+
+
+def warp_affine_joints(joints, mat):
+ """Apply affine transformation defined by the transform matrix on the
+ joints.
+
+ Args:
+ joints (np.ndarray[..., 2]): Origin coordinate of joints.
+ mat (np.ndarray[3, 2]): The affine matrix.
+
+ Returns:
+ np.ndarray[..., 2]: Result coordinate of joints.
+ """
+ joints = np.array(joints)
+ shape = joints.shape
+ joints = joints.reshape(-1, 2)
+ return np.dot(
+ np.concatenate((joints, joints[:, 0:1] * 0 + 1), axis=1),
+ mat.T).reshape(shape)
+
+
+def affine_transform_torch(pts, t):
+ npts = pts.shape[0]
+ pts_homo = torch.cat([pts, torch.ones(npts, 1, device=pts.device)], dim=1)
+ out = torch.mm(t, torch.t(pts_homo))
+ return torch.t(out[:2, :])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/smoother.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/smoother.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b57768c03b48ff84877acbceb6e27b82832c04d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/smoother.py
@@ -0,0 +1,227 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import warnings
+from typing import Dict, Union
+
+import numpy as np
+from mmcv import Config, is_seq_of
+
+from mmpose.core.post_processing.temporal_filters import build_filter
+
+
+class Smoother():
+ """Smoother to apply temporal smoothing on pose estimation results with a
+ filter.
+
+ Note:
+ T: The temporal length of the pose sequence
+ K: The keypoint number of each target
+ C: The keypoint coordinate dimension
+
+ Args:
+ filter_cfg (dict | str): The filter config. See example config files in
+ `configs/_base_/filters/` for details. Alternatively a config file
+ path can be accepted and the config will be loaded.
+ keypoint_dim (int): The keypoint coordinate dimension, which is
+ also indicated as C. Default: 2
+ keypoint_key (str): The dict key of the keypoints in the pose results.
+ Default: 'keypoints'
+ Example:
+ >>> import numpy as np
+ >>> # Build dummy pose result
+ >>> results = []
+ >>> for t in range(10):
+ >>> results_t = []
+ >>> for track_id in range(2):
+ >>> result = {
+ >>> 'track_id': track_id,
+ >>> 'keypoints': np.random.rand(17, 3)
+ >>> }
+ >>> results_t.append(result)
+ >>> results.append(results_t)
+ >>> # Example 1: Smooth multi-frame pose results offline.
+ >>> filter_cfg = dict(type='GaussianFilter', window_size=3)
+ >>> smoother = Smoother(filter_cfg, keypoint_dim=2)
+ >>> smoothed_results = smoother.smooth(results)
+ >>> # Example 2: Smooth pose results online frame-by-frame
+ >>> filter_cfg = dict(type='GaussianFilter', window_size=3)
+ >>> smoother = Smoother(filter_cfg, keypoint_dim=2)
+ >>> for result_t in results:
+ >>> smoothed_result_t = smoother.smooth(result_t)
+ """
+
+ def __init__(self,
+ filter_cfg: Union[Dict, str],
+ keypoint_dim: int = 2,
+ keypoint_key: str = 'keypoints'):
+ if isinstance(filter_cfg, str):
+ filter_cfg = Config.fromfile(filter_cfg).filter_cfg
+ self.filter_cfg = filter_cfg
+ self._filter = build_filter(filter_cfg)
+ self.keypoint_dim = keypoint_dim
+ self.key = keypoint_key
+ self.padding_size = self._filter.window_size - 1
+ self.history = {}
+
+ def _get_filter(self):
+ fltr = self._filter
+ if not fltr.shareable:
+ # If the filter is not shareable, build a new filter for the next
+ # requires
+ self._filter = build_filter(self.filter_cfg)
+ return fltr
+
+ def _collate_pose(self, results):
+ """Collate the pose results to pose sequences.
+
+ Args:
+ results (list[list[dict]]): The pose results of multiple frames.
+
+ Returns:
+ dict[str, np.ndarray]: A dict of collated pose sequences, where
+ the key is the track_id (in untracked scenario, the target index
+ will be used as the track_id), and the value is the pose sequence
+ in an array of shape [T, K, C]
+ """
+
+ if self._has_track_id(results):
+ # If the results have track_id, use it as the target indicator
+ results = [{res['track_id']: res
+ for res in results_t} for results_t in results]
+ track_ids = results[0].keys()
+
+ for t, results_t in enumerate(results[1:]):
+ if results_t.keys() != track_ids:
+ raise ValueError(f'Inconsistent track ids in frame {t+1}')
+
+ collated = {
+ id: np.stack([
+ results_t[id][self.key][:, :self.keypoint_dim]
+ for results_t in results
+ ])
+ for id in track_ids
+ }
+ else:
+ # If the results don't have track_id, use the target index
+ # as the target indicator
+ n_target = len(results[0])
+ for t, results_t in enumerate(results[1:]):
+ if len(results_t) != n_target:
+ raise ValueError(
+ f'Inconsistent target number in frame {t+1}: '
+ f'{len(results_t)} vs {n_target}')
+
+ collated = {
+ id: np.stack([
+ results_t[id][self.key][:, :self.keypoint_dim]
+ for results_t in results
+ ])
+ for id in range(n_target)
+ }
+
+ return collated
+
+ def _scatter_pose(self, results, poses):
+ """Scatter the smoothed pose sequences and use them to update the pose
+ results.
+
+ Args:
+ results (list[list[dict]]): The original pose results
+ poses (dict[str, np.ndarray]): The smoothed pose sequences
+
+ Returns:
+ list[list[dict]]: The updated pose results
+ """
+ updated_results = []
+ for t, results_t in enumerate(results):
+ updated_results_t = []
+ if self._has_track_id(results):
+ id2result = ((result['track_id'], result)
+ for result in results_t)
+ else:
+ id2result = enumerate(results_t)
+
+ for track_id, result in id2result:
+ result = copy.deepcopy(result)
+ result[self.key][:, :self.keypoint_dim] = poses[track_id][t]
+ updated_results_t.append(result)
+
+ updated_results.append(updated_results_t)
+ return updated_results
+
+ @staticmethod
+ def _has_track_id(results):
+ """Check if the pose results contain track_id."""
+ return 'track_id' in results[0][0]
+
+ def smooth(self, results):
+ """Apply temporal smoothing on pose estimation sequences.
+
+ Args:
+ results (list[dict] | list[list[dict]]): The pose results of a
+ single frame (non-nested list) or multiple frames (nested
+ list). The result of each target is a dict, which should
+ contains:
+
+ - track_id (optional, Any): The track ID of the target
+ - keypoints (np.ndarray): The keypoint coordinates in [K, C]
+
+ Returns:
+ (list[dict] | list[list[dict]]): Temporal smoothed pose results,
+ which has the same data structure as the input's.
+ """
+
+ # Check if input is empty
+ if not (results) or not (results[0]):
+ warnings.warn('Smoother received empty result.')
+ return results
+
+ # Check input is single frame or sequence
+ if is_seq_of(results, dict):
+ single_frame = True
+ results = [results]
+ else:
+ assert is_seq_of(results, list)
+ single_frame = False
+
+ # Get temporal length of input
+ T = len(results)
+
+ # Collate the input results to pose sequences
+ poses = self._collate_pose(results)
+
+ # Smooth the pose sequence of each target
+ smoothed_poses = {}
+ update_history = {}
+ for track_id, pose in poses.items():
+ if track_id in self.history:
+ # For tracked target, get its filter and pose history
+ pose_history, pose_filter = self.history[track_id]
+ if self.padding_size > 0:
+ # Pad the pose sequence with pose history
+ pose = np.concatenate((pose_history, pose), axis=0)
+ else:
+ # For new target, build a new filter
+ pose_filter = self._get_filter()
+
+ # Update the history information
+ if self.padding_size > 0:
+ pose_history = pose[-self.padding_size:].copy()
+ else:
+ pose_history = None
+ update_history[track_id] = (pose_history, pose_filter)
+
+ # Smooth the pose sequence with the filter
+ smoothed_pose = pose_filter(pose)
+ smoothed_poses[track_id] = smoothed_pose[-T:]
+
+ self.history = update_history
+
+ # Scatter the pose sequences back to the format of results
+ smoothed_results = self._scatter_pose(results, smoothed_poses)
+
+ # If the input is single frame, remove the nested list to keep the
+ # output structure consistent with the input's
+ if single_frame:
+ smoothed_results = smoothed_results[0]
+ return smoothed_results
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8aea62513b14fdb6ac740c06e82683a1e27363db
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .builder import build_filter
+from .gaussian_filter import GaussianFilter
+from .one_euro_filter import OneEuroFilter
+from .savizky_golay_filter import SavizkyGolayFilter
+from .smoothnet_filter import SmoothNetFilter
+
+__all__ = [
+ 'build_filter', 'GaussianFilter', 'OneEuroFilter', 'SavizkyGolayFilter',
+ 'SmoothNetFilter'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/builder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..adb914c5222db967c9cdb56fa9f469ff47792f79
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/builder.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.utils import Registry
+
+FILTERS = Registry('filters')
+
+
+def build_filter(cfg):
+ """Build filters function."""
+ return FILTERS.build(cfg)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c6ce0127092235c370f8e398751884f09a18bf5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/filter.py
@@ -0,0 +1,42 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+
+
+class TemporalFilter(metaclass=ABCMeta):
+ """Base class of temporal filter.
+
+ A subclass should implement the method __call__().
+
+ Parameters:
+ window_size (int): the size of the sliding window.
+ """
+
+ # If the filter can be shared by multiple humans or targets
+ _shareable: bool = True
+
+ def __init__(self, window_size=1):
+ self._window_size = window_size
+
+ @property
+ def window_size(self):
+ return self._window_size
+
+ @property
+ def shareable(self):
+ return self._shareable
+
+ @abstractmethod
+ def __call__(self, x):
+ """Apply filter to a pose sequence.
+
+ Note:
+ T: The temporal length of the pose sequence
+ K: The keypoint number of each target
+ C: The keypoint coordinate dimension
+
+ Args:
+ x (np.ndarray): input pose sequence in shape [T, K, C]
+
+ Returns:
+ np.ndarray: Smoothed pose sequence in shape [T, K, C]
+ """
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/gaussian_filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/gaussian_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..b737cdb15aeb9985c0666afeb26e919893343262
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/gaussian_filter.py
@@ -0,0 +1,44 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+from scipy.ndimage.filters import gaussian_filter1d
+from scipy.signal import medfilt
+
+from .builder import FILTERS
+from .filter import TemporalFilter
+
+
+@FILTERS.register_module(name=['GaussianFilter', 'gaussian'])
+class GaussianFilter(TemporalFilter):
+ """Apply median filter and then gaussian filter.
+
+ Adapted from:
+ https://github.com/akanazawa/human_dynamics/blob/mas
+ ter/src/util/smooth_bbox.py.
+
+ Args:
+ window_size (int): The size of the filter window (i.e., the number
+ of coefficients). window_length must be a positive odd integer.
+ Default: 11
+ sigma (float): Sigma for gaussian smoothing. Default: 4.0
+ """
+
+ def __init__(self, window_size: int = 11, sigma: float = 4.0):
+ super().__init__(window_size)
+ assert window_size % 2 == 1, (
+ 'The window size of GaussianFilter should'
+ f'be odd, but got {window_size}')
+ self.sigma = sigma
+
+ def __call__(self, x: np.ndarray):
+
+ assert x.ndim == 3, ('Input should be an array with shape [T, K, C]'
+ f', but got invalid shape {x.shape}')
+
+ T = x.shape[0]
+ if T < self.window_size:
+ pad_width = [(self.window_size - T, 0), (0, 0), (0, 0)]
+ x = np.pad(x, pad_width, mode='edge')
+ smoothed = medfilt(x, (self.window_size, 1, 1))
+
+ smoothed = gaussian_filter1d(smoothed, self.sigma, axis=0)
+ return smoothed[-T:]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/one_euro_filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/one_euro_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..b954a97fd79543f243a087510a20c4e0037b9ef5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/one_euro_filter.py
@@ -0,0 +1,113 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/HoBeom/OneEuroFilter-Numpy
+# Original licence: Copyright (c) HoBeom Jeon, under the MIT License.
+# ------------------------------------------------------------------------------
+import math
+
+import numpy as np
+
+from .builder import FILTERS
+from .filter import TemporalFilter
+
+
+def smoothing_factor(t_e, cutoff):
+ r = 2 * math.pi * cutoff * t_e
+ return r / (r + 1)
+
+
+def exponential_smoothing(a, x, x_prev):
+ return a * x + (1 - a) * x_prev
+
+
+class OneEuro:
+
+ def __init__(self, t0, x0, dx0, min_cutoff, beta, d_cutoff=1.0):
+ super(OneEuro, self).__init__()
+ """Initialize the one euro filter."""
+ # The parameters.
+ self.min_cutoff = float(min_cutoff)
+ self.beta = float(beta)
+ self.d_cutoff = float(d_cutoff)
+ # Previous values.
+ self.x_prev = x0
+ self.dx_prev = dx0
+ self.t_prev = t0
+
+ def __call__(self, x, t=None):
+ """Compute the filtered signal."""
+
+ if t is None:
+ # Assume input is feed frame by frame if not specified
+ t = self.t_prev + 1
+
+ t_e = t - self.t_prev
+
+ # The filtered derivative of the signal.
+ a_d = smoothing_factor(t_e, self.d_cutoff) # [k, c]
+ dx = (x - self.x_prev) / t_e
+ dx_hat = exponential_smoothing(a_d, dx, self.dx_prev)
+
+ # The filtered signal.
+ cutoff = self.min_cutoff + self.beta * np.abs(dx_hat)
+ a = smoothing_factor(t_e, cutoff)
+ x_hat = exponential_smoothing(a, x, self.x_prev)
+ # Memorize the previous values.
+ self.x_prev = x_hat
+ self.dx_prev = dx_hat
+ self.t_prev = t
+ return x_hat
+
+
+@FILTERS.register_module(name=['OneEuroFilter', 'oneeuro'])
+class OneEuroFilter(TemporalFilter):
+ """Oneeuro filter, source code: https://github.com/mkocabas/VIBE/blob/c0
+ c3f77d587351c806e901221a9dc05d1ffade4b/lib/utils/smooth_pose.py.
+
+ Args:
+ min_cutoff (float, optional): Decreasing the minimum cutoff frequency
+ decreases slow speed jitter
+ beta (float, optional): Increasing the speed coefficient(beta)
+ decreases speed lag.
+ """
+
+ # Not shareable because the filter holds status of a specific target
+ _shareable: bool = False
+
+ def __init__(self, min_cutoff=0.004, beta=0.7):
+ # OneEuroFilter has Markov Property and maintains status variables
+ # within the class, thus has a windows_size of 1
+ super().__init__(window_size=1)
+ self.min_cutoff = min_cutoff
+ self.beta = beta
+ self._one_euro = None
+
+ def __call__(self, x: np.ndarray):
+ assert x.ndim == 3, ('Input should be an array with shape [T, K, C]'
+ f', but got invalid shape {x.shape}')
+
+ pred_pose_hat = x.copy()
+
+ if self._one_euro is None:
+ # The filter is invoked for the first time
+ # Initialize the filter
+ self._one_euro = OneEuro(
+ np.zeros_like(x[0]),
+ x[0],
+ dx0=0.0,
+ min_cutoff=self.min_cutoff,
+ beta=self.beta,
+ )
+ t0 = 1
+ else:
+ # The filter has been invoked
+ t0 = 0
+
+ for t, pose in enumerate(x):
+ if t < t0:
+ # If the filter is invoked for the first time
+ # set pred_pose_hat[0] = x[0]
+ continue
+ pose = self._one_euro(pose)
+ pred_pose_hat[t] = pose
+
+ return pred_pose_hat
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/savizky_golay_filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/savizky_golay_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..18e0528f6cec71f19fe1c4a1f26560c1438bd1ce
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/savizky_golay_filter.py
@@ -0,0 +1,50 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+from scipy.signal import savgol_filter
+
+from .builder import FILTERS
+from .filter import TemporalFilter
+
+
+@FILTERS.register_module(name=['SavizkyGolayFilter', 'savgol'])
+class SavizkyGolayFilter(TemporalFilter):
+ """Savizky-Golay filter.
+
+ Adapted from:
+ https://docs.scipy.org/doc/scipy/reference/generated/
+ scipy.signal.savgol_filter.html.
+
+ Args:
+ window_size (int): The size of the filter window (i.e., the number
+ of coefficients). window_length must be a positive odd integer.
+ Default: 11
+ polyorder (int): The order of the polynomial used to fit the samples.
+ polyorder must be less than window_size.
+ """
+
+ def __init__(self, window_size: int = 11, polyorder: int = 2):
+ super().__init__(window_size)
+
+ # 1-D Savitzky-Golay filter
+ assert polyorder > 0, (
+ f'Got invalid parameter polyorder={polyorder}. Polyorder '
+ 'should be positive.')
+ assert polyorder < window_size, (
+ f'Got invalid parameters polyorder={polyorder} and '
+ f'window_size={window_size}. Polyorder should be less than '
+ 'window_size.')
+ self.polyorder = polyorder
+
+ def __call__(self, x: np.ndarray):
+
+ assert x.ndim == 3, ('Input should be an array with shape [T, K, C]'
+ f', but got invalid shape {x.shape}')
+
+ T = x.shape[0]
+ if T < self.window_size:
+ pad_width = [(self.window_size - T, 0), (0, 0), (0, 0)]
+ x = np.pad(x, pad_width, mode='edge')
+
+ smoothed = savgol_filter(x, self.window_size, self.polyorder, axis=0)
+
+ return smoothed[-T:]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/smoothnet_filter.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/smoothnet_filter.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7f8df520ad9457722f738c33b79d69d3a99fb9e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/post_processing/temporal_filters/smoothnet_filter.py
@@ -0,0 +1,226 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from typing import Optional
+
+import numpy as np
+import torch
+from mmcv.runner import load_checkpoint
+from torch import Tensor, nn
+
+from .builder import FILTERS
+from .filter import TemporalFilter
+
+
+class SmoothNetResBlock(nn.Module):
+ """Residual block module used in SmoothNet.
+
+ Args:
+ in_channels (int): Input channel number.
+ hidden_channels (int): The hidden feature channel number.
+ dropout (float): Dropout probability. Default: 0.5
+
+ Shape:
+ Input: (*, in_channels)
+ Output: (*, in_channels)
+ """
+
+ def __init__(self, in_channels, hidden_channels, dropout=0.5):
+ super().__init__()
+ self.linear1 = nn.Linear(in_channels, hidden_channels)
+ self.linear2 = nn.Linear(hidden_channels, in_channels)
+ self.lrelu = nn.LeakyReLU(0.2, inplace=True)
+ self.dropout = nn.Dropout(p=dropout, inplace=True)
+
+ def forward(self, x):
+ identity = x
+ x = self.linear1(x)
+ x = self.dropout(x)
+ x = self.lrelu(x)
+ x = self.linear2(x)
+ x = self.dropout(x)
+ x = self.lrelu(x)
+
+ out = x + identity
+ return out
+
+
+class SmoothNet(nn.Module):
+ """SmoothNet is a plug-and-play temporal-only network to refine human
+ poses. It works for 2d/3d/6d pose smoothing.
+
+ "SmoothNet: A Plug-and-Play Network for Refining Human Poses in Videos",
+ arXiv'2021. More details can be found in the `paper
+ `__ .
+
+ Note:
+ N: The batch size
+ T: The temporal length of the pose sequence
+ C: The total pose dimension (e.g. keypoint_number * keypoint_dim)
+
+ Args:
+ window_size (int): The size of the input window.
+ output_size (int): The size of the output window.
+ hidden_size (int): The hidden feature dimension in the encoder,
+ the decoder and between residual blocks. Default: 512
+ res_hidden_size (int): The hidden feature dimension inside the
+ residual blocks. Default: 256
+ num_blocks (int): The number of residual blocks. Default: 3
+ dropout (float): Dropout probability. Default: 0.5
+
+ Shape:
+ Input: (N, C, T) the original pose sequence
+ Output: (N, C, T) the smoothed pose sequence
+ """
+
+ def __init__(self,
+ window_size: int,
+ output_size: int,
+ hidden_size: int = 512,
+ res_hidden_size: int = 256,
+ num_blocks: int = 3,
+ dropout: float = 0.5):
+ super().__init__()
+ self.window_size = window_size
+ self.output_size = output_size
+ self.hidden_size = hidden_size
+ self.res_hidden_size = res_hidden_size
+ self.num_blocks = num_blocks
+ self.dropout = dropout
+
+ assert output_size <= window_size, (
+ 'The output size should be less than or equal to the window size.',
+ f' Got output_size=={output_size} and window_size=={window_size}')
+
+ # Build encoder layers
+ self.encoder = nn.Sequential(
+ nn.Linear(window_size, hidden_size),
+ nn.LeakyReLU(0.1, inplace=True))
+
+ # Build residual blocks
+ res_blocks = []
+ for _ in range(num_blocks):
+ res_blocks.append(
+ SmoothNetResBlock(
+ in_channels=hidden_size,
+ hidden_channels=res_hidden_size,
+ dropout=dropout))
+ self.res_blocks = nn.Sequential(*res_blocks)
+
+ # Build decoder layers
+ self.decoder = nn.Linear(hidden_size, output_size)
+
+ def forward(self, x: Tensor) -> Tensor:
+ """Forward function."""
+ N, C, T = x.shape
+ num_windows = T - self.window_size + 1
+
+ assert T >= self.window_size, (
+ 'Input sequence length must be no less than the window size. ',
+ f'Got x.shape[2]=={T} and window_size=={self.window_size}')
+
+ # Unfold x to obtain input sliding windows
+ # [N, C, num_windows, window_size]
+ x = x.unfold(2, self.window_size, 1)
+
+ # Forward layers
+ x = self.encoder(x)
+ x = self.res_blocks(x)
+ x = self.decoder(x) # [N, C, num_windows, output_size]
+
+ # Accumulate output ensembles
+ out = x.new_zeros(N, C, T)
+ count = x.new_zeros(T)
+
+ for t in range(num_windows):
+ out[..., t:t + self.output_size] += x[:, :, t]
+ count[t:t + self.output_size] += 1.0
+
+ return out.div(count)
+
+
+@FILTERS.register_module(name=['SmoothNetFilter', 'SmoothNet', 'smoothnet'])
+class SmoothNetFilter(TemporalFilter):
+ """Apply SmoothNet filter.
+
+ "SmoothNet: A Plug-and-Play Network for Refining Human Poses in Videos",
+ arXiv'2021. More details can be found in the `paper
+ `__ .
+
+ Args:
+ window_size (int): The size of the filter window. It's also the
+ window_size of SmoothNet model.
+ output_size (int): The output window size of SmoothNet model.
+ checkpoint (str): The checkpoint file of the pretrained SmoothNet
+ model. Please note that `checkpoint` should be matched with
+ `window_size` and `output_size`.
+ hidden_size (int): SmoothNet argument. See :class:`SmoothNet` for
+ details. Default: 512
+ hidden_res_size (int): SmoothNet argument. See :class:`SmoothNet`
+ for details. Default: 256
+ num_blocks (int): SmoothNet argument. See :class:`SmoothNet` for
+ details. Default: 3
+ device (str): Device for model inference. Default: 'cpu'
+ root_index (int, optional): If not None, relative keypoint coordinates
+ will be calculated as the SmoothNet input, by centering the
+ keypoints around the root point. The model output will be
+ converted back to absolute coordinates. Default: None
+ """
+
+ def __init__(
+ self,
+ window_size: int,
+ output_size: int,
+ checkpoint: Optional[str] = None,
+ hidden_size: int = 512,
+ res_hidden_size: int = 256,
+ num_blocks: int = 3,
+ device: str = 'cpu',
+ root_index: Optional[int] = None,
+ ):
+ super().__init__(window_size)
+ self.device = device
+ self.root_index = root_index
+ self.smoothnet = SmoothNet(window_size, output_size, hidden_size,
+ res_hidden_size, num_blocks)
+ if checkpoint:
+ load_checkpoint(self.smoothnet, checkpoint)
+ self.smoothnet.to(device)
+ self.smoothnet.eval()
+
+ for p in self.smoothnet.parameters():
+ p.requires_grad_(False)
+
+ def __call__(self, x: np.ndarray):
+ assert x.ndim == 3, ('Input should be an array with shape [T, K, C]'
+ f', but got invalid shape {x.shape}')
+
+ root_index = self.root_index
+ if root_index is not None:
+ x_root = x[:, root_index:root_index + 1]
+ x = np.delete(x, root_index, axis=1)
+ x = x - x_root
+
+ T, K, C = x.shape
+
+ if T < self.window_size:
+ # Skip smoothing if the input length is less than the window size
+ smoothed = x
+ else:
+ dtype = x.dtype
+
+ # Convert to tensor and forward the model
+ with torch.no_grad():
+ x = torch.tensor(x, dtype=torch.float32, device=self.device)
+ x = x.view(1, T, K * C).permute(0, 2, 1) # to [1, KC, T]
+ smoothed = self.smoothnet(x) # in shape [1, KC, T]
+
+ # Convert model output back to input shape and format
+ smoothed = smoothed.permute(0, 2, 1).view(T, K, C) # to [T, K, C]
+ smoothed = smoothed.cpu().numpy().astype(dtype) # to numpy.ndarray
+
+ if root_index is not None:
+ smoothed += x_root
+ smoothed = np.concatenate(
+ (smoothed[:, :root_index], x_root, smoothed[:, root_index:]),
+ axis=1)
+
+ return smoothed
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..512e7680bcce478ca00f79e536ee54cd02de93df
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .dist_utils import allreduce_grads, sync_random_seed
+from .model_util_hooks import ModelSetEpochHook
+from .regularizations import WeightNormClipHook
+
+__all__ = [
+ 'allreduce_grads', 'WeightNormClipHook', 'sync_random_seed',
+ 'ModelSetEpochHook'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/dist_utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/dist_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..b81f925ad7aa51ce800e27bead8eb8ba021c2592
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/dist_utils.py
@@ -0,0 +1,90 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import OrderedDict
+
+import numpy as np
+import torch
+import torch.distributed as dist
+from mmcv.runner import get_dist_info
+from torch._utils import (_flatten_dense_tensors, _take_tensors,
+ _unflatten_dense_tensors)
+
+
+def _allreduce_coalesced(tensors, world_size, bucket_size_mb=-1):
+ """Allreduce parameters as a whole."""
+ if bucket_size_mb > 0:
+ bucket_size_bytes = bucket_size_mb * 1024 * 1024
+ buckets = _take_tensors(tensors, bucket_size_bytes)
+ else:
+ buckets = OrderedDict()
+ for tensor in tensors:
+ tp = tensor.type()
+ if tp not in buckets:
+ buckets[tp] = []
+ buckets[tp].append(tensor)
+ buckets = buckets.values()
+
+ for bucket in buckets:
+ flat_tensors = _flatten_dense_tensors(bucket)
+ dist.all_reduce(flat_tensors)
+ flat_tensors.div_(world_size)
+ for tensor, synced in zip(
+ bucket, _unflatten_dense_tensors(flat_tensors, bucket)):
+ tensor.copy_(synced)
+
+
+def allreduce_grads(params, coalesce=True, bucket_size_mb=-1):
+ """Allreduce gradients.
+
+ Args:
+ params (list[torch.Parameters]): List of parameters of a model
+ coalesce (bool, optional): Whether allreduce parameters as a whole.
+ Default: True.
+ bucket_size_mb (int, optional): Size of bucket, the unit is MB.
+ Default: -1.
+ """
+ grads = [
+ param.grad.data for param in params
+ if param.requires_grad and param.grad is not None
+ ]
+ world_size = dist.get_world_size()
+ if coalesce:
+ _allreduce_coalesced(grads, world_size, bucket_size_mb)
+ else:
+ for tensor in grads:
+ dist.all_reduce(tensor.div_(world_size))
+
+
+def sync_random_seed(seed=None, device='cuda'):
+ """Make sure different ranks share the same seed.
+
+ All workers must call
+ this function, otherwise it will deadlock. This method is generally used in
+ `DistributedSampler`, because the seed should be identical across all
+ processes in the distributed group.
+ In distributed sampling, different ranks should sample non-overlapped
+ data in the dataset. Therefore, this function is used to make sure that
+ each rank shuffles the data indices in the same order based
+ on the same seed. Then different ranks could use different indices
+ to select non-overlapped data from the same data list.
+ Args:
+ seed (int, Optional): The seed. Default to None.
+ device (str): The device where the seed will be put on.
+ Default to 'cuda'.
+ Returns:
+ int: Seed to be used.
+ """
+ if seed is None:
+ seed = np.random.randint(2**31)
+ assert isinstance(seed, int)
+
+ rank, world_size = get_dist_info()
+
+ if world_size == 1:
+ return seed
+
+ if rank == 0:
+ random_num = torch.tensor(seed, dtype=torch.int32, device=device)
+ else:
+ random_num = torch.tensor(0, dtype=torch.int32, device=device)
+ dist.broadcast(random_num, src=0)
+ return random_num.item()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/model_util_hooks.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/model_util_hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..d308a8a57a04f1a2acaa841ac2e8ad42439bb633
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/model_util_hooks.py
@@ -0,0 +1,13 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.runner import HOOKS, Hook
+
+
+@HOOKS.register_module()
+class ModelSetEpochHook(Hook):
+ """The hook that tells model the current epoch in training."""
+
+ def __init__(self):
+ pass
+
+ def before_epoch(self, runner):
+ runner.model.module.set_train_epoch(runner.epoch + 1)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/regularizations.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/regularizations.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c7449038066016f6efb60e126111ace962fe98
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/utils/regularizations.py
@@ -0,0 +1,86 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod, abstractproperty
+
+import torch
+
+
+class PytorchModuleHook(metaclass=ABCMeta):
+ """Base class for PyTorch module hook registers.
+
+ An instance of a subclass of PytorchModuleHook can be used to
+ register hook to a pytorch module using the `register` method like:
+ hook_register.register(module)
+
+ Subclasses should add/overwrite the following methods:
+ - __init__
+ - hook
+ - hook_type
+ """
+
+ @abstractmethod
+ def hook(self, *args, **kwargs):
+ """Hook function."""
+
+ @abstractproperty
+ def hook_type(self) -> str:
+ """Hook type Subclasses should overwrite this function to return a
+ string value in.
+
+ {`forward`, `forward_pre`, `backward`}
+ """
+
+ def register(self, module):
+ """Register the hook function to the module.
+
+ Args:
+ module (pytorch module): the module to register the hook.
+
+ Returns:
+ handle (torch.utils.hooks.RemovableHandle): a handle to remove
+ the hook by calling handle.remove()
+ """
+ assert isinstance(module, torch.nn.Module)
+
+ if self.hook_type == 'forward':
+ h = module.register_forward_hook(self.hook)
+ elif self.hook_type == 'forward_pre':
+ h = module.register_forward_pre_hook(self.hook)
+ elif self.hook_type == 'backward':
+ h = module.register_backward_hook(self.hook)
+ else:
+ raise ValueError(f'Invalid hook type {self.hook}')
+
+ return h
+
+
+class WeightNormClipHook(PytorchModuleHook):
+ """Apply weight norm clip regularization.
+
+ The module's parameter will be clip to a given maximum norm before each
+ forward pass.
+
+ Args:
+ max_norm (float): The maximum norm of the parameter.
+ module_param_names (str|list): The parameter name (or name list) to
+ apply weight norm clip.
+ """
+
+ def __init__(self, max_norm=1.0, module_param_names='weight'):
+ self.module_param_names = module_param_names if isinstance(
+ module_param_names, list) else [module_param_names]
+ self.max_norm = max_norm
+
+ @property
+ def hook_type(self):
+ return 'forward_pre'
+
+ def hook(self, module, _input):
+ for name in self.module_param_names:
+ assert name in module._parameters, f'{name} is not a parameter' \
+ f' of the module {type(module)}'
+ param = module._parameters[name]
+
+ with torch.no_grad():
+ m = param.norm().item()
+ if m > self.max_norm:
+ param.mul_(self.max_norm / (m + 1e-6))
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c87fc29145b1eff15713ca79bc36708a4836ecf8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .image import (imshow_bboxes, imshow_keypoints, imshow_keypoints_3d,
+ imshow_mesh_3d, imshow_multiview_keypoints_3d)
+
+__all__ = [
+ 'imshow_keypoints', 'imshow_keypoints_3d', 'imshow_bboxes',
+ 'imshow_mesh_3d', 'imshow_multiview_keypoints_3d'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/image.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/image.py
new file mode 100644
index 0000000000000000000000000000000000000000..0d40cb60115822a5564e165e4eef08609adbcfd8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/core/visualization/image.py
@@ -0,0 +1,522 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+import os
+import warnings
+
+import cv2
+import mmcv
+import numpy as np
+from matplotlib import pyplot as plt
+from mmcv.utils.misc import deprecated_api_warning
+from mmcv.visualization.color import color_val
+
+try:
+ import trimesh
+ has_trimesh = True
+except (ImportError, ModuleNotFoundError):
+ has_trimesh = False
+
+try:
+ os.environ['PYOPENGL_PLATFORM'] = 'egl'
+ import pyrender
+ has_pyrender = True
+except (ImportError, ModuleNotFoundError):
+ has_pyrender = False
+
+
+def imshow_bboxes(img,
+ bboxes,
+ labels=None,
+ colors='green',
+ text_color='white',
+ thickness=1,
+ font_scale=0.5,
+ show=True,
+ win_name='',
+ wait_time=0,
+ out_file=None):
+ """Draw bboxes with labels (optional) on an image. This is a wrapper of
+ mmcv.imshow_bboxes.
+
+ Args:
+ img (str or ndarray): The image to be displayed.
+ bboxes (ndarray): ndarray of shape (k, 4), each row is a bbox in
+ format [x1, y1, x2, y2].
+ labels (str or list[str], optional): labels of each bbox.
+ colors (list[str or tuple or :obj:`Color`]): A list of colors.
+ text_color (str or tuple or :obj:`Color`): Color of texts.
+ thickness (int): Thickness of lines.
+ font_scale (float): Font scales of texts.
+ show (bool): Whether to show the image.
+ win_name (str): The window name.
+ wait_time (int): Value of waitKey param.
+ out_file (str, optional): The filename to write the image.
+
+ Returns:
+ ndarray: The image with bboxes drawn on it.
+ """
+
+ # adapt to mmcv.imshow_bboxes input format
+ bboxes = np.split(
+ bboxes, bboxes.shape[0], axis=0) if bboxes.shape[0] > 0 else []
+ if not isinstance(colors, list):
+ colors = [colors for _ in range(len(bboxes))]
+ colors = [mmcv.color_val(c) for c in colors]
+ assert len(bboxes) == len(colors)
+
+ img = mmcv.imshow_bboxes(
+ img,
+ bboxes,
+ colors,
+ top_k=-1,
+ thickness=thickness,
+ show=False,
+ out_file=None)
+
+ if labels is not None:
+ if not isinstance(labels, list):
+ labels = [labels for _ in range(len(bboxes))]
+ assert len(labels) == len(bboxes)
+
+ for bbox, label, color in zip(bboxes, labels, colors):
+ if label is None:
+ continue
+ bbox_int = bbox[0, :4].astype(np.int32)
+ # roughly estimate the proper font size
+ text_size, text_baseline = cv2.getTextSize(label,
+ cv2.FONT_HERSHEY_DUPLEX,
+ font_scale, thickness)
+ text_x1 = bbox_int[0]
+ text_y1 = max(0, bbox_int[1] - text_size[1] - text_baseline)
+ text_x2 = bbox_int[0] + text_size[0]
+ text_y2 = text_y1 + text_size[1] + text_baseline
+ cv2.rectangle(img, (text_x1, text_y1), (text_x2, text_y2), color,
+ cv2.FILLED)
+ cv2.putText(img, label, (text_x1, text_y2 - text_baseline),
+ cv2.FONT_HERSHEY_DUPLEX, font_scale,
+ mmcv.color_val(text_color), thickness)
+
+ if show:
+ mmcv.imshow(img, win_name, wait_time)
+ if out_file is not None:
+ mmcv.imwrite(img, out_file)
+ return img
+
+
+@deprecated_api_warning({'pose_limb_color': 'pose_link_color'})
+def imshow_keypoints(img,
+ pose_result,
+ skeleton=None,
+ kpt_score_thr=0.3,
+ pose_kpt_color=None,
+ pose_link_color=None,
+ radius=4,
+ thickness=1,
+ show_keypoint_weight=False):
+ """Draw keypoints and links on an image.
+
+ Args:
+ img (str or Tensor): The image to draw poses on. If an image array
+ is given, id will be modified in-place.
+ pose_result (list[kpts]): The poses to draw. Each element kpts is
+ a set of K keypoints as an Kx3 numpy.ndarray, where each
+ keypoint is represented as x, y, score.
+ kpt_score_thr (float, optional): Minimum score of keypoints
+ to be shown. Default: 0.3.
+ pose_kpt_color (np.array[Nx3]`): Color of N keypoints. If None,
+ the keypoint will not be drawn.
+ pose_link_color (np.array[Mx3]): Color of M links. If None, the
+ links will not be drawn.
+ thickness (int): Thickness of lines.
+ """
+
+ img = mmcv.imread(img)
+ img_h, img_w, _ = img.shape
+
+ for kpts in pose_result:
+
+ kpts = np.array(kpts, copy=False)
+
+ # draw each point on image
+ if pose_kpt_color is not None:
+ assert len(pose_kpt_color) == len(kpts)
+
+ for kid, kpt in enumerate(kpts):
+ x_coord, y_coord, kpt_score = int(kpt[0]), int(kpt[1]), kpt[2]
+
+ if kpt_score < kpt_score_thr or pose_kpt_color[kid] is None:
+ # skip the point that should not be drawn
+ continue
+
+ color = tuple(int(c) for c in pose_kpt_color[kid])
+ if show_keypoint_weight:
+ img_copy = img.copy()
+ cv2.circle(img_copy, (int(x_coord), int(y_coord)), radius,
+ color, -1)
+ transparency = max(0, min(1, kpt_score))
+ cv2.addWeighted(
+ img_copy,
+ transparency,
+ img,
+ 1 - transparency,
+ 0,
+ dst=img)
+ else:
+ cv2.circle(img, (int(x_coord), int(y_coord)), radius,
+ color, -1)
+
+ # draw links
+ if skeleton is not None and pose_link_color is not None:
+ assert len(pose_link_color) == len(skeleton)
+
+ for sk_id, sk in enumerate(skeleton):
+ pos1 = (int(kpts[sk[0], 0]), int(kpts[sk[0], 1]))
+ pos2 = (int(kpts[sk[1], 0]), int(kpts[sk[1], 1]))
+
+ if (pos1[0] <= 0 or pos1[0] >= img_w or pos1[1] <= 0
+ or pos1[1] >= img_h or pos2[0] <= 0 or pos2[0] >= img_w
+ or pos2[1] <= 0 or pos2[1] >= img_h
+ or kpts[sk[0], 2] < kpt_score_thr
+ or kpts[sk[1], 2] < kpt_score_thr
+ or pose_link_color[sk_id] is None):
+ # skip the link that should not be drawn
+ continue
+ color = tuple(int(c) for c in pose_link_color[sk_id])
+ if show_keypoint_weight:
+ img_copy = img.copy()
+ X = (pos1[0], pos2[0])
+ Y = (pos1[1], pos2[1])
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((Y[0] - Y[1])**2 + (X[0] - X[1])**2)**0.5
+ angle = math.degrees(math.atan2(Y[0] - Y[1], X[0] - X[1]))
+ stickwidth = 2
+ polygon = cv2.ellipse2Poly(
+ (int(mX), int(mY)), (int(length / 2), int(stickwidth)),
+ int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(img_copy, polygon, color)
+ transparency = max(
+ 0, min(1, 0.5 * (kpts[sk[0], 2] + kpts[sk[1], 2])))
+ cv2.addWeighted(
+ img_copy,
+ transparency,
+ img,
+ 1 - transparency,
+ 0,
+ dst=img)
+ else:
+ cv2.line(img, pos1, pos2, color, thickness=thickness)
+
+ return img
+
+
+def imshow_keypoints_3d(
+ pose_result,
+ img=None,
+ skeleton=None,
+ pose_kpt_color=None,
+ pose_link_color=None,
+ vis_height=400,
+ kpt_score_thr=0.3,
+ num_instances=-1,
+ *,
+ axis_azimuth=70,
+ axis_limit=1.7,
+ axis_dist=10.0,
+ axis_elev=15.0,
+):
+ """Draw 3D keypoints and links in 3D coordinates.
+
+ Args:
+ pose_result (list[dict]): 3D pose results containing:
+ - "keypoints_3d" ([K,4]): 3D keypoints
+ - "title" (str): Optional. A string to specify the title of the
+ visualization of this pose result
+ img (str|np.ndarray): Opptional. The image or image path to show input
+ image and/or 2D pose. Note that the image should be given in BGR
+ channel order.
+ skeleton (list of [idx_i,idx_j]): Skeleton described by a list of
+ links, each is a pair of joint indices.
+ pose_kpt_color (np.ndarray[Nx3]`): Color of N keypoints. If None, do
+ not nddraw keypoints.
+ pose_link_color (np.array[Mx3]): Color of M links. If None, do not
+ draw links.
+ vis_height (int): The image height of the visualization. The width
+ will be N*vis_height depending on the number of visualized
+ items.
+ kpt_score_thr (float): Minimum score of keypoints to be shown.
+ Default: 0.3.
+ num_instances (int): Number of instances to be shown in 3D. If smaller
+ than 0, all the instances in the pose_result will be shown.
+ Otherwise, pad or truncate the pose_result to a length of
+ num_instances.
+ axis_azimuth (float): axis azimuth angle for 3D visualizations.
+ axis_dist (float): axis distance for 3D visualizations.
+ axis_elev (float): axis elevation view angle for 3D visualizations.
+ axis_limit (float): The axis limit to visualize 3d pose. The xyz
+ range will be set as:
+ - x: [x_c - axis_limit/2, x_c + axis_limit/2]
+ - y: [y_c - axis_limit/2, y_c + axis_limit/2]
+ - z: [0, axis_limit]
+ Where x_c, y_c is the mean value of x and y coordinates
+ figsize: (float): figure size in inch.
+ """
+
+ show_img = img is not None
+ if num_instances < 0:
+ num_instances = len(pose_result)
+ else:
+ if len(pose_result) > num_instances:
+ pose_result = pose_result[:num_instances]
+ elif len(pose_result) < num_instances:
+ pose_result += [dict()] * (num_instances - len(pose_result))
+ num_axis = num_instances + 1 if show_img else num_instances
+
+ plt.ioff()
+ fig = plt.figure(figsize=(vis_height * num_axis * 0.01, vis_height * 0.01))
+
+ if show_img:
+ img = mmcv.imread(img, channel_order='bgr')
+ img = mmcv.bgr2rgb(img)
+ img = mmcv.imrescale(img, scale=vis_height / img.shape[0])
+
+ ax_img = fig.add_subplot(1, num_axis, 1)
+ ax_img.get_xaxis().set_visible(False)
+ ax_img.get_yaxis().set_visible(False)
+ ax_img.set_axis_off()
+ ax_img.set_title('Input')
+ ax_img.imshow(img, aspect='equal')
+
+ for idx, res in enumerate(pose_result):
+ dummy = len(res) == 0
+ kpts = np.zeros((1, 3)) if dummy else res['keypoints_3d']
+ if kpts.shape[1] == 3:
+ kpts = np.concatenate([kpts, np.ones((kpts.shape[0], 1))], axis=1)
+ valid = kpts[:, 3] >= kpt_score_thr
+
+ ax_idx = idx + 2 if show_img else idx + 1
+ ax = fig.add_subplot(1, num_axis, ax_idx, projection='3d')
+ ax.view_init(
+ elev=axis_elev,
+ azim=axis_azimuth,
+ )
+ x_c = np.mean(kpts[valid, 0]) if sum(valid) > 0 else 0
+ y_c = np.mean(kpts[valid, 1]) if sum(valid) > 0 else 0
+ ax.set_xlim3d([x_c - axis_limit / 2, x_c + axis_limit / 2])
+ ax.set_ylim3d([y_c - axis_limit / 2, y_c + axis_limit / 2])
+ ax.set_zlim3d([0, axis_limit])
+ ax.set_aspect('auto')
+ ax.set_xticks([])
+ ax.set_yticks([])
+ ax.set_zticks([])
+ ax.set_xticklabels([])
+ ax.set_yticklabels([])
+ ax.set_zticklabels([])
+ ax.dist = axis_dist
+
+ if not dummy and pose_kpt_color is not None:
+ pose_kpt_color = np.array(pose_kpt_color)
+ assert len(pose_kpt_color) == len(kpts)
+ x_3d, y_3d, z_3d = np.split(kpts[:, :3], [1, 2], axis=1)
+ # matplotlib uses RGB color in [0, 1] value range
+ _color = pose_kpt_color[..., ::-1] / 255.
+ ax.scatter(
+ x_3d[valid],
+ y_3d[valid],
+ z_3d[valid],
+ marker='o',
+ color=_color[valid],
+ )
+
+ if not dummy and skeleton is not None and pose_link_color is not None:
+ pose_link_color = np.array(pose_link_color)
+ assert len(pose_link_color) == len(skeleton)
+ for link, link_color in zip(skeleton, pose_link_color):
+ link_indices = [_i for _i in link]
+ xs_3d = kpts[link_indices, 0]
+ ys_3d = kpts[link_indices, 1]
+ zs_3d = kpts[link_indices, 2]
+ kpt_score = kpts[link_indices, 3]
+ if kpt_score.min() > kpt_score_thr:
+ # matplotlib uses RGB color in [0, 1] value range
+ _color = link_color[::-1] / 255.
+ ax.plot(xs_3d, ys_3d, zs_3d, color=_color, zdir='z')
+
+ if 'title' in res:
+ ax.set_title(res['title'])
+
+ # convert figure to numpy array
+ fig.tight_layout()
+ fig.canvas.draw()
+ img_w, img_h = fig.canvas.get_width_height()
+ img_vis = np.frombuffer(
+ fig.canvas.tostring_rgb(), dtype=np.uint8).reshape(img_h, img_w, -1)
+ img_vis = mmcv.rgb2bgr(img_vis)
+
+ plt.close(fig)
+
+ return img_vis
+
+
+def imshow_mesh_3d(img,
+ vertices,
+ faces,
+ camera_center,
+ focal_length,
+ colors=(76, 76, 204)):
+ """Render 3D meshes on background image.
+
+ Args:
+ img(np.ndarray): Background image.
+ vertices (list of np.ndarray): Vetrex coordinates in camera space.
+ faces (list of np.ndarray): Faces of meshes.
+ camera_center ([2]): Center pixel.
+ focal_length ([2]): Focal length of camera.
+ colors (list[str or tuple or Color]): A list of mesh colors.
+ """
+
+ H, W, C = img.shape
+
+ if not has_pyrender:
+ warnings.warn('pyrender package is not installed.')
+ return img
+
+ if not has_trimesh:
+ warnings.warn('trimesh package is not installed.')
+ return img
+
+ try:
+ renderer = pyrender.OffscreenRenderer(
+ viewport_width=W, viewport_height=H)
+ except (ImportError, RuntimeError):
+ warnings.warn('pyrender package is not installed correctly.')
+ return img
+
+ if not isinstance(colors, list):
+ colors = [colors for _ in range(len(vertices))]
+ colors = [color_val(c) for c in colors]
+
+ depth_map = np.ones([H, W]) * np.inf
+ output_img = img
+ for idx in range(len(vertices)):
+ color = colors[idx]
+ color = [c / 255.0 for c in color]
+ color.append(1.0)
+ vert = vertices[idx]
+ face = faces[idx]
+
+ material = pyrender.MetallicRoughnessMaterial(
+ metallicFactor=0.2, alphaMode='OPAQUE', baseColorFactor=color)
+
+ mesh = trimesh.Trimesh(vert, face)
+ rot = trimesh.transformations.rotation_matrix(
+ np.radians(180), [1, 0, 0])
+ mesh.apply_transform(rot)
+ mesh = pyrender.Mesh.from_trimesh(mesh, material=material)
+
+ scene = pyrender.Scene(ambient_light=(0.5, 0.5, 0.5))
+ scene.add(mesh, 'mesh')
+
+ camera_pose = np.eye(4)
+ camera = pyrender.IntrinsicsCamera(
+ fx=focal_length[0],
+ fy=focal_length[1],
+ cx=camera_center[0],
+ cy=camera_center[1],
+ zfar=1e5)
+ scene.add(camera, pose=camera_pose)
+
+ light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=1)
+ light_pose = np.eye(4)
+
+ light_pose[:3, 3] = np.array([0, -1, 1])
+ scene.add(light, pose=light_pose)
+
+ light_pose[:3, 3] = np.array([0, 1, 1])
+ scene.add(light, pose=light_pose)
+
+ light_pose[:3, 3] = np.array([1, 1, 2])
+ scene.add(light, pose=light_pose)
+
+ color, rend_depth = renderer.render(
+ scene, flags=pyrender.RenderFlags.RGBA)
+
+ valid_mask = (rend_depth < depth_map) * (rend_depth > 0)
+ depth_map[valid_mask] = rend_depth[valid_mask]
+ valid_mask = valid_mask[:, :, None]
+ output_img = (
+ valid_mask * color[:, :, :3] + (1 - valid_mask) * output_img)
+
+ return output_img
+
+
+def imshow_multiview_keypoints_3d(
+ pose_result,
+ skeleton=None,
+ pose_kpt_color=None,
+ pose_link_color=None,
+ space_size=[8000, 8000, 2000],
+ space_center=[0, -500, 800],
+ kpt_score_thr=0.0,
+):
+ """Draw 3D keypoints and links in 3D coordinates.
+
+ Args:
+ pose_result (list[kpts]): The poses to draw. Each element kpts is
+ a set of K keypoints as an Kx4 numpy.ndarray, where each
+ keypoint is represented as x, y, z, score.
+ skeleton (list of [idx_i,idx_j]): Skeleton described by a list of
+ links, each is a pair of joint indices.
+ pose_kpt_color (np.ndarray[Nx3]`): Color of N keypoints. If None, do
+ not nddraw keypoints.
+ pose_link_color (np.array[Mx3]): Color of M links. If None, do not
+ draw links.
+ space_size: (list). Default: [8000, 8000, 2000].
+ space_center: (list). Default: [0, -500, 800].
+ kpt_score_thr (float): Minimum score of keypoints to be shown.
+ Default: 0.0.
+ """
+ fig = plt.figure()
+ ax = plt.axes(projection='3d')
+ ax.set_xlim3d(space_center[0] - space_size[0] * 0.5,
+ space_center[0] + space_size[0] * 0.5)
+ ax.set_ylim3d(space_center[1] - space_size[1] * 0.5,
+ space_center[1] + space_size[1] * 0.5)
+ ax.set_zlim3d(space_center[2] - space_size[2] * 0.5,
+ space_center[2] + space_size[2] * 0.5)
+ pose_kpt_color = np.array(pose_kpt_color)
+ pose_kpt_color = pose_kpt_color[..., ::-1] / 255.
+
+ for kpts in pose_result:
+ # draw each point on image
+ xs, ys, zs, scores = kpts.T
+ valid = scores > kpt_score_thr
+ ax.scatter(
+ xs[valid],
+ ys[valid],
+ zs[valid],
+ marker='o',
+ color=pose_kpt_color[valid])
+
+ for link, link_color in zip(skeleton, pose_link_color):
+ link_indices = [_i for _i in link]
+ xs_3d = kpts[link_indices, 0]
+ ys_3d = kpts[link_indices, 1]
+ zs_3d = kpts[link_indices, 2]
+ kpt_score = kpts[link_indices, 3]
+ if kpt_score.min() > kpt_score_thr:
+ # matplotlib uses RGB color in [0, 1] value range
+ _color = np.array(link_color[::-1]) / 255.
+ ax.plot(xs_3d, ys_3d, zs_3d, color=_color)
+
+ # convert figure to numpy array
+ fig.tight_layout()
+ fig.canvas.draw()
+ img_w, img_h = fig.canvas.get_width_height()
+ img_vis = np.frombuffer(
+ fig.canvas.tostring_rgb(), dtype=np.uint8).reshape(img_h, img_w, -1)
+ img_vis = mmcv.rgb2bgr(img_vis)
+
+ plt.close(fig)
+
+ return img_vis
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/deprecated.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/deprecated.py
new file mode 100644
index 0000000000000000000000000000000000000000..b930901722ab8fe57455f8eaf9e7c1c728b4b4f8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/deprecated.py
@@ -0,0 +1,199 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+from .datasets.builder import DATASETS
+from .datasets.datasets.base import Kpt2dSviewRgbImgTopDownDataset
+from .models.builder import HEADS, POSENETS
+from .models.detectors import AssociativeEmbedding
+from .models.heads import (AEHigherResolutionHead, AESimpleHead,
+ DeepposeRegressionHead, HMRMeshHead,
+ TopdownHeatmapMSMUHead,
+ TopdownHeatmapMultiStageHead,
+ TopdownHeatmapSimpleHead)
+
+
+@DATASETS.register_module()
+class TopDownFreiHandDataset(Kpt2dSviewRgbImgTopDownDataset):
+ """Deprecated TopDownFreiHandDataset."""
+
+ def __init__(self, *args, **kwargs):
+ raise (ImportError(
+ 'TopDownFreiHandDataset has been renamed into FreiHandDataset,'
+ 'check https://github.com/open-mmlab/mmpose/pull/202 for details.')
+ )
+
+ def _get_db(self):
+ return []
+
+ def evaluate(self, cfg, preds, output_dir, *args, **kwargs):
+ return None
+
+
+@DATASETS.register_module()
+class TopDownOneHand10KDataset(Kpt2dSviewRgbImgTopDownDataset):
+ """Deprecated TopDownOneHand10KDataset."""
+
+ def __init__(self, *args, **kwargs):
+ raise (ImportError(
+ 'TopDownOneHand10KDataset has been renamed into OneHand10KDataset,'
+ 'check https://github.com/open-mmlab/mmpose/pull/202 for details.')
+ )
+
+ def _get_db(self):
+ return []
+
+ def evaluate(self, cfg, preds, output_dir, *args, **kwargs):
+ return None
+
+
+@DATASETS.register_module()
+class TopDownPanopticDataset(Kpt2dSviewRgbImgTopDownDataset):
+ """Deprecated TopDownPanopticDataset."""
+
+ def __init__(self, *args, **kwargs):
+ raise (ImportError(
+ 'TopDownPanopticDataset has been renamed into PanopticDataset,'
+ 'check https://github.com/open-mmlab/mmpose/pull/202 for details.')
+ )
+
+ def _get_db(self):
+ return []
+
+ def evaluate(self, cfg, preds, output_dir, *args, **kwargs):
+ return None
+
+
+@HEADS.register_module()
+class BottomUpHigherResolutionHead(AEHigherResolutionHead):
+ """Bottom-up head for Higher Resolution.
+
+ BottomUpHigherResolutionHead has been renamed into AEHigherResolutionHead,
+ check https://github.com/open- mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'BottomUpHigherResolutionHead has been renamed into '
+ 'AEHigherResolutionHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class BottomUpSimpleHead(AESimpleHead):
+ """Bottom-up simple head.
+
+ BottomUpSimpleHead has been renamed into AESimpleHead, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'BottomUpHigherResolutionHead has been renamed into '
+ 'AEHigherResolutionHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class TopDownSimpleHead(TopdownHeatmapSimpleHead):
+ """Top-down heatmap simple head.
+
+ TopDownSimpleHead has been renamed into TopdownHeatmapSimpleHead, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'TopDownSimpleHead has been renamed into '
+ 'TopdownHeatmapSimpleHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class TopDownMultiStageHead(TopdownHeatmapMultiStageHead):
+ """Top-down heatmap multi-stage head.
+
+ TopDownMultiStageHead has been renamed into TopdownHeatmapMultiStageHead,
+ check https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'TopDownMultiStageHead has been renamed into '
+ 'TopdownHeatmapMultiStageHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class TopDownMSMUHead(TopdownHeatmapMSMUHead):
+ """Heads for multi-stage multi-unit heads.
+
+ TopDownMSMUHead has been renamed into TopdownHeatmapMSMUHead, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'TopDownMSMUHead has been renamed into '
+ 'TopdownHeatmapMSMUHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class MeshHMRHead(HMRMeshHead):
+ """SMPL parameters regressor head.
+
+ MeshHMRHead has been renamed into HMRMeshHead, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'MeshHMRHead has been renamed into '
+ 'HMRMeshHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@HEADS.register_module()
+class FcHead(DeepposeRegressionHead):
+ """FcHead (deprecated).
+
+ FcHead has been renamed into DeepposeRegressionHead, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'FcHead has been renamed into '
+ 'DeepposeRegressionHead, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
+
+
+@POSENETS.register_module()
+class BottomUp(AssociativeEmbedding):
+ """Associative Embedding.
+
+ BottomUp has been renamed into AssociativeEmbedding, check
+ https://github.com/open-mmlab/mmpose/pull/656 for details.
+ """
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ warnings.warn(
+ 'BottomUp has been renamed into '
+ 'AssociativeEmbedding, check '
+ 'https://github.com/open-mmlab/mmpose/pull/656 for details.',
+ DeprecationWarning)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..641d115a693abff882fa7604811430f8e6b605ab
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/__init__.py
@@ -0,0 +1,16 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .builder import (BACKBONES, HEADS, LOSSES, MESH_MODELS, NECKS, POSENETS,
+ build_backbone, build_head, build_loss, build_mesh_model,
+ build_neck, build_posenet)
+from .detectors import * # noqa
+from .heads import * # noqa
+from .losses import * # noqa
+from .necks import * # noqa
+from .utils import * # noqa
+
+
+__all__ = [
+ 'HEADS', 'NECKS', 'LOSSES', 'POSENETS', 'MESH_MODELS',
+ 'build_head', 'build_loss', 'build_posenet',
+ 'build_neck', 'build_mesh_model'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..06717917a2dbd08800587d3ffa193149e42a653c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/__init__.py
@@ -0,0 +1,41 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .alexnet import AlexNet
+from .cpm import CPM
+from .hourglass import HourglassNet
+from .hourglass_ae import HourglassAENet
+from .hrformer import HRFormer
+from .hrnet import HRNet
+from .i3d import I3D
+from .litehrnet import LiteHRNet
+from .mobilenet_v2 import MobileNetV2
+from .mobilenet_v3 import MobileNetV3
+from .mspn import MSPN
+from .pvt import PyramidVisionTransformer, PyramidVisionTransformerV2
+from .regnet import RegNet
+from .resnest import ResNeSt
+from .resnet import ResNet, ResNetV1d
+from .resnext import ResNeXt
+from .rsn import RSN
+from .scnet import SCNet
+from .seresnet import SEResNet
+from .seresnext import SEResNeXt
+from .shufflenet_v1 import ShuffleNetV1
+from .shufflenet_v2 import ShuffleNetV2
+from .swin import SwinTransformer
+from .tcformer import TCFormer
+from .tcn import TCN
+from .v2v_net import V2VNet
+from .vgg import VGG
+from .vipnas_mbv3 import ViPNAS_MobileNetV3
+from .vipnas_resnet import ViPNAS_ResNet
+from .hrt import HRT
+from .vit import ViT
+
+__all__ = [
+ 'AlexNet', 'HourglassNet', 'HourglassAENet', 'HRNet', 'MobileNetV2',
+ 'MobileNetV3', 'RegNet', 'ResNet', 'ResNetV1d', 'ResNeXt', 'SCNet',
+ 'SEResNet', 'SEResNeXt', 'ShuffleNetV1', 'ShuffleNetV2', 'CPM', 'RSN',
+ 'MSPN', 'ResNeSt', 'VGG', 'TCN', 'ViPNAS_ResNet', 'ViPNAS_MobileNetV3',
+ 'LiteHRNet', 'V2VNet', 'HRFormer', 'PyramidVisionTransformer',
+ 'PyramidVisionTransformerV2', 'SwinTransformer', 'I3D', 'TCFormer', 'ViT'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/alexnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/alexnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8efd74d118f5abe4d9c880ebe80ce7cbd58c6b2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/alexnet.py
@@ -0,0 +1,56 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.nn as nn
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+@BACKBONES.register_module()
+class AlexNet(BaseBackbone):
+ """`AlexNet `__ backbone.
+
+ The input for AlexNet is a 224x224 RGB image.
+
+ Args:
+ num_classes (int): number of classes for classification.
+ The default value is -1, which uses the backbone as
+ a feature extractor without the top classifier.
+ """
+
+ def __init__(self, num_classes=-1):
+ super().__init__()
+ self.num_classes = num_classes
+ self.features = nn.Sequential(
+ nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
+ nn.ReLU(inplace=True),
+ nn.MaxPool2d(kernel_size=3, stride=2),
+ nn.Conv2d(64, 192, kernel_size=5, padding=2),
+ nn.ReLU(inplace=True),
+ nn.MaxPool2d(kernel_size=3, stride=2),
+ nn.Conv2d(192, 384, kernel_size=3, padding=1),
+ nn.ReLU(inplace=True),
+ nn.Conv2d(384, 256, kernel_size=3, padding=1),
+ nn.ReLU(inplace=True),
+ nn.Conv2d(256, 256, kernel_size=3, padding=1),
+ nn.ReLU(inplace=True),
+ nn.MaxPool2d(kernel_size=3, stride=2),
+ )
+ if self.num_classes > 0:
+ self.classifier = nn.Sequential(
+ nn.Dropout(),
+ nn.Linear(256 * 6 * 6, 4096),
+ nn.ReLU(inplace=True),
+ nn.Dropout(),
+ nn.Linear(4096, 4096),
+ nn.ReLU(inplace=True),
+ nn.Linear(4096, num_classes),
+ )
+
+ def forward(self, x):
+
+ x = self.features(x)
+ if self.num_classes > 0:
+ x = x.view(x.size(0), 256 * 6 * 6)
+ x = self.classifier(x)
+
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/base_backbone.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/base_backbone.py
new file mode 100644
index 0000000000000000000000000000000000000000..8787d944d2233955a96d0446d9ead9f8fd8a6a9c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/base_backbone.py
@@ -0,0 +1,83 @@
+# # Copyright (c) OpenMMLab. All rights reserved.
+# import logging
+# from abc import ABCMeta, abstractmethod
+#
+# import torch.nn as nn
+#
+# from .utils import load_checkpoint
+#
+#
+# class BaseBackbone(nn.Module, metaclass=ABCMeta):
+# """Base backbone.
+#
+# This class defines the basic functions of a backbone. Any backbone that
+# inherits this class should at least define its own `forward` function.
+# """
+#
+# def init_weights(self, pretrained=None):
+# """Init backbone weights.
+#
+# Args:
+# pretrained (str | None): If pretrained is a string, then it
+# initializes backbone weights by loading the pretrained
+# checkpoint. If pretrained is None, then it follows default
+# initializer or customized initializer in subclasses.
+# """
+# if isinstance(pretrained, str):
+# logger = logging.getLogger()
+# load_checkpoint(self, pretrained, strict=False, logger=logger)
+# elif pretrained is None:
+# # use default initializer or customized initializer in subclasses
+# pass
+# else:
+# raise TypeError('pretrained must be a str or None.'
+# f' But received {type(pretrained)}.')
+#
+# @abstractmethod
+# def forward(self, x):
+# """Forward function.
+#
+# Args:
+# x (Tensor | tuple[Tensor]): x could be a torch.Tensor or a tuple of
+# torch.Tensor, containing input data for forward computation.
+# """
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+from abc import ABCMeta, abstractmethod
+
+import torch.nn as nn
+
+from .utils import load_checkpoint
+# from mmcv_custom.checkpoint import load_checkpoint
+
+class BaseBackbone(nn.Module, metaclass=ABCMeta):
+ """Base backbone.
+ This class defines the basic functions of a backbone. Any backbone that
+ inherits this class should at least define its own `forward` function.
+ """
+
+ def init_weights(self, pretrained=None, patch_padding='pad'):
+ """Init backbone weights.
+ Args:
+ pretrained (str | None): If pretrained is a string, then it
+ initializes backbone weights by loading the pretrained
+ checkpoint. If pretrained is None, then it follows default
+ initializer or customized initializer in subclasses.
+ """
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger, patch_padding=patch_padding)
+ elif pretrained is None:
+ # use default initializer or customized initializer in subclasses
+ pass
+ else:
+ raise TypeError('pretrained must be a str or None.'
+ f' But received {type(pretrained)}.')
+
+ @abstractmethod
+ def forward(self, x):
+ """Forward function.
+ Args:
+ x (Tensor | tuple[Tensor]): x could be a torch.Tensor or a tuple of
+ torch.Tensor, containing input data for forward computation.
+ """
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/cpm.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/cpm.py
new file mode 100644
index 0000000000000000000000000000000000000000..458245d755f930f4ff625a754aadbab5c13494a6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/cpm.py
@@ -0,0 +1,186 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch
+import torch.nn as nn
+from mmcv.cnn import ConvModule, constant_init, normal_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import load_checkpoint
+
+
+class CpmBlock(nn.Module):
+ """CpmBlock for Convolutional Pose Machine.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ channels (list): Output channels of each conv module.
+ kernels (list): Kernel sizes of each conv module.
+ """
+
+ def __init__(self,
+ in_channels,
+ channels=(128, 128, 128),
+ kernels=(11, 11, 11),
+ norm_cfg=None):
+ super().__init__()
+
+ assert len(channels) == len(kernels)
+ layers = []
+ for i in range(len(channels)):
+ if i == 0:
+ input_channels = in_channels
+ else:
+ input_channels = channels[i - 1]
+ layers.append(
+ ConvModule(
+ input_channels,
+ channels[i],
+ kernels[i],
+ padding=(kernels[i] - 1) // 2,
+ norm_cfg=norm_cfg))
+ self.model = nn.Sequential(*layers)
+
+ def forward(self, x):
+ """Model forward function."""
+ out = self.model(x)
+ return out
+
+
+@BACKBONES.register_module()
+class CPM(BaseBackbone):
+ """CPM backbone.
+
+ Convolutional Pose Machines.
+ More details can be found in the `paper
+ `__ .
+
+ Args:
+ in_channels (int): The input channels of the CPM.
+ out_channels (int): The output channels of the CPM.
+ feat_channels (int): Feature channel of each CPM stage.
+ middle_channels (int): Feature channel of conv after the middle stage.
+ num_stages (int): Number of stages.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+
+ Example:
+ >>> from mmpose.models import CPM
+ >>> import torch
+ >>> self = CPM(3, 17)
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 368, 368)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_output in level_outputs:
+ ... print(tuple(level_output.shape))
+ (1, 17, 46, 46)
+ (1, 17, 46, 46)
+ (1, 17, 46, 46)
+ (1, 17, 46, 46)
+ (1, 17, 46, 46)
+ (1, 17, 46, 46)
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ feat_channels=128,
+ middle_channels=32,
+ num_stages=6,
+ norm_cfg=dict(type='BN', requires_grad=True)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ assert in_channels == 3
+
+ self.num_stages = num_stages
+ assert self.num_stages >= 1
+
+ self.stem = nn.Sequential(
+ ConvModule(in_channels, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
+ ConvModule(128, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
+ ConvModule(128, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
+ ConvModule(128, 32, 5, padding=2, norm_cfg=norm_cfg),
+ ConvModule(32, 512, 9, padding=4, norm_cfg=norm_cfg),
+ ConvModule(512, 512, 1, padding=0, norm_cfg=norm_cfg),
+ ConvModule(512, out_channels, 1, padding=0, act_cfg=None))
+
+ self.middle = nn.Sequential(
+ ConvModule(in_channels, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
+ ConvModule(128, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
+ ConvModule(128, 128, 9, padding=4, norm_cfg=norm_cfg),
+ nn.MaxPool2d(kernel_size=3, stride=2, padding=1))
+
+ self.cpm_stages = nn.ModuleList([
+ CpmBlock(
+ middle_channels + out_channels,
+ channels=[feat_channels, feat_channels, feat_channels],
+ kernels=[11, 11, 11],
+ norm_cfg=norm_cfg) for _ in range(num_stages - 1)
+ ])
+
+ self.middle_conv = nn.ModuleList([
+ nn.Sequential(
+ ConvModule(
+ 128, middle_channels, 5, padding=2, norm_cfg=norm_cfg))
+ for _ in range(num_stages - 1)
+ ])
+
+ self.out_convs = nn.ModuleList([
+ nn.Sequential(
+ ConvModule(
+ feat_channels,
+ feat_channels,
+ 1,
+ padding=0,
+ norm_cfg=norm_cfg),
+ ConvModule(feat_channels, out_channels, 1, act_cfg=None))
+ for _ in range(num_stages - 1)
+ ])
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ """Model forward function."""
+ stage1_out = self.stem(x)
+ middle_out = self.middle(x)
+ out_feats = []
+
+ out_feats.append(stage1_out)
+
+ for ind in range(self.num_stages - 1):
+ single_stage = self.cpm_stages[ind]
+ out_conv = self.out_convs[ind]
+
+ inp_feat = torch.cat(
+ [out_feats[-1], self.middle_conv[ind](middle_out)], 1)
+ cpm_feat = single_stage(inp_feat)
+ out_feat = out_conv(cpm_feat)
+ out_feats.append(out_feat)
+
+ return out_feats
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf75fad9895ebfd3f3c2a6bffedb3d7e4cc77cba
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass.py
@@ -0,0 +1,212 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+from mmcv.cnn import ConvModule, constant_init, normal_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .resnet import BasicBlock, ResLayer
+from .utils import load_checkpoint
+
+
+class HourglassModule(nn.Module):
+ """Hourglass Module for HourglassNet backbone.
+
+ Generate module recursively and use BasicBlock as the base unit.
+
+ Args:
+ depth (int): Depth of current HourglassModule.
+ stage_channels (list[int]): Feature channels of sub-modules in current
+ and follow-up HourglassModule.
+ stage_blocks (list[int]): Number of sub-modules stacked in current and
+ follow-up HourglassModule.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+ """
+
+ def __init__(self,
+ depth,
+ stage_channels,
+ stage_blocks,
+ norm_cfg=dict(type='BN', requires_grad=True)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ self.depth = depth
+
+ cur_block = stage_blocks[0]
+ next_block = stage_blocks[1]
+
+ cur_channel = stage_channels[0]
+ next_channel = stage_channels[1]
+
+ self.up1 = ResLayer(
+ BasicBlock, cur_block, cur_channel, cur_channel, norm_cfg=norm_cfg)
+
+ self.low1 = ResLayer(
+ BasicBlock,
+ cur_block,
+ cur_channel,
+ next_channel,
+ stride=2,
+ norm_cfg=norm_cfg)
+
+ if self.depth > 1:
+ self.low2 = HourglassModule(depth - 1, stage_channels[1:],
+ stage_blocks[1:])
+ else:
+ self.low2 = ResLayer(
+ BasicBlock,
+ next_block,
+ next_channel,
+ next_channel,
+ norm_cfg=norm_cfg)
+
+ self.low3 = ResLayer(
+ BasicBlock,
+ cur_block,
+ next_channel,
+ cur_channel,
+ norm_cfg=norm_cfg,
+ downsample_first=False)
+
+ self.up2 = nn.Upsample(scale_factor=2)
+
+ def forward(self, x):
+ """Model forward function."""
+ up1 = self.up1(x)
+ low1 = self.low1(x)
+ low2 = self.low2(low1)
+ low3 = self.low3(low2)
+ up2 = self.up2(low3)
+ return up1 + up2
+
+
+@BACKBONES.register_module()
+class HourglassNet(BaseBackbone):
+ """HourglassNet backbone.
+
+ Stacked Hourglass Networks for Human Pose Estimation.
+ More details can be found in the `paper
+ `__ .
+
+ Args:
+ downsample_times (int): Downsample times in a HourglassModule.
+ num_stacks (int): Number of HourglassModule modules stacked,
+ 1 for Hourglass-52, 2 for Hourglass-104.
+ stage_channels (list[int]): Feature channel of each sub-module in a
+ HourglassModule.
+ stage_blocks (list[int]): Number of sub-modules stacked in a
+ HourglassModule.
+ feat_channel (int): Feature channel of conv after a HourglassModule.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+
+ Example:
+ >>> from mmpose.models import HourglassNet
+ >>> import torch
+ >>> self = HourglassNet()
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 511, 511)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_output in level_outputs:
+ ... print(tuple(level_output.shape))
+ (1, 256, 128, 128)
+ (1, 256, 128, 128)
+ """
+
+ def __init__(self,
+ downsample_times=5,
+ num_stacks=2,
+ stage_channels=(256, 256, 384, 384, 384, 512),
+ stage_blocks=(2, 2, 2, 2, 2, 4),
+ feat_channel=256,
+ norm_cfg=dict(type='BN', requires_grad=True)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ self.num_stacks = num_stacks
+ assert self.num_stacks >= 1
+ assert len(stage_channels) == len(stage_blocks)
+ assert len(stage_channels) > downsample_times
+
+ cur_channel = stage_channels[0]
+
+ self.stem = nn.Sequential(
+ ConvModule(3, 128, 7, padding=3, stride=2, norm_cfg=norm_cfg),
+ ResLayer(BasicBlock, 1, 128, 256, stride=2, norm_cfg=norm_cfg))
+
+ self.hourglass_modules = nn.ModuleList([
+ HourglassModule(downsample_times, stage_channels, stage_blocks)
+ for _ in range(num_stacks)
+ ])
+
+ self.inters = ResLayer(
+ BasicBlock,
+ num_stacks - 1,
+ cur_channel,
+ cur_channel,
+ norm_cfg=norm_cfg)
+
+ self.conv1x1s = nn.ModuleList([
+ ConvModule(
+ cur_channel, cur_channel, 1, norm_cfg=norm_cfg, act_cfg=None)
+ for _ in range(num_stacks - 1)
+ ])
+
+ self.out_convs = nn.ModuleList([
+ ConvModule(
+ cur_channel, feat_channel, 3, padding=1, norm_cfg=norm_cfg)
+ for _ in range(num_stacks)
+ ])
+
+ self.remap_convs = nn.ModuleList([
+ ConvModule(
+ feat_channel, cur_channel, 1, norm_cfg=norm_cfg, act_cfg=None)
+ for _ in range(num_stacks - 1)
+ ])
+
+ self.relu = nn.ReLU(inplace=True)
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ """Model forward function."""
+ inter_feat = self.stem(x)
+ out_feats = []
+
+ for ind in range(self.num_stacks):
+ single_hourglass = self.hourglass_modules[ind]
+ out_conv = self.out_convs[ind]
+
+ hourglass_feat = single_hourglass(inter_feat)
+ out_feat = out_conv(hourglass_feat)
+ out_feats.append(out_feat)
+
+ if ind < self.num_stacks - 1:
+ inter_feat = self.conv1x1s[ind](
+ inter_feat) + self.remap_convs[ind](
+ out_feat)
+ inter_feat = self.inters[ind](self.relu(inter_feat))
+
+ return out_feats
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass_ae.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass_ae.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a700e5cb2157fd1dc16771145f065e991b270ea
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hourglass_ae.py
@@ -0,0 +1,212 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+from mmcv.cnn import ConvModule, MaxPool2d, constant_init, normal_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import load_checkpoint
+
+
+class HourglassAEModule(nn.Module):
+ """Modified Hourglass Module for HourglassNet_AE backbone.
+
+ Generate module recursively and use BasicBlock as the base unit.
+
+ Args:
+ depth (int): Depth of current HourglassModule.
+ stage_channels (list[int]): Feature channels of sub-modules in current
+ and follow-up HourglassModule.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+ """
+
+ def __init__(self,
+ depth,
+ stage_channels,
+ norm_cfg=dict(type='BN', requires_grad=True)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ self.depth = depth
+
+ cur_channel = stage_channels[0]
+ next_channel = stage_channels[1]
+
+ self.up1 = ConvModule(
+ cur_channel, cur_channel, 3, padding=1, norm_cfg=norm_cfg)
+
+ self.pool1 = MaxPool2d(2, 2)
+
+ self.low1 = ConvModule(
+ cur_channel, next_channel, 3, padding=1, norm_cfg=norm_cfg)
+
+ if self.depth > 1:
+ self.low2 = HourglassAEModule(depth - 1, stage_channels[1:])
+ else:
+ self.low2 = ConvModule(
+ next_channel, next_channel, 3, padding=1, norm_cfg=norm_cfg)
+
+ self.low3 = ConvModule(
+ next_channel, cur_channel, 3, padding=1, norm_cfg=norm_cfg)
+
+ self.up2 = nn.UpsamplingNearest2d(scale_factor=2)
+
+ def forward(self, x):
+ """Model forward function."""
+ up1 = self.up1(x)
+ pool1 = self.pool1(x)
+ low1 = self.low1(pool1)
+ low2 = self.low2(low1)
+ low3 = self.low3(low2)
+ up2 = self.up2(low3)
+ return up1 + up2
+
+
+@BACKBONES.register_module()
+class HourglassAENet(BaseBackbone):
+ """Hourglass-AE Network proposed by Newell et al.
+
+ Associative Embedding: End-to-End Learning for Joint
+ Detection and Grouping.
+
+ More details can be found in the `paper
+ `__ .
+
+ Args:
+ downsample_times (int): Downsample times in a HourglassModule.
+ num_stacks (int): Number of HourglassModule modules stacked,
+ 1 for Hourglass-52, 2 for Hourglass-104.
+ stage_channels (list[int]): Feature channel of each sub-module in a
+ HourglassModule.
+ stage_blocks (list[int]): Number of sub-modules stacked in a
+ HourglassModule.
+ feat_channels (int): Feature channel of conv after a HourglassModule.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+
+ Example:
+ >>> from mmpose.models import HourglassAENet
+ >>> import torch
+ >>> self = HourglassAENet()
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 512, 512)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_output in level_outputs:
+ ... print(tuple(level_output.shape))
+ (1, 34, 128, 128)
+ """
+
+ def __init__(self,
+ downsample_times=4,
+ num_stacks=1,
+ out_channels=34,
+ stage_channels=(256, 384, 512, 640, 768),
+ feat_channels=256,
+ norm_cfg=dict(type='BN', requires_grad=True)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ self.num_stacks = num_stacks
+ assert self.num_stacks >= 1
+ assert len(stage_channels) > downsample_times
+
+ cur_channels = stage_channels[0]
+
+ self.stem = nn.Sequential(
+ ConvModule(3, 64, 7, padding=3, stride=2, norm_cfg=norm_cfg),
+ ConvModule(64, 128, 3, padding=1, norm_cfg=norm_cfg),
+ MaxPool2d(2, 2),
+ ConvModule(128, 128, 3, padding=1, norm_cfg=norm_cfg),
+ ConvModule(128, feat_channels, 3, padding=1, norm_cfg=norm_cfg),
+ )
+
+ self.hourglass_modules = nn.ModuleList([
+ nn.Sequential(
+ HourglassAEModule(
+ downsample_times, stage_channels, norm_cfg=norm_cfg),
+ ConvModule(
+ feat_channels,
+ feat_channels,
+ 3,
+ padding=1,
+ norm_cfg=norm_cfg),
+ ConvModule(
+ feat_channels,
+ feat_channels,
+ 3,
+ padding=1,
+ norm_cfg=norm_cfg)) for _ in range(num_stacks)
+ ])
+
+ self.out_convs = nn.ModuleList([
+ ConvModule(
+ cur_channels,
+ out_channels,
+ 1,
+ padding=0,
+ norm_cfg=None,
+ act_cfg=None) for _ in range(num_stacks)
+ ])
+
+ self.remap_out_convs = nn.ModuleList([
+ ConvModule(
+ out_channels,
+ feat_channels,
+ 1,
+ norm_cfg=norm_cfg,
+ act_cfg=None) for _ in range(num_stacks - 1)
+ ])
+
+ self.remap_feature_convs = nn.ModuleList([
+ ConvModule(
+ feat_channels,
+ feat_channels,
+ 1,
+ norm_cfg=norm_cfg,
+ act_cfg=None) for _ in range(num_stacks - 1)
+ ])
+
+ self.relu = nn.ReLU(inplace=True)
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ """Model forward function."""
+ inter_feat = self.stem(x)
+ out_feats = []
+
+ for ind in range(self.num_stacks):
+ single_hourglass = self.hourglass_modules[ind]
+ out_conv = self.out_convs[ind]
+
+ hourglass_feat = single_hourglass(inter_feat)
+ out_feat = out_conv(hourglass_feat)
+ out_feats.append(out_feat)
+
+ if ind < self.num_stacks - 1:
+ inter_feat = inter_feat + self.remap_out_convs[ind](
+ out_feat) + self.remap_feature_convs[ind](
+ hourglass_feat)
+
+ return out_feats
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..b843300a9fdb85908678c5a3fd45ce19e97ce2fe
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrformer.py
@@ -0,0 +1,746 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+import math
+
+import torch
+import torch.nn as nn
+# from timm.models.layers import to_2tuple, trunc_normal_
+from mmcv.cnn import (build_activation_layer, build_conv_layer,
+ build_norm_layer, trunc_normal_init)
+from mmcv.cnn.bricks.transformer import build_dropout
+from mmcv.runner import BaseModule
+from torch.nn.functional import pad
+
+from ..builder import BACKBONES
+from .hrnet import Bottleneck, HRModule, HRNet
+
+
+def nlc_to_nchw(x, hw_shape):
+ """Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor.
+
+ Args:
+ x (Tensor): The input tensor of shape [N, L, C] before conversion.
+ hw_shape (Sequence[int]): The height and width of output feature map.
+
+ Returns:
+ Tensor: The output tensor of shape [N, C, H, W] after conversion.
+ """
+ H, W = hw_shape
+ assert len(x.shape) == 3
+ B, L, C = x.shape
+ assert L == H * W, 'The seq_len doesn\'t match H, W'
+ return x.transpose(1, 2).reshape(B, C, H, W)
+
+
+def nchw_to_nlc(x):
+ """Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor.
+
+ Args:
+ x (Tensor): The input tensor of shape [N, C, H, W] before conversion.
+
+ Returns:
+ Tensor: The output tensor of shape [N, L, C] after conversion.
+ """
+ assert len(x.shape) == 4
+ return x.flatten(2).transpose(1, 2).contiguous()
+
+
+def build_drop_path(drop_path_rate):
+ """Build drop path layer."""
+ return build_dropout(dict(type='DropPath', drop_prob=drop_path_rate))
+
+
+class WindowMSA(BaseModule):
+ """Window based multi-head self-attention (W-MSA) module with relative
+ position bias.
+
+ Args:
+ embed_dims (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (tuple[int]): The height and width of the window.
+ qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.
+ Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ attn_drop_rate (float, optional): Dropout ratio of attention weight.
+ Default: 0.0
+ proj_drop_rate (float, optional): Dropout ratio of output. Default: 0.
+ with_rpe (bool, optional): If True, use relative position bias.
+ Default: True.
+ init_cfg (dict | None, optional): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ window_size,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop_rate=0.,
+ proj_drop_rate=0.,
+ with_rpe=True,
+ init_cfg=None):
+
+ super().__init__(init_cfg=init_cfg)
+ self.embed_dims = embed_dims
+ self.window_size = window_size # Wh, Ww
+ self.num_heads = num_heads
+ head_embed_dims = embed_dims // num_heads
+ self.scale = qk_scale or head_embed_dims**-0.5
+
+ self.with_rpe = with_rpe
+ if self.with_rpe:
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros(
+ (2 * window_size[0] - 1) * (2 * window_size[1] - 1),
+ num_heads)) # 2*Wh-1 * 2*Ww-1, nH
+
+ Wh, Ww = self.window_size
+ rel_index_coords = self.double_step_seq(2 * Ww - 1, Wh, 1, Ww)
+ rel_position_index = rel_index_coords + rel_index_coords.T
+ rel_position_index = rel_position_index.flip(1).contiguous()
+ self.register_buffer('relative_position_index', rel_position_index)
+
+ self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop_rate)
+ self.proj = nn.Linear(embed_dims, embed_dims)
+ self.proj_drop = nn.Dropout(proj_drop_rate)
+
+ self.softmax = nn.Softmax(dim=-1)
+
+ def init_weights(self):
+ trunc_normal_init(self.relative_position_bias_table, std=0.02)
+
+ def forward(self, x, mask=None):
+ """
+ Args:
+
+ x (tensor): input features with shape of (B*num_windows, N, C)
+ mask (tensor | None, Optional): mask with shape of (num_windows,
+ Wh*Ww, Wh*Ww), value should be between (-inf, 0].
+ """
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads,
+ C // self.num_heads).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv[0], qkv[1], qkv[2]
+
+ q = q * self.scale
+ attn = (q @ k.transpose(-2, -1))
+
+ if self.with_rpe:
+ relative_position_bias = self.relative_position_bias_table[
+ self.relative_position_index.view(-1)].view(
+ self.window_size[0] * self.window_size[1],
+ self.window_size[0] * self.window_size[1],
+ -1) # Wh*Ww,Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(
+ 2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
+ attn = attn + relative_position_bias.unsqueeze(0)
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B // nW, nW, self.num_heads, N,
+ N) + mask.unsqueeze(1).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+ @staticmethod
+ def double_step_seq(step1, len1, step2, len2):
+ seq1 = torch.arange(0, step1 * len1, step1)
+ seq2 = torch.arange(0, step2 * len2, step2)
+ return (seq1[:, None] + seq2[None, :]).reshape(1, -1)
+
+
+class LocalWindowSelfAttention(BaseModule):
+ r""" Local-window Self Attention (LSA) module with relative position bias.
+
+ This module is the short-range self-attention module in the
+ Interlaced Sparse Self-Attention `_.
+
+ Args:
+ embed_dims (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (tuple[int] | int): The height and width of the window.
+ qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.
+ Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ attn_drop_rate (float, optional): Dropout ratio of attention weight.
+ Default: 0.0
+ proj_drop_rate (float, optional): Dropout ratio of output. Default: 0.
+ with_rpe (bool, optional): If True, use relative position bias.
+ Default: True.
+ with_pad_mask (bool, optional): If True, mask out the padded tokens in
+ the attention process. Default: False.
+ init_cfg (dict | None, optional): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ window_size,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop_rate=0.,
+ proj_drop_rate=0.,
+ with_rpe=True,
+ with_pad_mask=False,
+ init_cfg=None):
+ super().__init__(init_cfg=init_cfg)
+ if isinstance(window_size, int):
+ window_size = (window_size, window_size)
+ self.window_size = window_size
+ self.with_pad_mask = with_pad_mask
+ self.attn = WindowMSA(
+ embed_dims=embed_dims,
+ num_heads=num_heads,
+ window_size=window_size,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop_rate=attn_drop_rate,
+ proj_drop_rate=proj_drop_rate,
+ with_rpe=with_rpe,
+ init_cfg=init_cfg)
+
+ def forward(self, x, H, W, **kwargs):
+ """Forward function."""
+ B, N, C = x.shape
+ x = x.view(B, H, W, C)
+ Wh, Ww = self.window_size
+
+ # center-pad the feature on H and W axes
+ pad_h = math.ceil(H / Wh) * Wh - H
+ pad_w = math.ceil(W / Ww) * Ww - W
+ x = pad(x, (0, 0, pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
+ pad_h - pad_h // 2))
+
+ # permute
+ x = x.view(B, math.ceil(H / Wh), Wh, math.ceil(W / Ww), Ww, C)
+ x = x.permute(0, 1, 3, 2, 4, 5)
+ x = x.reshape(-1, Wh * Ww, C) # (B*num_window, Wh*Ww, C)
+
+ # attention
+ if self.with_pad_mask and pad_h > 0 and pad_w > 0:
+ pad_mask = x.new_zeros(1, H, W, 1)
+ pad_mask = pad(
+ pad_mask, [
+ 0, 0, pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
+ pad_h - pad_h // 2
+ ],
+ value=-float('inf'))
+ pad_mask = pad_mask.view(1, math.ceil(H / Wh), Wh,
+ math.ceil(W / Ww), Ww, 1)
+ pad_mask = pad_mask.permute(1, 3, 0, 2, 4, 5)
+ pad_mask = pad_mask.reshape(-1, Wh * Ww)
+ pad_mask = pad_mask[:, None, :].expand([-1, Wh * Ww, -1])
+ out = self.attn(x, pad_mask, **kwargs)
+ else:
+ out = self.attn(x, **kwargs)
+
+ # reverse permutation
+ out = out.reshape(B, math.ceil(H / Wh), math.ceil(W / Ww), Wh, Ww, C)
+ out = out.permute(0, 1, 3, 2, 4, 5)
+ out = out.reshape(B, H + pad_h, W + pad_w, C)
+
+ # de-pad
+ out = out[:, pad_h // 2:H + pad_h // 2, pad_w // 2:W + pad_w // 2]
+ return out.reshape(B, N, C)
+
+
+class CrossFFN(BaseModule):
+ r"""FFN with Depthwise Conv of HRFormer.
+
+ Args:
+ in_features (int): The feature dimension.
+ hidden_features (int, optional): The hidden dimension of FFNs.
+ Defaults: The same as in_features.
+ act_cfg (dict, optional): Config of activation layer.
+ Default: dict(type='GELU').
+ dw_act_cfg (dict, optional): Config of activation layer appended
+ right after DW Conv. Default: dict(type='GELU').
+ norm_cfg (dict, optional): Config of norm layer.
+ Default: dict(type='SyncBN').
+ init_cfg (dict | list | None, optional): The init config.
+ Default: None.
+ """
+
+ def __init__(self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_cfg=dict(type='GELU'),
+ dw_act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='SyncBN'),
+ init_cfg=None):
+ super().__init__(init_cfg=init_cfg)
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Conv2d(in_features, hidden_features, kernel_size=1)
+ self.act1 = build_activation_layer(act_cfg)
+ self.norm1 = build_norm_layer(norm_cfg, hidden_features)[1]
+ self.dw3x3 = nn.Conv2d(
+ hidden_features,
+ hidden_features,
+ kernel_size=3,
+ stride=1,
+ groups=hidden_features,
+ padding=1)
+ self.act2 = build_activation_layer(dw_act_cfg)
+ self.norm2 = build_norm_layer(norm_cfg, hidden_features)[1]
+ self.fc2 = nn.Conv2d(hidden_features, out_features, kernel_size=1)
+ self.act3 = build_activation_layer(act_cfg)
+ self.norm3 = build_norm_layer(norm_cfg, out_features)[1]
+
+ # put the modules togather
+ self.layers = [
+ self.fc1, self.norm1, self.act1, self.dw3x3, self.norm2, self.act2,
+ self.fc2, self.norm3, self.act3
+ ]
+
+ def forward(self, x, H, W):
+ """Forward function."""
+ x = nlc_to_nchw(x, (H, W))
+ for layer in self.layers:
+ x = layer(x)
+ x = nchw_to_nlc(x)
+ return x
+
+
+class HRFormerBlock(BaseModule):
+ """High-Resolution Block for HRFormer.
+
+ Args:
+ in_features (int): The input dimension.
+ out_features (int): The output dimension.
+ num_heads (int): The number of head within each LSA.
+ window_size (int, optional): The window size for the LSA.
+ Default: 7
+ mlp_ratio (int, optional): The expansion ration of FFN.
+ Default: 4
+ act_cfg (dict, optional): Config of activation layer.
+ Default: dict(type='GELU').
+ norm_cfg (dict, optional): Config of norm layer.
+ Default: dict(type='SyncBN').
+ transformer_norm_cfg (dict, optional): Config of transformer norm
+ layer. Default: dict(type='LN', eps=1e-6).
+ init_cfg (dict | list | None, optional): The init config.
+ Default: None.
+ """
+
+ expansion = 1
+
+ def __init__(self,
+ in_features,
+ out_features,
+ num_heads,
+ window_size=7,
+ mlp_ratio=4.0,
+ drop_path=0.0,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='SyncBN'),
+ transformer_norm_cfg=dict(type='LN', eps=1e-6),
+ init_cfg=None,
+ **kwargs):
+ super(HRFormerBlock, self).__init__(init_cfg=init_cfg)
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.mlp_ratio = mlp_ratio
+
+ self.norm1 = build_norm_layer(transformer_norm_cfg, in_features)[1]
+ self.attn = LocalWindowSelfAttention(
+ in_features,
+ num_heads=num_heads,
+ window_size=window_size,
+ init_cfg=None,
+ **kwargs)
+
+ self.norm2 = build_norm_layer(transformer_norm_cfg, out_features)[1]
+ self.ffn = CrossFFN(
+ in_features=in_features,
+ hidden_features=int(in_features * mlp_ratio),
+ out_features=out_features,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ dw_act_cfg=act_cfg,
+ init_cfg=None)
+
+ self.drop_path = build_drop_path(
+ drop_path) if drop_path > 0.0 else nn.Identity()
+
+ def forward(self, x):
+ """Forward function."""
+ B, C, H, W = x.size()
+ # Attention
+ x = x.view(B, C, -1).permute(0, 2, 1)
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
+ # FFN
+ x = x + self.drop_path(self.ffn(self.norm2(x), H, W))
+ x = x.permute(0, 2, 1).view(B, C, H, W)
+ return x
+
+ def extra_repr(self):
+ """(Optional) Set the extra information about this module."""
+ return 'num_heads={}, window_size={}, mlp_ratio={}'.format(
+ self.num_heads, self.window_size, self.mlp_ratio)
+
+
+class HRFomerModule(HRModule):
+ """High-Resolution Module for HRFormer.
+
+ Args:
+ num_branches (int): The number of branches in the HRFormerModule.
+ block (nn.Module): The building block of HRFormer.
+ The block should be the HRFormerBlock.
+ num_blocks (tuple): The number of blocks in each branch.
+ The length must be equal to num_branches.
+ num_inchannels (tuple): The number of input channels in each branch.
+ The length must be equal to num_branches.
+ num_channels (tuple): The number of channels in each branch.
+ The length must be equal to num_branches.
+ num_heads (tuple): The number of heads within the LSAs.
+ num_window_sizes (tuple): The window size for the LSAs.
+ num_mlp_ratios (tuple): The expansion ratio for the FFNs.
+ drop_path (int, optional): The drop path rate of HRFomer.
+ Default: 0.0
+ multiscale_output (bool, optional): Whether to output multi-level
+ features produced by multiple branches. If False, only the first
+ level feature will be output. Default: True.
+ conv_cfg (dict, optional): Config of the conv layers.
+ Default: None.
+ norm_cfg (dict, optional): Config of the norm layers appended
+ right after conv. Default: dict(type='SyncBN', requires_grad=True)
+ transformer_norm_cfg (dict, optional): Config of the norm layers.
+ Default: dict(type='LN', eps=1e-6)
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False
+ upsample_cfg(dict, optional): The config of upsample layers in fuse
+ layers. Default: dict(mode='bilinear', align_corners=False)
+ """
+
+ def __init__(self,
+ num_branches,
+ block,
+ num_blocks,
+ num_inchannels,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ multiscale_output=True,
+ drop_paths=0.0,
+ with_rpe=True,
+ with_pad_mask=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='SyncBN', requires_grad=True),
+ transformer_norm_cfg=dict(type='LN', eps=1e-6),
+ with_cp=False,
+ upsample_cfg=dict(mode='bilinear', align_corners=False)):
+
+ self.transformer_norm_cfg = transformer_norm_cfg
+ self.drop_paths = drop_paths
+ self.num_heads = num_heads
+ self.num_window_sizes = num_window_sizes
+ self.num_mlp_ratios = num_mlp_ratios
+ self.with_rpe = with_rpe
+ self.with_pad_mask = with_pad_mask
+
+ super().__init__(num_branches, block, num_blocks, num_inchannels,
+ num_channels, multiscale_output, with_cp, conv_cfg,
+ norm_cfg, upsample_cfg)
+
+ def _make_one_branch(self,
+ branch_index,
+ block,
+ num_blocks,
+ num_channels,
+ stride=1):
+ """Build one branch."""
+ # HRFormerBlock does not support down sample layer yet.
+ assert stride == 1 and self.in_channels[branch_index] == num_channels[
+ branch_index]
+ layers = []
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index],
+ num_heads=self.num_heads[branch_index],
+ window_size=self.num_window_sizes[branch_index],
+ mlp_ratio=self.num_mlp_ratios[branch_index],
+ drop_path=self.drop_paths[0],
+ norm_cfg=self.norm_cfg,
+ transformer_norm_cfg=self.transformer_norm_cfg,
+ init_cfg=None,
+ with_rpe=self.with_rpe,
+ with_pad_mask=self.with_pad_mask))
+
+ self.in_channels[
+ branch_index] = self.in_channels[branch_index] * block.expansion
+ for i in range(1, num_blocks[branch_index]):
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index],
+ num_heads=self.num_heads[branch_index],
+ window_size=self.num_window_sizes[branch_index],
+ mlp_ratio=self.num_mlp_ratios[branch_index],
+ drop_path=self.drop_paths[i],
+ norm_cfg=self.norm_cfg,
+ transformer_norm_cfg=self.transformer_norm_cfg,
+ init_cfg=None,
+ with_rpe=self.with_rpe,
+ with_pad_mask=self.with_pad_mask))
+ return nn.Sequential(*layers)
+
+ def _make_fuse_layers(self):
+ """Build fuse layers."""
+ if self.num_branches == 1:
+ return None
+ num_branches = self.num_branches
+ num_inchannels = self.in_channels
+ fuse_layers = []
+ for i in range(num_branches if self.multiscale_output else 1):
+ fuse_layer = []
+ for j in range(num_branches):
+ if j > i:
+ fuse_layer.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ num_inchannels[j],
+ num_inchannels[i],
+ kernel_size=1,
+ stride=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ num_inchannels[i])[1],
+ nn.Upsample(
+ scale_factor=2**(j - i),
+ mode=self.upsample_cfg['mode'],
+ align_corners=self.
+ upsample_cfg['align_corners'])))
+ elif j == i:
+ fuse_layer.append(None)
+ else:
+ conv3x3s = []
+ for k in range(i - j):
+ if k == i - j - 1:
+ num_outchannels_conv3x3 = num_inchannels[i]
+ with_out_act = False
+ else:
+ num_outchannels_conv3x3 = num_inchannels[j]
+ with_out_act = True
+ sub_modules = [
+ build_conv_layer(
+ self.conv_cfg,
+ num_inchannels[j],
+ num_inchannels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=num_inchannels[j],
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg,
+ num_inchannels[j])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ num_inchannels[j],
+ num_outchannels_conv3x3,
+ kernel_size=1,
+ stride=1,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg,
+ num_outchannels_conv3x3)[1]
+ ]
+ if with_out_act:
+ sub_modules.append(nn.ReLU(False))
+ conv3x3s.append(nn.Sequential(*sub_modules))
+ fuse_layer.append(nn.Sequential(*conv3x3s))
+ fuse_layers.append(nn.ModuleList(fuse_layer))
+
+ return nn.ModuleList(fuse_layers)
+
+ def get_num_inchannels(self):
+ """Return the number of input channels."""
+ return self.in_channels
+
+
+@BACKBONES.register_module()
+class HRFormer(HRNet):
+ """HRFormer backbone.
+
+ This backbone is the implementation of `HRFormer: High-Resolution
+ Transformer for Dense Prediction `_.
+
+ Args:
+ extra (dict): Detailed configuration for each stage of HRNet.
+ There must be 4 stages, the configuration for each stage must have
+ 5 keys:
+
+ - num_modules (int): The number of HRModule in this stage.
+ - num_branches (int): The number of branches in the HRModule.
+ - block (str): The type of block.
+ - num_blocks (tuple): The number of blocks in each branch.
+ The length must be equal to num_branches.
+ - num_channels (tuple): The number of channels in each branch.
+ The length must be equal to num_branches.
+ in_channels (int): Number of input image channels. Normally 3.
+ conv_cfg (dict): Dictionary to construct and config conv layer.
+ Default: None.
+ norm_cfg (dict): Config of norm layer.
+ Use `SyncBN` by default.
+ transformer_norm_cfg (dict): Config of transformer norm layer.
+ Use `LN` by default.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ Example:
+ >>> from mmpose.models import HRFormer
+ >>> import torch
+ >>> extra = dict(
+ >>> stage1=dict(
+ >>> num_modules=1,
+ >>> num_branches=1,
+ >>> block='BOTTLENECK',
+ >>> num_blocks=(2, ),
+ >>> num_channels=(64, )),
+ >>> stage2=dict(
+ >>> num_modules=1,
+ >>> num_branches=2,
+ >>> block='HRFORMER',
+ >>> window_sizes=(7, 7),
+ >>> num_heads=(1, 2),
+ >>> mlp_ratios=(4, 4),
+ >>> num_blocks=(2, 2),
+ >>> num_channels=(32, 64)),
+ >>> stage3=dict(
+ >>> num_modules=4,
+ >>> num_branches=3,
+ >>> block='HRFORMER',
+ >>> window_sizes=(7, 7, 7),
+ >>> num_heads=(1, 2, 4),
+ >>> mlp_ratios=(4, 4, 4),
+ >>> num_blocks=(2, 2, 2),
+ >>> num_channels=(32, 64, 128)),
+ >>> stage4=dict(
+ >>> num_modules=2,
+ >>> num_branches=4,
+ >>> block='HRFORMER',
+ >>> window_sizes=(7, 7, 7, 7),
+ >>> num_heads=(1, 2, 4, 8),
+ >>> mlp_ratios=(4, 4, 4, 4),
+ >>> num_blocks=(2, 2, 2, 2),
+ >>> num_channels=(32, 64, 128, 256)))
+ >>> self = HRFormer(extra, in_channels=1)
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 1, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 32, 8, 8)
+ (1, 64, 4, 4)
+ (1, 128, 2, 2)
+ (1, 256, 1, 1)
+ """
+
+ blocks_dict = {'BOTTLENECK': Bottleneck, 'HRFORMERBLOCK': HRFormerBlock}
+
+ def __init__(self,
+ extra,
+ in_channels=3,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN', requires_grad=True),
+ transformer_norm_cfg=dict(type='LN', eps=1e-6),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=False,
+ frozen_stages=-1):
+
+ # stochastic depth
+ depths = [
+ extra[stage]['num_blocks'][0] * extra[stage]['num_modules']
+ for stage in ['stage2', 'stage3', 'stage4']
+ ]
+ depth_s2, depth_s3, _ = depths
+ drop_path_rate = extra['drop_path_rate']
+ dpr = [
+ x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
+ ]
+ extra['stage2']['drop_path_rates'] = dpr[0:depth_s2]
+ extra['stage3']['drop_path_rates'] = dpr[depth_s2:depth_s2 + depth_s3]
+ extra['stage4']['drop_path_rates'] = dpr[depth_s2 + depth_s3:]
+
+ # HRFormer use bilinear upsample as default
+ upsample_cfg = extra.get('upsample', {
+ 'mode': 'bilinear',
+ 'align_corners': False
+ })
+ extra['upsample'] = upsample_cfg
+ self.transformer_norm_cfg = transformer_norm_cfg
+ self.with_rpe = extra.get('with_rpe', True)
+ self.with_pad_mask = extra.get('with_pad_mask', False)
+
+ super().__init__(extra, in_channels, conv_cfg, norm_cfg, norm_eval,
+ with_cp, zero_init_residual, frozen_stages)
+
+ def _make_stage(self,
+ layer_config,
+ num_inchannels,
+ multiscale_output=True):
+ """Make each stage."""
+ num_modules = layer_config['num_modules']
+ num_branches = layer_config['num_branches']
+ num_blocks = layer_config['num_blocks']
+ num_channels = layer_config['num_channels']
+ block = self.blocks_dict[layer_config['block']]
+ num_heads = layer_config['num_heads']
+ num_window_sizes = layer_config['window_sizes']
+ num_mlp_ratios = layer_config['mlp_ratios']
+ drop_path_rates = layer_config['drop_path_rates']
+
+ modules = []
+ for i in range(num_modules):
+ # multiscale_output is only used at the last module
+ if not multiscale_output and i == num_modules - 1:
+ reset_multiscale_output = False
+ else:
+ reset_multiscale_output = True
+
+ modules.append(
+ HRFomerModule(
+ num_branches,
+ block,
+ num_blocks,
+ num_inchannels,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ reset_multiscale_output,
+ drop_paths=drop_path_rates[num_blocks[0] *
+ i:num_blocks[0] * (i + 1)],
+ with_rpe=self.with_rpe,
+ with_pad_mask=self.with_pad_mask,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ transformer_norm_cfg=self.transformer_norm_cfg,
+ with_cp=self.with_cp,
+ upsample_cfg=self.upsample_cfg))
+ num_inchannels = modules[-1].get_num_inchannels()
+
+ return nn.Sequential(*modules), num_inchannels
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..87dc8cef555b5e8d78fcc69293047b0cbe2ea8a6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrnet.py
@@ -0,0 +1,604 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
+ normal_init)
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .resnet import BasicBlock, Bottleneck, get_expansion
+from .utils import load_checkpoint
+
+
+class HRModule(nn.Module):
+ """High-Resolution Module for HRNet.
+
+ In this module, every branch has 4 BasicBlocks/Bottlenecks. Fusion/Exchange
+ is in this module.
+ """
+
+ def __init__(self,
+ num_branches,
+ blocks,
+ num_blocks,
+ in_channels,
+ num_channels,
+ multiscale_output=False,
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ upsample_cfg=dict(mode='nearest', align_corners=None)):
+
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self._check_branches(num_branches, num_blocks, in_channels,
+ num_channels)
+
+ self.in_channels = in_channels
+ self.num_branches = num_branches
+
+ self.multiscale_output = multiscale_output
+ self.norm_cfg = norm_cfg
+ self.conv_cfg = conv_cfg
+ self.upsample_cfg = upsample_cfg
+ self.with_cp = with_cp
+ self.branches = self._make_branches(num_branches, blocks, num_blocks,
+ num_channels)
+ self.fuse_layers = self._make_fuse_layers()
+ self.relu = nn.ReLU(inplace=True)
+
+ @staticmethod
+ def _check_branches(num_branches, num_blocks, in_channels, num_channels):
+ """Check input to avoid ValueError."""
+ if num_branches != len(num_blocks):
+ error_msg = f'NUM_BRANCHES({num_branches}) ' \
+ f'!= NUM_BLOCKS({len(num_blocks)})'
+ raise ValueError(error_msg)
+
+ if num_branches != len(num_channels):
+ error_msg = f'NUM_BRANCHES({num_branches}) ' \
+ f'!= NUM_CHANNELS({len(num_channels)})'
+ raise ValueError(error_msg)
+
+ if num_branches != len(in_channels):
+ error_msg = f'NUM_BRANCHES({num_branches}) ' \
+ f'!= NUM_INCHANNELS({len(in_channels)})'
+ raise ValueError(error_msg)
+
+ def _make_one_branch(self,
+ branch_index,
+ block,
+ num_blocks,
+ num_channels,
+ stride=1):
+ """Make one branch."""
+ downsample = None
+ if stride != 1 or \
+ self.in_channels[branch_index] != \
+ num_channels[branch_index] * get_expansion(block):
+ downsample = nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ self.in_channels[branch_index],
+ num_channels[branch_index] * get_expansion(block),
+ kernel_size=1,
+ stride=stride,
+ bias=False),
+ build_norm_layer(
+ self.norm_cfg,
+ num_channels[branch_index] * get_expansion(block))[1])
+
+ layers = []
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index] * get_expansion(block),
+ stride=stride,
+ downsample=downsample,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg))
+ self.in_channels[branch_index] = \
+ num_channels[branch_index] * get_expansion(block)
+ for _ in range(1, num_blocks[branch_index]):
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index] * get_expansion(block),
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg))
+
+ return nn.Sequential(*layers)
+
+ def _make_branches(self, num_branches, block, num_blocks, num_channels):
+ """Make branches."""
+ branches = []
+
+ for i in range(num_branches):
+ branches.append(
+ self._make_one_branch(i, block, num_blocks, num_channels))
+
+ return nn.ModuleList(branches)
+
+ def _make_fuse_layers(self):
+ """Make fuse layer."""
+ if self.num_branches == 1:
+ return None
+
+ num_branches = self.num_branches
+ in_channels = self.in_channels
+ fuse_layers = []
+ num_out_branches = num_branches if self.multiscale_output else 1
+
+ for i in range(num_out_branches):
+ fuse_layer = []
+ for j in range(num_branches):
+ if j > i:
+ fuse_layer.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg, in_channels[i])[1],
+ nn.Upsample(
+ scale_factor=2**(j - i),
+ mode=self.upsample_cfg['mode'],
+ align_corners=self.
+ upsample_cfg['align_corners'])))
+ elif j == i:
+ fuse_layer.append(None)
+ else:
+ conv_downsamples = []
+ for k in range(i - j):
+ if k == i - j - 1:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[i])[1]))
+ else:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[j])[1],
+ nn.ReLU(inplace=True)))
+ fuse_layer.append(nn.Sequential(*conv_downsamples))
+ fuse_layers.append(nn.ModuleList(fuse_layer))
+
+ return nn.ModuleList(fuse_layers)
+
+ def forward(self, x):
+ """Forward function."""
+ if self.num_branches == 1:
+ return [self.branches[0](x[0])]
+
+ for i in range(self.num_branches):
+ x[i] = self.branches[i](x[i])
+
+ x_fuse = []
+ for i in range(len(self.fuse_layers)):
+ y = 0
+ for j in range(self.num_branches):
+ if i == j:
+ y += x[j]
+ else:
+ y += self.fuse_layers[i][j](x[j])
+ x_fuse.append(self.relu(y))
+ return x_fuse
+
+
+@BACKBONES.register_module()
+class HRNet(nn.Module):
+ """HRNet backbone.
+
+ `High-Resolution Representations for Labeling Pixels and Regions
+ `__
+
+ Args:
+ extra (dict): detailed configuration for each stage of HRNet.
+ in_channels (int): Number of input image channels. Default: 3.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ zero_init_residual (bool): whether to use zero init for last norm layer
+ in resblocks to let them behave as identity.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+
+ Example:
+ >>> from mmpose.models import HRNet
+ >>> import torch
+ >>> extra = dict(
+ >>> stage1=dict(
+ >>> num_modules=1,
+ >>> num_branches=1,
+ >>> block='BOTTLENECK',
+ >>> num_blocks=(4, ),
+ >>> num_channels=(64, )),
+ >>> stage2=dict(
+ >>> num_modules=1,
+ >>> num_branches=2,
+ >>> block='BASIC',
+ >>> num_blocks=(4, 4),
+ >>> num_channels=(32, 64)),
+ >>> stage3=dict(
+ >>> num_modules=4,
+ >>> num_branches=3,
+ >>> block='BASIC',
+ >>> num_blocks=(4, 4, 4),
+ >>> num_channels=(32, 64, 128)),
+ >>> stage4=dict(
+ >>> num_modules=3,
+ >>> num_branches=4,
+ >>> block='BASIC',
+ >>> num_blocks=(4, 4, 4, 4),
+ >>> num_channels=(32, 64, 128, 256)))
+ >>> self = HRNet(extra, in_channels=1)
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 1, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 32, 8, 8)
+ """
+
+ blocks_dict = {'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck}
+
+ def __init__(self,
+ extra,
+ in_channels=3,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=False,
+ frozen_stages=-1):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self.extra = extra
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+ self.zero_init_residual = zero_init_residual
+ self.frozen_stages = frozen_stages
+
+ # stem net
+ self.norm1_name, norm1 = build_norm_layer(self.norm_cfg, 64, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(self.norm_cfg, 64, postfix=2)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ 64,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False)
+
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ self.conv_cfg,
+ 64,
+ 64,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False)
+
+ self.add_module(self.norm2_name, norm2)
+ self.relu = nn.ReLU(inplace=True)
+
+ self.upsample_cfg = self.extra.get('upsample', {
+ 'mode': 'nearest',
+ 'align_corners': None
+ })
+
+ # stage 1
+ self.stage1_cfg = self.extra['stage1']
+ num_channels = self.stage1_cfg['num_channels'][0]
+ block_type = self.stage1_cfg['block']
+ num_blocks = self.stage1_cfg['num_blocks'][0]
+
+ block = self.blocks_dict[block_type]
+ stage1_out_channels = num_channels * get_expansion(block)
+ self.layer1 = self._make_layer(block, 64, stage1_out_channels,
+ num_blocks)
+
+ # stage 2
+ self.stage2_cfg = self.extra['stage2']
+ num_channels = self.stage2_cfg['num_channels']
+ block_type = self.stage2_cfg['block']
+
+ block = self.blocks_dict[block_type]
+ num_channels = [
+ channel * get_expansion(block) for channel in num_channels
+ ]
+ self.transition1 = self._make_transition_layer([stage1_out_channels],
+ num_channels)
+ self.stage2, pre_stage_channels = self._make_stage(
+ self.stage2_cfg, num_channels)
+
+ # stage 3
+ self.stage3_cfg = self.extra['stage3']
+ num_channels = self.stage3_cfg['num_channels']
+ block_type = self.stage3_cfg['block']
+
+ block = self.blocks_dict[block_type]
+ num_channels = [
+ channel * get_expansion(block) for channel in num_channels
+ ]
+ self.transition2 = self._make_transition_layer(pre_stage_channels,
+ num_channels)
+ self.stage3, pre_stage_channels = self._make_stage(
+ self.stage3_cfg, num_channels)
+
+ # stage 4
+ self.stage4_cfg = self.extra['stage4']
+ num_channels = self.stage4_cfg['num_channels']
+ block_type = self.stage4_cfg['block']
+
+ block = self.blocks_dict[block_type]
+ num_channels = [
+ channel * get_expansion(block) for channel in num_channels
+ ]
+ self.transition3 = self._make_transition_layer(pre_stage_channels,
+ num_channels)
+
+ self.stage4, pre_stage_channels = self._make_stage(
+ self.stage4_cfg,
+ num_channels,
+ multiscale_output=self.stage4_cfg.get('multiscale_output', False))
+
+ self._freeze_stages()
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: the normalization layer named "norm2" """
+ return getattr(self, self.norm2_name)
+
+ def _make_transition_layer(self, num_channels_pre_layer,
+ num_channels_cur_layer):
+ """Make transition layer."""
+ num_branches_cur = len(num_channels_cur_layer)
+ num_branches_pre = len(num_channels_pre_layer)
+
+ transition_layers = []
+ for i in range(num_branches_cur):
+ if i < num_branches_pre:
+ if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
+ transition_layers.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ num_channels_pre_layer[i],
+ num_channels_cur_layer[i],
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ num_channels_cur_layer[i])[1],
+ nn.ReLU(inplace=True)))
+ else:
+ transition_layers.append(None)
+ else:
+ conv_downsamples = []
+ for j in range(i + 1 - num_branches_pre):
+ in_channels = num_channels_pre_layer[-1]
+ out_channels = num_channels_cur_layer[i] \
+ if j == i - num_branches_pre else in_channels
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg, out_channels)[1],
+ nn.ReLU(inplace=True)))
+ transition_layers.append(nn.Sequential(*conv_downsamples))
+
+ return nn.ModuleList(transition_layers)
+
+ def _make_layer(self, block, in_channels, out_channels, blocks, stride=1):
+ """Make layer."""
+ downsample = None
+ if stride != 1 or in_channels != out_channels:
+ downsample = nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=1,
+ stride=stride,
+ bias=False),
+ build_norm_layer(self.norm_cfg, out_channels)[1])
+
+ layers = []
+ layers.append(
+ block(
+ in_channels,
+ out_channels,
+ stride=stride,
+ downsample=downsample,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg))
+ for _ in range(1, blocks):
+ layers.append(
+ block(
+ out_channels,
+ out_channels,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg))
+
+ return nn.Sequential(*layers)
+
+ def _make_stage(self, layer_config, in_channels, multiscale_output=True):
+ """Make stage."""
+ num_modules = layer_config['num_modules']
+ num_branches = layer_config['num_branches']
+ num_blocks = layer_config['num_blocks']
+ num_channels = layer_config['num_channels']
+ block = self.blocks_dict[layer_config['block']]
+
+ hr_modules = []
+ for i in range(num_modules):
+ # multi_scale_output is only used for the last module
+ if not multiscale_output and i == num_modules - 1:
+ reset_multiscale_output = False
+ else:
+ reset_multiscale_output = True
+
+ hr_modules.append(
+ HRModule(
+ num_branches,
+ block,
+ num_blocks,
+ in_channels,
+ num_channels,
+ reset_multiscale_output,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ upsample_cfg=self.upsample_cfg))
+
+ in_channels = hr_modules[-1].in_channels
+
+ return nn.Sequential(*hr_modules), in_channels
+
+ def _freeze_stages(self):
+ """Freeze parameters."""
+ if self.frozen_stages >= 0:
+ self.norm1.eval()
+ self.norm2.eval()
+
+ for m in [self.conv1, self.norm1, self.conv2, self.norm2]:
+ for param in m.parameters():
+ param.requires_grad = False
+
+ for i in range(1, self.frozen_stages + 1):
+ if i == 1:
+ m = getattr(self, 'layer1')
+ else:
+ m = getattr(self, f'stage{i}')
+
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ if i < 4:
+ m = getattr(self, f'transition{i}')
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+
+ if self.zero_init_residual:
+ for m in self.modules():
+ if isinstance(m, Bottleneck):
+ constant_init(m.norm3, 0)
+ elif isinstance(m, BasicBlock):
+ constant_init(m.norm2, 0)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ """Forward function."""
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu(x)
+ x = self.conv2(x)
+ x = self.norm2(x)
+ x = self.relu(x)
+ x = self.layer1(x)
+
+ x_list = []
+ for i in range(self.stage2_cfg['num_branches']):
+ if self.transition1[i] is not None:
+ x_list.append(self.transition1[i](x))
+ else:
+ x_list.append(x)
+ y_list = self.stage2(x_list)
+
+ x_list = []
+ for i in range(self.stage3_cfg['num_branches']):
+ if self.transition2[i] is not None:
+ x_list.append(self.transition2[i](y_list[-1]))
+ else:
+ x_list.append(y_list[i])
+ y_list = self.stage3(x_list)
+
+ x_list = []
+ for i in range(self.stage4_cfg['num_branches']):
+ if self.transition3[i] is not None:
+ x_list.append(self.transition3[i](y_list[-1]))
+ else:
+ x_list.append(y_list[i])
+ y_list = self.stage4(x_list)
+
+ return y_list
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt.py
new file mode 100644
index 0000000000000000000000000000000000000000..67be3d4429d03360698701b7cd6e67e7c7a0b4ad
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt.py
@@ -0,0 +1,676 @@
+# --------------------------------------------------------
+# High Resolution Transformer
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Written by Rao Fu, RainbowSecret
+# --------------------------------------------------------
+
+import pdb
+import torch
+import torch.nn as nn
+from mmcv.cnn import (
+ build_conv_layer,
+ build_norm_layer,
+ constant_init,
+ kaiming_init,
+ normal_init,
+)
+# from mmcv.runner import load_checkpoint
+from .hrt_checkpoint import load_checkpoint
+from mmcv.runner.checkpoint import load_state_dict
+from mmcv.utils.parrots_wrapper import _BatchNorm
+
+from mmpose.models.utils.ops import resize
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .modules.bottleneck_block import Bottleneck
+from .modules.transformer_block import GeneralTransformerBlock
+
+
+class HighResolutionTransformerModule(nn.Module):
+ def __init__(
+ self,
+ num_branches,
+ blocks,
+ num_blocks,
+ in_channels,
+ num_channels,
+ multiscale_output,
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type="BN", requires_grad=True),
+ num_heads=None,
+ num_window_sizes=None,
+ num_mlp_ratios=None,
+ drop_paths=0.0,
+ ):
+ super(HighResolutionTransformerModule, self).__init__()
+ self._check_branches(num_branches, num_blocks, in_channels, num_channels)
+
+ self.in_channels = in_channels
+ self.num_branches = num_branches
+
+ self.multiscale_output = multiscale_output
+ self.norm_cfg = norm_cfg
+ self.conv_cfg = conv_cfg
+ self.with_cp = with_cp
+ self.branches = self._make_branches(
+ num_branches,
+ blocks,
+ num_blocks,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ drop_paths,
+ )
+ self.fuse_layers = self._make_fuse_layers()
+ self.relu = nn.ReLU(inplace=True)
+
+ # MHSA parameters
+ self.num_heads = num_heads
+ self.num_window_sizes = num_window_sizes
+ self.num_mlp_ratios = num_mlp_ratios
+
+ def _check_branches(self, num_branches, num_blocks, in_channels, num_channels):
+ logger = get_root_logger()
+ if num_branches != len(num_blocks):
+ error_msg = "NUM_BRANCHES({}) <> NUM_BLOCKS({})".format(
+ num_branches, len(num_blocks)
+ )
+ logger.error(error_msg)
+ raise ValueError(error_msg)
+
+ if num_branches != len(num_channels):
+ error_msg = "NUM_BRANCHES({}) <> NUM_CHANNELS({})".format(
+ num_branches, len(num_channels)
+ )
+ logger.error(error_msg)
+ raise ValueError(error_msg)
+
+ if num_branches != len(in_channels):
+ error_msg = "NUM_BRANCHES({}) <> IN_CHANNELS({})".format(
+ num_branches, len(in_channels)
+ )
+ logger.error(error_msg)
+ raise ValueError(error_msg)
+
+ def _make_one_branch(
+ self,
+ branch_index,
+ block,
+ num_blocks,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ drop_paths,
+ stride=1,
+ ):
+ """Make one branch."""
+ downsample = None
+ if (
+ stride != 1
+ or self.in_channels[branch_index]
+ != num_channels[branch_index] * block.expansion
+ ):
+ downsample = nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ self.in_channels[branch_index],
+ num_channels[branch_index] * block.expansion,
+ kernel_size=1,
+ stride=stride,
+ bias=False,
+ ),
+ build_norm_layer(
+ self.norm_cfg, num_channels[branch_index] * block.expansion
+ )[1],
+ )
+
+ layers = []
+
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index],
+ num_heads=num_heads[branch_index],
+ window_size=num_window_sizes[branch_index],
+ mlp_ratio=num_mlp_ratios[branch_index],
+ drop_path=drop_paths[0],
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ )
+ )
+ self.in_channels[branch_index] = num_channels[branch_index] * block.expansion
+ for i in range(1, num_blocks[branch_index]):
+ layers.append(
+ block(
+ self.in_channels[branch_index],
+ num_channels[branch_index],
+ num_heads=num_heads[branch_index],
+ window_size=num_window_sizes[branch_index],
+ mlp_ratio=num_mlp_ratios[branch_index],
+ drop_path=drop_paths[i],
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ )
+ )
+
+ return nn.Sequential(*layers)
+
+ def _make_branches(
+ self,
+ num_branches,
+ block,
+ num_blocks,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ drop_paths,
+ ):
+ """Make branches."""
+ branches = []
+
+ for i in range(num_branches):
+ branches.append(
+ self._make_one_branch(
+ i,
+ block,
+ num_blocks,
+ num_channels,
+ num_heads,
+ num_window_sizes,
+ num_mlp_ratios,
+ drop_paths,
+ )
+ )
+
+ return nn.ModuleList(branches)
+
+ def _make_fuse_layers(self):
+ """Build fuse layer."""
+ if self.num_branches == 1:
+ return None
+
+ num_branches = self.num_branches
+ in_channels = self.in_channels
+ fuse_layers = []
+ num_out_branches = num_branches if self.multiscale_output else 1
+ for i in range(num_out_branches):
+ fuse_layer = []
+ for j in range(num_branches):
+ if j > i:
+ fuse_layer.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, in_channels[i])[1],
+ nn.Upsample(
+ scale_factor=2 ** (j - i),
+ mode="bilinear",
+ align_corners=False,
+ ),
+ )
+ )
+ elif j == i:
+ fuse_layer.append(None)
+ else:
+ conv_downsamples = []
+ for k in range(i - j):
+ if k == i - j - 1:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=in_channels[j],
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, in_channels[j])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=1,
+ stride=1,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, in_channels[i])[1],
+ )
+ )
+ else:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=in_channels[j],
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, in_channels[j])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=1,
+ stride=1,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, in_channels[j])[1],
+ nn.ReLU(inplace=True),
+ )
+ )
+ fuse_layer.append(nn.Sequential(*conv_downsamples))
+ fuse_layers.append(nn.ModuleList(fuse_layer))
+ return nn.ModuleList(fuse_layers)
+
+ def forward(self, x):
+ """Forward function."""
+ if self.num_branches == 1:
+ return [self.branches[0](x[0])]
+
+ for i in range(self.num_branches):
+ x[i] = self.branches[i](x[i])
+
+ x_fuse = []
+ for i in range(len(self.fuse_layers)):
+ y = x[0] if i == 0 else self.fuse_layers[i][0](x[0])
+ for j in range(1, self.num_branches):
+ if i == j:
+ y += x[j]
+ elif j > i:
+ y = y + resize(
+ self.fuse_layers[i][j](x[j]),
+ size=x[i].shape[2:],
+ mode="bilinear",
+ align_corners=False,
+ )
+ else:
+ y += self.fuse_layers[i][j](x[j])
+ x_fuse.append(self.relu(y))
+ return x_fuse
+
+
+@BACKBONES.register_module()
+class HRT(nn.Module):
+ """HRT backbone.
+ High Resolution Transformer Backbone
+ """
+
+ blocks_dict = {
+ "BOTTLENECK": Bottleneck,
+ "TRANSFORMER_BLOCK": GeneralTransformerBlock,
+ }
+
+ def __init__(
+ self,
+ extra,
+ in_channels=3,
+ conv_cfg=None,
+ norm_cfg=dict(type="BN", requires_grad=True),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=False,
+ ):
+ super(HRT, self).__init__()
+ self.extra = extra
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+ self.zero_init_residual = zero_init_residual
+
+ # stem net
+ self.norm1_name, norm1 = build_norm_layer(self.norm_cfg, 64, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(self.norm_cfg, 64, postfix=2)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ 64,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False,
+ )
+ self.add_module(self.norm1_name, norm1)
+
+ self.conv2 = build_conv_layer(
+ self.conv_cfg, 64, 64, kernel_size=3, stride=2, padding=1, bias=False
+ )
+ self.add_module(self.norm2_name, norm2)
+ self.relu = nn.ReLU(inplace=True)
+
+ # generat drop path rate list
+ depth_s2 = (
+ self.extra["stage2"]["num_blocks"][0] * self.extra["stage2"]["num_modules"]
+ )
+ depth_s3 = (
+ self.extra["stage3"]["num_blocks"][0] * self.extra["stage3"]["num_modules"]
+ )
+ depth_s4 = (
+ self.extra["stage4"]["num_blocks"][0] * self.extra["stage4"]["num_modules"]
+ )
+ depths = [depth_s2, depth_s3, depth_s4]
+ drop_path_rate = self.extra["drop_path_rate"]
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))]
+
+ logger = get_root_logger()
+ logger.info(dpr)
+
+ # stage 1
+ self.stage1_cfg = self.extra["stage1"]
+ num_channels = self.stage1_cfg["num_channels"][0]
+ block_type = self.stage1_cfg["block"]
+ num_blocks = self.stage1_cfg["num_blocks"][0]
+
+ block = self.blocks_dict[block_type]
+ stage1_out_channels = num_channels * block.expansion
+ self.layer1 = self._make_layer(block, 64, num_channels, num_blocks)
+
+ # stage 2
+ self.stage2_cfg = self.extra["stage2"]
+ num_channels = self.stage2_cfg["num_channels"]
+ block_type = self.stage2_cfg["block"]
+
+ block = self.blocks_dict[block_type]
+ num_channels = [channel * block.expansion for channel in num_channels]
+ self.transition1 = self._make_transition_layer(
+ [stage1_out_channels], num_channels
+ )
+ self.stage2, pre_stage_channels = self._make_stage(
+ self.stage2_cfg, num_channels, drop_paths=dpr[0:depth_s2]
+ )
+
+ # stage 3
+ self.stage3_cfg = self.extra["stage3"]
+ num_channels = self.stage3_cfg["num_channels"]
+ block_type = self.stage3_cfg["block"]
+
+ block = self.blocks_dict[block_type]
+ num_channels = [channel * block.expansion for channel in num_channels]
+ self.transition2 = self._make_transition_layer(pre_stage_channels, num_channels)
+ self.stage3, pre_stage_channels = self._make_stage(
+ self.stage3_cfg,
+ num_channels,
+ drop_paths=dpr[depth_s2 : depth_s2 + depth_s3],
+ )
+
+ # stage 4
+ self.stage4_cfg = self.extra["stage4"]
+ num_channels = self.stage4_cfg["num_channels"]
+ block_type = self.stage4_cfg["block"]
+
+ block = self.blocks_dict[block_type]
+ num_channels = [channel * block.expansion for channel in num_channels]
+ self.transition3 = self._make_transition_layer(pre_stage_channels, num_channels)
+ self.stage4, pre_stage_channels = self._make_stage(
+ self.stage4_cfg,
+ num_channels,
+ multiscale_output=self.stage4_cfg.get("multiscale_output", True),
+ drop_paths=dpr[depth_s2 + depth_s3 :],
+ )
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: the normalization layer named "norm2" """
+ return getattr(self, self.norm2_name)
+
+ def _make_transition_layer(self, num_channels_pre_layer, num_channels_cur_layer):
+ """Make transition layer."""
+ num_branches_cur = len(num_channels_cur_layer)
+ num_branches_pre = len(num_channels_pre_layer)
+
+ transition_layers = []
+ for i in range(num_branches_cur):
+ if i < num_branches_pre:
+ if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
+ transition_layers.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ num_channels_pre_layer[i],
+ num_channels_cur_layer[i],
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, num_channels_cur_layer[i])[
+ 1
+ ],
+ nn.ReLU(inplace=True),
+ )
+ )
+ else:
+ transition_layers.append(None)
+ else:
+ conv_downsamples = []
+ for j in range(i + 1 - num_branches_pre):
+ in_channels = num_channels_pre_layer[-1]
+ out_channels = (
+ num_channels_cur_layer[i]
+ if j == i - num_branches_pre
+ else in_channels
+ )
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, out_channels)[1],
+ nn.ReLU(inplace=True),
+ )
+ )
+ transition_layers.append(nn.Sequential(*conv_downsamples))
+
+ return nn.ModuleList(transition_layers)
+
+ def _make_layer(
+ self,
+ block,
+ inplanes,
+ planes,
+ blocks,
+ stride=1,
+ num_heads=1,
+ window_size=7,
+ mlp_ratio=4.0,
+ ):
+ """Make each layer."""
+ downsample = None
+ if stride != 1 or inplanes != planes * block.expansion:
+ downsample = nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ inplanes,
+ planes * block.expansion,
+ kernel_size=1,
+ stride=stride,
+ bias=False,
+ ),
+ build_norm_layer(self.norm_cfg, planes * block.expansion)[1],
+ )
+
+ layers = []
+ if isinstance(block, GeneralTransformerBlock):
+ layers.append(
+ block(
+ inplanes,
+ planes,
+ num_heads=num_heads,
+ window_size=window_size,
+ mlp_ratio=mlp_ratio,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ )
+ )
+ else:
+ layers.append(
+ block(
+ inplanes,
+ planes,
+ stride,
+ downsample=downsample,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ )
+ )
+ inplanes = planes * block.expansion
+ for i in range(1, blocks):
+ layers.append(
+ block(
+ inplanes,
+ planes,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ )
+ )
+
+ return nn.Sequential(*layers)
+
+ def _make_stage(
+ self, layer_config, in_channels, multiscale_output=True, drop_paths=0.0
+ ):
+ """Make each stage."""
+ num_modules = layer_config["num_modules"]
+ num_branches = layer_config["num_branches"]
+ num_blocks = layer_config["num_blocks"]
+ num_channels = layer_config["num_channels"]
+ block = self.blocks_dict[layer_config["block"]]
+
+ num_heads = layer_config["num_heads"]
+ num_window_sizes = layer_config["num_window_sizes"]
+ num_mlp_ratios = layer_config["num_mlp_ratios"]
+
+ hr_modules = []
+ for i in range(num_modules):
+ # multi_scale_output is only used for the last module
+ if not multiscale_output and i == num_modules - 1:
+ reset_multiscale_output = False
+ else:
+ reset_multiscale_output = True
+
+ hr_modules.append(
+ HighResolutionTransformerModule(
+ num_branches,
+ block,
+ num_blocks,
+ in_channels,
+ num_channels,
+ reset_multiscale_output,
+ with_cp=self.with_cp,
+ norm_cfg=self.norm_cfg,
+ conv_cfg=self.conv_cfg,
+ num_heads=num_heads,
+ num_window_sizes=num_window_sizes,
+ num_mlp_ratios=num_mlp_ratios,
+ drop_paths=drop_paths[num_blocks[0] * i : num_blocks[0] * (i + 1)],
+ )
+ )
+
+ return nn.Sequential(*hr_modules), in_channels
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ ckpt = load_checkpoint(self, pretrained, strict=False)
+ if "model" in ckpt:
+ msg = self.load_state_dict(ckpt["model"], strict=False)
+ logger.info(msg)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ """mmseg: kaiming_init(m)"""
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+
+ if self.zero_init_residual:
+ for m in self.modules():
+ if isinstance(m, Bottleneck):
+ constant_init(m.norm3, 0)
+ elif isinstance(m, BasicBlock):
+ constant_init(m.norm2, 0)
+ else:
+ raise TypeError("pretrained must be a str or None")
+
+ def forward(self, x):
+ """Forward function."""
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu(x)
+ x = self.conv2(x)
+ x = self.norm2(x)
+ x = self.relu(x)
+ x = self.layer1(x)
+
+ x_list = []
+ for i in range(self.stage2_cfg["num_branches"]):
+ if self.transition1[i] is not None:
+ x_list.append(self.transition1[i](x))
+ else:
+ x_list.append(x)
+ y_list = self.stage2(x_list)
+
+ x_list = []
+ for i in range(self.stage3_cfg["num_branches"]):
+ if self.transition2[i] is not None:
+ x_list.append(self.transition2[i](y_list[-1]))
+ else:
+ x_list.append(y_list[i])
+ y_list = self.stage3(x_list)
+
+ x_list = []
+ for i in range(self.stage4_cfg["num_branches"]):
+ if self.transition3[i] is not None:
+ x_list.append(self.transition3[i](y_list[-1]))
+ else:
+ x_list.append(y_list[i])
+ y_list = self.stage4(x_list)
+
+ return y_list
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super(HRT, self).train(mode)
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt_checkpoint.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt_checkpoint.py
new file mode 100644
index 0000000000000000000000000000000000000000..e27749d45ad2e1b24e50de8b85af90b4464e91ba
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/hrt_checkpoint.py
@@ -0,0 +1,500 @@
+# Copyright (c) Open-MMLab. All rights reserved.
+import io
+import os
+import os.path as osp
+import pkgutil
+import time
+import warnings
+from collections import OrderedDict
+from importlib import import_module
+from tempfile import TemporaryDirectory
+
+import torch
+import torchvision
+from torch.optim import Optimizer
+from torch.utils import model_zoo
+from torch.nn import functional as F
+
+import mmcv
+from mmcv.fileio import FileClient
+from mmcv.fileio import load as load_file
+from mmcv.parallel import is_module_wrapper
+from mmcv.utils import mkdir_or_exist
+from mmcv.runner import get_dist_info
+
+ENV_MMCV_HOME = 'MMCV_HOME'
+ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME'
+DEFAULT_CACHE_DIR = '~/.cache'
+
+
+def _get_mmcv_home():
+ mmcv_home = os.path.expanduser(
+ os.getenv(
+ ENV_MMCV_HOME,
+ os.path.join(
+ os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv')))
+
+ mkdir_or_exist(mmcv_home)
+ return mmcv_home
+
+
+def load_state_dict(module, state_dict, strict=False, logger=None):
+ """Load state_dict to a module.
+
+ This method is modified from :meth:`torch.nn.Module.load_state_dict`.
+ Default value for ``strict`` is set to ``False`` and the message for
+ param mismatch will be shown even if strict is False.
+
+ Args:
+ module (Module): Module that receives the state_dict.
+ state_dict (OrderedDict): Weights.
+ strict (bool): whether to strictly enforce that the keys
+ in :attr:`state_dict` match the keys returned by this module's
+ :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.
+ logger (:obj:`logging.Logger`, optional): Logger to log the error
+ message. If not specified, print function will be used.
+ """
+ unexpected_keys = []
+ all_missing_keys = []
+ err_msg = []
+
+ metadata = getattr(state_dict, '_metadata', None)
+ state_dict = state_dict.copy()
+ if metadata is not None:
+ state_dict._metadata = metadata
+
+ # use _load_from_state_dict to enable checkpoint version control
+ def load(module, prefix=''):
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_module_wrapper(module):
+ module = module.module
+ local_metadata = {} if metadata is None else metadata.get(
+ prefix[:-1], {})
+ module._load_from_state_dict(state_dict, prefix, local_metadata, True,
+ all_missing_keys, unexpected_keys,
+ err_msg)
+ for name, child in module._modules.items():
+ if child is not None:
+ load(child, prefix + name + '.')
+
+ load(module)
+ load = None # break load->load reference cycle
+
+ # ignore "num_batches_tracked" of BN layers
+ missing_keys = [
+ key for key in all_missing_keys if 'num_batches_tracked' not in key
+ ]
+
+ if unexpected_keys:
+ err_msg.append('unexpected key in source '
+ f'state_dict: {", ".join(unexpected_keys)}\n')
+ if missing_keys:
+ err_msg.append(
+ f'missing keys in source state_dict: {", ".join(missing_keys)}\n')
+
+ rank, _ = get_dist_info()
+ if len(err_msg) > 0 and rank == 0:
+ err_msg.insert(
+ 0, 'The model and loaded state dict do not match exactly\n')
+ err_msg = '\n'.join(err_msg)
+ if strict:
+ raise RuntimeError(err_msg)
+ elif logger is not None:
+ logger.warning(err_msg)
+ else:
+ print(err_msg)
+
+
+def load_url_dist(url, model_dir=None):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ if rank == 0:
+ checkpoint = model_zoo.load_url(url, model_dir=model_dir)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ checkpoint = model_zoo.load_url(url, model_dir=model_dir)
+ return checkpoint
+
+
+def load_pavimodel_dist(model_path, map_location=None):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ try:
+ from pavi import modelcloud
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ if rank == 0:
+ model = modelcloud.get(model_path)
+ with TemporaryDirectory() as tmp_dir:
+ downloaded_file = osp.join(tmp_dir, model.name)
+ model.download(downloaded_file)
+ checkpoint = torch.load(downloaded_file, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ model = modelcloud.get(model_path)
+ with TemporaryDirectory() as tmp_dir:
+ downloaded_file = osp.join(tmp_dir, model.name)
+ model.download(downloaded_file)
+ checkpoint = torch.load(
+ downloaded_file, map_location=map_location)
+ return checkpoint
+
+
+def load_fileclient_dist(filename, backend, map_location):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ allowed_backends = ['ceph']
+ if backend not in allowed_backends:
+ raise ValueError(f'Load from Backend {backend} is not supported.')
+ if rank == 0:
+ fileclient = FileClient(backend=backend)
+ buffer = io.BytesIO(fileclient.get(filename))
+ checkpoint = torch.load(buffer, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ fileclient = FileClient(backend=backend)
+ buffer = io.BytesIO(fileclient.get(filename))
+ checkpoint = torch.load(buffer, map_location=map_location)
+ return checkpoint
+
+
+def get_torchvision_models():
+ model_urls = dict()
+ for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__):
+ if ispkg:
+ continue
+ _zoo = import_module(f'torchvision.models.{name}')
+ if hasattr(_zoo, 'model_urls'):
+ _urls = getattr(_zoo, 'model_urls')
+ model_urls.update(_urls)
+ return model_urls
+
+
+def get_external_models():
+ mmcv_home = _get_mmcv_home()
+ default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json')
+ default_urls = load_file(default_json_path)
+ assert isinstance(default_urls, dict)
+ external_json_path = osp.join(mmcv_home, 'open_mmlab.json')
+ if osp.exists(external_json_path):
+ external_urls = load_file(external_json_path)
+ assert isinstance(external_urls, dict)
+ default_urls.update(external_urls)
+
+ return default_urls
+
+
+def get_mmcls_models():
+ mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json')
+ mmcls_urls = load_file(mmcls_json_path)
+
+ return mmcls_urls
+
+
+def get_deprecated_model_names():
+ deprecate_json_path = osp.join(mmcv.__path__[0],
+ 'model_zoo/deprecated.json')
+ deprecate_urls = load_file(deprecate_json_path)
+ assert isinstance(deprecate_urls, dict)
+
+ return deprecate_urls
+
+
+def _process_mmcls_checkpoint(checkpoint):
+ state_dict = checkpoint['state_dict']
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k.startswith('backbone.'):
+ new_state_dict[k[9:]] = v
+ new_checkpoint = dict(state_dict=new_state_dict)
+
+ return new_checkpoint
+
+
+def _load_checkpoint(filename, map_location=None):
+ """Load checkpoint from somewhere (modelzoo, file, url).
+
+ Args:
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str | None): Same as :func:`torch.load`. Default: None.
+
+ Returns:
+ dict | OrderedDict: The loaded checkpoint. It can be either an
+ OrderedDict storing model weights or a dict containing other
+ information, which depends on the checkpoint.
+ """
+ if filename.startswith('modelzoo://'):
+ warnings.warn('The URL scheme of "modelzoo://" is deprecated, please '
+ 'use "torchvision://" instead')
+ model_urls = get_torchvision_models()
+ model_name = filename[11:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ elif filename.startswith('torchvision://'):
+ model_urls = get_torchvision_models()
+ model_name = filename[14:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ elif filename.startswith('open-mmlab://'):
+ model_urls = get_external_models()
+ model_name = filename[13:]
+ deprecated_urls = get_deprecated_model_names()
+ if model_name in deprecated_urls:
+ warnings.warn(f'open-mmlab://{model_name} is deprecated in favor '
+ f'of open-mmlab://{deprecated_urls[model_name]}')
+ model_name = deprecated_urls[model_name]
+ model_url = model_urls[model_name]
+ # check if is url
+ if model_url.startswith(('http://', 'https://')):
+ checkpoint = load_url_dist(model_url)
+ else:
+ filename = osp.join(_get_mmcv_home(), model_url)
+ if not osp.isfile(filename):
+ raise IOError(f'{filename} is not a checkpoint file')
+ checkpoint = torch.load(filename, map_location=map_location)
+ elif filename.startswith('mmcls://'):
+ model_urls = get_mmcls_models()
+ model_name = filename[8:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ checkpoint = _process_mmcls_checkpoint(checkpoint)
+ elif filename.startswith(('http://', 'https://')):
+ checkpoint = load_url_dist(filename)
+ elif filename.startswith('pavi://'):
+ model_path = filename[7:]
+ checkpoint = load_pavimodel_dist(model_path, map_location=map_location)
+ elif filename.startswith('s3://'):
+ checkpoint = load_fileclient_dist(
+ filename, backend='ceph', map_location=map_location)
+ else:
+ if not osp.isfile(filename):
+ raise IOError(f'{filename} is not a checkpoint file')
+ checkpoint = torch.load(filename, map_location=map_location)
+ return checkpoint
+
+
+def load_checkpoint(model,
+ filename,
+ map_location='cpu',
+ strict=False,
+ logger=None):
+ """Load checkpoint from a file or URI.
+
+ Args:
+ model (Module): Module to load checkpoint.
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str): Same as :func:`torch.load`.
+ strict (bool): Whether to allow different params for the model and
+ checkpoint.
+ logger (:mod:`logging.Logger` or None): The logger for error message.
+
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ checkpoint = _load_checkpoint(filename, map_location)
+ # OrderedDict is a subclass of dict
+ if not isinstance(checkpoint, dict):
+ raise RuntimeError(
+ f'No state_dict found in checkpoint file {filename}')
+ # get state_dict from checkpoint
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ elif 'model' in checkpoint:
+ state_dict = checkpoint['model']
+ else:
+ state_dict = checkpoint
+ # strip prefix of state_dict
+ if list(state_dict.keys())[0].startswith('module.'):
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
+
+ # for MoBY, load model of online branch
+ if sorted(list(state_dict.keys()))[0].startswith('encoder'):
+ state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')}
+
+ # reshape absolute position embedding
+ if state_dict.get('absolute_pos_embed') is not None:
+ absolute_pos_embed = state_dict['absolute_pos_embed']
+ N1, L, C1 = absolute_pos_embed.size()
+ N2, C2, H, W = model.absolute_pos_embed.size()
+ if N1 != N2 or C1 != C2 or L != H*W:
+ logger.warning("Error in loading absolute_pos_embed, pass")
+ else:
+ state_dict['absolute_pos_embed'] = absolute_pos_embed.view(N2, H, W, C2).permute(0, 3, 1, 2)
+
+ # interpolate position bias table if needed
+ # relative_position_bias_table_keys = [k for k in state_dict.keys() if "relative_position_bias_table" in k]
+ # for table_key in relative_position_bias_table_keys:
+ # table_pretrained = state_dict[table_key]
+ # table_current = model.state_dict()[table_key]
+ # L1, nH1 = table_pretrained.size()
+ # L2, nH2 = table_current.size()
+ # if nH1 != nH2:
+ # logger.warning(f"Error in loading {table_key}, pass")
+ # else:
+ # if L1 != L2:
+ # S1 = int(L1 ** 0.5)
+ # S2 = int(L2 ** 0.5)
+ # table_pretrained_resized = F.interpolate(
+ # table_pretrained.permute(1, 0).view(1, nH1, S1, S1),
+ # size=(S2, S2), mode='bicubic')
+ # state_dict[table_key] = table_pretrained_resized.view(nH2, L2).permute(1, 0)
+
+ # load state_dict
+ load_state_dict(model, state_dict, strict, logger)
+ return checkpoint
+
+
+def weights_to_cpu(state_dict):
+ """Copy a model state_dict to cpu.
+
+ Args:
+ state_dict (OrderedDict): Model weights on GPU.
+
+ Returns:
+ OrderedDict: Model weights on GPU.
+ """
+ state_dict_cpu = OrderedDict()
+ for key, val in state_dict.items():
+ state_dict_cpu[key] = val.cpu()
+ return state_dict_cpu
+
+
+def _save_to_state_dict(module, destination, prefix, keep_vars):
+ """Saves module state to `destination` dictionary.
+
+ This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.
+
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (dict): A dict where state will be stored.
+ prefix (str): The prefix for parameters and buffers used in this
+ module.
+ """
+ for name, param in module._parameters.items():
+ if param is not None:
+ destination[prefix + name] = param if keep_vars else param.detach()
+ for name, buf in module._buffers.items():
+ # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d
+ if buf is not None:
+ destination[prefix + name] = buf if keep_vars else buf.detach()
+
+
+def get_state_dict(module, destination=None, prefix='', keep_vars=False):
+ """Returns a dictionary containing a whole state of the module.
+
+ Both parameters and persistent buffers (e.g. running averages) are
+ included. Keys are corresponding parameter and buffer names.
+
+ This method is modified from :meth:`torch.nn.Module.state_dict` to
+ recursively check parallel module in case that the model has a complicated
+ structure, e.g., nn.Module(nn.Module(DDP)).
+
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (OrderedDict): Returned dict for the state of the
+ module.
+ prefix (str): Prefix of the key.
+ keep_vars (bool): Whether to keep the variable property of the
+ parameters. Default: False.
+
+ Returns:
+ dict: A dictionary containing a whole state of the module.
+ """
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_module_wrapper(module):
+ module = module.module
+
+ # below is the same as torch.nn.Module.state_dict()
+ if destination is None:
+ destination = OrderedDict()
+ destination._metadata = OrderedDict()
+ destination._metadata[prefix[:-1]] = local_metadata = dict(
+ version=module._version)
+ _save_to_state_dict(module, destination, prefix, keep_vars)
+ for name, child in module._modules.items():
+ if child is not None:
+ get_state_dict(
+ child, destination, prefix + name + '.', keep_vars=keep_vars)
+ for hook in module._state_dict_hooks.values():
+ hook_result = hook(module, destination, prefix, local_metadata)
+ if hook_result is not None:
+ destination = hook_result
+ return destination
+
+
+def save_checkpoint(model, filename, optimizer=None, meta=None):
+ """Save checkpoint to file.
+
+ The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
+ ``optimizer``. By default ``meta`` will contain version and time info.
+
+ Args:
+ model (Module): Module whose params are to be saved.
+ filename (str): Checkpoint filename.
+ optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
+ meta (dict, optional): Metadata to be saved in checkpoint.
+ """
+ if meta is None:
+ meta = {}
+ elif not isinstance(meta, dict):
+ raise TypeError(f'meta must be a dict or None, but got {type(meta)}')
+ meta.update(mmcv_version=mmcv.__version__, time=time.asctime())
+
+ if is_module_wrapper(model):
+ model = model.module
+
+ if hasattr(model, 'CLASSES') and model.CLASSES is not None:
+ # save class name to the meta
+ meta.update(CLASSES=model.CLASSES)
+
+ checkpoint = {
+ 'meta': meta,
+ 'state_dict': weights_to_cpu(get_state_dict(model))
+ }
+ # save optimizer state dict in the checkpoint
+ if isinstance(optimizer, Optimizer):
+ checkpoint['optimizer'] = optimizer.state_dict()
+ elif isinstance(optimizer, dict):
+ checkpoint['optimizer'] = {}
+ for name, optim in optimizer.items():
+ checkpoint['optimizer'][name] = optim.state_dict()
+
+ if filename.startswith('pavi://'):
+ try:
+ from pavi import modelcloud
+ from pavi.exception import NodeNotFoundError
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+ model_path = filename[7:]
+ root = modelcloud.Folder()
+ model_dir, model_name = osp.split(model_path)
+ try:
+ model = modelcloud.get(model_dir)
+ except NodeNotFoundError:
+ model = root.create_training_model(model_dir)
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint_file = osp.join(tmp_dir, model_name)
+ with open(checkpoint_file, 'wb') as f:
+ torch.save(checkpoint, f)
+ f.flush()
+ model.create_file(checkpoint_file, name=model_name)
+ else:
+ mmcv.mkdir_or_exist(osp.dirname(filename))
+ # immediately flush buffer
+ with open(filename, 'wb') as f:
+ torch.save(checkpoint, f)
+ f.flush()
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/i3d.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/i3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f330abac1facc16db743ef3ffbcd23248d6865
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/i3d.py
@@ -0,0 +1,215 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+# Code is modified from `Third-party pytorch implementation of i3d
+# `.
+
+import torch
+import torch.nn as nn
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class Conv3dBlock(nn.Module):
+ """Basic 3d convolution block for I3D.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (float): The multiplier of in_channels and out_channels.
+ Default: 1.
+ kernel_size (tuple[int]): kernel size of the 3d convolution layer.
+ Default: (1, 1, 1).
+ stride (tuple[int]): stride of the block. Default: (1, 1, 1)
+ padding (tuple[int]): padding of the input tensor. Default: (0, 0, 0)
+ use_bias (bool): whether to enable bias in 3d convolution layer.
+ Default: False
+ use_bn (bool): whether to use Batch Normalization after 3d convolution
+ layer. Default: True
+ use_relu (bool): whether to use ReLU after Batch Normalization layer.
+ Default: True
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ expansion=1.0,
+ kernel_size=(1, 1, 1),
+ stride=(1, 1, 1),
+ padding=(0, 0, 0),
+ use_bias=False,
+ use_bn=True,
+ use_relu=True):
+ super().__init__()
+
+ in_channels = int(in_channels * expansion)
+ out_channels = int(out_channels * expansion)
+
+ self.conv3d = nn.Conv3d(
+ in_channels,
+ out_channels,
+ kernel_size,
+ padding=padding,
+ stride=stride,
+ bias=use_bias)
+
+ self.use_bn = use_bn
+ self.use_relu = use_relu
+
+ if self.use_bn:
+ self.batch3d = nn.BatchNorm3d(out_channels)
+
+ if self.use_relu:
+ self.activation = nn.ReLU(inplace=True)
+
+ def forward(self, x):
+ """Forward function."""
+ out = self.conv3d(x)
+ if self.use_bn:
+ out = self.batch3d(out)
+ if self.use_relu:
+ out = self.activation(out)
+ return out
+
+
+class Mixed(nn.Module):
+ """Inception block for I3D.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (float): The multiplier of in_channels and out_channels.
+ Default: 1.
+ """
+
+ def __init__(self, in_channels, out_channels, expansion=1.0):
+ super(Mixed, self).__init__()
+ # Branch 0
+ self.branch_0 = Conv3dBlock(
+ in_channels, out_channels[0], expansion, kernel_size=(1, 1, 1))
+
+ # Branch 1
+ branch_1_conv1 = Conv3dBlock(
+ in_channels, out_channels[1], expansion, kernel_size=(1, 1, 1))
+ branch_1_conv2 = Conv3dBlock(
+ out_channels[1],
+ out_channels[2],
+ expansion,
+ kernel_size=(3, 3, 3),
+ padding=(1, 1, 1))
+ self.branch_1 = nn.Sequential(branch_1_conv1, branch_1_conv2)
+
+ # Branch 2
+ branch_2_conv1 = Conv3dBlock(
+ in_channels, out_channels[3], expansion, kernel_size=(1, 1, 1))
+ branch_2_conv2 = Conv3dBlock(
+ out_channels[3],
+ out_channels[4],
+ expansion,
+ kernel_size=(3, 3, 3),
+ padding=(1, 1, 1))
+ self.branch_2 = nn.Sequential(branch_2_conv1, branch_2_conv2)
+
+ # Branch3
+ branch_3_pool = nn.MaxPool3d(
+ kernel_size=(3, 3, 3),
+ stride=(1, 1, 1),
+ padding=(1, 1, 1),
+ ceil_mode=True)
+ branch_3_conv2 = Conv3dBlock(
+ in_channels, out_channels[5], expansion, kernel_size=(1, 1, 1))
+ self.branch_3 = nn.Sequential(branch_3_pool, branch_3_conv2)
+
+ def forward(self, x):
+ """Forward function."""
+ out_0 = self.branch_0(x)
+ out_1 = self.branch_1(x)
+ out_2 = self.branch_2(x)
+ out_3 = self.branch_3(x)
+ out = torch.cat((out_0, out_1, out_2, out_3), 1)
+ return out
+
+
+@BACKBONES.register_module()
+class I3D(BaseBackbone):
+ """I3D backbone.
+
+ Please refer to the `paper `__ for
+ details.
+
+ Args:
+ in_channels (int): Input channels of the backbone, which is decided
+ on the input modality.
+ expansion (float): The multiplier of in_channels and out_channels.
+ Default: 1.
+ """
+
+ def __init__(self, in_channels=3, expansion=1.0):
+ super(I3D, self).__init__()
+
+ # expansion must be an integer multiple of 1/8
+ expansion = round(8 * expansion) / 8.0
+
+ # xut Layer
+ self.conv3d_1a_7x7 = Conv3dBlock(
+ out_channels=64,
+ in_channels=in_channels / expansion,
+ expansion=expansion,
+ kernel_size=(7, 7, 7),
+ stride=(2, 2, 2),
+ padding=(2, 3, 3))
+ self.maxPool3d_2a_3x3 = nn.MaxPool3d(
+ kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))
+
+ # Layer 2
+ self.conv3d_2b_1x1 = Conv3dBlock(
+ out_channels=64,
+ in_channels=64,
+ expansion=expansion,
+ kernel_size=(1, 1, 1))
+ self.conv3d_2c_3x3 = Conv3dBlock(
+ out_channels=192,
+ in_channels=64,
+ expansion=expansion,
+ kernel_size=(3, 3, 3),
+ padding=(1, 1, 1))
+ self.maxPool3d_3a_3x3 = nn.MaxPool3d(
+ kernel_size=(1, 3, 3), stride=(1, 2, 2), padding=(0, 1, 1))
+
+ # Mixed_3b
+ self.mixed_3b = Mixed(192, [64, 96, 128, 16, 32, 32], expansion)
+ self.mixed_3c = Mixed(256, [128, 128, 192, 32, 96, 64], expansion)
+ self.maxPool3d_4a_3x3 = nn.MaxPool3d(
+ kernel_size=(3, 3, 3), stride=(2, 2, 2), padding=(1, 1, 1))
+
+ # Mixed 4
+ self.mixed_4b = Mixed(480, [192, 96, 208, 16, 48, 64], expansion)
+ self.mixed_4c = Mixed(512, [160, 112, 224, 24, 64, 64], expansion)
+ self.mixed_4d = Mixed(512, [128, 128, 256, 24, 64, 64], expansion)
+ self.mixed_4e = Mixed(512, [112, 144, 288, 32, 64, 64], expansion)
+ self.mixed_4f = Mixed(528, [256, 160, 320, 32, 128, 128], expansion)
+
+ self.maxPool3d_5a_2x2 = nn.MaxPool3d(
+ kernel_size=(2, 2, 2), stride=(2, 2, 2), padding=(0, 0, 0))
+
+ # Mixed 5
+ self.mixed_5b = Mixed(832, [256, 160, 320, 32, 128, 128], expansion)
+ self.mixed_5c = Mixed(832, [384, 192, 384, 48, 128, 128], expansion)
+
+ def forward(self, x):
+ out = self.conv3d_1a_7x7(x)
+ out = self.maxPool3d_2a_3x3(out)
+ out = self.conv3d_2b_1x1(out)
+ out = self.conv3d_2c_3x3(out)
+ out = self.maxPool3d_3a_3x3(out)
+ out = self.mixed_3b(out)
+ out = self.mixed_3c(out)
+ out = self.maxPool3d_4a_3x3(out)
+ out = self.mixed_4b(out)
+ out = self.mixed_4c(out)
+ out = self.mixed_4d(out)
+ out = self.mixed_4e(out)
+ out = self.mixed_4f(out)
+ out = self.maxPool3d_5a_2x2(out)
+ out = self.mixed_5b(out)
+ out = self.mixed_5c(out)
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/litehrnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/litehrnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..954368841eb631e3dc6c77e9810f6980f3739bf3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/litehrnet.py
@@ -0,0 +1,984 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/HRNet/Lite-HRNet
+# Original licence: Apache License 2.0.
+# ------------------------------------------------------------------------------
+
+import mmcv
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+from mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule,
+ build_conv_layer, build_norm_layer, constant_init,
+ normal_init)
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .utils import channel_shuffle, load_checkpoint
+
+
+class SpatialWeighting(nn.Module):
+ """Spatial weighting module.
+
+ Args:
+ channels (int): The channels of the module.
+ ratio (int): channel reduction ratio.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ act_cfg (dict): Config dict for activation layer.
+ Default: (dict(type='ReLU'), dict(type='Sigmoid')).
+ The last ConvModule uses Sigmoid by default.
+ """
+
+ def __init__(self,
+ channels,
+ ratio=16,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=(dict(type='ReLU'), dict(type='Sigmoid'))):
+ super().__init__()
+ if isinstance(act_cfg, dict):
+ act_cfg = (act_cfg, act_cfg)
+ assert len(act_cfg) == 2
+ assert mmcv.is_tuple_of(act_cfg, dict)
+ self.global_avgpool = nn.AdaptiveAvgPool2d(1)
+ self.conv1 = ConvModule(
+ in_channels=channels,
+ out_channels=int(channels / ratio),
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg[0])
+ self.conv2 = ConvModule(
+ in_channels=int(channels / ratio),
+ out_channels=channels,
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg[1])
+
+ def forward(self, x):
+ out = self.global_avgpool(x)
+ out = self.conv1(out)
+ out = self.conv2(out)
+ return x * out
+
+
+class CrossResolutionWeighting(nn.Module):
+ """Cross-resolution channel weighting module.
+
+ Args:
+ channels (int): The channels of the module.
+ ratio (int): channel reduction ratio.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ act_cfg (dict): Config dict for activation layer.
+ Default: (dict(type='ReLU'), dict(type='Sigmoid')).
+ The last ConvModule uses Sigmoid by default.
+ """
+
+ def __init__(self,
+ channels,
+ ratio=16,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=(dict(type='ReLU'), dict(type='Sigmoid'))):
+ super().__init__()
+ if isinstance(act_cfg, dict):
+ act_cfg = (act_cfg, act_cfg)
+ assert len(act_cfg) == 2
+ assert mmcv.is_tuple_of(act_cfg, dict)
+ self.channels = channels
+ total_channel = sum(channels)
+ self.conv1 = ConvModule(
+ in_channels=total_channel,
+ out_channels=int(total_channel / ratio),
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg[0])
+ self.conv2 = ConvModule(
+ in_channels=int(total_channel / ratio),
+ out_channels=total_channel,
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg[1])
+
+ def forward(self, x):
+ mini_size = x[-1].size()[-2:]
+ out = [F.adaptive_avg_pool2d(s, mini_size) for s in x[:-1]] + [x[-1]]
+ out = torch.cat(out, dim=1)
+ out = self.conv1(out)
+ out = self.conv2(out)
+ out = torch.split(out, self.channels, dim=1)
+ out = [
+ s * F.interpolate(a, size=s.size()[-2:], mode='nearest')
+ for s, a in zip(x, out)
+ ]
+ return out
+
+
+class ConditionalChannelWeighting(nn.Module):
+ """Conditional channel weighting block.
+
+ Args:
+ in_channels (int): The input channels of the block.
+ stride (int): Stride of the 3x3 convolution layer.
+ reduce_ratio (int): channel reduction ratio.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ in_channels,
+ stride,
+ reduce_ratio,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ with_cp=False):
+ super().__init__()
+ self.with_cp = with_cp
+ self.stride = stride
+ assert stride in [1, 2]
+
+ branch_channels = [channel // 2 for channel in in_channels]
+
+ self.cross_resolution_weighting = CrossResolutionWeighting(
+ branch_channels,
+ ratio=reduce_ratio,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg)
+
+ self.depthwise_convs = nn.ModuleList([
+ ConvModule(
+ channel,
+ channel,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ groups=channel,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None) for channel in branch_channels
+ ])
+
+ self.spatial_weighting = nn.ModuleList([
+ SpatialWeighting(channels=channel, ratio=4)
+ for channel in branch_channels
+ ])
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ x = [s.chunk(2, dim=1) for s in x]
+ x1 = [s[0] for s in x]
+ x2 = [s[1] for s in x]
+
+ x2 = self.cross_resolution_weighting(x2)
+ x2 = [dw(s) for s, dw in zip(x2, self.depthwise_convs)]
+ x2 = [sw(s) for s, sw in zip(x2, self.spatial_weighting)]
+
+ out = [torch.cat([s1, s2], dim=1) for s1, s2 in zip(x1, x2)]
+ out = [channel_shuffle(s, 2) for s in out]
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+class Stem(nn.Module):
+ """Stem network block.
+
+ Args:
+ in_channels (int): The input channels of the block.
+ stem_channels (int): Output channels of the stem layer.
+ out_channels (int): The output channels of the block.
+ expand_ratio (int): adjusts number of channels of the hidden layer
+ in InvertedResidual by this amount.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ in_channels,
+ stem_channels,
+ out_channels,
+ expand_ratio,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ with_cp=False):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.with_cp = with_cp
+
+ self.conv1 = ConvModule(
+ in_channels=in_channels,
+ out_channels=stem_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=dict(type='ReLU'))
+
+ mid_channels = int(round(stem_channels * expand_ratio))
+ branch_channels = stem_channels // 2
+ if stem_channels == self.out_channels:
+ inc_channels = self.out_channels - branch_channels
+ else:
+ inc_channels = self.out_channels - stem_channels
+
+ self.branch1 = nn.Sequential(
+ ConvModule(
+ branch_channels,
+ branch_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=branch_channels,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None),
+ ConvModule(
+ branch_channels,
+ inc_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='ReLU')),
+ )
+
+ self.expand_conv = ConvModule(
+ branch_channels,
+ mid_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='ReLU'))
+ self.depthwise_conv = ConvModule(
+ mid_channels,
+ mid_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=mid_channels,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+ self.linear_conv = ConvModule(
+ mid_channels,
+ branch_channels
+ if stem_channels == self.out_channels else stem_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='ReLU'))
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ x = self.conv1(x)
+ x1, x2 = x.chunk(2, dim=1)
+
+ x2 = self.expand_conv(x2)
+ x2 = self.depthwise_conv(x2)
+ x2 = self.linear_conv(x2)
+
+ out = torch.cat((self.branch1(x1), x2), dim=1)
+
+ out = channel_shuffle(out, 2)
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+class IterativeHead(nn.Module):
+ """Extra iterative head for feature learning.
+
+ Args:
+ in_channels (int): The input channels of the block.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ """
+
+ def __init__(self, in_channels, norm_cfg=dict(type='BN')):
+ super().__init__()
+ projects = []
+ num_branchs = len(in_channels)
+ self.in_channels = in_channels[::-1]
+
+ for i in range(num_branchs):
+ if i != num_branchs - 1:
+ projects.append(
+ DepthwiseSeparableConvModule(
+ in_channels=self.in_channels[i],
+ out_channels=self.in_channels[i + 1],
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='ReLU'),
+ dw_act_cfg=None,
+ pw_act_cfg=dict(type='ReLU')))
+ else:
+ projects.append(
+ DepthwiseSeparableConvModule(
+ in_channels=self.in_channels[i],
+ out_channels=self.in_channels[i],
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='ReLU'),
+ dw_act_cfg=None,
+ pw_act_cfg=dict(type='ReLU')))
+ self.projects = nn.ModuleList(projects)
+
+ def forward(self, x):
+ x = x[::-1]
+
+ y = []
+ last_x = None
+ for i, s in enumerate(x):
+ if last_x is not None:
+ last_x = F.interpolate(
+ last_x,
+ size=s.size()[-2:],
+ mode='bilinear',
+ align_corners=True)
+ s = s + last_x
+ s = self.projects[i](s)
+ y.append(s)
+ last_x = s
+
+ return y[::-1]
+
+
+class ShuffleUnit(nn.Module):
+ """InvertedResidual block for ShuffleNetV2 backbone.
+
+ Args:
+ in_channels (int): The input channels of the block.
+ out_channels (int): The output channels of the block.
+ stride (int): Stride of the 3x3 convolution layer. Default: 1
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ stride=1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ with_cp=False):
+ super().__init__()
+ self.stride = stride
+ self.with_cp = with_cp
+
+ branch_features = out_channels // 2
+ if self.stride == 1:
+ assert in_channels == branch_features * 2, (
+ f'in_channels ({in_channels}) should equal to '
+ f'branch_features * 2 ({branch_features * 2}) '
+ 'when stride is 1')
+
+ if in_channels != branch_features * 2:
+ assert self.stride != 1, (
+ f'stride ({self.stride}) should not equal 1 when '
+ f'in_channels != branch_features * 2')
+
+ if self.stride > 1:
+ self.branch1 = nn.Sequential(
+ ConvModule(
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ groups=in_channels,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None),
+ ConvModule(
+ in_channels,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ )
+
+ self.branch2 = nn.Sequential(
+ ConvModule(
+ in_channels if (self.stride > 1) else branch_features,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ ConvModule(
+ branch_features,
+ branch_features,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ groups=branch_features,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None),
+ ConvModule(
+ branch_features,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ if self.stride > 1:
+ out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
+ else:
+ x1, x2 = x.chunk(2, dim=1)
+ out = torch.cat((x1, self.branch2(x2)), dim=1)
+
+ out = channel_shuffle(out, 2)
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+class LiteHRModule(nn.Module):
+ """High-Resolution Module for LiteHRNet.
+
+ It contains conditional channel weighting blocks and
+ shuffle blocks.
+
+
+ Args:
+ num_branches (int): Number of branches in the module.
+ num_blocks (int): Number of blocks in the module.
+ in_channels (list(int)): Number of input image channels.
+ reduce_ratio (int): Channel reduction ratio.
+ module_type (str): 'LITE' or 'NAIVE'
+ multiscale_output (bool): Whether to output multi-scale features.
+ with_fuse (bool): Whether to use fuse layers.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ """
+
+ def __init__(
+ self,
+ num_branches,
+ num_blocks,
+ in_channels,
+ reduce_ratio,
+ module_type,
+ multiscale_output=False,
+ with_fuse=True,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ with_cp=False,
+ ):
+ super().__init__()
+ self._check_branches(num_branches, in_channels)
+
+ self.in_channels = in_channels
+ self.num_branches = num_branches
+
+ self.module_type = module_type
+ self.multiscale_output = multiscale_output
+ self.with_fuse = with_fuse
+ self.norm_cfg = norm_cfg
+ self.conv_cfg = conv_cfg
+ self.with_cp = with_cp
+
+ if self.module_type.upper() == 'LITE':
+ self.layers = self._make_weighting_blocks(num_blocks, reduce_ratio)
+ elif self.module_type.upper() == 'NAIVE':
+ self.layers = self._make_naive_branches(num_branches, num_blocks)
+ else:
+ raise ValueError("module_type should be either 'LITE' or 'NAIVE'.")
+ if self.with_fuse:
+ self.fuse_layers = self._make_fuse_layers()
+ self.relu = nn.ReLU()
+
+ def _check_branches(self, num_branches, in_channels):
+ """Check input to avoid ValueError."""
+ if num_branches != len(in_channels):
+ error_msg = f'NUM_BRANCHES({num_branches}) ' \
+ f'!= NUM_INCHANNELS({len(in_channels)})'
+ raise ValueError(error_msg)
+
+ def _make_weighting_blocks(self, num_blocks, reduce_ratio, stride=1):
+ """Make channel weighting blocks."""
+ layers = []
+ for i in range(num_blocks):
+ layers.append(
+ ConditionalChannelWeighting(
+ self.in_channels,
+ stride=stride,
+ reduce_ratio=reduce_ratio,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ with_cp=self.with_cp))
+
+ return nn.Sequential(*layers)
+
+ def _make_one_branch(self, branch_index, num_blocks, stride=1):
+ """Make one branch."""
+ layers = []
+ layers.append(
+ ShuffleUnit(
+ self.in_channels[branch_index],
+ self.in_channels[branch_index],
+ stride=stride,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=dict(type='ReLU'),
+ with_cp=self.with_cp))
+ for i in range(1, num_blocks):
+ layers.append(
+ ShuffleUnit(
+ self.in_channels[branch_index],
+ self.in_channels[branch_index],
+ stride=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=dict(type='ReLU'),
+ with_cp=self.with_cp))
+
+ return nn.Sequential(*layers)
+
+ def _make_naive_branches(self, num_branches, num_blocks):
+ """Make branches."""
+ branches = []
+
+ for i in range(num_branches):
+ branches.append(self._make_one_branch(i, num_blocks))
+
+ return nn.ModuleList(branches)
+
+ def _make_fuse_layers(self):
+ """Make fuse layer."""
+ if self.num_branches == 1:
+ return None
+
+ num_branches = self.num_branches
+ in_channels = self.in_channels
+ fuse_layers = []
+ num_out_branches = num_branches if self.multiscale_output else 1
+ for i in range(num_out_branches):
+ fuse_layer = []
+ for j in range(num_branches):
+ if j > i:
+ fuse_layer.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg, in_channels[i])[1],
+ nn.Upsample(
+ scale_factor=2**(j - i), mode='nearest')))
+ elif j == i:
+ fuse_layer.append(None)
+ else:
+ conv_downsamples = []
+ for k in range(i - j):
+ if k == i - j - 1:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=in_channels[j],
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[j])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[i],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[i])[1]))
+ else:
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=in_channels[j],
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[j])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels[j],
+ in_channels[j],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ in_channels[j])[1],
+ nn.ReLU(inplace=True)))
+ fuse_layer.append(nn.Sequential(*conv_downsamples))
+ fuse_layers.append(nn.ModuleList(fuse_layer))
+
+ return nn.ModuleList(fuse_layers)
+
+ def forward(self, x):
+ """Forward function."""
+ if self.num_branches == 1:
+ return [self.layers[0](x[0])]
+
+ if self.module_type.upper() == 'LITE':
+ out = self.layers(x)
+ elif self.module_type.upper() == 'NAIVE':
+ for i in range(self.num_branches):
+ x[i] = self.layers[i](x[i])
+ out = x
+
+ if self.with_fuse:
+ out_fuse = []
+ for i in range(len(self.fuse_layers)):
+ # `y = 0` will lead to decreased accuracy (0.5~1 mAP)
+ y = out[0] if i == 0 else self.fuse_layers[i][0](out[0])
+ for j in range(self.num_branches):
+ if i == j:
+ y += out[j]
+ else:
+ y += self.fuse_layers[i][j](out[j])
+ out_fuse.append(self.relu(y))
+ out = out_fuse
+ if not self.multiscale_output:
+ out = [out[0]]
+ return out
+
+
+@BACKBONES.register_module()
+class LiteHRNet(nn.Module):
+ """Lite-HRNet backbone.
+
+ `Lite-HRNet: A Lightweight High-Resolution Network
+ `_.
+
+ Code adapted from 'https://github.com/HRNet/Lite-HRNet'.
+
+ Args:
+ extra (dict): detailed configuration for each stage of HRNet.
+ in_channels (int): Number of input image channels. Default: 3.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+
+ Example:
+ >>> from mmpose.models import LiteHRNet
+ >>> import torch
+ >>> extra=dict(
+ >>> stem=dict(stem_channels=32, out_channels=32, expand_ratio=1),
+ >>> num_stages=3,
+ >>> stages_spec=dict(
+ >>> num_modules=(2, 4, 2),
+ >>> num_branches=(2, 3, 4),
+ >>> num_blocks=(2, 2, 2),
+ >>> module_type=('LITE', 'LITE', 'LITE'),
+ >>> with_fuse=(True, True, True),
+ >>> reduce_ratios=(8, 8, 8),
+ >>> num_channels=(
+ >>> (40, 80),
+ >>> (40, 80, 160),
+ >>> (40, 80, 160, 320),
+ >>> )),
+ >>> with_head=False)
+ >>> self = LiteHRNet(extra, in_channels=1)
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 1, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 40, 8, 8)
+ """
+
+ def __init__(self,
+ extra,
+ in_channels=3,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ norm_eval=False,
+ with_cp=False):
+ super().__init__()
+ self.extra = extra
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ self.stem = Stem(
+ in_channels,
+ stem_channels=self.extra['stem']['stem_channels'],
+ out_channels=self.extra['stem']['out_channels'],
+ expand_ratio=self.extra['stem']['expand_ratio'],
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg)
+
+ self.num_stages = self.extra['num_stages']
+ self.stages_spec = self.extra['stages_spec']
+
+ num_channels_last = [
+ self.stem.out_channels,
+ ]
+ for i in range(self.num_stages):
+ num_channels = self.stages_spec['num_channels'][i]
+ num_channels = [num_channels[i] for i in range(len(num_channels))]
+ setattr(
+ self, f'transition{i}',
+ self._make_transition_layer(num_channels_last, num_channels))
+
+ stage, num_channels_last = self._make_stage(
+ self.stages_spec, i, num_channels, multiscale_output=True)
+ setattr(self, f'stage{i}', stage)
+
+ self.with_head = self.extra['with_head']
+ if self.with_head:
+ self.head_layer = IterativeHead(
+ in_channels=num_channels_last,
+ norm_cfg=self.norm_cfg,
+ )
+
+ def _make_transition_layer(self, num_channels_pre_layer,
+ num_channels_cur_layer):
+ """Make transition layer."""
+ num_branches_cur = len(num_channels_cur_layer)
+ num_branches_pre = len(num_channels_pre_layer)
+
+ transition_layers = []
+ for i in range(num_branches_cur):
+ if i < num_branches_pre:
+ if num_channels_cur_layer[i] != num_channels_pre_layer[i]:
+ transition_layers.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ num_channels_pre_layer[i],
+ num_channels_pre_layer[i],
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ groups=num_channels_pre_layer[i],
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ num_channels_pre_layer[i])[1],
+ build_conv_layer(
+ self.conv_cfg,
+ num_channels_pre_layer[i],
+ num_channels_cur_layer[i],
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg,
+ num_channels_cur_layer[i])[1],
+ nn.ReLU()))
+ else:
+ transition_layers.append(None)
+ else:
+ conv_downsamples = []
+ for j in range(i + 1 - num_branches_pre):
+ in_channels = num_channels_pre_layer[-1]
+ out_channels = num_channels_cur_layer[i] \
+ if j == i - num_branches_pre else in_channels
+ conv_downsamples.append(
+ nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ groups=in_channels,
+ bias=False),
+ build_norm_layer(self.norm_cfg, in_channels)[1],
+ build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=False),
+ build_norm_layer(self.norm_cfg, out_channels)[1],
+ nn.ReLU()))
+ transition_layers.append(nn.Sequential(*conv_downsamples))
+
+ return nn.ModuleList(transition_layers)
+
+ def _make_stage(self,
+ stages_spec,
+ stage_index,
+ in_channels,
+ multiscale_output=True):
+ num_modules = stages_spec['num_modules'][stage_index]
+ num_branches = stages_spec['num_branches'][stage_index]
+ num_blocks = stages_spec['num_blocks'][stage_index]
+ reduce_ratio = stages_spec['reduce_ratios'][stage_index]
+ with_fuse = stages_spec['with_fuse'][stage_index]
+ module_type = stages_spec['module_type'][stage_index]
+
+ modules = []
+ for i in range(num_modules):
+ # multi_scale_output is only used last module
+ if not multiscale_output and i == num_modules - 1:
+ reset_multiscale_output = False
+ else:
+ reset_multiscale_output = True
+
+ modules.append(
+ LiteHRModule(
+ num_branches,
+ num_blocks,
+ in_channels,
+ reduce_ratio,
+ module_type,
+ multiscale_output=reset_multiscale_output,
+ with_fuse=with_fuse,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ with_cp=self.with_cp))
+ in_channels = modules[-1].in_channels
+
+ return nn.Sequential(*modules), in_channels
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ """Forward function."""
+ x = self.stem(x)
+
+ y_list = [x]
+ for i in range(self.num_stages):
+ x_list = []
+ transition = getattr(self, f'transition{i}')
+ for j in range(self.stages_spec['num_branches'][i]):
+ if transition[j]:
+ if j >= len(y_list):
+ x_list.append(transition[j](y_list[-1]))
+ else:
+ x_list.append(transition[j](y_list[j]))
+ else:
+ x_list.append(y_list[j])
+ y_list = getattr(self, f'stage{i}')(x_list)
+
+ x = y_list
+ if self.with_head:
+ x = self.head_layer(x)
+
+ return [x[0]]
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v2.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dc0cd1b7dfdec2aa751861e39fc1c1a45ec488e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v2.py
@@ -0,0 +1,275 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import ConvModule, constant_init, kaiming_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import load_checkpoint, make_divisible
+
+
+class InvertedResidual(nn.Module):
+ """InvertedResidual block for MobileNetV2.
+
+ Args:
+ in_channels (int): The input channels of the InvertedResidual block.
+ out_channels (int): The output channels of the InvertedResidual block.
+ stride (int): Stride of the middle (first) 3x3 convolution.
+ expand_ratio (int): adjusts number of channels of the hidden layer
+ in InvertedResidual by this amount.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU6').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ stride,
+ expand_ratio,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU6'),
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.stride = stride
+ assert stride in [1, 2], f'stride must in [1, 2]. ' \
+ f'But received {stride}.'
+ self.with_cp = with_cp
+ self.use_res_connect = self.stride == 1 and in_channels == out_channels
+ hidden_dim = int(round(in_channels * expand_ratio))
+
+ layers = []
+ if expand_ratio != 1:
+ layers.append(
+ ConvModule(
+ in_channels=in_channels,
+ out_channels=hidden_dim,
+ kernel_size=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+ layers.extend([
+ ConvModule(
+ in_channels=hidden_dim,
+ out_channels=hidden_dim,
+ kernel_size=3,
+ stride=stride,
+ padding=1,
+ groups=hidden_dim,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ ConvModule(
+ in_channels=hidden_dim,
+ out_channels=out_channels,
+ kernel_size=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+ ])
+ self.conv = nn.Sequential(*layers)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ if self.use_res_connect:
+ return x + self.conv(x)
+ return self.conv(x)
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+@BACKBONES.register_module()
+class MobileNetV2(BaseBackbone):
+ """MobileNetV2 backbone.
+
+ Args:
+ widen_factor (float): Width multiplier, multiply number of
+ channels in each layer by this amount. Default: 1.0.
+ out_indices (None or Sequence[int]): Output from which stages.
+ Default: (7, ).
+ frozen_stages (int): Stages to be frozen (all param fixed).
+ Default: -1, which means not freezing any parameters.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU6').
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ # Parameters to build layers. 4 parameters are needed to construct a
+ # layer, from left to right: expand_ratio, channel, num_blocks, stride.
+ arch_settings = [[1, 16, 1, 1], [6, 24, 2, 2], [6, 32, 3, 2],
+ [6, 64, 4, 2], [6, 96, 3, 1], [6, 160, 3, 2],
+ [6, 320, 1, 1]]
+
+ def __init__(self,
+ widen_factor=1.,
+ out_indices=(7, ),
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU6'),
+ norm_eval=False,
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.widen_factor = widen_factor
+ self.out_indices = out_indices
+ for index in out_indices:
+ if index not in range(0, 8):
+ raise ValueError('the item in out_indices must in '
+ f'range(0, 8). But received {index}')
+
+ if frozen_stages not in range(-1, 8):
+ raise ValueError('frozen_stages must be in range(-1, 8). '
+ f'But received {frozen_stages}')
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.act_cfg = act_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ self.in_channels = make_divisible(32 * widen_factor, 8)
+
+ self.conv1 = ConvModule(
+ in_channels=3,
+ out_channels=self.in_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=self.act_cfg)
+
+ self.layers = []
+
+ for i, layer_cfg in enumerate(self.arch_settings):
+ expand_ratio, channel, num_blocks, stride = layer_cfg
+ out_channels = make_divisible(channel * widen_factor, 8)
+ inverted_res_layer = self.make_layer(
+ out_channels=out_channels,
+ num_blocks=num_blocks,
+ stride=stride,
+ expand_ratio=expand_ratio)
+ layer_name = f'layer{i + 1}'
+ self.add_module(layer_name, inverted_res_layer)
+ self.layers.append(layer_name)
+
+ if widen_factor > 1.0:
+ self.out_channel = int(1280 * widen_factor)
+ else:
+ self.out_channel = 1280
+
+ layer = ConvModule(
+ in_channels=self.in_channels,
+ out_channels=self.out_channel,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=self.act_cfg)
+ self.add_module('conv2', layer)
+ self.layers.append('conv2')
+
+ def make_layer(self, out_channels, num_blocks, stride, expand_ratio):
+ """Stack InvertedResidual blocks to build a layer for MobileNetV2.
+
+ Args:
+ out_channels (int): out_channels of block.
+ num_blocks (int): number of blocks.
+ stride (int): stride of the first block. Default: 1
+ expand_ratio (int): Expand the number of channels of the
+ hidden layer in InvertedResidual by this ratio. Default: 6.
+ """
+ layers = []
+ for i in range(num_blocks):
+ if i >= 1:
+ stride = 1
+ layers.append(
+ InvertedResidual(
+ self.in_channels,
+ out_channels,
+ stride,
+ expand_ratio=expand_ratio,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=self.act_cfg,
+ with_cp=self.with_cp))
+ self.in_channels = out_channels
+
+ return nn.Sequential(*layers)
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ x = self.conv1(x)
+
+ outs = []
+ for i, layer_name in enumerate(self.layers):
+ layer = getattr(self, layer_name)
+ x = layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ for param in self.conv1.parameters():
+ param.requires_grad = False
+ for i in range(1, self.frozen_stages + 1):
+ layer = getattr(self, f'layer{i}')
+ layer.eval()
+ for param in layer.parameters():
+ param.requires_grad = False
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v3.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..d640abec79f06d689f2d4bc1e92999946bc07261
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mobilenet_v3.py
@@ -0,0 +1,188 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+
+import torch.nn as nn
+from mmcv.cnn import ConvModule, constant_init, kaiming_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import InvertedResidual, load_checkpoint
+
+
+@BACKBONES.register_module()
+class MobileNetV3(BaseBackbone):
+ """MobileNetV3 backbone.
+
+ Args:
+ arch (str): Architecture of mobilnetv3, from {small, big}.
+ Default: small.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ out_indices (None or Sequence[int]): Output from which stages.
+ Default: (-1, ), which means output tensors from final stage.
+ frozen_stages (int): Stages to be frozen (all param fixed).
+ Default: -1, which means not freezing any parameters.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save
+ some memory while slowing down the training speed.
+ Default: False.
+ """
+ # Parameters to build each block:
+ # [kernel size, mid channels, out channels, with_se, act type, stride]
+ arch_settings = {
+ 'small': [[3, 16, 16, True, 'ReLU', 2],
+ [3, 72, 24, False, 'ReLU', 2],
+ [3, 88, 24, False, 'ReLU', 1],
+ [5, 96, 40, True, 'HSwish', 2],
+ [5, 240, 40, True, 'HSwish', 1],
+ [5, 240, 40, True, 'HSwish', 1],
+ [5, 120, 48, True, 'HSwish', 1],
+ [5, 144, 48, True, 'HSwish', 1],
+ [5, 288, 96, True, 'HSwish', 2],
+ [5, 576, 96, True, 'HSwish', 1],
+ [5, 576, 96, True, 'HSwish', 1]],
+ 'big': [[3, 16, 16, False, 'ReLU', 1],
+ [3, 64, 24, False, 'ReLU', 2],
+ [3, 72, 24, False, 'ReLU', 1],
+ [5, 72, 40, True, 'ReLU', 2],
+ [5, 120, 40, True, 'ReLU', 1],
+ [5, 120, 40, True, 'ReLU', 1],
+ [3, 240, 80, False, 'HSwish', 2],
+ [3, 200, 80, False, 'HSwish', 1],
+ [3, 184, 80, False, 'HSwish', 1],
+ [3, 184, 80, False, 'HSwish', 1],
+ [3, 480, 112, True, 'HSwish', 1],
+ [3, 672, 112, True, 'HSwish', 1],
+ [5, 672, 160, True, 'HSwish', 1],
+ [5, 672, 160, True, 'HSwish', 2],
+ [5, 960, 160, True, 'HSwish', 1]]
+ } # yapf: disable
+
+ def __init__(self,
+ arch='small',
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ out_indices=(-1, ),
+ frozen_stages=-1,
+ norm_eval=False,
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ assert arch in self.arch_settings
+ for index in out_indices:
+ if index not in range(-len(self.arch_settings[arch]),
+ len(self.arch_settings[arch])):
+ raise ValueError('the item in out_indices must in '
+ f'range(0, {len(self.arch_settings[arch])}). '
+ f'But received {index}')
+
+ if frozen_stages not in range(-1, len(self.arch_settings[arch])):
+ raise ValueError('frozen_stages must be in range(-1, '
+ f'{len(self.arch_settings[arch])}). '
+ f'But received {frozen_stages}')
+ self.arch = arch
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ self.in_channels = 16
+ self.conv1 = ConvModule(
+ in_channels=3,
+ out_channels=self.in_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type='HSwish'))
+
+ self.layers = self._make_layer()
+ self.feat_dim = self.arch_settings[arch][-1][2]
+
+ def _make_layer(self):
+ layers = []
+ layer_setting = self.arch_settings[self.arch]
+ for i, params in enumerate(layer_setting):
+ (kernel_size, mid_channels, out_channels, with_se, act,
+ stride) = params
+ if with_se:
+ se_cfg = dict(
+ channels=mid_channels,
+ ratio=4,
+ act_cfg=(dict(type='ReLU'), dict(type='HSigmoid')))
+ else:
+ se_cfg = None
+
+ layer = InvertedResidual(
+ in_channels=self.in_channels,
+ out_channels=out_channels,
+ mid_channels=mid_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ se_cfg=se_cfg,
+ with_expand_conv=True,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=dict(type=act),
+ with_cp=self.with_cp)
+ self.in_channels = out_channels
+ layer_name = f'layer{i + 1}'
+ self.add_module(layer_name, layer)
+ layers.append(layer_name)
+ return layers
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ x = self.conv1(x)
+
+ outs = []
+ for i, layer_name in enumerate(self.layers):
+ layer = getattr(self, layer_name)
+ x = layer(x)
+ if i in self.out_indices or \
+ i - len(self.layers) in self.out_indices:
+ outs.append(x)
+
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ for param in self.conv1.parameters():
+ param.requires_grad = False
+ for i in range(1, self.frozen_stages + 1):
+ layer = getattr(self, f'layer{i}')
+ layer.eval()
+ for param in layer.parameters():
+ param.requires_grad = False
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/basic_block.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/basic_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..44feef44dfc43a7b40b82752d9a82df35f1108ba
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/basic_block.py
@@ -0,0 +1,126 @@
+# --------------------------------------------------------
+# High Resolution Transformer
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Written by Rao Fu, RainbowSecret
+# --------------------------------------------------------
+
+import os
+import copy
+import logging
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+from .transformer_block import TransformerBlock
+
+from mmcv.cnn import (
+ build_conv_layer,
+ build_norm_layer,
+ build_plugin_layer,
+ constant_init,
+ kaiming_init,
+)
+
+
+class BasicBlock(nn.Module):
+ """Only replce the second 3x3 Conv with the TransformerBlocker"""
+
+ expansion = 1
+
+ def __init__(
+ self,
+ inplanes,
+ planes,
+ stride=1,
+ downsample=None,
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type="BN"),
+ mhsa_flag=False,
+ num_heads=1,
+ num_halo_block=1,
+ num_mlp_ratio=4,
+ num_sr_ratio=1,
+ with_rpe=False,
+ with_ffn=True,
+ ):
+ super(BasicBlock, self).__init__()
+ norm_cfg = copy.deepcopy(norm_cfg)
+
+ self.in_channels = inplanes
+ self.out_channels = planes
+ self.stride = stride
+ self.with_cp = with_cp
+ self.downsample = downsample
+
+ self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
+
+ self.conv1 = build_conv_layer(
+ conv_cfg,
+ inplanes,
+ planes,
+ 3,
+ stride=stride,
+ padding=1,
+ dilation=1,
+ bias=False,
+ )
+ self.add_module(self.norm1_name, norm1)
+
+ if not mhsa_flag:
+ self.conv2 = build_conv_layer(
+ conv_cfg, planes, planes, 3, padding=1, bias=False
+ )
+ self.add_module(self.norm2_name, norm2)
+ else:
+ self.conv2 = TransformerBlock(
+ planes,
+ num_heads=num_heads,
+ mlp_ratio=num_mlp_ratio,
+ sr_ratio=num_sr_ratio,
+ input_resolution=num_resolution,
+ with_rpe=with_rpe,
+ with_ffn=with_ffn,
+ )
+
+ self.relu = nn.ReLU(inplace=True)
+
+ @property
+ def norm1(self):
+ """nn.Module: normalization layer after the first convolution layer"""
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: normalization layer after the second convolution layer"""
+ return getattr(self, self.norm2_name)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/bottleneck_block.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/bottleneck_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ccd11c24b3e10391fd751ca8a7b7e571acd7aee
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/bottleneck_block.py
@@ -0,0 +1,122 @@
+# --------------------------------------------------------
+# High Resolution Transformer
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Written by Rao Fu, RainbowSecret
+# --------------------------------------------------------
+
+import os
+import copy
+import logging
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+
+class Bottleneck(nn.Module):
+ expansion = 4
+
+ def __init__(
+ self,
+ inplanes,
+ planes,
+ stride=1,
+ downsample=None,
+ with_cp=None,
+ norm_cfg=dict(type="BN"),
+ conv_cfg=None,
+ ):
+ super(Bottleneck, self).__init__()
+ norm_cfg = copy.deepcopy(norm_cfg)
+
+ self.in_channels = inplanes
+ self.out_channels = planes
+ self.stride = stride
+ self.with_cp = with_cp
+ self.downsample = downsample
+
+ self.conv1_stride = 1
+ self.conv2_stride = stride
+
+ self.norm1_name, norm1 = build_norm_layer(norm_cfg, planes, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(norm_cfg, planes, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ norm_cfg, planes * self.expansion, postfix=3
+ )
+
+ self.conv1 = build_conv_layer(
+ conv_cfg,
+ inplanes,
+ planes,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False,
+ )
+ self.add_module(self.norm1_name, norm1)
+
+ self.conv2 = build_conv_layer(
+ conv_cfg,
+ planes,
+ planes,
+ kernel_size=3,
+ stride=self.conv2_stride,
+ padding=1,
+ bias=False,
+ )
+ self.add_module(self.norm2_name, norm2)
+
+ self.conv3 = build_conv_layer(
+ conv_cfg, planes, planes * self.expansion, kernel_size=1, bias=False
+ )
+ self.add_module(self.norm3_name, norm3)
+ self.relu = nn.ReLU(inplace=True)
+
+ @property
+ def norm1(self):
+ """nn.Module: normalization layer after the first convolution layer"""
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: normalization layer after the second convolution layer"""
+ return getattr(self, self.norm2_name)
+
+ @property
+ def norm3(self):
+ """nn.Module: normalization layer after the third convolution layer"""
+ return getattr(self, self.norm3_name)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+ out = self.relu(out)
+
+ out = self.conv3(out)
+ out = self.norm3(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/ffn_block.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/ffn_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..00ef023334a3eb2ff4eb7172b4b75131d7c08262
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/ffn_block.py
@@ -0,0 +1,195 @@
+# --------------------------------------------------------
+# High Resolution Transformer
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Written by Rao Fu, RainbowSecret
+# --------------------------------------------------------
+
+import torch
+import torch.nn as nn
+
+
+class Mlp(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x, H, W):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class MlpDW(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ dw_act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Conv2d(in_features, hidden_features, kernel_size=1)
+ self.act1 = act_layer()
+ self.dw3x3 = nn.Conv2d(
+ hidden_features,
+ hidden_features,
+ kernel_size=3,
+ stride=1,
+ groups=hidden_features,
+ padding=1,
+ )
+ self.act2 = dw_act_layer()
+ self.fc2 = nn.Conv2d(hidden_features, out_features, kernel_size=1)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x, H, W):
+ B, N, C = x.shape
+
+ if N == (H * W + 1):
+ cls_tokens = x[:, 0, :]
+ x_ = x[:, 1:, :].permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+ else:
+ x_ = x.permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+
+ x_ = self.fc1(x_)
+ x_ = self.act1(x_)
+ x_ = self.dw3x3(x_)
+ x_ = self.act2(x_)
+ x_ = self.drop(x_)
+ x_ = self.fc2(x_)
+ x_ = self.drop(x_)
+ x_ = x_.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+
+ if N == (H * W + 1):
+ x = torch.cat((cls_tokens.unsqueeze(1), x_), dim=1)
+ else:
+ x = x_
+
+ return x
+
+
+class MlpDWBN(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ dw_act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Conv2d(in_features, hidden_features, kernel_size=1)
+ self.act1 = act_layer()
+ self.norm1 = nn.BatchNorm2d(hidden_features)
+ self.dw3x3 = nn.Conv2d(
+ hidden_features,
+ hidden_features,
+ kernel_size=3,
+ stride=1,
+ groups=hidden_features,
+ padding=1,
+ )
+ self.act2 = dw_act_layer()
+ self.norm2 = nn.BatchNorm2d(hidden_features)
+ self.fc2 = nn.Conv2d(hidden_features, out_features, kernel_size=1)
+ self.act3 = act_layer()
+ self.norm3 = nn.BatchNorm2d(out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x, H, W):
+ B, N, C = x.shape
+
+ if N == (H * W + 1):
+ cls_tokens = x[:, 0, :]
+ x_ = x[:, 1:, :].permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+ else:
+ x_ = x.permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+
+ x_ = self.fc1(x_)
+ x_ = self.norm1(x_)
+ x_ = self.act1(x_)
+ x_ = self.dw3x3(x_)
+ x_ = self.norm2(x_)
+ x_ = self.act2(x_)
+ x_ = self.drop(x_)
+ x_ = self.fc2(x_)
+ x_ = self.norm3(x_)
+ x_ = self.act3(x_)
+ x_ = self.drop(x_)
+ x_ = x_.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+
+ if N == (H * W + 1):
+ x = torch.cat((cls_tokens.unsqueeze(1), x_), dim=1)
+ else:
+ x = x_
+
+ return x
+
+
+class MlpDWBN2D(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ dw_act_layer=nn.GELU,
+ drop=0.0,
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Conv2d(in_features, hidden_features, kernel_size=1)
+ self.act1 = act_layer()
+ self.norm1 = nn.BatchNorm2d(hidden_features)
+ self.dw3x3 = nn.Conv2d(
+ hidden_features,
+ hidden_features,
+ kernel_size=3,
+ stride=1,
+ groups=hidden_features,
+ padding=1,
+ )
+ self.act2 = dw_act_layer()
+ self.norm2 = nn.BatchNorm2d(hidden_features)
+ self.fc2 = nn.Conv2d(hidden_features, out_features, kernel_size=1)
+ self.act3 = act_layer()
+ self.norm3 = nn.BatchNorm2d(out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.norm1(x)
+ x = self.act1(x)
+ x = self.dw3x3(x)
+ x = self.norm2(x)
+ x = self.act2(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.norm3(x)
+ x = self.act3(x)
+ x = self.drop(x)
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_attention.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..d726ea377a407bdb4e8cf5d0bc44a371a1e3545b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_attention.py
@@ -0,0 +1,348 @@
+# --------------------------------------------------------
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Modified by RainbowSecret from:
+# https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/activation.py#L852
+# --------------------------------------------------------
+
+import copy
+import math
+import warnings
+import torch
+import torch.nn.functional as F
+from torch import nn, Tensor
+from torch.nn.modules.module import Module
+from torch._jit_internal import Optional, Tuple
+from torch.overrides import has_torch_function, handle_torch_function
+from torch.nn.functional import linear, pad, softmax, dropout
+
+
+class MultiheadAttention(Module):
+ bias_k: Optional[torch.Tensor]
+ bias_v: Optional[torch.Tensor]
+
+ def __init__(
+ self,
+ embed_dim,
+ num_heads,
+ dropout=0.0,
+ bias=True,
+ add_bias_kv=False,
+ add_zero_attn=False,
+ kdim=None,
+ vdim=None,
+ ):
+ super(MultiheadAttention, self).__init__()
+ self.embed_dim = embed_dim
+ self.kdim = kdim if kdim is not None else embed_dim
+ self.vdim = vdim if vdim is not None else embed_dim
+ self._qkv_same_embed_dim = self.kdim == embed_dim and self.vdim == embed_dim
+
+ self.num_heads = num_heads
+ self.dropout = dropout
+ self.head_dim = embed_dim // num_heads
+ assert (
+ self.head_dim * num_heads == self.embed_dim
+ ), "embed_dim must be divisible by num_heads"
+
+ self.k_proj = nn.Linear(self.kdim, embed_dim, bias=bias)
+ self.v_proj = nn.Linear(self.vdim, embed_dim, bias=bias)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
+ self.out_proj = nn.Linear(embed_dim, embed_dim)
+
+ self.in_proj_bias = None
+ self.in_proj_weight = None
+ self.bias_k = self.bias_v = None
+ self.q_proj_weight = None
+ self.k_proj_weight = None
+ self.v_proj_weight = None
+ self.add_zero_attn = add_zero_attn
+
+ def __setstate__(self, state):
+ # Support loading old MultiheadAttention checkpoints generated by v1.1.0
+ if "_qkv_same_embed_dim" not in state:
+ state["_qkv_same_embed_dim"] = True
+
+ super(MultiheadAttention, self).__setstate__(state)
+
+ def forward(
+ self,
+ query,
+ key,
+ value,
+ key_padding_mask=None,
+ need_weights=False,
+ attn_mask=None,
+ residual_attn=None,
+ ):
+ if not self._qkv_same_embed_dim:
+ return self.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ self.in_proj_weight,
+ self.in_proj_bias,
+ self.bias_k,
+ self.bias_v,
+ self.add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ training=self.training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ use_separate_proj_weight=True,
+ q_proj_weight=self.q_proj_weight,
+ k_proj_weight=self.k_proj_weight,
+ v_proj_weight=self.v_proj_weight,
+ out_dim=self.vdim,
+ residual_attn=residual_attn,
+ )
+ else:
+ return self.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ self.in_proj_weight,
+ self.in_proj_bias,
+ self.bias_k,
+ self.bias_v,
+ self.add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ training=self.training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ out_dim=self.vdim,
+ residual_attn=residual_attn,
+ )
+
+ def multi_head_attention_forward(
+ self,
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ embed_dim_to_check: int,
+ num_heads: int,
+ in_proj_weight: Tensor,
+ in_proj_bias: Tensor,
+ bias_k: Optional[Tensor],
+ bias_v: Optional[Tensor],
+ add_zero_attn: bool,
+ dropout_p: float,
+ out_proj_weight: Tensor,
+ out_proj_bias: Tensor,
+ training: bool = True,
+ key_padding_mask: Optional[Tensor] = None,
+ need_weights: bool = False,
+ attn_mask: Optional[Tensor] = None,
+ use_separate_proj_weight: bool = False,
+ q_proj_weight: Optional[Tensor] = None,
+ k_proj_weight: Optional[Tensor] = None,
+ v_proj_weight: Optional[Tensor] = None,
+ static_k: Optional[Tensor] = None,
+ static_v: Optional[Tensor] = None,
+ out_dim: Optional[Tensor] = None,
+ residual_attn: Optional[Tensor] = None,
+ ) -> Tuple[Tensor, Optional[Tensor]]:
+ if not torch.jit.is_scripting():
+ tens_ops = (
+ query,
+ key,
+ value,
+ in_proj_weight,
+ in_proj_bias,
+ bias_k,
+ bias_v,
+ out_proj_weight,
+ out_proj_bias,
+ )
+ if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(
+ tens_ops
+ ):
+ return handle_torch_function(
+ multi_head_attention_forward,
+ tens_ops,
+ query,
+ key,
+ value,
+ embed_dim_to_check,
+ num_heads,
+ in_proj_weight,
+ in_proj_bias,
+ bias_k,
+ bias_v,
+ add_zero_attn,
+ dropout_p,
+ out_proj_weight,
+ out_proj_bias,
+ training=training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ use_separate_proj_weight=use_separate_proj_weight,
+ q_proj_weight=q_proj_weight,
+ k_proj_weight=k_proj_weight,
+ v_proj_weight=v_proj_weight,
+ static_k=static_k,
+ static_v=static_v,
+ )
+ tgt_len, bsz, embed_dim = query.size()
+ key = query if key is None else key
+ value = query if value is None else value
+
+ assert embed_dim == embed_dim_to_check
+ # allow MHA to have different sizes for the feature dimension
+ assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
+
+ head_dim = embed_dim // num_heads
+ v_head_dim = out_dim // num_heads
+ assert (
+ head_dim * num_heads == embed_dim
+ ), "embed_dim must be divisible by num_heads"
+ scaling = float(head_dim) ** -0.5
+
+ q = self.q_proj(query) * scaling
+ k = self.k_proj(key)
+ v = self.v_proj(value)
+
+ if attn_mask is not None:
+ assert (
+ attn_mask.dtype == torch.float32
+ or attn_mask.dtype == torch.float64
+ or attn_mask.dtype == torch.float16
+ or attn_mask.dtype == torch.uint8
+ or attn_mask.dtype == torch.bool
+ ), "Only float, byte, and bool types are supported for attn_mask, not {}".format(
+ attn_mask.dtype
+ )
+ if attn_mask.dtype == torch.uint8:
+ warnings.warn(
+ "Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
+ )
+ attn_mask = attn_mask.to(torch.bool)
+
+ if attn_mask.dim() == 2:
+ attn_mask = attn_mask.unsqueeze(0)
+ if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
+ raise RuntimeError("The size of the 2D attn_mask is not correct.")
+ elif attn_mask.dim() == 3:
+ if list(attn_mask.size()) != [
+ bsz * num_heads,
+ query.size(0),
+ key.size(0),
+ ]:
+ raise RuntimeError("The size of the 3D attn_mask is not correct.")
+ else:
+ raise RuntimeError(
+ "attn_mask's dimension {} is not supported".format(attn_mask.dim())
+ )
+
+ # convert ByteTensor key_padding_mask to bool
+ if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
+ warnings.warn(
+ "Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
+ )
+ key_padding_mask = key_padding_mask.to(torch.bool)
+
+ q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
+ if k is not None:
+ k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
+ if v is not None:
+ v = v.contiguous().view(-1, bsz * num_heads, v_head_dim).transpose(0, 1)
+
+ src_len = k.size(1)
+
+ if key_padding_mask is not None:
+ assert key_padding_mask.size(0) == bsz
+ assert key_padding_mask.size(1) == src_len
+
+ if add_zero_attn:
+ src_len += 1
+ k = torch.cat(
+ [
+ k,
+ torch.zeros(
+ (k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device
+ ),
+ ],
+ dim=1,
+ )
+ v = torch.cat(
+ [
+ v,
+ torch.zeros(
+ (v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device
+ ),
+ ],
+ dim=1,
+ )
+ if attn_mask is not None:
+ attn_mask = pad(attn_mask, (0, 1))
+ if key_padding_mask is not None:
+ key_padding_mask = pad(key_padding_mask, (0, 1))
+
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
+ assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len]
+
+ """
+ Attention weight for the invalid region is -inf
+ """
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_output_weights.masked_fill_(attn_mask, float("-inf"))
+ else:
+ attn_output_weights += attn_mask
+
+ if key_padding_mask is not None:
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ )
+ attn_output_weights = attn_output_weights.masked_fill(
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
+ float("-inf"),
+ )
+ attn_output_weights = attn_output_weights.view(
+ bsz * num_heads, tgt_len, src_len
+ )
+
+ if residual_attn is not None:
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ )
+ attn_output_weights += residual_attn.unsqueeze(0)
+ attn_output_weights = attn_output_weights.view(
+ bsz * num_heads, tgt_len, src_len
+ )
+
+ """
+ Reweight the attention map before softmax().
+ attn_output_weights: (b*n_head, n, hw)
+ """
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
+ attn_output_weights = dropout(
+ attn_output_weights, p=dropout_p, training=training
+ )
+
+ attn_output = torch.bmm(attn_output_weights, v)
+ assert list(attn_output.size()) == [bsz * num_heads, tgt_len, v_head_dim]
+ attn_output = (
+ attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, out_dim)
+ )
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
+
+ if need_weights:
+ # average attention weights over heads
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ )
+ return attn_output, attn_output_weights.sum(dim=1) / num_heads
+ else:
+ return attn_output
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_attention.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..deb25dfa96cc592cc58c825dc0eccd726c1592ed
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_attention.py
@@ -0,0 +1,435 @@
+# --------------------------------------------------------
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Modified by Lang Huang, RainbowSecret from:
+# https://github.com/openseg-group/openseg.pytorch/blob/master/lib/models/modules/isa_block.py
+# --------------------------------------------------------
+
+
+import copy
+import math
+import warnings
+import torch
+from torch import nn, Tensor
+from torch.nn import functional as F
+from torch._jit_internal import Optional, Tuple
+from torch.overrides import has_torch_function, handle_torch_function
+from torch.nn.functional import linear, pad, softmax, dropout
+
+from einops import rearrange
+from timm.models.layers import to_2tuple, trunc_normal_
+
+from .multihead_attention import MultiheadAttention
+
+
+class MHA_(MultiheadAttention):
+ """ "Multihead Attention with extra flags on the q/k/v and out projections."""
+
+ bias_k: Optional[torch.Tensor]
+ bias_v: Optional[torch.Tensor]
+
+ def __init__(self, *args, rpe=False, window_size=7, **kwargs):
+ super(MHA_, self).__init__(*args, **kwargs)
+
+ self.rpe = rpe
+ if rpe:
+ self.window_size = [window_size] * 2
+ # define a parameter table of relative position bias
+ # self.relative_position_bias_table = nn.Parameter(
+ # torch.zeros(
+ # (2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1),
+ # self.num_heads,
+ # )
+ # ) # 2*Wh-1 * 2*Ww-1, nH
+ # get pair-wise relative position index for each token inside the window
+ coords_h = torch.arange(self.window_size[0])
+ coords_w = torch.arange(self.window_size[1])
+ coords = torch.stack(torch.meshgrid([coords_h, coords_w])) # 2, Wh, Ww
+ coords_flatten = torch.flatten(coords, 1) # 2, Wh*Ww
+ relative_coords = (
+ coords_flatten[:, :, None] - coords_flatten[:, None, :]
+ ) # 2, Wh*Ww, Wh*Ww
+ relative_coords = relative_coords.permute(
+ 1, 2, 0
+ ).contiguous() # Wh*Ww, Wh*Ww, 2
+ relative_coords[:, :, 0] += self.window_size[0] - 1 # shift to start from 0
+ relative_coords[:, :, 1] += self.window_size[1] - 1
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
+ relative_position_index = relative_coords.sum(-1) # Wh*Ww, Wh*Ww
+ self.register_buffer("relative_position_index", relative_position_index)
+ # trunc_normal_(self.relative_position_bias_table, std=0.02)
+
+ def forward(
+ self,
+ query,
+ key,
+ value,
+ key_padding_mask=None,
+ need_weights=False,
+ attn_mask=None,
+ do_qkv_proj=True,
+ do_out_proj=True,
+ rpe=True,
+ ):
+ if not self._qkv_same_embed_dim:
+ return self.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ self.in_proj_weight,
+ self.in_proj_bias,
+ self.bias_k,
+ self.bias_v,
+ self.add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ training=self.training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ use_separate_proj_weight=True,
+ q_proj_weight=self.q_proj_weight,
+ k_proj_weight=self.k_proj_weight,
+ v_proj_weight=self.v_proj_weight,
+ out_dim=self.vdim,
+ do_qkv_proj=do_qkv_proj,
+ do_out_proj=do_out_proj,
+ rpe=rpe,
+ )
+ else:
+ return self.multi_head_attention_forward(
+ query,
+ key,
+ value,
+ self.embed_dim,
+ self.num_heads,
+ self.in_proj_weight,
+ self.in_proj_bias,
+ self.bias_k,
+ self.bias_v,
+ self.add_zero_attn,
+ self.dropout,
+ self.out_proj.weight,
+ self.out_proj.bias,
+ training=self.training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ out_dim=self.vdim,
+ do_qkv_proj=do_qkv_proj,
+ do_out_proj=do_out_proj,
+ rpe=rpe,
+ )
+
+ def multi_head_attention_forward(
+ self,
+ query: Tensor,
+ key: Tensor,
+ value: Tensor,
+ embed_dim_to_check: int,
+ num_heads: int,
+ in_proj_weight: Tensor,
+ in_proj_bias: Tensor,
+ bias_k: Optional[Tensor],
+ bias_v: Optional[Tensor],
+ add_zero_attn: bool,
+ dropout_p: float,
+ out_proj_weight: Tensor,
+ out_proj_bias: Tensor,
+ training: bool = True,
+ key_padding_mask: Optional[Tensor] = None,
+ need_weights: bool = False,
+ attn_mask: Optional[Tensor] = None,
+ use_separate_proj_weight: bool = False,
+ q_proj_weight: Optional[Tensor] = None,
+ k_proj_weight: Optional[Tensor] = None,
+ v_proj_weight: Optional[Tensor] = None,
+ static_k: Optional[Tensor] = None,
+ static_v: Optional[Tensor] = None,
+ out_dim: Optional[Tensor] = None,
+ do_qkv_proj: bool = True,
+ do_out_proj: bool = True,
+ rpe=True,
+ ) -> Tuple[Tensor, Optional[Tensor]]:
+ if not torch.jit.is_scripting():
+ tens_ops = (
+ query,
+ key,
+ value,
+ in_proj_weight,
+ in_proj_bias,
+ bias_k,
+ bias_v,
+ out_proj_weight,
+ out_proj_bias,
+ )
+ if any([type(t) is not Tensor for t in tens_ops]) and has_torch_function(
+ tens_ops
+ ):
+ return handle_torch_function(
+ multi_head_attention_forward,
+ tens_ops,
+ query,
+ key,
+ value,
+ embed_dim_to_check,
+ num_heads,
+ in_proj_weight,
+ in_proj_bias,
+ bias_k,
+ bias_v,
+ add_zero_attn,
+ dropout_p,
+ out_proj_weight,
+ out_proj_bias,
+ training=training,
+ key_padding_mask=key_padding_mask,
+ need_weights=need_weights,
+ attn_mask=attn_mask,
+ use_separate_proj_weight=use_separate_proj_weight,
+ q_proj_weight=q_proj_weight,
+ k_proj_weight=k_proj_weight,
+ v_proj_weight=v_proj_weight,
+ static_k=static_k,
+ static_v=static_v,
+ )
+ tgt_len, bsz, embed_dim = query.size()
+ key = query if key is None else key
+ value = query if value is None else value
+
+ assert embed_dim == embed_dim_to_check
+ # allow MHA to have different sizes for the feature dimension
+ assert key.size(0) == value.size(0) and key.size(1) == value.size(1)
+
+ head_dim = embed_dim // num_heads
+ v_head_dim = out_dim // num_heads
+ assert (
+ head_dim * num_heads == embed_dim
+ ), "embed_dim must be divisible by num_heads"
+ scaling = float(head_dim) ** -0.5
+
+ # whether or not use the original query/key/value
+ q = self.q_proj(query) * scaling if do_qkv_proj else query
+ k = self.k_proj(key) if do_qkv_proj else key
+ v = self.v_proj(value) if do_qkv_proj else value
+
+ if attn_mask is not None:
+ assert (
+ attn_mask.dtype == torch.float32
+ or attn_mask.dtype == torch.float64
+ or attn_mask.dtype == torch.float16
+ or attn_mask.dtype == torch.uint8
+ or attn_mask.dtype == torch.bool
+ ), "Only float, byte, and bool types are supported for attn_mask, not {}".format(
+ attn_mask.dtype
+ )
+ if attn_mask.dtype == torch.uint8:
+ warnings.warn(
+ "Byte tensor for attn_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
+ )
+ attn_mask = attn_mask.to(torch.bool)
+
+ if attn_mask.dim() == 2:
+ attn_mask = attn_mask.unsqueeze(0)
+ if list(attn_mask.size()) != [1, query.size(0), key.size(0)]:
+ raise RuntimeError("The size of the 2D attn_mask is not correct.")
+ elif attn_mask.dim() == 3:
+ if list(attn_mask.size()) != [
+ bsz * num_heads,
+ query.size(0),
+ key.size(0),
+ ]:
+ raise RuntimeError("The size of the 3D attn_mask is not correct.")
+ else:
+ raise RuntimeError(
+ "attn_mask's dimension {} is not supported".format(attn_mask.dim())
+ )
+
+ # convert ByteTensor key_padding_mask to bool
+ if key_padding_mask is not None and key_padding_mask.dtype == torch.uint8:
+ warnings.warn(
+ "Byte tensor for key_padding_mask in nn.MultiheadAttention is deprecated. Use bool tensor instead."
+ )
+ key_padding_mask = key_padding_mask.to(torch.bool)
+
+ q = q.contiguous().view(tgt_len, bsz * num_heads, head_dim).transpose(0, 1)
+ if k is not None:
+ k = k.contiguous().view(-1, bsz * num_heads, head_dim).transpose(0, 1)
+ if v is not None:
+ v = v.contiguous().view(-1, bsz * num_heads, v_head_dim).transpose(0, 1)
+
+ src_len = k.size(1)
+
+ if key_padding_mask is not None:
+ assert key_padding_mask.size(0) == bsz
+ assert key_padding_mask.size(1) == src_len
+
+ if add_zero_attn:
+ src_len += 1
+ k = torch.cat(
+ [
+ k,
+ torch.zeros(
+ (k.size(0), 1) + k.size()[2:], dtype=k.dtype, device=k.device
+ ),
+ ],
+ dim=1,
+ )
+ v = torch.cat(
+ [
+ v,
+ torch.zeros(
+ (v.size(0), 1) + v.size()[2:], dtype=v.dtype, device=v.device
+ ),
+ ],
+ dim=1,
+ )
+ if attn_mask is not None:
+ attn_mask = pad(attn_mask, (0, 1))
+ if key_padding_mask is not None:
+ key_padding_mask = pad(key_padding_mask, (0, 1))
+
+ attn_output_weights = torch.bmm(q, k.transpose(1, 2))
+ assert list(attn_output_weights.size()) == [bsz * num_heads, tgt_len, src_len]
+
+ """
+ Add relative position embedding
+ """
+ if self.rpe and rpe:
+ # NOTE: for simplicity, we assume the src_len == tgt_len == window_size**2 here
+ # print('src, tar, window', src_len, tgt_len, self.window_size[0], self.window_size[1])
+ # assert src_len == self.window_size[0] * self.window_size[1] \
+ # and tgt_len == self.window_size[0] * self.window_size[1], \
+ # f"src{src_len}, tgt{tgt_len}, window{self.window_size[0]}"
+ # relative_position_bias = self.relative_position_bias_table[
+ # self.relative_position_index.view(-1)
+ # ].view(
+ # self.window_size[0] * self.window_size[1],
+ # self.window_size[0] * self.window_size[1],
+ # -1,
+ # ) # Wh*Ww,Wh*Ww,nH
+ # relative_position_bias = relative_position_bias.permute(
+ # 2, 0, 1
+ # ).contiguous() # nH, Wh*Ww, Wh*Ww
+ # HELLO!!!!!
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ ) # + relative_position_bias.unsqueeze(0)
+ attn_output_weights = attn_output_weights.view(
+ bsz * num_heads, tgt_len, src_len
+ )
+
+ """
+ Attention weight for the invalid region is -inf
+ """
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_output_weights.masked_fill_(attn_mask, float("-inf"))
+ else:
+ attn_output_weights += attn_mask
+
+ if key_padding_mask is not None:
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ )
+ attn_output_weights = attn_output_weights.masked_fill(
+ key_padding_mask.unsqueeze(1).unsqueeze(2),
+ float("-inf"),
+ )
+ attn_output_weights = attn_output_weights.view(
+ bsz * num_heads, tgt_len, src_len
+ )
+
+ """
+ Reweight the attention map before softmax().
+ attn_output_weights: (b*n_head, n, hw)
+ """
+ attn_output_weights = softmax(attn_output_weights, dim=-1)
+ attn_output_weights = dropout(
+ attn_output_weights, p=dropout_p, training=training
+ )
+
+ attn_output = torch.bmm(attn_output_weights, v)
+ assert list(attn_output.size()) == [bsz * num_heads, tgt_len, v_head_dim]
+ attn_output = (
+ attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, out_dim)
+ )
+ if do_out_proj:
+ attn_output = linear(attn_output, out_proj_weight, out_proj_bias)
+
+ if need_weights:
+ # average attention weights over heads
+ attn_output_weights = attn_output_weights.view(
+ bsz, num_heads, tgt_len, src_len
+ )
+ return attn_output, q, k, attn_output_weights.sum(dim=1) / num_heads
+ else:
+ return attn_output, q, k # additionaly return the query and key
+
+
+class PadBlock(object):
+ """ "Make the size of feature map divisible by local group size."""
+
+ def __init__(self, local_group_size=7):
+ self.lgs = local_group_size
+ if not isinstance(self.lgs, (tuple, list)):
+ self.lgs = to_2tuple(self.lgs)
+ assert len(self.lgs) == 2
+
+ def pad_if_needed(self, x, size):
+ n, h, w, c = size
+ pad_h = math.ceil(h / self.lgs[0]) * self.lgs[0] - h
+ pad_w = math.ceil(w / self.lgs[1]) * self.lgs[1] - w
+ if pad_h > 0 or pad_w > 0: # center-pad the feature on H and W axes
+ return F.pad(
+ x,
+ (0, 0, pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2),
+ )
+ return x
+
+ def depad_if_needed(self, x, size):
+ n, h, w, c = size
+ pad_h = math.ceil(h / self.lgs[0]) * self.lgs[0] - h
+ pad_w = math.ceil(w / self.lgs[1]) * self.lgs[1] - w
+ if pad_h > 0 or pad_w > 0: # remove the center-padding on feature
+ return x[:, pad_h // 2 : pad_h // 2 + h, pad_w // 2 : pad_w // 2 + w, :]
+ return x
+
+
+class LocalPermuteModule(object):
+ """ "Permute the feature map to gather pixels in local groups, and the reverse permutation"""
+
+ def __init__(self, local_group_size=7):
+ self.lgs = local_group_size
+ if not isinstance(self.lgs, (tuple, list)):
+ self.lgs = to_2tuple(self.lgs)
+ assert len(self.lgs) == 2
+
+ def permute(self, x, size):
+ n, h, w, c = size
+ return rearrange(
+ x,
+ "n (qh ph) (qw pw) c -> (ph pw) (n qh qw) c",
+ n=n,
+ qh=h // self.lgs[0],
+ ph=self.lgs[0],
+ qw=w // self.lgs[0],
+ pw=self.lgs[0],
+ c=c,
+ )
+
+ def rev_permute(self, x, size):
+ n, h, w, c = size
+ return rearrange(
+ x,
+ "(ph pw) (n qh qw) c -> n (qh ph) (qw pw) c",
+ n=n,
+ qh=h // self.lgs[0],
+ ph=self.lgs[0],
+ qw=w // self.lgs[0],
+ pw=self.lgs[0],
+ c=c,
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_pool_attention.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_pool_attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..3b039022102a9a26fc1210e24910edd6d9ada560
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/multihead_isa_pool_attention.py
@@ -0,0 +1,59 @@
+# --------------------------------------------------------
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Modified by Lang Huang, RainbowSecret from:
+# https://github.com/openseg-group/openseg.pytorch/blob/master/lib/models/modules/isa_block.py
+# --------------------------------------------------------
+
+import os
+import pdb
+import math
+import torch
+import torch.nn as nn
+
+from .multihead_isa_attention import MHA_, PadBlock, LocalPermuteModule
+
+
+class InterlacedPoolAttention(nn.Module):
+ r"""interlaced sparse multi-head self attention (ISA) module with relative position bias.
+ Args:
+ dim (int): Number of input channels.
+ window_size (tuple[int]): Window size.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key, value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of head_dim ** -0.5 if set
+ attn_drop (float, optional): Dropout ratio of attention weight. Default: 0.0
+ proj_drop (float, optional): Dropout ratio of output. Default: 0.0
+ """
+
+ def __init__(self, embed_dim, num_heads, window_size=7, rpe=True, **kwargs):
+ super(InterlacedPoolAttention, self).__init__()
+
+ self.dim = embed_dim
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.with_rpe = rpe
+
+ self.attn = MHA_(
+ embed_dim, num_heads, rpe=rpe, window_size=window_size, **kwargs
+ )
+ self.pad_helper = PadBlock(window_size)
+ self.permute_helper = LocalPermuteModule(window_size)
+
+ def forward(self, x, H, W, **kwargs):
+ B, N, C = x.shape
+ x = x.view(B, H, W, C)
+ # attention
+ # pad
+ x_pad = self.pad_helper.pad_if_needed(x, x.size())
+ # permute
+ x_permute = self.permute_helper.permute(x_pad, x_pad.size())
+ # attention
+ out, _, _ = self.attn(
+ x_permute, x_permute, x_permute, rpe=self.with_rpe, **kwargs
+ )
+ # reverse permutation
+ out = self.permute_helper.rev_permute(out, x_pad.size())
+ # de-pad, pooling with `ceil_mode=True` will do implicit padding, so we need to remove it, too
+ out = self.pad_helper.depad_if_needed(out, x.size())
+ return out.reshape(B, N, C)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/transformer_block.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/transformer_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..9571e8c70843662d466d3903acc5d54eab27bd4c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/modules/transformer_block.py
@@ -0,0 +1,211 @@
+# --------------------------------------------------------
+# High Resolution Transformer
+# Copyright (c) 2021 Microsoft
+# Licensed under The MIT License [see LICENSE for details]
+# Written by Rao Fu, RainbowSecret
+# --------------------------------------------------------
+
+import os
+import math
+import logging
+import torch
+import torch.nn as nn
+from functools import partial
+
+from .multihead_isa_pool_attention import InterlacedPoolAttention
+
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+BN_MOMENTUM = 0.1
+
+
+def drop_path(x, drop_prob: float = 0.0, training: bool = False):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+ This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
+ the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
+ changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
+ 'survival rate' as the argument.
+ """
+ if drop_prob == 0.0 or not training:
+ return x
+ keep_prob = 1 - drop_prob
+ shape = (x.shape[0],) + (1,) * (
+ x.ndim - 1
+ ) # work with diff dim tensors, not just 2D ConvNets
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
+ random_tensor.floor_() # binarize
+ output = x.div(keep_prob) * random_tensor
+ return output
+
+
+class DropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
+
+ def __init__(self, drop_prob=None):
+ super(DropPath, self).__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, x):
+ return drop_path(x, self.drop_prob, self.training)
+
+ def extra_repr(self):
+ # (Optional)Set the extra information about this module. You can test
+ # it by printing an object of this class.
+ return "drop_prob={}".format(self.drop_prob)
+
+
+class MlpDWBN(nn.Module):
+ def __init__(
+ self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ dw_act_layer=nn.GELU,
+ drop=0.0,
+ conv_cfg=None,
+ norm_cfg=dict(type="BN", requires_grad=True),
+ ):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = build_conv_layer(
+ conv_cfg,
+ in_features,
+ hidden_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=True,
+ )
+ self.act1 = act_layer()
+ self.norm1 = build_norm_layer(norm_cfg, hidden_features)[1]
+ self.dw3x3 = build_conv_layer(
+ conv_cfg,
+ hidden_features,
+ hidden_features,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ groups=hidden_features,
+ )
+ self.act2 = dw_act_layer()
+ self.norm2 = build_norm_layer(norm_cfg, hidden_features)[1]
+ self.fc2 = build_conv_layer(
+ conv_cfg,
+ hidden_features,
+ out_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ bias=True,
+ )
+ self.act3 = act_layer()
+ self.norm3 = build_norm_layer(norm_cfg, out_features)[1]
+ # self.drop = nn.Dropout(drop, inplace=True)
+
+ def forward(self, x, H, W):
+ if len(x.shape) == 3:
+ B, N, C = x.shape
+ if N == (H * W + 1):
+ cls_tokens = x[:, 0, :]
+ x_ = x[:, 1:, :].permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+ else:
+ x_ = x.permute(0, 2, 1).contiguous().reshape(B, C, H, W)
+
+ x_ = self.fc1(x_)
+ x_ = self.norm1(x_)
+ x_ = self.act1(x_)
+ x_ = self.dw3x3(x_)
+ x_ = self.norm2(x_)
+ x_ = self.act2(x_)
+ # x_ = self.drop(x_)
+ x_ = self.fc2(x_)
+ x_ = self.norm3(x_)
+ x_ = self.act3(x_)
+ # x_ = self.drop(x_)
+ x_ = x_.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+ if N == (H * W + 1):
+ x = torch.cat((cls_tokens.unsqueeze(1), x_), dim=1)
+ else:
+ x = x_
+ return x
+
+ elif len(x.shape) == 4:
+ x = self.fc1(x)
+ x = self.norm1(x)
+ x = self.act1(x)
+ x = self.dw3x3(x)
+ x = self.norm2(x)
+ x = self.act2(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.norm3(x)
+ x = self.act3(x)
+ x = self.drop(x)
+ return x
+
+ else:
+ raise RuntimeError("Unsupported input shape: {}".format(x.shape))
+
+
+class GeneralTransformerBlock(nn.Module):
+ expansion = 1
+
+ def __init__(
+ self,
+ inplanes,
+ planes,
+ num_heads,
+ window_size=7,
+ mlp_ratio=4.0,
+ qkv_bias=True,
+ qk_scale=None,
+ drop=0.0,
+ attn_drop=0.0,
+ drop_path=0.0,
+ act_layer=nn.GELU,
+ norm_layer=partial(nn.LayerNorm, eps=1e-6),
+ conv_cfg=None,
+ norm_cfg=dict(type="BN", requires_grad=True),
+ ):
+ super().__init__()
+ self.dim = inplanes
+ self.out_dim = planes
+ self.num_heads = num_heads
+ self.window_size = window_size
+ self.mlp_ratio = mlp_ratio
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+
+ self.attn = InterlacedPoolAttention(
+ self.dim, num_heads=num_heads, window_size=window_size, dropout=attn_drop
+ )
+
+ self.norm1 = norm_layer(self.dim)
+ self.norm2 = norm_layer(self.out_dim)
+ self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
+ mlp_hidden_dim = int(self.dim * mlp_ratio)
+ self.mlp = MlpDWBN(
+ in_features=self.dim,
+ hidden_features=mlp_hidden_dim,
+ out_features=self.out_dim,
+ act_layer=act_layer,
+ dw_act_layer=act_layer,
+ drop=drop,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ )
+
+ def forward(self, x):
+ B, C, H, W = x.size()
+ # reshape
+ x = x.view(B, C, -1).permute(0, 2, 1).contiguous()
+ # Attention
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
+ # FFN
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
+ # reshape
+ x = x.permute(0, 2, 1).contiguous().view(B, C, H, W)
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mspn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mspn.py
new file mode 100644
index 0000000000000000000000000000000000000000..71cee34e399780e8b67eac43d862b65a3ce05412
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/mspn.py
@@ -0,0 +1,513 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy as cp
+from collections import OrderedDict
+
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import (ConvModule, MaxPool2d, constant_init, kaiming_init,
+ normal_init)
+from mmcv.runner.checkpoint import load_state_dict
+
+from mmpose.utils import get_root_logger
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .resnet import Bottleneck as _Bottleneck
+from .utils.utils import get_state_dict
+
+
+class Bottleneck(_Bottleneck):
+ expansion = 4
+ """Bottleneck block for MSPN.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ stride (int): stride of the block. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self, in_channels, out_channels, **kwargs):
+ super().__init__(in_channels, out_channels * 4, **kwargs)
+
+
+class DownsampleModule(nn.Module):
+ """Downsample module for MSPN.
+
+ Args:
+ block (nn.Module): Downsample block.
+ num_blocks (list): Number of blocks in each downsample unit.
+ num_units (int): Numbers of downsample units. Default: 4
+ has_skip (bool): Have skip connections from prior upsample
+ module or not. Default:False
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ in_channels (int): Number of channels of the input feature to
+ downsample module. Default: 64
+ """
+
+ def __init__(self,
+ block,
+ num_blocks,
+ num_units=4,
+ has_skip=False,
+ norm_cfg=dict(type='BN'),
+ in_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.has_skip = has_skip
+ self.in_channels = in_channels
+ assert len(num_blocks) == num_units
+ self.num_blocks = num_blocks
+ self.num_units = num_units
+ self.norm_cfg = norm_cfg
+ self.layer1 = self._make_layer(block, in_channels, num_blocks[0])
+ for i in range(1, num_units):
+ module_name = f'layer{i + 1}'
+ self.add_module(
+ module_name,
+ self._make_layer(
+ block, in_channels * pow(2, i), num_blocks[i], stride=2))
+
+ def _make_layer(self, block, out_channels, blocks, stride=1):
+ downsample = None
+ if stride != 1 or self.in_channels != out_channels * block.expansion:
+ downsample = ConvModule(
+ self.in_channels,
+ out_channels * block.expansion,
+ kernel_size=1,
+ stride=stride,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+
+ units = list()
+ units.append(
+ block(
+ self.in_channels,
+ out_channels,
+ stride=stride,
+ downsample=downsample,
+ norm_cfg=self.norm_cfg))
+ self.in_channels = out_channels * block.expansion
+ for _ in range(1, blocks):
+ units.append(block(self.in_channels, out_channels))
+
+ return nn.Sequential(*units)
+
+ def forward(self, x, skip1, skip2):
+ out = list()
+ for i in range(self.num_units):
+ module_name = f'layer{i + 1}'
+ module_i = getattr(self, module_name)
+ x = module_i(x)
+ if self.has_skip:
+ x = x + skip1[i] + skip2[i]
+ out.append(x)
+ out.reverse()
+
+ return tuple(out)
+
+
+class UpsampleUnit(nn.Module):
+ """Upsample unit for upsample module.
+
+ Args:
+ ind (int): Indicates whether to interpolate (>0) and whether to
+ generate feature map for the next hourglass-like module.
+ num_units (int): Number of units that form a upsample module. Along
+ with ind and gen_cross_conv, nm_units is used to decide whether
+ to generate feature map for the next hourglass-like module.
+ in_channels (int): Channel number of the skip-in feature maps from
+ the corresponding downsample unit.
+ unit_channels (int): Channel number in this unit. Default:256.
+ gen_skip: (bool): Whether or not to generate skips for the posterior
+ downsample module. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ out_channels (int): Number of channels of feature output by upsample
+ module. Must equal to in_channels of downsample module. Default:64
+ """
+
+ def __init__(self,
+ ind,
+ num_units,
+ in_channels,
+ unit_channels=256,
+ gen_skip=False,
+ gen_cross_conv=False,
+ norm_cfg=dict(type='BN'),
+ out_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.num_units = num_units
+ self.norm_cfg = norm_cfg
+ self.in_skip = ConvModule(
+ in_channels,
+ unit_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+ self.relu = nn.ReLU(inplace=True)
+
+ self.ind = ind
+ if self.ind > 0:
+ self.up_conv = ConvModule(
+ unit_channels,
+ unit_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+
+ self.gen_skip = gen_skip
+ if self.gen_skip:
+ self.out_skip1 = ConvModule(
+ in_channels,
+ in_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ self.out_skip2 = ConvModule(
+ unit_channels,
+ in_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ self.gen_cross_conv = gen_cross_conv
+ if self.ind == num_units - 1 and self.gen_cross_conv:
+ self.cross_conv = ConvModule(
+ unit_channels,
+ out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ def forward(self, x, up_x):
+ out = self.in_skip(x)
+
+ if self.ind > 0:
+ up_x = F.interpolate(
+ up_x,
+ size=(x.size(2), x.size(3)),
+ mode='bilinear',
+ align_corners=True)
+ up_x = self.up_conv(up_x)
+ out = out + up_x
+ out = self.relu(out)
+
+ skip1 = None
+ skip2 = None
+ if self.gen_skip:
+ skip1 = self.out_skip1(x)
+ skip2 = self.out_skip2(out)
+
+ cross_conv = None
+ if self.ind == self.num_units - 1 and self.gen_cross_conv:
+ cross_conv = self.cross_conv(out)
+
+ return out, skip1, skip2, cross_conv
+
+
+class UpsampleModule(nn.Module):
+ """Upsample module for MSPN.
+
+ Args:
+ unit_channels (int): Channel number in the upsample units.
+ Default:256.
+ num_units (int): Numbers of upsample units. Default: 4
+ gen_skip (bool): Whether to generate skip for posterior downsample
+ module or not. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ out_channels (int): Number of channels of feature output by upsample
+ module. Must equal to in_channels of downsample module. Default:64
+ """
+
+ def __init__(self,
+ unit_channels=256,
+ num_units=4,
+ gen_skip=False,
+ gen_cross_conv=False,
+ norm_cfg=dict(type='BN'),
+ out_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.in_channels = list()
+ for i in range(num_units):
+ self.in_channels.append(Bottleneck.expansion * out_channels *
+ pow(2, i))
+ self.in_channels.reverse()
+ self.num_units = num_units
+ self.gen_skip = gen_skip
+ self.gen_cross_conv = gen_cross_conv
+ self.norm_cfg = norm_cfg
+ for i in range(num_units):
+ module_name = f'up{i + 1}'
+ self.add_module(
+ module_name,
+ UpsampleUnit(
+ i,
+ self.num_units,
+ self.in_channels[i],
+ unit_channels,
+ self.gen_skip,
+ self.gen_cross_conv,
+ norm_cfg=self.norm_cfg,
+ out_channels=64))
+
+ def forward(self, x):
+ out = list()
+ skip1 = list()
+ skip2 = list()
+ cross_conv = None
+ for i in range(self.num_units):
+ module_i = getattr(self, f'up{i + 1}')
+ if i == 0:
+ outi, skip1_i, skip2_i, _ = module_i(x[i], None)
+ elif i == self.num_units - 1:
+ outi, skip1_i, skip2_i, cross_conv = module_i(x[i], out[i - 1])
+ else:
+ outi, skip1_i, skip2_i, _ = module_i(x[i], out[i - 1])
+ out.append(outi)
+ skip1.append(skip1_i)
+ skip2.append(skip2_i)
+ skip1.reverse()
+ skip2.reverse()
+
+ return out, skip1, skip2, cross_conv
+
+
+class SingleStageNetwork(nn.Module):
+ """Single_stage Network.
+
+ Args:
+ unit_channels (int): Channel number in the upsample units. Default:256.
+ num_units (int): Numbers of downsample/upsample units. Default: 4
+ gen_skip (bool): Whether to generate skip for posterior downsample
+ module or not. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ has_skip (bool): Have skip connections from prior upsample
+ module or not. Default:False
+ num_blocks (list): Number of blocks in each downsample unit.
+ Default: [2, 2, 2, 2] Note: Make sure num_units==len(num_blocks)
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ in_channels (int): Number of channels of the feature from ResNetTop.
+ Default: 64.
+ """
+
+ def __init__(self,
+ has_skip=False,
+ gen_skip=False,
+ gen_cross_conv=False,
+ unit_channels=256,
+ num_units=4,
+ num_blocks=[2, 2, 2, 2],
+ norm_cfg=dict(type='BN'),
+ in_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ num_blocks = cp.deepcopy(num_blocks)
+ super().__init__()
+ assert len(num_blocks) == num_units
+ self.has_skip = has_skip
+ self.gen_skip = gen_skip
+ self.gen_cross_conv = gen_cross_conv
+ self.num_units = num_units
+ self.unit_channels = unit_channels
+ self.num_blocks = num_blocks
+ self.norm_cfg = norm_cfg
+
+ self.downsample = DownsampleModule(Bottleneck, num_blocks, num_units,
+ has_skip, norm_cfg, in_channels)
+ self.upsample = UpsampleModule(unit_channels, num_units, gen_skip,
+ gen_cross_conv, norm_cfg, in_channels)
+
+ def forward(self, x, skip1, skip2):
+ mid = self.downsample(x, skip1, skip2)
+ out, skip1, skip2, cross_conv = self.upsample(mid)
+
+ return out, skip1, skip2, cross_conv
+
+
+class ResNetTop(nn.Module):
+ """ResNet top for MSPN.
+
+ Args:
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ channels (int): Number of channels of the feature output by ResNetTop.
+ """
+
+ def __init__(self, norm_cfg=dict(type='BN'), channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.top = nn.Sequential(
+ ConvModule(
+ 3,
+ channels,
+ kernel_size=7,
+ stride=2,
+ padding=3,
+ norm_cfg=norm_cfg,
+ inplace=True), MaxPool2d(kernel_size=3, stride=2, padding=1))
+
+ def forward(self, img):
+ return self.top(img)
+
+
+@BACKBONES.register_module()
+class MSPN(BaseBackbone):
+ """MSPN backbone. Paper ref: Li et al. "Rethinking on Multi-Stage Networks
+ for Human Pose Estimation" (CVPR 2020).
+
+ Args:
+ unit_channels (int): Number of Channels in an upsample unit.
+ Default: 256
+ num_stages (int): Number of stages in a multi-stage MSPN. Default: 4
+ num_units (int): Number of downsample/upsample units in a single-stage
+ network. Default: 4
+ Note: Make sure num_units == len(self.num_blocks)
+ num_blocks (list): Number of bottlenecks in each
+ downsample unit. Default: [2, 2, 2, 2]
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ res_top_channels (int): Number of channels of feature from ResNetTop.
+ Default: 64.
+
+ Example:
+ >>> from mmpose.models import MSPN
+ >>> import torch
+ >>> self = MSPN(num_stages=2,num_units=2,num_blocks=[2,2])
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 511, 511)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_output in level_outputs:
+ ... for feature in level_output:
+ ... print(tuple(feature.shape))
+ ...
+ (1, 256, 64, 64)
+ (1, 256, 128, 128)
+ (1, 256, 64, 64)
+ (1, 256, 128, 128)
+ """
+
+ def __init__(self,
+ unit_channels=256,
+ num_stages=4,
+ num_units=4,
+ num_blocks=[2, 2, 2, 2],
+ norm_cfg=dict(type='BN'),
+ res_top_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ num_blocks = cp.deepcopy(num_blocks)
+ super().__init__()
+ self.unit_channels = unit_channels
+ self.num_stages = num_stages
+ self.num_units = num_units
+ self.num_blocks = num_blocks
+ self.norm_cfg = norm_cfg
+
+ assert self.num_stages > 0
+ assert self.num_units > 1
+ assert self.num_units == len(self.num_blocks)
+ self.top = ResNetTop(norm_cfg=norm_cfg)
+ self.multi_stage_mspn = nn.ModuleList([])
+ for i in range(self.num_stages):
+ if i == 0:
+ has_skip = False
+ else:
+ has_skip = True
+ if i != self.num_stages - 1:
+ gen_skip = True
+ gen_cross_conv = True
+ else:
+ gen_skip = False
+ gen_cross_conv = False
+ self.multi_stage_mspn.append(
+ SingleStageNetwork(has_skip, gen_skip, gen_cross_conv,
+ unit_channels, num_units, num_blocks,
+ norm_cfg, res_top_channels))
+
+ def forward(self, x):
+ """Model forward function."""
+ out_feats = []
+ skip1 = None
+ skip2 = None
+ x = self.top(x)
+ for i in range(self.num_stages):
+ out, skip1, skip2, x = self.multi_stage_mspn[i](x, skip1, skip2)
+ out_feats.append(out)
+
+ return out_feats
+
+ def init_weights(self, pretrained=None):
+ """Initialize model weights."""
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ state_dict_tmp = get_state_dict(pretrained)
+ state_dict = OrderedDict()
+ state_dict['top'] = OrderedDict()
+ state_dict['bottlenecks'] = OrderedDict()
+ for k, v in state_dict_tmp.items():
+ if k.startswith('layer'):
+ if 'downsample.0' in k:
+ state_dict['bottlenecks'][k.replace(
+ 'downsample.0', 'downsample.conv')] = v
+ elif 'downsample.1' in k:
+ state_dict['bottlenecks'][k.replace(
+ 'downsample.1', 'downsample.bn')] = v
+ else:
+ state_dict['bottlenecks'][k] = v
+ elif k.startswith('conv1'):
+ state_dict['top'][k.replace('conv1', 'top.0.conv')] = v
+ elif k.startswith('bn1'):
+ state_dict['top'][k.replace('bn1', 'top.0.bn')] = v
+
+ load_state_dict(
+ self.top, state_dict['top'], strict=False, logger=logger)
+ for i in range(self.num_stages):
+ load_state_dict(
+ self.multi_stage_mspn[i].downsample,
+ state_dict['bottlenecks'],
+ strict=False,
+ logger=logger)
+ else:
+ for m in self.multi_stage_mspn.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ elif isinstance(m, nn.Linear):
+ normal_init(m, std=0.01)
+
+ for m in self.top.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/pvt.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/pvt.py
new file mode 100644
index 0000000000000000000000000000000000000000..62527a7dc817513c08f42ccbb166c75cab514873
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/pvt.py
@@ -0,0 +1,592 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+import warnings
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import (Conv2d, build_activation_layer, build_norm_layer,
+ constant_init, normal_init, trunc_normal_init)
+from mmcv.cnn.bricks.drop import build_dropout
+from mmcv.cnn.bricks.transformer import MultiheadAttention
+from mmcv.cnn.utils.weight_init import trunc_normal_
+from mmcv.runner import (BaseModule, ModuleList, Sequential, _load_checkpoint,
+ load_state_dict)
+from torch.nn.modules.utils import _pair as to_2tuple
+
+from ...utils import get_root_logger
+from ..builder import BACKBONES
+from ..utils import PatchEmbed, nchw_to_nlc, nlc_to_nchw, pvt_convert
+
+
+class MixFFN(BaseModule):
+ """An implementation of MixFFN of PVT.
+
+ The differences between MixFFN & FFN:
+ 1. Use 1X1 Conv to replace Linear layer.
+ 2. Introduce 3X3 Depth-wise Conv to encode positional information.
+
+ Args:
+ embed_dims (int): The feature dimension. Same as
+ `MultiheadAttention`.
+ feedforward_channels (int): The hidden dimension of FFNs.
+ act_cfg (dict, optional): The activation config for FFNs.
+ Default: dict(type='GELU').
+ ffn_drop (float, optional): Probability of an element to be
+ zeroed in FFN. Default 0.0.
+ dropout_layer (obj:`ConfigDict`): The dropout_layer used
+ when adding the shortcut.
+ Default: None.
+ use_conv (bool): If True, add 3x3 DWConv between two Linear layers.
+ Defaults: False.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims,
+ feedforward_channels,
+ act_cfg=dict(type='GELU'),
+ ffn_drop=0.,
+ dropout_layer=None,
+ use_conv=False,
+ init_cfg=None):
+ super(MixFFN, self).__init__(init_cfg=init_cfg)
+
+ self.embed_dims = embed_dims
+ self.feedforward_channels = feedforward_channels
+ self.act_cfg = act_cfg
+ activate = build_activation_layer(act_cfg)
+
+ in_channels = embed_dims
+ fc1 = Conv2d(
+ in_channels=in_channels,
+ out_channels=feedforward_channels,
+ kernel_size=1,
+ stride=1,
+ bias=True)
+ if use_conv:
+ # 3x3 depth wise conv to provide positional encode information
+ dw_conv = Conv2d(
+ in_channels=feedforward_channels,
+ out_channels=feedforward_channels,
+ kernel_size=3,
+ stride=1,
+ padding=(3 - 1) // 2,
+ bias=True,
+ groups=feedforward_channels)
+ fc2 = Conv2d(
+ in_channels=feedforward_channels,
+ out_channels=in_channels,
+ kernel_size=1,
+ stride=1,
+ bias=True)
+ drop = nn.Dropout(ffn_drop)
+ layers = [fc1, activate, drop, fc2, drop]
+ if use_conv:
+ layers.insert(1, dw_conv)
+ self.layers = Sequential(*layers)
+ self.dropout_layer = build_dropout(
+ dropout_layer) if dropout_layer else torch.nn.Identity()
+
+ def forward(self, x, hw_shape, identity=None):
+ out = nlc_to_nchw(x, hw_shape)
+ out = self.layers(out)
+ out = nchw_to_nlc(out)
+ if identity is None:
+ identity = x
+ return identity + self.dropout_layer(out)
+
+
+class SpatialReductionAttention(MultiheadAttention):
+ """An implementation of Spatial Reduction Attention of PVT.
+
+ This module is modified from MultiheadAttention which is a module from
+ mmcv.cnn.bricks.transformer.
+
+ Args:
+ embed_dims (int): The embedding dimension.
+ num_heads (int): Parallel attention heads.
+ attn_drop (float): A Dropout layer on attn_output_weights.
+ Default: 0.0.
+ proj_drop (float): A Dropout layer after `nn.MultiheadAttention`.
+ Default: 0.0.
+ dropout_layer (obj:`ConfigDict`): The dropout_layer used
+ when adding the shortcut. Default: None.
+ batch_first (bool): Key, Query and Value are shape of
+ (batch, n, embed_dim)
+ or (n, batch, embed_dim). Default: False.
+ qkv_bias (bool): enable bias for qkv if True. Default: True.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN').
+ sr_ratio (int): The ratio of spatial reduction of Spatial Reduction
+ Attention of PVT. Default: 1.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ attn_drop=0.,
+ proj_drop=0.,
+ dropout_layer=None,
+ batch_first=True,
+ qkv_bias=True,
+ norm_cfg=dict(type='LN'),
+ sr_ratio=1,
+ init_cfg=None):
+ super().__init__(
+ embed_dims,
+ num_heads,
+ attn_drop,
+ proj_drop,
+ batch_first=batch_first,
+ dropout_layer=dropout_layer,
+ bias=qkv_bias,
+ init_cfg=init_cfg)
+
+ self.sr_ratio = sr_ratio
+ if sr_ratio > 1:
+ self.sr = Conv2d(
+ in_channels=embed_dims,
+ out_channels=embed_dims,
+ kernel_size=sr_ratio,
+ stride=sr_ratio)
+ # The ret[0] of build_norm_layer is norm name.
+ self.norm = build_norm_layer(norm_cfg, embed_dims)[1]
+
+ # handle the BC-breaking from https://github.com/open-mmlab/mmcv/pull/1418 # noqa
+ from mmpose import digit_version, mmcv_version
+ if mmcv_version < digit_version('1.3.17'):
+ warnings.warn('The legacy version of forward function in'
+ 'SpatialReductionAttention is deprecated in'
+ 'mmcv>=1.3.17 and will no longer support in the'
+ 'future. Please upgrade your mmcv.')
+ self.forward = self.legacy_forward
+
+ def forward(self, x, hw_shape, identity=None):
+
+ x_q = x
+ if self.sr_ratio > 1:
+ x_kv = nlc_to_nchw(x, hw_shape)
+ x_kv = self.sr(x_kv)
+ x_kv = nchw_to_nlc(x_kv)
+ x_kv = self.norm(x_kv)
+ else:
+ x_kv = x
+
+ if identity is None:
+ identity = x_q
+
+ # Because the dataflow('key', 'query', 'value') of
+ # ``torch.nn.MultiheadAttention`` is (num_query, batch,
+ # embed_dims), We should adjust the shape of dataflow from
+ # batch_first (batch, num_query, embed_dims) to num_query_first
+ # (num_query ,batch, embed_dims), and recover ``attn_output``
+ # from num_query_first to batch_first.
+ if self.batch_first:
+ x_q = x_q.transpose(0, 1)
+ x_kv = x_kv.transpose(0, 1)
+
+ out = self.attn(query=x_q, key=x_kv, value=x_kv)[0]
+
+ if self.batch_first:
+ out = out.transpose(0, 1)
+
+ return identity + self.dropout_layer(self.proj_drop(out))
+
+ def legacy_forward(self, x, hw_shape, identity=None):
+ """multi head attention forward in mmcv version < 1.3.17."""
+ x_q = x
+ if self.sr_ratio > 1:
+ x_kv = nlc_to_nchw(x, hw_shape)
+ x_kv = self.sr(x_kv)
+ x_kv = nchw_to_nlc(x_kv)
+ x_kv = self.norm(x_kv)
+ else:
+ x_kv = x
+
+ if identity is None:
+ identity = x_q
+
+ out = self.attn(query=x_q, key=x_kv, value=x_kv)[0]
+
+ return identity + self.dropout_layer(self.proj_drop(out))
+
+
+class PVTEncoderLayer(BaseModule):
+ """Implements one encoder layer in PVT.
+
+ Args:
+ embed_dims (int): The feature dimension.
+ num_heads (int): Parallel attention heads.
+ feedforward_channels (int): The hidden dimension for FFNs.
+ drop_rate (float): Probability of an element to be zeroed.
+ after the feed forward layer. Default: 0.0.
+ attn_drop_rate (float): The drop out rate for attention layer.
+ Default: 0.0.
+ drop_path_rate (float): stochastic depth rate. Default: 0.0.
+ qkv_bias (bool): enable bias for qkv if True.
+ Default: True.
+ act_cfg (dict): The activation config for FFNs.
+ Default: dict(type='GELU').
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN').
+ sr_ratio (int): The ratio of spatial reduction of Spatial Reduction
+ Attention of PVT. Default: 1.
+ use_conv_ffn (bool): If True, use Convolutional FFN to replace FFN.
+ Default: False.
+ init_cfg (dict, optional): Initialization config dict.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ feedforward_channels,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.,
+ qkv_bias=True,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='LN'),
+ sr_ratio=1,
+ use_conv_ffn=False,
+ init_cfg=None):
+ super(PVTEncoderLayer, self).__init__(init_cfg=init_cfg)
+
+ # The ret[0] of build_norm_layer is norm name.
+ self.norm1 = build_norm_layer(norm_cfg, embed_dims)[1]
+
+ self.attn = SpatialReductionAttention(
+ embed_dims=embed_dims,
+ num_heads=num_heads,
+ attn_drop=attn_drop_rate,
+ proj_drop=drop_rate,
+ dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate),
+ qkv_bias=qkv_bias,
+ norm_cfg=norm_cfg,
+ sr_ratio=sr_ratio)
+
+ # The ret[0] of build_norm_layer is norm name.
+ self.norm2 = build_norm_layer(norm_cfg, embed_dims)[1]
+
+ self.ffn = MixFFN(
+ embed_dims=embed_dims,
+ feedforward_channels=feedforward_channels,
+ ffn_drop=drop_rate,
+ dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate),
+ use_conv=use_conv_ffn,
+ act_cfg=act_cfg)
+
+ def forward(self, x, hw_shape):
+ x = self.attn(self.norm1(x), hw_shape, identity=x)
+ x = self.ffn(self.norm2(x), hw_shape, identity=x)
+
+ return x
+
+
+class AbsolutePositionEmbedding(BaseModule):
+ """An implementation of the absolute position embedding in PVT.
+
+ Args:
+ pos_shape (int): The shape of the absolute position embedding.
+ pos_dim (int): The dimension of the absolute position embedding.
+ drop_rate (float): Probability of an element to be zeroed.
+ Default: 0.0.
+ """
+
+ def __init__(self, pos_shape, pos_dim, drop_rate=0., init_cfg=None):
+ super().__init__(init_cfg=init_cfg)
+
+ if isinstance(pos_shape, int):
+ pos_shape = to_2tuple(pos_shape)
+ elif isinstance(pos_shape, tuple):
+ if len(pos_shape) == 1:
+ pos_shape = to_2tuple(pos_shape[0])
+ assert len(pos_shape) == 2, \
+ f'The size of image should have length 1 or 2, ' \
+ f'but got {len(pos_shape)}'
+ self.pos_shape = pos_shape
+ self.pos_dim = pos_dim
+
+ self.pos_embed = nn.Parameter(
+ torch.zeros(1, pos_shape[0] * pos_shape[1], pos_dim))
+ self.drop = nn.Dropout(p=drop_rate)
+
+ def init_weights(self):
+ trunc_normal_(self.pos_embed, std=0.02)
+
+ def resize_pos_embed(self, pos_embed, input_shape, mode='bilinear'):
+ """Resize pos_embed weights.
+
+ Resize pos_embed using bilinear interpolate method.
+
+ Args:
+ pos_embed (torch.Tensor): Position embedding weights.
+ input_shape (tuple): Tuple for (downsampled input image height,
+ downsampled input image width).
+ mode (str): Algorithm used for upsampling:
+ ``'nearest'`` | ``'linear'`` | ``'bilinear'`` | ``'bicubic'`` |
+ ``'trilinear'``. Default: ``'bilinear'``.
+
+ Return:
+ torch.Tensor: The resized pos_embed of shape [B, L_new, C].
+ """
+ assert pos_embed.ndim == 3, 'shape of pos_embed must be [B, L, C]'
+ pos_h, pos_w = self.pos_shape
+ pos_embed_weight = pos_embed[:, (-1 * pos_h * pos_w):]
+ pos_embed_weight = pos_embed_weight.reshape(
+ 1, pos_h, pos_w, self.pos_dim).permute(0, 3, 1, 2).contiguous()
+ pos_embed_weight = F.interpolate(
+ pos_embed_weight, size=input_shape, mode=mode)
+ pos_embed_weight = torch.flatten(pos_embed_weight,
+ 2).transpose(1, 2).contiguous()
+ pos_embed = pos_embed_weight
+
+ return pos_embed
+
+ def forward(self, x, hw_shape, mode='bilinear'):
+ pos_embed = self.resize_pos_embed(self.pos_embed, hw_shape, mode)
+ return self.drop(x + pos_embed)
+
+
+@BACKBONES.register_module()
+class PyramidVisionTransformer(BaseModule):
+ """Pyramid Vision Transformer (PVT)
+
+ Implementation of `Pyramid Vision Transformer: A Versatile Backbone for
+ Dense Prediction without Convolutions
+ `_.
+
+ Args:
+ pretrain_img_size (int | tuple[int]): The size of input image when
+ pretrain. Defaults: 224.
+ in_channels (int): Number of input channels. Default: 3.
+ embed_dims (int): Embedding dimension. Default: 64.
+ num_stags (int): The num of stages. Default: 4.
+ num_layers (Sequence[int]): The layer number of each transformer encode
+ layer. Default: [3, 4, 6, 3].
+ num_heads (Sequence[int]): The attention heads of each transformer
+ encode layer. Default: [1, 2, 5, 8].
+ patch_sizes (Sequence[int]): The patch_size of each patch embedding.
+ Default: [4, 2, 2, 2].
+ strides (Sequence[int]): The stride of each patch embedding.
+ Default: [4, 2, 2, 2].
+ paddings (Sequence[int]): The padding of each patch embedding.
+ Default: [0, 0, 0, 0].
+ sr_ratios (Sequence[int]): The spatial reduction rate of each
+ transformer encode layer. Default: [8, 4, 2, 1].
+ out_indices (Sequence[int] | int): Output from which stages.
+ Default: (0, 1, 2, 3).
+ mlp_ratios (Sequence[int]): The ratio of the mlp hidden dim to the
+ embedding dim of each transformer encode layer.
+ Default: [8, 8, 4, 4].
+ qkv_bias (bool): Enable bias for qkv if True. Default: True.
+ drop_rate (float): Probability of an element to be zeroed.
+ Default 0.0.
+ attn_drop_rate (float): The drop out rate for attention layer.
+ Default 0.0.
+ drop_path_rate (float): stochastic depth rate. Default 0.1.
+ use_abs_pos_embed (bool): If True, add absolute position embedding to
+ the patch embedding. Defaults: True.
+ use_conv_ffn (bool): If True, use Convolutional FFN to replace FFN.
+ Default: False.
+ act_cfg (dict): The activation config for FFNs.
+ Default: dict(type='GELU').
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN').
+ pretrained (str, optional): model pretrained path. Default: None.
+ convert_weights (bool): The flag indicates whether the
+ pre-trained model is from the original repo. We may need
+ to convert some keys to make it compatible.
+ Default: True.
+ init_cfg (dict or list[dict], optional): Initialization config dict.
+ Default: None.
+ """
+
+ def __init__(self,
+ pretrain_img_size=224,
+ in_channels=3,
+ embed_dims=64,
+ num_stages=4,
+ num_layers=[3, 4, 6, 3],
+ num_heads=[1, 2, 5, 8],
+ patch_sizes=[4, 2, 2, 2],
+ strides=[4, 2, 2, 2],
+ paddings=[0, 0, 0, 0],
+ sr_ratios=[8, 4, 2, 1],
+ out_indices=(0, 1, 2, 3),
+ mlp_ratios=[8, 8, 4, 4],
+ qkv_bias=True,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.1,
+ use_abs_pos_embed=True,
+ norm_after_stage=False,
+ use_conv_ffn=False,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='LN', eps=1e-6),
+ pretrained=None,
+ convert_weights=True,
+ init_cfg=None):
+ super().__init__(init_cfg=init_cfg)
+
+ self.convert_weights = convert_weights
+ if isinstance(pretrain_img_size, int):
+ pretrain_img_size = to_2tuple(pretrain_img_size)
+ elif isinstance(pretrain_img_size, tuple):
+ if len(pretrain_img_size) == 1:
+ pretrain_img_size = to_2tuple(pretrain_img_size[0])
+ assert len(pretrain_img_size) == 2, \
+ f'The size of image should have length 1 or 2, ' \
+ f'but got {len(pretrain_img_size)}'
+
+ assert not (init_cfg and pretrained), \
+ 'init_cfg and pretrained cannot be setting at the same time'
+ if isinstance(pretrained, str):
+ self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
+ elif pretrained is None:
+ self.init_cfg = init_cfg
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ self.embed_dims = embed_dims
+
+ self.num_stages = num_stages
+ self.num_layers = num_layers
+ self.num_heads = num_heads
+ self.patch_sizes = patch_sizes
+ self.strides = strides
+ self.sr_ratios = sr_ratios
+ assert num_stages == len(num_layers) == len(num_heads) \
+ == len(patch_sizes) == len(strides) == len(sr_ratios)
+
+ self.out_indices = out_indices
+ assert max(out_indices) < self.num_stages
+ self.pretrained = pretrained
+
+ # transformer encoder
+ dpr = [
+ x.item()
+ for x in torch.linspace(0, drop_path_rate, sum(num_layers))
+ ] # stochastic num_layer decay rule
+
+ cur = 0
+ self.layers = ModuleList()
+ for i, num_layer in enumerate(num_layers):
+ embed_dims_i = embed_dims * num_heads[i]
+ patch_embed = PatchEmbed(
+ in_channels=in_channels,
+ embed_dims=embed_dims_i,
+ kernel_size=patch_sizes[i],
+ stride=strides[i],
+ padding=paddings[i],
+ bias=True,
+ norm_cfg=norm_cfg)
+
+ layers = ModuleList()
+ if use_abs_pos_embed:
+ pos_shape = pretrain_img_size // np.prod(patch_sizes[:i + 1])
+ pos_embed = AbsolutePositionEmbedding(
+ pos_shape=pos_shape,
+ pos_dim=embed_dims_i,
+ drop_rate=drop_rate)
+ layers.append(pos_embed)
+ layers.extend([
+ PVTEncoderLayer(
+ embed_dims=embed_dims_i,
+ num_heads=num_heads[i],
+ feedforward_channels=mlp_ratios[i] * embed_dims_i,
+ drop_rate=drop_rate,
+ attn_drop_rate=attn_drop_rate,
+ drop_path_rate=dpr[cur + idx],
+ qkv_bias=qkv_bias,
+ act_cfg=act_cfg,
+ norm_cfg=norm_cfg,
+ sr_ratio=sr_ratios[i],
+ use_conv_ffn=use_conv_ffn) for idx in range(num_layer)
+ ])
+ in_channels = embed_dims_i
+ # The ret[0] of build_norm_layer is norm name.
+ if norm_after_stage:
+ norm = build_norm_layer(norm_cfg, embed_dims_i)[1]
+ else:
+ norm = nn.Identity()
+ self.layers.append(ModuleList([patch_embed, layers, norm]))
+ cur += num_layer
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ self.init_cfg = dict(type='Pretrained', checkpoint=pretrained)
+
+ logger = get_root_logger()
+ if self.init_cfg is None:
+ logger.warn(f'No pre-trained weights for '
+ f'{self.__class__.__name__}, '
+ f'training start from scratch')
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ constant_init(m, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[
+ 1] * m.out_channels
+ fan_out //= m.groups
+ normal_init(m, 0, math.sqrt(2.0 / fan_out))
+ elif isinstance(m, AbsolutePositionEmbedding):
+ m.init_weights()
+ else:
+ assert 'checkpoint' in self.init_cfg, f'Only support ' \
+ f'specify `Pretrained` in ' \
+ f'`init_cfg` in ' \
+ f'{self.__class__.__name__} '
+ checkpoint = _load_checkpoint(
+ self.init_cfg['checkpoint'], logger=logger, map_location='cpu')
+ logger.warn(f'Load pre-trained model for '
+ f'{self.__class__.__name__} from original repo')
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ elif 'model' in checkpoint:
+ state_dict = checkpoint['model']
+ else:
+ state_dict = checkpoint
+ if self.convert_weights:
+ # Because pvt backbones are not supported by mmcls,
+ # so we need to convert pre-trained weights to match this
+ # implementation.
+ state_dict = pvt_convert(state_dict)
+ load_state_dict(self, state_dict, strict=False, logger=logger)
+
+ def forward(self, x):
+ outs = []
+
+ for i, layer in enumerate(self.layers):
+ x, hw_shape = layer[0](x)
+
+ for block in layer[1]:
+ x = block(x, hw_shape)
+ x = layer[2](x)
+ x = nlc_to_nchw(x, hw_shape)
+ if i in self.out_indices:
+ outs.append(x)
+
+ return outs
+
+
+@BACKBONES.register_module()
+class PyramidVisionTransformerV2(PyramidVisionTransformer):
+ """Implementation of `PVTv2: Improved Baselines with Pyramid Vision
+ Transformer `_."""
+
+ def __init__(self, **kwargs):
+ super(PyramidVisionTransformerV2, self).__init__(
+ patch_sizes=[7, 3, 3, 3],
+ paddings=[3, 1, 1, 1],
+ use_abs_pos_embed=False,
+ norm_after_stage=True,
+ use_conv_ffn=True,
+ **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/regnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/regnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..693417c2d61066e4e9a90989ad61700448028e58
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/regnet.py
@@ -0,0 +1,317 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import numpy as np
+import torch.nn as nn
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+from ..builder import BACKBONES
+from .resnet import ResNet
+from .resnext import Bottleneck
+
+
+@BACKBONES.register_module()
+class RegNet(ResNet):
+ """RegNet backbone.
+
+ More details can be found in `paper `__ .
+
+ Args:
+ arch (dict): The parameter of RegNets.
+ - w0 (int): initial width
+ - wa (float): slope of width
+ - wm (float): quantization parameter to quantize the width
+ - depth (int): depth of the backbone
+ - group_w (int): width of group
+ - bot_mul (float): bottleneck ratio, i.e. expansion of bottleneck.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ base_channels (int): Base channels after stem layer.
+ in_channels (int): Number of input image channels. Default: 3.
+ dilations (Sequence[int]): Dilation of each stage.
+ out_indices (Sequence[int]): Output from which stages.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer. Default: "pytorch".
+ frozen_stages (int): Stages to be frozen (all param fixed). -1 means
+ not freezing any parameters. Default: -1.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN', requires_grad=True).
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+
+ Example:
+ >>> from mmpose.models import RegNet
+ >>> import torch
+ >>> self = RegNet(
+ arch=dict(
+ w0=88,
+ wa=26.31,
+ wm=2.25,
+ group_w=48,
+ depth=25,
+ bot_mul=1.0),
+ out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 96, 8, 8)
+ (1, 192, 4, 4)
+ (1, 432, 2, 2)
+ (1, 1008, 1, 1)
+ """
+ arch_settings = {
+ 'regnetx_400mf':
+ dict(w0=24, wa=24.48, wm=2.54, group_w=16, depth=22, bot_mul=1.0),
+ 'regnetx_800mf':
+ dict(w0=56, wa=35.73, wm=2.28, group_w=16, depth=16, bot_mul=1.0),
+ 'regnetx_1.6gf':
+ dict(w0=80, wa=34.01, wm=2.25, group_w=24, depth=18, bot_mul=1.0),
+ 'regnetx_3.2gf':
+ dict(w0=88, wa=26.31, wm=2.25, group_w=48, depth=25, bot_mul=1.0),
+ 'regnetx_4.0gf':
+ dict(w0=96, wa=38.65, wm=2.43, group_w=40, depth=23, bot_mul=1.0),
+ 'regnetx_6.4gf':
+ dict(w0=184, wa=60.83, wm=2.07, group_w=56, depth=17, bot_mul=1.0),
+ 'regnetx_8.0gf':
+ dict(w0=80, wa=49.56, wm=2.88, group_w=120, depth=23, bot_mul=1.0),
+ 'regnetx_12gf':
+ dict(w0=168, wa=73.36, wm=2.37, group_w=112, depth=19, bot_mul=1.0),
+ }
+
+ def __init__(self,
+ arch,
+ in_channels=3,
+ stem_channels=32,
+ base_channels=32,
+ strides=(2, 2, 2, 2),
+ dilations=(1, 1, 1, 1),
+ out_indices=(3, ),
+ style='pytorch',
+ deep_stem=False,
+ avg_down=False,
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN', requires_grad=True),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=True):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super(ResNet, self).__init__()
+
+ # Generate RegNet parameters first
+ if isinstance(arch, str):
+ assert arch in self.arch_settings, \
+ f'"arch": "{arch}" is not one of the' \
+ ' arch_settings'
+ arch = self.arch_settings[arch]
+ elif not isinstance(arch, dict):
+ raise TypeError('Expect "arch" to be either a string '
+ f'or a dict, got {type(arch)}')
+
+ widths, num_stages = self.generate_regnet(
+ arch['w0'],
+ arch['wa'],
+ arch['wm'],
+ arch['depth'],
+ )
+ # Convert to per stage format
+ stage_widths, stage_blocks = self.get_stages_from_blocks(widths)
+ # Generate group widths and bot muls
+ group_widths = [arch['group_w'] for _ in range(num_stages)]
+ self.bottleneck_ratio = [arch['bot_mul'] for _ in range(num_stages)]
+ # Adjust the compatibility of stage_widths and group_widths
+ stage_widths, group_widths = self.adjust_width_group(
+ stage_widths, self.bottleneck_ratio, group_widths)
+
+ # Group params by stage
+ self.stage_widths = stage_widths
+ self.group_widths = group_widths
+ self.depth = sum(stage_blocks)
+ self.stem_channels = stem_channels
+ self.base_channels = base_channels
+ self.num_stages = num_stages
+ assert 1 <= num_stages <= 4
+ self.strides = strides
+ self.dilations = dilations
+ assert len(strides) == len(dilations) == num_stages
+ self.out_indices = out_indices
+ assert max(out_indices) < num_stages
+ self.style = style
+ self.deep_stem = deep_stem
+ if self.deep_stem:
+ raise NotImplementedError(
+ 'deep_stem has not been implemented for RegNet')
+ self.avg_down = avg_down
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.with_cp = with_cp
+ self.norm_eval = norm_eval
+ self.zero_init_residual = zero_init_residual
+ self.stage_blocks = stage_blocks[:num_stages]
+
+ self._make_stem_layer(in_channels, stem_channels)
+
+ _in_channels = stem_channels
+ self.res_layers = []
+ for i, num_blocks in enumerate(self.stage_blocks):
+ stride = self.strides[i]
+ dilation = self.dilations[i]
+ group_width = self.group_widths[i]
+ width = int(round(self.stage_widths[i] * self.bottleneck_ratio[i]))
+ stage_groups = width // group_width
+
+ res_layer = self.make_res_layer(
+ block=Bottleneck,
+ num_blocks=num_blocks,
+ in_channels=_in_channels,
+ out_channels=self.stage_widths[i],
+ expansion=1,
+ stride=stride,
+ dilation=dilation,
+ style=self.style,
+ avg_down=self.avg_down,
+ with_cp=self.with_cp,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ base_channels=self.stage_widths[i],
+ groups=stage_groups,
+ width_per_group=group_width)
+ _in_channels = self.stage_widths[i]
+ layer_name = f'layer{i + 1}'
+ self.add_module(layer_name, res_layer)
+ self.res_layers.append(layer_name)
+
+ self._freeze_stages()
+
+ self.feat_dim = stage_widths[-1]
+
+ def _make_stem_layer(self, in_channels, base_channels):
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ base_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ bias=False)
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, base_channels, postfix=1)
+ self.add_module(self.norm1_name, norm1)
+ self.relu = nn.ReLU(inplace=True)
+
+ @staticmethod
+ def generate_regnet(initial_width,
+ width_slope,
+ width_parameter,
+ depth,
+ divisor=8):
+ """Generates per block width from RegNet parameters.
+
+ Args:
+ initial_width ([int]): Initial width of the backbone
+ width_slope ([float]): Slope of the quantized linear function
+ width_parameter ([int]): Parameter used to quantize the width.
+ depth ([int]): Depth of the backbone.
+ divisor (int, optional): The divisor of channels. Defaults to 8.
+
+ Returns:
+ list, int: return a list of widths of each stage and the number of
+ stages
+ """
+ assert width_slope >= 0
+ assert initial_width > 0
+ assert width_parameter > 1
+ assert initial_width % divisor == 0
+ widths_cont = np.arange(depth) * width_slope + initial_width
+ ks = np.round(
+ np.log(widths_cont / initial_width) / np.log(width_parameter))
+ widths = initial_width * np.power(width_parameter, ks)
+ widths = np.round(np.divide(widths, divisor)) * divisor
+ num_stages = len(np.unique(widths))
+ widths, widths_cont = widths.astype(int).tolist(), widths_cont.tolist()
+ return widths, num_stages
+
+ @staticmethod
+ def quantize_float(number, divisor):
+ """Converts a float to closest non-zero int divisible by divior.
+
+ Args:
+ number (int): Original number to be quantized.
+ divisor (int): Divisor used to quantize the number.
+
+ Returns:
+ int: quantized number that is divisible by devisor.
+ """
+ return int(round(number / divisor) * divisor)
+
+ def adjust_width_group(self, widths, bottleneck_ratio, groups):
+ """Adjusts the compatibility of widths and groups.
+
+ Args:
+ widths (list[int]): Width of each stage.
+ bottleneck_ratio (float): Bottleneck ratio.
+ groups (int): number of groups in each stage
+
+ Returns:
+ tuple(list): The adjusted widths and groups of each stage.
+ """
+ bottleneck_width = [
+ int(w * b) for w, b in zip(widths, bottleneck_ratio)
+ ]
+ groups = [min(g, w_bot) for g, w_bot in zip(groups, bottleneck_width)]
+ bottleneck_width = [
+ self.quantize_float(w_bot, g)
+ for w_bot, g in zip(bottleneck_width, groups)
+ ]
+ widths = [
+ int(w_bot / b)
+ for w_bot, b in zip(bottleneck_width, bottleneck_ratio)
+ ]
+ return widths, groups
+
+ def get_stages_from_blocks(self, widths):
+ """Gets widths/stage_blocks of network at each stage.
+
+ Args:
+ widths (list[int]): Width in each stage.
+
+ Returns:
+ tuple(list): width and depth of each stage
+ """
+ width_diff = [
+ width != width_prev
+ for width, width_prev in zip(widths + [0], [0] + widths)
+ ]
+ stage_widths = [
+ width for width, diff in zip(widths, width_diff[:-1]) if diff
+ ]
+ stage_blocks = np.diff([
+ depth for depth, diff in zip(range(len(width_diff)), width_diff)
+ if diff
+ ]).tolist()
+ return stage_widths, stage_blocks
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu(x)
+
+ outs = []
+ for i, layer_name in enumerate(self.res_layers):
+ res_layer = getattr(self, layer_name)
+ x = res_layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnest.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnest.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a2d4081df1417155f0626646f5fe3d0dbfc2864
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnest.py
@@ -0,0 +1,338 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+from ..builder import BACKBONES
+from .resnet import Bottleneck as _Bottleneck
+from .resnet import ResLayer, ResNetV1d
+
+
+class RSoftmax(nn.Module):
+ """Radix Softmax module in ``SplitAttentionConv2d``.
+
+ Args:
+ radix (int): Radix of input.
+ groups (int): Groups of input.
+ """
+
+ def __init__(self, radix, groups):
+ super().__init__()
+ self.radix = radix
+ self.groups = groups
+
+ def forward(self, x):
+ batch = x.size(0)
+ if self.radix > 1:
+ x = x.view(batch, self.groups, self.radix, -1).transpose(1, 2)
+ x = F.softmax(x, dim=1)
+ x = x.reshape(batch, -1)
+ else:
+ x = torch.sigmoid(x)
+ return x
+
+
+class SplitAttentionConv2d(nn.Module):
+ """Split-Attention Conv2d.
+
+ Args:
+ in_channels (int): Same as nn.Conv2d.
+ out_channels (int): Same as nn.Conv2d.
+ kernel_size (int | tuple[int]): Same as nn.Conv2d.
+ stride (int | tuple[int]): Same as nn.Conv2d.
+ padding (int | tuple[int]): Same as nn.Conv2d.
+ dilation (int | tuple[int]): Same as nn.Conv2d.
+ groups (int): Same as nn.Conv2d.
+ radix (int): Radix of SpltAtConv2d. Default: 2
+ reduction_factor (int): Reduction factor of SplitAttentionConv2d.
+ Default: 4.
+ conv_cfg (dict): Config dict for convolution layer. Default: None,
+ which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer. Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ channels,
+ kernel_size,
+ stride=1,
+ padding=0,
+ dilation=1,
+ groups=1,
+ radix=2,
+ reduction_factor=4,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN')):
+ super().__init__()
+ inter_channels = max(in_channels * radix // reduction_factor, 32)
+ self.radix = radix
+ self.groups = groups
+ self.channels = channels
+ self.conv = build_conv_layer(
+ conv_cfg,
+ in_channels,
+ channels * radix,
+ kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ groups=groups * radix,
+ bias=False)
+ self.norm0_name, norm0 = build_norm_layer(
+ norm_cfg, channels * radix, postfix=0)
+ self.add_module(self.norm0_name, norm0)
+ self.relu = nn.ReLU(inplace=True)
+ self.fc1 = build_conv_layer(
+ None, channels, inter_channels, 1, groups=self.groups)
+ self.norm1_name, norm1 = build_norm_layer(
+ norm_cfg, inter_channels, postfix=1)
+ self.add_module(self.norm1_name, norm1)
+ self.fc2 = build_conv_layer(
+ None, inter_channels, channels * radix, 1, groups=self.groups)
+ self.rsoftmax = RSoftmax(radix, groups)
+
+ @property
+ def norm0(self):
+ return getattr(self, self.norm0_name)
+
+ @property
+ def norm1(self):
+ return getattr(self, self.norm1_name)
+
+ def forward(self, x):
+ x = self.conv(x)
+ x = self.norm0(x)
+ x = self.relu(x)
+
+ batch, rchannel = x.shape[:2]
+ if self.radix > 1:
+ splits = x.view(batch, self.radix, -1, *x.shape[2:])
+ gap = splits.sum(dim=1)
+ else:
+ gap = x
+ gap = F.adaptive_avg_pool2d(gap, 1)
+ gap = self.fc1(gap)
+
+ gap = self.norm1(gap)
+ gap = self.relu(gap)
+
+ atten = self.fc2(gap)
+ atten = self.rsoftmax(atten).view(batch, -1, 1, 1)
+
+ if self.radix > 1:
+ attens = atten.view(batch, self.radix, -1, *atten.shape[2:])
+ out = torch.sum(attens * splits, dim=1)
+ else:
+ out = atten * x
+ return out.contiguous()
+
+
+class Bottleneck(_Bottleneck):
+ """Bottleneck block for ResNeSt.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ groups (int): Groups of conv2.
+ width_per_group (int): Width per group of conv2. 64x4d indicates
+ ``groups=64, width_per_group=4`` and 32x8d indicates
+ ``groups=32, width_per_group=8``.
+ radix (int): Radix of SpltAtConv2d. Default: 2
+ reduction_factor (int): Reduction factor of SplitAttentionConv2d.
+ Default: 4.
+ avg_down_stride (bool): Whether to use average pool for stride in
+ Bottleneck. Default: True.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ groups=1,
+ width_per_group=4,
+ base_channels=64,
+ radix=2,
+ reduction_factor=4,
+ avg_down_stride=True,
+ **kwargs):
+ super().__init__(in_channels, out_channels, **kwargs)
+
+ self.groups = groups
+ self.width_per_group = width_per_group
+
+ # For ResNet bottleneck, middle channels are determined by expansion
+ # and out_channels, but for ResNeXt bottleneck, it is determined by
+ # groups and width_per_group and the stage it is located in.
+ if groups != 1:
+ assert self.mid_channels % base_channels == 0
+ self.mid_channels = (
+ groups * width_per_group * self.mid_channels // base_channels)
+
+ self.avg_down_stride = avg_down_stride and self.conv2_stride > 1
+
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=1)
+ self.norm3_name, norm3 = build_norm_layer(
+ self.norm_cfg, self.out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ self.in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = SplitAttentionConv2d(
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=3,
+ stride=1 if self.avg_down_stride else self.conv2_stride,
+ padding=self.dilation,
+ dilation=self.dilation,
+ groups=groups,
+ radix=radix,
+ reduction_factor=reduction_factor,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg)
+ delattr(self, self.norm2_name)
+
+ if self.avg_down_stride:
+ self.avd_layer = nn.AvgPool2d(3, self.conv2_stride, padding=1)
+
+ self.conv3 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.out_channels,
+ kernel_size=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+
+ if self.avg_down_stride:
+ out = self.avd_layer(out)
+
+ out = self.conv3(out)
+ out = self.norm3(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+@BACKBONES.register_module()
+class ResNeSt(ResNetV1d):
+ """ResNeSt backbone.
+
+ Please refer to the `paper `__
+ for details.
+
+ Args:
+ depth (int): Network depth, from {50, 101, 152, 200}.
+ groups (int): Groups of conv2 in Bottleneck. Default: 32.
+ width_per_group (int): Width per group of conv2 in Bottleneck.
+ Default: 4.
+ radix (int): Radix of SpltAtConv2d. Default: 2
+ reduction_factor (int): Reduction factor of SplitAttentionConv2d.
+ Default: 4.
+ avg_down_stride (bool): Whether to use average pool for stride in
+ Bottleneck. Default: True.
+ in_channels (int): Number of input image channels. Default: 3.
+ stem_channels (int): Output channels of the stem layer. Default: 64.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+ """
+
+ arch_settings = {
+ 50: (Bottleneck, (3, 4, 6, 3)),
+ 101: (Bottleneck, (3, 4, 23, 3)),
+ 152: (Bottleneck, (3, 8, 36, 3)),
+ 200: (Bottleneck, (3, 24, 36, 3)),
+ 269: (Bottleneck, (3, 30, 48, 8))
+ }
+
+ def __init__(self,
+ depth,
+ groups=1,
+ width_per_group=4,
+ radix=2,
+ reduction_factor=4,
+ avg_down_stride=True,
+ **kwargs):
+ self.groups = groups
+ self.width_per_group = width_per_group
+ self.radix = radix
+ self.reduction_factor = reduction_factor
+ self.avg_down_stride = avg_down_stride
+ super().__init__(depth=depth, **kwargs)
+
+ def make_res_layer(self, **kwargs):
+ return ResLayer(
+ groups=self.groups,
+ width_per_group=self.width_per_group,
+ base_channels=self.base_channels,
+ radix=self.radix,
+ reduction_factor=self.reduction_factor,
+ avg_down_stride=self.avg_down_stride,
+ **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..649496a755020140d94eb32fbe79d1ff135c86ca
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnet.py
@@ -0,0 +1,701 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import (ConvModule, build_conv_layer, build_norm_layer,
+ constant_init, kaiming_init)
+from mmcv.utils.parrots_wrapper import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class BasicBlock(nn.Module):
+ """BasicBlock for ResNet.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (int): The ratio of ``out_channels/mid_channels`` where
+ ``mid_channels`` is the output channels of conv1. This is a
+ reserved argument in BasicBlock and should always be 1. Default: 1.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None.
+ style (str): `pytorch` or `caffe`. It is unused and reserved for
+ unified API with Bottleneck.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ expansion=1,
+ stride=1,
+ dilation=1,
+ downsample=None,
+ style='pytorch',
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN')):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.expansion = expansion
+ assert self.expansion == 1
+ assert out_channels % expansion == 0
+ self.mid_channels = out_channels // expansion
+ self.stride = stride
+ self.dilation = dilation
+ self.style = style
+ self.with_cp = with_cp
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+
+ self.norm1_name, norm1 = build_norm_layer(
+ norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ norm_cfg, out_channels, postfix=2)
+
+ self.conv1 = build_conv_layer(
+ conv_cfg,
+ in_channels,
+ self.mid_channels,
+ 3,
+ stride=stride,
+ padding=dilation,
+ dilation=dilation,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ conv_cfg,
+ self.mid_channels,
+ out_channels,
+ 3,
+ padding=1,
+ bias=False)
+ self.add_module(self.norm2_name, norm2)
+
+ self.relu = nn.ReLU(inplace=True)
+ self.downsample = downsample
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: the normalization layer named "norm2" """
+ return getattr(self, self.norm2_name)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+class Bottleneck(nn.Module):
+ """Bottleneck block for ResNet.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (int): The ratio of ``out_channels/mid_channels`` where
+ ``mid_channels`` is the input/output channels of conv2. Default: 4.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None.
+ style (str): ``"pytorch"`` or ``"caffe"``. If set to "pytorch", the
+ stride-two layer is the 3x3 conv layer, otherwise the stride-two
+ layer is the first 1x1 conv layer. Default: "pytorch".
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ expansion=4,
+ stride=1,
+ dilation=1,
+ downsample=None,
+ style='pytorch',
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN')):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ assert style in ['pytorch', 'caffe']
+
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.expansion = expansion
+ assert out_channels % expansion == 0
+ self.mid_channels = out_channels // expansion
+ self.stride = stride
+ self.dilation = dilation
+ self.style = style
+ self.with_cp = with_cp
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+
+ if self.style == 'pytorch':
+ self.conv1_stride = 1
+ self.conv2_stride = stride
+ else:
+ self.conv1_stride = stride
+ self.conv2_stride = 1
+
+ self.norm1_name, norm1 = build_norm_layer(
+ norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ norm_cfg, self.mid_channels, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ norm_cfg, out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ conv_cfg,
+ in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ conv_cfg,
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=3,
+ stride=self.conv2_stride,
+ padding=dilation,
+ dilation=dilation,
+ bias=False)
+
+ self.add_module(self.norm2_name, norm2)
+ self.conv3 = build_conv_layer(
+ conv_cfg,
+ self.mid_channels,
+ out_channels,
+ kernel_size=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+ self.relu = nn.ReLU(inplace=True)
+ self.downsample = downsample
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: the normalization layer named "norm2" """
+ return getattr(self, self.norm2_name)
+
+ @property
+ def norm3(self):
+ """nn.Module: the normalization layer named "norm3" """
+ return getattr(self, self.norm3_name)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+ out = self.relu(out)
+
+ out = self.conv3(out)
+ out = self.norm3(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+def get_expansion(block, expansion=None):
+ """Get the expansion of a residual block.
+
+ The block expansion will be obtained by the following order:
+
+ 1. If ``expansion`` is given, just return it.
+ 2. If ``block`` has the attribute ``expansion``, then return
+ ``block.expansion``.
+ 3. Return the default value according the the block type:
+ 1 for ``BasicBlock`` and 4 for ``Bottleneck``.
+
+ Args:
+ block (class): The block class.
+ expansion (int | None): The given expansion ratio.
+
+ Returns:
+ int: The expansion of the block.
+ """
+ if isinstance(expansion, int):
+ assert expansion > 0
+ elif expansion is None:
+ if hasattr(block, 'expansion'):
+ expansion = block.expansion
+ elif issubclass(block, BasicBlock):
+ expansion = 1
+ elif issubclass(block, Bottleneck):
+ expansion = 4
+ else:
+ raise TypeError(f'expansion is not specified for {block.__name__}')
+ else:
+ raise TypeError('expansion must be an integer or None')
+
+ return expansion
+
+
+class ResLayer(nn.Sequential):
+ """ResLayer to build ResNet style backbone.
+
+ Args:
+ block (nn.Module): Residual block used to build ResLayer.
+ num_blocks (int): Number of blocks.
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (int, optional): The expansion for BasicBlock/Bottleneck.
+ If not specified, it will firstly be obtained via
+ ``block.expansion``. If the block has no attribute "expansion",
+ the following default values will be used: 1 for BasicBlock and
+ 4 for Bottleneck. Default: None.
+ stride (int): stride of the first block. Default: 1.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ downsample_first (bool): Downsample at the first block or last block.
+ False for Hourglass, True for ResNet. Default: True
+ """
+
+ def __init__(self,
+ block,
+ num_blocks,
+ in_channels,
+ out_channels,
+ expansion=None,
+ stride=1,
+ avg_down=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ downsample_first=True,
+ **kwargs):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ self.block = block
+ self.expansion = get_expansion(block, expansion)
+
+ downsample = None
+ if stride != 1 or in_channels != out_channels:
+ downsample = []
+ conv_stride = stride
+ if avg_down and stride != 1:
+ conv_stride = 1
+ downsample.append(
+ nn.AvgPool2d(
+ kernel_size=stride,
+ stride=stride,
+ ceil_mode=True,
+ count_include_pad=False))
+ downsample.extend([
+ build_conv_layer(
+ conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=1,
+ stride=conv_stride,
+ bias=False),
+ build_norm_layer(norm_cfg, out_channels)[1]
+ ])
+ downsample = nn.Sequential(*downsample)
+
+ layers = []
+ if downsample_first:
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=stride,
+ downsample=downsample,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+ in_channels = out_channels
+ for _ in range(1, num_blocks):
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+ else: # downsample_first=False is for HourglassModule
+ for i in range(0, num_blocks - 1):
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ expansion=self.expansion,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=stride,
+ downsample=downsample,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ **kwargs))
+
+ super().__init__(*layers)
+
+
+@BACKBONES.register_module()
+class ResNet(BaseBackbone):
+ """ResNet backbone.
+
+ Please refer to the `paper `__ for
+ details.
+
+ Args:
+ depth (int): Network depth, from {18, 34, 50, 101, 152}.
+ in_channels (int): Number of input image channels. Default: 3.
+ stem_channels (int): Output channels of the stem layer. Default: 64.
+ base_channels (int): Middle channels of the first stage. Default: 64.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+
+ Example:
+ >>> from mmpose.models import ResNet
+ >>> import torch
+ >>> self = ResNet(depth=18, out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 64, 8, 8)
+ (1, 128, 4, 4)
+ (1, 256, 2, 2)
+ (1, 512, 1, 1)
+ """
+
+ arch_settings = {
+ 18: (BasicBlock, (2, 2, 2, 2)),
+ 34: (BasicBlock, (3, 4, 6, 3)),
+ 50: (Bottleneck, (3, 4, 6, 3)),
+ 101: (Bottleneck, (3, 4, 23, 3)),
+ 152: (Bottleneck, (3, 8, 36, 3))
+ }
+
+ def __init__(self,
+ depth,
+ in_channels=3,
+ stem_channels=64,
+ base_channels=64,
+ expansion=None,
+ num_stages=4,
+ strides=(1, 2, 2, 2),
+ dilations=(1, 1, 1, 1),
+ out_indices=(3, ),
+ style='pytorch',
+ deep_stem=False,
+ avg_down=False,
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN', requires_grad=True),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=True):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ if depth not in self.arch_settings:
+ raise KeyError(f'invalid depth {depth} for resnet')
+ self.depth = depth
+ self.stem_channels = stem_channels
+ self.base_channels = base_channels
+ self.num_stages = num_stages
+ assert 1 <= num_stages <= 4
+ self.strides = strides
+ self.dilations = dilations
+ assert len(strides) == len(dilations) == num_stages
+ self.out_indices = out_indices
+ assert max(out_indices) < num_stages
+ self.style = style
+ self.deep_stem = deep_stem
+ self.avg_down = avg_down
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.with_cp = with_cp
+ self.norm_eval = norm_eval
+ self.zero_init_residual = zero_init_residual
+ self.block, stage_blocks = self.arch_settings[depth]
+ self.stage_blocks = stage_blocks[:num_stages]
+ self.expansion = get_expansion(self.block, expansion)
+
+ self._make_stem_layer(in_channels, stem_channels)
+
+ self.res_layers = []
+ _in_channels = stem_channels
+ _out_channels = base_channels * self.expansion
+ for i, num_blocks in enumerate(self.stage_blocks):
+ stride = strides[i]
+ dilation = dilations[i]
+ res_layer = self.make_res_layer(
+ block=self.block,
+ num_blocks=num_blocks,
+ in_channels=_in_channels,
+ out_channels=_out_channels,
+ expansion=self.expansion,
+ stride=stride,
+ dilation=dilation,
+ style=self.style,
+ avg_down=self.avg_down,
+ with_cp=with_cp,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg)
+ _in_channels = _out_channels
+ _out_channels *= 2
+ layer_name = f'layer{i + 1}'
+ self.add_module(layer_name, res_layer)
+ self.res_layers.append(layer_name)
+
+ self._freeze_stages()
+
+ self.feat_dim = res_layer[-1].out_channels
+
+ def make_res_layer(self, **kwargs):
+ """Make a ResLayer."""
+ return ResLayer(**kwargs)
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ def _make_stem_layer(self, in_channels, stem_channels):
+ """Make stem layer."""
+ if self.deep_stem:
+ self.stem = nn.Sequential(
+ ConvModule(
+ in_channels,
+ stem_channels // 2,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True),
+ ConvModule(
+ stem_channels // 2,
+ stem_channels // 2,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True),
+ ConvModule(
+ stem_channels // 2,
+ stem_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True))
+ else:
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ stem_channels,
+ kernel_size=7,
+ stride=2,
+ padding=3,
+ bias=False)
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, stem_channels, postfix=1)
+ self.add_module(self.norm1_name, norm1)
+ self.relu = nn.ReLU(inplace=True)
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+
+ def _freeze_stages(self):
+ """Freeze parameters."""
+ if self.frozen_stages >= 0:
+ if self.deep_stem:
+ self.stem.eval()
+ for param in self.stem.parameters():
+ param.requires_grad = False
+ else:
+ self.norm1.eval()
+ for m in [self.conv1, self.norm1]:
+ for param in m.parameters():
+ param.requires_grad = False
+
+ for i in range(1, self.frozen_stages + 1):
+ m = getattr(self, f'layer{i}')
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ super().init_weights(pretrained)
+ if pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+
+ if self.zero_init_residual:
+ for m in self.modules():
+ if isinstance(m, Bottleneck):
+ constant_init(m.norm3, 0)
+ elif isinstance(m, BasicBlock):
+ constant_init(m.norm2, 0)
+
+ def forward(self, x):
+ """Forward function."""
+ if self.deep_stem:
+ x = self.stem(x)
+ else:
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu(x)
+ x = self.maxpool(x)
+ outs = []
+ for i, layer_name in enumerate(self.res_layers):
+ res_layer = getattr(self, layer_name)
+ x = res_layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ # trick: eval have effect on BatchNorm only
+ if isinstance(m, _BatchNorm):
+ m.eval()
+
+
+@BACKBONES.register_module()
+class ResNetV1d(ResNet):
+ r"""ResNetV1d variant described in `Bag of Tricks
+ `__.
+
+ Compared with default ResNet(ResNetV1b), ResNetV1d replaces the 7x7 conv in
+ the input stem with three 3x3 convs. And in the downsampling block, a 2x2
+ avg_pool with stride 2 is added before conv, whose stride is changed to 1.
+ """
+
+ def __init__(self, **kwargs):
+ super().__init__(deep_stem=True, avg_down=True, **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnext.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnext.py
new file mode 100644
index 0000000000000000000000000000000000000000..c10dc33f98ac3229c77bf306acf19950c295f904
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/resnext.py
@@ -0,0 +1,162 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+from ..builder import BACKBONES
+from .resnet import Bottleneck as _Bottleneck
+from .resnet import ResLayer, ResNet
+
+
+class Bottleneck(_Bottleneck):
+ """Bottleneck block for ResNeXt.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ groups (int): Groups of conv2.
+ width_per_group (int): Width per group of conv2. 64x4d indicates
+ ``groups=64, width_per_group=4`` and 32x8d indicates
+ ``groups=32, width_per_group=8``.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ base_channels=64,
+ groups=32,
+ width_per_group=4,
+ **kwargs):
+ super().__init__(in_channels, out_channels, **kwargs)
+ self.groups = groups
+ self.width_per_group = width_per_group
+
+ # For ResNet bottleneck, middle channels are determined by expansion
+ # and out_channels, but for ResNeXt bottleneck, it is determined by
+ # groups and width_per_group and the stage it is located in.
+ if groups != 1:
+ assert self.mid_channels % base_channels == 0
+ self.mid_channels = (
+ groups * width_per_group * self.mid_channels // base_channels)
+
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ self.norm_cfg, self.out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ self.in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=3,
+ stride=self.conv2_stride,
+ padding=self.dilation,
+ dilation=self.dilation,
+ groups=groups,
+ bias=False)
+
+ self.add_module(self.norm2_name, norm2)
+ self.conv3 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.out_channels,
+ kernel_size=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+
+@BACKBONES.register_module()
+class ResNeXt(ResNet):
+ """ResNeXt backbone.
+
+ Please refer to the `paper `__ for
+ details.
+
+ Args:
+ depth (int): Network depth, from {50, 101, 152}.
+ groups (int): Groups of conv2 in Bottleneck. Default: 32.
+ width_per_group (int): Width per group of conv2 in Bottleneck.
+ Default: 4.
+ in_channels (int): Number of input image channels. Default: 3.
+ stem_channels (int): Output channels of the stem layer. Default: 64.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+
+ Example:
+ >>> from mmpose.models import ResNeXt
+ >>> import torch
+ >>> self = ResNeXt(depth=50, out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 32, 32)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 256, 8, 8)
+ (1, 512, 4, 4)
+ (1, 1024, 2, 2)
+ (1, 2048, 1, 1)
+ """
+
+ arch_settings = {
+ 50: (Bottleneck, (3, 4, 6, 3)),
+ 101: (Bottleneck, (3, 4, 23, 3)),
+ 152: (Bottleneck, (3, 8, 36, 3))
+ }
+
+ def __init__(self, depth, groups=32, width_per_group=4, **kwargs):
+ self.groups = groups
+ self.width_per_group = width_per_group
+ super().__init__(depth, **kwargs)
+
+ def make_res_layer(self, **kwargs):
+ return ResLayer(
+ groups=self.groups,
+ width_per_group=self.width_per_group,
+ base_channels=self.base_channels,
+ **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/rsn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/rsn.py
new file mode 100644
index 0000000000000000000000000000000000000000..29038afe2a77dcb3d3b027b1549d478916a50727
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/rsn.py
@@ -0,0 +1,616 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy as cp
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import (ConvModule, MaxPool2d, constant_init, kaiming_init,
+ normal_init)
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class RSB(nn.Module):
+ """Residual Steps block for RSN. Paper ref: Cai et al. "Learning Delicate
+ Local Representations for Multi-Person Pose Estimation" (ECCV 2020).
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ num_steps (int): Numbers of steps in RSB
+ stride (int): stride of the block. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ expand_times (int): Times by which the in_channels are expanded.
+ Default:26.
+ res_top_channels (int): Number of channels of feature output by
+ ResNet_top. Default:64.
+ """
+
+ expansion = 1
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ num_steps=4,
+ stride=1,
+ downsample=None,
+ with_cp=False,
+ norm_cfg=dict(type='BN'),
+ expand_times=26,
+ res_top_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ assert num_steps > 1
+ self.in_channels = in_channels
+ self.branch_channels = self.in_channels * expand_times
+ self.branch_channels //= res_top_channels
+ self.out_channels = out_channels
+ self.stride = stride
+ self.downsample = downsample
+ self.with_cp = with_cp
+ self.norm_cfg = norm_cfg
+ self.num_steps = num_steps
+ self.conv_bn_relu1 = ConvModule(
+ self.in_channels,
+ self.num_steps * self.branch_channels,
+ kernel_size=1,
+ stride=self.stride,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=False)
+ for i in range(self.num_steps):
+ for j in range(i + 1):
+ module_name = f'conv_bn_relu2_{i + 1}_{j + 1}'
+ self.add_module(
+ module_name,
+ ConvModule(
+ self.branch_channels,
+ self.branch_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ norm_cfg=self.norm_cfg,
+ inplace=False))
+ self.conv_bn3 = ConvModule(
+ self.num_steps * self.branch_channels,
+ self.out_channels * self.expansion,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ act_cfg=None,
+ norm_cfg=self.norm_cfg,
+ inplace=False)
+ self.relu = nn.ReLU(inplace=False)
+
+ def forward(self, x):
+ """Forward function."""
+
+ identity = x
+ x = self.conv_bn_relu1(x)
+ spx = torch.split(x, self.branch_channels, 1)
+ outputs = list()
+ outs = list()
+ for i in range(self.num_steps):
+ outputs_i = list()
+ outputs.append(outputs_i)
+ for j in range(i + 1):
+ if j == 0:
+ inputs = spx[i]
+ else:
+ inputs = outputs[i][j - 1]
+ if i > j:
+ inputs = inputs + outputs[i - 1][j]
+ module_name = f'conv_bn_relu2_{i + 1}_{j + 1}'
+ module_i_j = getattr(self, module_name)
+ outputs[i].append(module_i_j(inputs))
+
+ outs.append(outputs[i][i])
+ out = torch.cat(tuple(outs), 1)
+ out = self.conv_bn3(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(identity)
+ out = out + identity
+
+ out = self.relu(out)
+
+ return out
+
+
+class Downsample_module(nn.Module):
+ """Downsample module for RSN.
+
+ Args:
+ block (nn.Module): Downsample block.
+ num_blocks (list): Number of blocks in each downsample unit.
+ num_units (int): Numbers of downsample units. Default: 4
+ has_skip (bool): Have skip connections from prior upsample
+ module or not. Default:False
+ num_steps (int): Number of steps in a block. Default:4
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ in_channels (int): Number of channels of the input feature to
+ downsample module. Default: 64
+ expand_times (int): Times by which the in_channels are expanded.
+ Default:26.
+ """
+
+ def __init__(self,
+ block,
+ num_blocks,
+ num_steps=4,
+ num_units=4,
+ has_skip=False,
+ norm_cfg=dict(type='BN'),
+ in_channels=64,
+ expand_times=26):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.has_skip = has_skip
+ self.in_channels = in_channels
+ assert len(num_blocks) == num_units
+ self.num_blocks = num_blocks
+ self.num_units = num_units
+ self.num_steps = num_steps
+ self.norm_cfg = norm_cfg
+ self.layer1 = self._make_layer(
+ block,
+ in_channels,
+ num_blocks[0],
+ expand_times=expand_times,
+ res_top_channels=in_channels)
+ for i in range(1, num_units):
+ module_name = f'layer{i + 1}'
+ self.add_module(
+ module_name,
+ self._make_layer(
+ block,
+ in_channels * pow(2, i),
+ num_blocks[i],
+ stride=2,
+ expand_times=expand_times,
+ res_top_channels=in_channels))
+
+ def _make_layer(self,
+ block,
+ out_channels,
+ blocks,
+ stride=1,
+ expand_times=26,
+ res_top_channels=64):
+ downsample = None
+ if stride != 1 or self.in_channels != out_channels * block.expansion:
+ downsample = ConvModule(
+ self.in_channels,
+ out_channels * block.expansion,
+ kernel_size=1,
+ stride=stride,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+
+ units = list()
+ units.append(
+ block(
+ self.in_channels,
+ out_channels,
+ num_steps=self.num_steps,
+ stride=stride,
+ downsample=downsample,
+ norm_cfg=self.norm_cfg,
+ expand_times=expand_times,
+ res_top_channels=res_top_channels))
+ self.in_channels = out_channels * block.expansion
+ for _ in range(1, blocks):
+ units.append(
+ block(
+ self.in_channels,
+ out_channels,
+ num_steps=self.num_steps,
+ expand_times=expand_times,
+ res_top_channels=res_top_channels))
+
+ return nn.Sequential(*units)
+
+ def forward(self, x, skip1, skip2):
+ out = list()
+ for i in range(self.num_units):
+ module_name = f'layer{i + 1}'
+ module_i = getattr(self, module_name)
+ x = module_i(x)
+ if self.has_skip:
+ x = x + skip1[i] + skip2[i]
+ out.append(x)
+ out.reverse()
+
+ return tuple(out)
+
+
+class Upsample_unit(nn.Module):
+ """Upsample unit for upsample module.
+
+ Args:
+ ind (int): Indicates whether to interpolate (>0) and whether to
+ generate feature map for the next hourglass-like module.
+ num_units (int): Number of units that form a upsample module. Along
+ with ind and gen_cross_conv, nm_units is used to decide whether
+ to generate feature map for the next hourglass-like module.
+ in_channels (int): Channel number of the skip-in feature maps from
+ the corresponding downsample unit.
+ unit_channels (int): Channel number in this unit. Default:256.
+ gen_skip: (bool): Whether or not to generate skips for the posterior
+ downsample module. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ out_channels (in): Number of channels of feature output by upsample
+ module. Must equal to in_channels of downsample module. Default:64
+ """
+
+ def __init__(self,
+ ind,
+ num_units,
+ in_channels,
+ unit_channels=256,
+ gen_skip=False,
+ gen_cross_conv=False,
+ norm_cfg=dict(type='BN'),
+ out_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.num_units = num_units
+ self.norm_cfg = norm_cfg
+ self.in_skip = ConvModule(
+ in_channels,
+ unit_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+ self.relu = nn.ReLU(inplace=True)
+
+ self.ind = ind
+ if self.ind > 0:
+ self.up_conv = ConvModule(
+ unit_channels,
+ unit_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ act_cfg=None,
+ inplace=True)
+
+ self.gen_skip = gen_skip
+ if self.gen_skip:
+ self.out_skip1 = ConvModule(
+ in_channels,
+ in_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ self.out_skip2 = ConvModule(
+ unit_channels,
+ in_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ self.gen_cross_conv = gen_cross_conv
+ if self.ind == num_units - 1 and self.gen_cross_conv:
+ self.cross_conv = ConvModule(
+ unit_channels,
+ out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=self.norm_cfg,
+ inplace=True)
+
+ def forward(self, x, up_x):
+ out = self.in_skip(x)
+
+ if self.ind > 0:
+ up_x = F.interpolate(
+ up_x,
+ size=(x.size(2), x.size(3)),
+ mode='bilinear',
+ align_corners=True)
+ up_x = self.up_conv(up_x)
+ out = out + up_x
+ out = self.relu(out)
+
+ skip1 = None
+ skip2 = None
+ if self.gen_skip:
+ skip1 = self.out_skip1(x)
+ skip2 = self.out_skip2(out)
+
+ cross_conv = None
+ if self.ind == self.num_units - 1 and self.gen_cross_conv:
+ cross_conv = self.cross_conv(out)
+
+ return out, skip1, skip2, cross_conv
+
+
+class Upsample_module(nn.Module):
+ """Upsample module for RSN.
+
+ Args:
+ unit_channels (int): Channel number in the upsample units.
+ Default:256.
+ num_units (int): Numbers of upsample units. Default: 4
+ gen_skip (bool): Whether to generate skip for posterior downsample
+ module or not. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ out_channels (int): Number of channels of feature output by upsample
+ module. Must equal to in_channels of downsample module. Default:64
+ """
+
+ def __init__(self,
+ unit_channels=256,
+ num_units=4,
+ gen_skip=False,
+ gen_cross_conv=False,
+ norm_cfg=dict(type='BN'),
+ out_channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.in_channels = list()
+ for i in range(num_units):
+ self.in_channels.append(RSB.expansion * out_channels * pow(2, i))
+ self.in_channels.reverse()
+ self.num_units = num_units
+ self.gen_skip = gen_skip
+ self.gen_cross_conv = gen_cross_conv
+ self.norm_cfg = norm_cfg
+ for i in range(num_units):
+ module_name = f'up{i + 1}'
+ self.add_module(
+ module_name,
+ Upsample_unit(
+ i,
+ self.num_units,
+ self.in_channels[i],
+ unit_channels,
+ self.gen_skip,
+ self.gen_cross_conv,
+ norm_cfg=self.norm_cfg,
+ out_channels=64))
+
+ def forward(self, x):
+ out = list()
+ skip1 = list()
+ skip2 = list()
+ cross_conv = None
+ for i in range(self.num_units):
+ module_i = getattr(self, f'up{i + 1}')
+ if i == 0:
+ outi, skip1_i, skip2_i, _ = module_i(x[i], None)
+ elif i == self.num_units - 1:
+ outi, skip1_i, skip2_i, cross_conv = module_i(x[i], out[i - 1])
+ else:
+ outi, skip1_i, skip2_i, _ = module_i(x[i], out[i - 1])
+ out.append(outi)
+ skip1.append(skip1_i)
+ skip2.append(skip2_i)
+ skip1.reverse()
+ skip2.reverse()
+
+ return out, skip1, skip2, cross_conv
+
+
+class Single_stage_RSN(nn.Module):
+ """Single_stage Residual Steps Network.
+
+ Args:
+ unit_channels (int): Channel number in the upsample units. Default:256.
+ num_units (int): Numbers of downsample/upsample units. Default: 4
+ gen_skip (bool): Whether to generate skip for posterior downsample
+ module or not. Default:False
+ gen_cross_conv (bool): Whether to generate feature map for the next
+ hourglass-like module. Default:False
+ has_skip (bool): Have skip connections from prior upsample
+ module or not. Default:False
+ num_steps (int): Number of steps in RSB. Default: 4
+ num_blocks (list): Number of blocks in each downsample unit.
+ Default: [2, 2, 2, 2] Note: Make sure num_units==len(num_blocks)
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ in_channels (int): Number of channels of the feature from ResNet_Top.
+ Default: 64.
+ expand_times (int): Times by which the in_channels are expanded in RSB.
+ Default:26.
+ """
+
+ def __init__(self,
+ has_skip=False,
+ gen_skip=False,
+ gen_cross_conv=False,
+ unit_channels=256,
+ num_units=4,
+ num_steps=4,
+ num_blocks=[2, 2, 2, 2],
+ norm_cfg=dict(type='BN'),
+ in_channels=64,
+ expand_times=26):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ num_blocks = cp.deepcopy(num_blocks)
+ super().__init__()
+ assert len(num_blocks) == num_units
+ self.has_skip = has_skip
+ self.gen_skip = gen_skip
+ self.gen_cross_conv = gen_cross_conv
+ self.num_units = num_units
+ self.num_steps = num_steps
+ self.unit_channels = unit_channels
+ self.num_blocks = num_blocks
+ self.norm_cfg = norm_cfg
+
+ self.downsample = Downsample_module(RSB, num_blocks, num_steps,
+ num_units, has_skip, norm_cfg,
+ in_channels, expand_times)
+ self.upsample = Upsample_module(unit_channels, num_units, gen_skip,
+ gen_cross_conv, norm_cfg, in_channels)
+
+ def forward(self, x, skip1, skip2):
+ mid = self.downsample(x, skip1, skip2)
+ out, skip1, skip2, cross_conv = self.upsample(mid)
+
+ return out, skip1, skip2, cross_conv
+
+
+class ResNet_top(nn.Module):
+ """ResNet top for RSN.
+
+ Args:
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ channels (int): Number of channels of the feature output by ResNet_top.
+ """
+
+ def __init__(self, norm_cfg=dict(type='BN'), channels=64):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.top = nn.Sequential(
+ ConvModule(
+ 3,
+ channels,
+ kernel_size=7,
+ stride=2,
+ padding=3,
+ norm_cfg=norm_cfg,
+ inplace=True), MaxPool2d(kernel_size=3, stride=2, padding=1))
+
+ def forward(self, img):
+ return self.top(img)
+
+
+@BACKBONES.register_module()
+class RSN(BaseBackbone):
+ """Residual Steps Network backbone. Paper ref: Cai et al. "Learning
+ Delicate Local Representations for Multi-Person Pose Estimation" (ECCV
+ 2020).
+
+ Args:
+ unit_channels (int): Number of Channels in an upsample unit.
+ Default: 256
+ num_stages (int): Number of stages in a multi-stage RSN. Default: 4
+ num_units (int): NUmber of downsample/upsample units in a single-stage
+ RSN. Default: 4 Note: Make sure num_units == len(self.num_blocks)
+ num_blocks (list): Number of RSBs (Residual Steps Block) in each
+ downsample unit. Default: [2, 2, 2, 2]
+ num_steps (int): Number of steps in a RSB. Default:4
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ res_top_channels (int): Number of channels of feature from ResNet_top.
+ Default: 64.
+ expand_times (int): Times by which the in_channels are expanded in RSB.
+ Default:26.
+ Example:
+ >>> from mmpose.models import RSN
+ >>> import torch
+ >>> self = RSN(num_stages=2,num_units=2,num_blocks=[2,2])
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 511, 511)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_output in level_outputs:
+ ... for feature in level_output:
+ ... print(tuple(feature.shape))
+ ...
+ (1, 256, 64, 64)
+ (1, 256, 128, 128)
+ (1, 256, 64, 64)
+ (1, 256, 128, 128)
+ """
+
+ def __init__(self,
+ unit_channels=256,
+ num_stages=4,
+ num_units=4,
+ num_blocks=[2, 2, 2, 2],
+ num_steps=4,
+ norm_cfg=dict(type='BN'),
+ res_top_channels=64,
+ expand_times=26):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ num_blocks = cp.deepcopy(num_blocks)
+ super().__init__()
+ self.unit_channels = unit_channels
+ self.num_stages = num_stages
+ self.num_units = num_units
+ self.num_blocks = num_blocks
+ self.num_steps = num_steps
+ self.norm_cfg = norm_cfg
+
+ assert self.num_stages > 0
+ assert self.num_steps > 1
+ assert self.num_units > 1
+ assert self.num_units == len(self.num_blocks)
+ self.top = ResNet_top(norm_cfg=norm_cfg)
+ self.multi_stage_rsn = nn.ModuleList([])
+ for i in range(self.num_stages):
+ if i == 0:
+ has_skip = False
+ else:
+ has_skip = True
+ if i != self.num_stages - 1:
+ gen_skip = True
+ gen_cross_conv = True
+ else:
+ gen_skip = False
+ gen_cross_conv = False
+ self.multi_stage_rsn.append(
+ Single_stage_RSN(has_skip, gen_skip, gen_cross_conv,
+ unit_channels, num_units, num_steps,
+ num_blocks, norm_cfg, res_top_channels,
+ expand_times))
+
+ def forward(self, x):
+ """Model forward function."""
+ out_feats = []
+ skip1 = None
+ skip2 = None
+ x = self.top(x)
+ for i in range(self.num_stages):
+ out, skip1, skip2, x = self.multi_stage_rsn[i](x, skip1, skip2)
+ out_feats.append(out)
+
+ return out_feats
+
+ def init_weights(self, pretrained=None):
+ """Initialize model weights."""
+ for m in self.multi_stage_rsn.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ elif isinstance(m, nn.Linear):
+ normal_init(m, std=0.01)
+
+ for m in self.top.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/scnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/scnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..3786c5731d685638cfa64a83e5d4a5e2eee545de
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/scnet.py
@@ -0,0 +1,248 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+from ..builder import BACKBONES
+from .resnet import Bottleneck, ResNet
+
+
+class SCConv(nn.Module):
+ """SCConv (Self-calibrated Convolution)
+
+ Args:
+ in_channels (int): The input channels of the SCConv.
+ out_channels (int): The output channel of the SCConv.
+ stride (int): stride of SCConv.
+ pooling_r (int): size of pooling for scconv.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ stride,
+ pooling_r,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN', momentum=0.1)):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+
+ assert in_channels == out_channels
+
+ self.k2 = nn.Sequential(
+ nn.AvgPool2d(kernel_size=pooling_r, stride=pooling_r),
+ build_conv_layer(
+ conv_cfg,
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=False),
+ build_norm_layer(norm_cfg, in_channels)[1],
+ )
+ self.k3 = nn.Sequential(
+ build_conv_layer(
+ conv_cfg,
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ bias=False),
+ build_norm_layer(norm_cfg, in_channels)[1],
+ )
+ self.k4 = nn.Sequential(
+ build_conv_layer(
+ conv_cfg,
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=stride,
+ padding=1,
+ bias=False),
+ build_norm_layer(norm_cfg, out_channels)[1],
+ nn.ReLU(inplace=True),
+ )
+
+ def forward(self, x):
+ """Forward function."""
+ identity = x
+
+ out = torch.sigmoid(
+ torch.add(identity, F.interpolate(self.k2(x),
+ identity.size()[2:])))
+ out = torch.mul(self.k3(x), out)
+ out = self.k4(out)
+
+ return out
+
+
+class SCBottleneck(Bottleneck):
+ """SC(Self-calibrated) Bottleneck.
+
+ Args:
+ in_channels (int): The input channels of the SCBottleneck block.
+ out_channels (int): The output channel of the SCBottleneck block.
+ """
+
+ pooling_r = 4
+
+ def __init__(self, in_channels, out_channels, **kwargs):
+ super().__init__(in_channels, out_channels, **kwargs)
+ self.mid_channels = out_channels // self.expansion // 2
+
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ self.norm_cfg, out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=1,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+
+ self.k1 = nn.Sequential(
+ build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ bias=False),
+ build_norm_layer(self.norm_cfg, self.mid_channels)[1],
+ nn.ReLU(inplace=True))
+
+ self.conv2 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=1,
+ bias=False)
+ self.add_module(self.norm2_name, norm2)
+
+ self.scconv = SCConv(self.mid_channels, self.mid_channels, self.stride,
+ self.pooling_r, self.conv_cfg, self.norm_cfg)
+
+ self.conv3 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels * 2,
+ out_channels,
+ kernel_size=1,
+ stride=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out_a = self.conv1(x)
+ out_a = self.norm1(out_a)
+ out_a = self.relu(out_a)
+
+ out_a = self.k1(out_a)
+
+ out_b = self.conv2(x)
+ out_b = self.norm2(out_b)
+ out_b = self.relu(out_b)
+
+ out_b = self.scconv(out_b)
+
+ out = self.conv3(torch.cat([out_a, out_b], dim=1))
+ out = self.norm3(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+@BACKBONES.register_module()
+class SCNet(ResNet):
+ """SCNet backbone.
+
+ Improving Convolutional Networks with Self-Calibrated Convolutions,
+ Jiang-Jiang Liu, Qibin Hou, Ming-Ming Cheng, Changhu Wang, Jiashi Feng,
+ IEEE CVPR, 2020.
+ http://mftp.mmcheng.net/Papers/20cvprSCNet.pdf
+
+ Args:
+ depth (int): Depth of scnet, from {50, 101}.
+ in_channels (int): Number of input image channels. Normally 3.
+ base_channels (int): Number of base channels of hidden layer.
+ num_stages (int): SCNet stages, normally 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ dilations (Sequence[int]): Dilation of each stage.
+ out_indices (Sequence[int]): Output from which stages.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters.
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity.
+
+ Example:
+ >>> from mmpose.models import SCNet
+ >>> import torch
+ >>> self = SCNet(depth=50, out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 224, 224)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 256, 56, 56)
+ (1, 512, 28, 28)
+ (1, 1024, 14, 14)
+ (1, 2048, 7, 7)
+ """
+
+ arch_settings = {
+ 50: (SCBottleneck, [3, 4, 6, 3]),
+ 101: (SCBottleneck, [3, 4, 23, 3])
+ }
+
+ def __init__(self, depth, **kwargs):
+ if depth not in self.arch_settings:
+ raise KeyError(f'invalid depth {depth} for SCNet')
+ super().__init__(depth, **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac2d53b40a4593bce96d5c7c3bb4e06d38353d0b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnet.py
@@ -0,0 +1,125 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.utils.checkpoint as cp
+
+from ..builder import BACKBONES
+from .resnet import Bottleneck, ResLayer, ResNet
+from .utils.se_layer import SELayer
+
+
+class SEBottleneck(Bottleneck):
+ """SEBottleneck block for SEResNet.
+
+ Args:
+ in_channels (int): The input channels of the SEBottleneck block.
+ out_channels (int): The output channel of the SEBottleneck block.
+ se_ratio (int): Squeeze ratio in SELayer. Default: 16
+ """
+
+ def __init__(self, in_channels, out_channels, se_ratio=16, **kwargs):
+ super().__init__(in_channels, out_channels, **kwargs)
+ self.se_layer = SELayer(out_channels, ratio=se_ratio)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+ out = self.relu(out)
+
+ out = self.conv3(out)
+ out = self.norm3(out)
+
+ out = self.se_layer(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+@BACKBONES.register_module()
+class SEResNet(ResNet):
+ """SEResNet backbone.
+
+ Please refer to the `paper `__ for
+ details.
+
+ Args:
+ depth (int): Network depth, from {50, 101, 152}.
+ se_ratio (int): Squeeze ratio in SELayer. Default: 16.
+ in_channels (int): Number of input image channels. Default: 3.
+ stem_channels (int): Output channels of the stem layer. Default: 64.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+
+ Example:
+ >>> from mmpose.models import SEResNet
+ >>> import torch
+ >>> self = SEResNet(depth=50, out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 224, 224)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 256, 56, 56)
+ (1, 512, 28, 28)
+ (1, 1024, 14, 14)
+ (1, 2048, 7, 7)
+ """
+
+ arch_settings = {
+ 50: (SEBottleneck, (3, 4, 6, 3)),
+ 101: (SEBottleneck, (3, 4, 23, 3)),
+ 152: (SEBottleneck, (3, 8, 36, 3))
+ }
+
+ def __init__(self, depth, se_ratio=16, **kwargs):
+ if depth not in self.arch_settings:
+ raise KeyError(f'invalid depth {depth} for SEResNet')
+ self.se_ratio = se_ratio
+ super().__init__(depth, **kwargs)
+
+ def make_res_layer(self, **kwargs):
+ return ResLayer(se_ratio=self.se_ratio, **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnext.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnext.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5c4e4ce03684f8a9bd0c6166969c01bace54bd2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/seresnext.py
@@ -0,0 +1,168 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.cnn import build_conv_layer, build_norm_layer
+
+from ..builder import BACKBONES
+from .resnet import ResLayer
+from .seresnet import SEBottleneck as _SEBottleneck
+from .seresnet import SEResNet
+
+
+class SEBottleneck(_SEBottleneck):
+ """SEBottleneck block for SEResNeXt.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ base_channels (int): Middle channels of the first stage. Default: 64.
+ groups (int): Groups of conv2.
+ width_per_group (int): Width per group of conv2. 64x4d indicates
+ ``groups=64, width_per_group=4`` and 32x8d indicates
+ ``groups=32, width_per_group=8``.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None
+ se_ratio (int): Squeeze ratio in SELayer. Default: 16
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ base_channels=64,
+ groups=32,
+ width_per_group=4,
+ se_ratio=16,
+ **kwargs):
+ super().__init__(in_channels, out_channels, se_ratio, **kwargs)
+ self.groups = groups
+ self.width_per_group = width_per_group
+
+ # We follow the same rational of ResNext to compute mid_channels.
+ # For SEResNet bottleneck, middle channels are determined by expansion
+ # and out_channels, but for SEResNeXt bottleneck, it is determined by
+ # groups and width_per_group and the stage it is located in.
+ if groups != 1:
+ assert self.mid_channels % base_channels == 0
+ self.mid_channels = (
+ groups * width_per_group * self.mid_channels // base_channels)
+
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ self.norm_cfg, self.mid_channels, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ self.norm_cfg, self.out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ self.in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=3,
+ stride=self.conv2_stride,
+ padding=self.dilation,
+ dilation=self.dilation,
+ groups=groups,
+ bias=False)
+
+ self.add_module(self.norm2_name, norm2)
+ self.conv3 = build_conv_layer(
+ self.conv_cfg,
+ self.mid_channels,
+ self.out_channels,
+ kernel_size=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+
+@BACKBONES.register_module()
+class SEResNeXt(SEResNet):
+ """SEResNeXt backbone.
+
+ Please refer to the `paper `__ for
+ details.
+
+ Args:
+ depth (int): Network depth, from {50, 101, 152}.
+ groups (int): Groups of conv2 in Bottleneck. Default: 32.
+ width_per_group (int): Width per group of conv2 in Bottleneck.
+ Default: 4.
+ se_ratio (int): Squeeze ratio in SELayer. Default: 16.
+ in_channels (int): Number of input image channels. Default: 3.
+ stem_channels (int): Output channels of the stem layer. Default: 64.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+
+ Example:
+ >>> from mmpose.models import SEResNeXt
+ >>> import torch
+ >>> self = SEResNet(depth=50, out_indices=(0, 1, 2, 3))
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 3, 224, 224)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 256, 56, 56)
+ (1, 512, 28, 28)
+ (1, 1024, 14, 14)
+ (1, 2048, 7, 7)
+ """
+
+ arch_settings = {
+ 50: (SEBottleneck, (3, 4, 6, 3)),
+ 101: (SEBottleneck, (3, 4, 23, 3)),
+ 152: (SEBottleneck, (3, 8, 36, 3))
+ }
+
+ def __init__(self, depth, groups=32, width_per_group=4, **kwargs):
+ self.groups = groups
+ self.width_per_group = width_per_group
+ super().__init__(depth, **kwargs)
+
+ def make_res_layer(self, **kwargs):
+ return ResLayer(
+ groups=self.groups,
+ width_per_group=self.width_per_group,
+ base_channels=self.base_channels,
+ **kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v1.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v1.py
new file mode 100644
index 0000000000000000000000000000000000000000..9f98cbd2132250ec13adcce6e642c966b0dbd7cc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v1.py
@@ -0,0 +1,329 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import (ConvModule, build_activation_layer, constant_init,
+ normal_init)
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import channel_shuffle, load_checkpoint, make_divisible
+
+
+class ShuffleUnit(nn.Module):
+ """ShuffleUnit block.
+
+ ShuffleNet unit with pointwise group convolution (GConv) and channel
+ shuffle.
+
+ Args:
+ in_channels (int): The input channels of the ShuffleUnit.
+ out_channels (int): The output channels of the ShuffleUnit.
+ groups (int, optional): The number of groups to be used in grouped 1x1
+ convolutions in each ShuffleUnit. Default: 3
+ first_block (bool, optional): Whether it is the first ShuffleUnit of a
+ sequential ShuffleUnits. Default: True, which means not using the
+ grouped 1x1 convolution.
+ combine (str, optional): The ways to combine the input and output
+ branches. Default: 'add'.
+ conv_cfg (dict): Config dict for convolution layer. Default: None,
+ which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ with_cp (bool, optional): Use checkpoint or not. Using checkpoint
+ will save some memory while slowing down the training speed.
+ Default: False.
+
+ Returns:
+ Tensor: The output tensor.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ groups=3,
+ first_block=True,
+ combine='add',
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.first_block = first_block
+ self.combine = combine
+ self.groups = groups
+ self.bottleneck_channels = self.out_channels // 4
+ self.with_cp = with_cp
+
+ if self.combine == 'add':
+ self.depthwise_stride = 1
+ self._combine_func = self._add
+ assert in_channels == out_channels, (
+ 'in_channels must be equal to out_channels when combine '
+ 'is add')
+ elif self.combine == 'concat':
+ self.depthwise_stride = 2
+ self._combine_func = self._concat
+ self.out_channels -= self.in_channels
+ self.avgpool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
+ else:
+ raise ValueError(f'Cannot combine tensors with {self.combine}. '
+ 'Only "add" and "concat" are supported')
+
+ self.first_1x1_groups = 1 if first_block else self.groups
+ self.g_conv_1x1_compress = ConvModule(
+ in_channels=self.in_channels,
+ out_channels=self.bottleneck_channels,
+ kernel_size=1,
+ groups=self.first_1x1_groups,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+
+ self.depthwise_conv3x3_bn = ConvModule(
+ in_channels=self.bottleneck_channels,
+ out_channels=self.bottleneck_channels,
+ kernel_size=3,
+ stride=self.depthwise_stride,
+ padding=1,
+ groups=self.bottleneck_channels,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+
+ self.g_conv_1x1_expand = ConvModule(
+ in_channels=self.bottleneck_channels,
+ out_channels=self.out_channels,
+ kernel_size=1,
+ groups=self.groups,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+
+ self.act = build_activation_layer(act_cfg)
+
+ @staticmethod
+ def _add(x, out):
+ # residual connection
+ return x + out
+
+ @staticmethod
+ def _concat(x, out):
+ # concatenate along channel axis
+ return torch.cat((x, out), 1)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ residual = x
+
+ out = self.g_conv_1x1_compress(x)
+ out = self.depthwise_conv3x3_bn(out)
+
+ if self.groups > 1:
+ out = channel_shuffle(out, self.groups)
+
+ out = self.g_conv_1x1_expand(out)
+
+ if self.combine == 'concat':
+ residual = self.avgpool(residual)
+ out = self.act(out)
+ out = self._combine_func(residual, out)
+ else:
+ out = self._combine_func(residual, out)
+ out = self.act(out)
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+@BACKBONES.register_module()
+class ShuffleNetV1(BaseBackbone):
+ """ShuffleNetV1 backbone.
+
+ Args:
+ groups (int, optional): The number of groups to be used in grouped 1x1
+ convolutions in each ShuffleUnit. Default: 3.
+ widen_factor (float, optional): Width multiplier - adjusts the number
+ of channels in each layer by this amount. Default: 1.0.
+ out_indices (Sequence[int]): Output from which stages.
+ Default: (2, )
+ frozen_stages (int): Stages to be frozen (all param fixed).
+ Default: -1, which means not freezing any parameters.
+ conv_cfg (dict): Config dict for convolution layer. Default: None,
+ which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ groups=3,
+ widen_factor=1.0,
+ out_indices=(2, ),
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ norm_eval=False,
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.stage_blocks = [4, 8, 4]
+ self.groups = groups
+
+ for index in out_indices:
+ if index not in range(0, 3):
+ raise ValueError('the item in out_indices must in '
+ f'range(0, 3). But received {index}')
+
+ if frozen_stages not in range(-1, 3):
+ raise ValueError('frozen_stages must be in range(-1, 3). '
+ f'But received {frozen_stages}')
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.act_cfg = act_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ if groups == 1:
+ channels = (144, 288, 576)
+ elif groups == 2:
+ channels = (200, 400, 800)
+ elif groups == 3:
+ channels = (240, 480, 960)
+ elif groups == 4:
+ channels = (272, 544, 1088)
+ elif groups == 8:
+ channels = (384, 768, 1536)
+ else:
+ raise ValueError(f'{groups} groups is not supported for 1x1 '
+ 'Grouped Convolutions')
+
+ channels = [make_divisible(ch * widen_factor, 8) for ch in channels]
+
+ self.in_channels = int(24 * widen_factor)
+
+ self.conv1 = ConvModule(
+ in_channels=3,
+ out_channels=self.in_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+
+ self.layers = nn.ModuleList()
+ for i, num_blocks in enumerate(self.stage_blocks):
+ first_block = (i == 0)
+ layer = self.make_layer(channels[i], num_blocks, first_block)
+ self.layers.append(layer)
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ for param in self.conv1.parameters():
+ param.requires_grad = False
+ for i in range(self.frozen_stages):
+ layer = self.layers[i]
+ layer.eval()
+ for param in layer.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for name, m in self.named_modules():
+ if isinstance(m, nn.Conv2d):
+ if 'conv1' in name:
+ normal_init(m, mean=0, std=0.01)
+ else:
+ normal_init(m, mean=0, std=1.0 / m.weight.shape[1])
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, val=1, bias=0.0001)
+ if isinstance(m, _BatchNorm):
+ if m.running_mean is not None:
+ nn.init.constant_(m.running_mean, 0)
+ else:
+ raise TypeError('pretrained must be a str or None. But received '
+ f'{type(pretrained)}')
+
+ def make_layer(self, out_channels, num_blocks, first_block=False):
+ """Stack ShuffleUnit blocks to make a layer.
+
+ Args:
+ out_channels (int): out_channels of the block.
+ num_blocks (int): Number of blocks.
+ first_block (bool, optional): Whether is the first ShuffleUnit of a
+ sequential ShuffleUnits. Default: False, which means using
+ the grouped 1x1 convolution.
+ """
+ layers = []
+ for i in range(num_blocks):
+ first_block = first_block if i == 0 else False
+ combine_mode = 'concat' if i == 0 else 'add'
+ layers.append(
+ ShuffleUnit(
+ self.in_channels,
+ out_channels,
+ groups=self.groups,
+ first_block=first_block,
+ combine=combine_mode,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=self.act_cfg,
+ with_cp=self.with_cp))
+ self.in_channels = out_channels
+
+ return nn.Sequential(*layers)
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.maxpool(x)
+
+ outs = []
+ for i, layer in enumerate(self.layers):
+ x = layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v2.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v2.py
new file mode 100644
index 0000000000000000000000000000000000000000..e93533367afe4efa01fa67d14cafcca006c990e8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/shufflenet_v2.py
@@ -0,0 +1,302 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import ConvModule, constant_init, normal_init
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import channel_shuffle, load_checkpoint
+
+
+class InvertedResidual(nn.Module):
+ """InvertedResidual block for ShuffleNetV2 backbone.
+
+ Args:
+ in_channels (int): The input channels of the block.
+ out_channels (int): The output channels of the block.
+ stride (int): Stride of the 3x3 convolution layer. Default: 1
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ stride=1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.stride = stride
+ self.with_cp = with_cp
+
+ branch_features = out_channels // 2
+ if self.stride == 1:
+ assert in_channels == branch_features * 2, (
+ f'in_channels ({in_channels}) should equal to '
+ f'branch_features * 2 ({branch_features * 2}) '
+ 'when stride is 1')
+
+ if in_channels != branch_features * 2:
+ assert self.stride != 1, (
+ f'stride ({self.stride}) should not equal 1 when '
+ f'in_channels != branch_features * 2')
+
+ if self.stride > 1:
+ self.branch1 = nn.Sequential(
+ ConvModule(
+ in_channels,
+ in_channels,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ groups=in_channels,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None),
+ ConvModule(
+ in_channels,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ )
+
+ self.branch2 = nn.Sequential(
+ ConvModule(
+ in_channels if (self.stride > 1) else branch_features,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg),
+ ConvModule(
+ branch_features,
+ branch_features,
+ kernel_size=3,
+ stride=self.stride,
+ padding=1,
+ groups=branch_features,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None),
+ ConvModule(
+ branch_features,
+ branch_features,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ if self.stride > 1:
+ out = torch.cat((self.branch1(x), self.branch2(x)), dim=1)
+ else:
+ x1, x2 = x.chunk(2, dim=1)
+ out = torch.cat((x1, self.branch2(x2)), dim=1)
+
+ out = channel_shuffle(out, 2)
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
+
+
+@BACKBONES.register_module()
+class ShuffleNetV2(BaseBackbone):
+ """ShuffleNetV2 backbone.
+
+ Args:
+ widen_factor (float): Width multiplier - adjusts the number of
+ channels in each layer by this amount. Default: 1.0.
+ out_indices (Sequence[int]): Output from which stages.
+ Default: (0, 1, 2, 3).
+ frozen_stages (int): Stages to be frozen (all param fixed).
+ Default: -1, which means not freezing any parameters.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ """
+
+ def __init__(self,
+ widen_factor=1.0,
+ out_indices=(3, ),
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ norm_eval=False,
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.stage_blocks = [4, 8, 4]
+ for index in out_indices:
+ if index not in range(0, 4):
+ raise ValueError('the item in out_indices must in '
+ f'range(0, 4). But received {index}')
+
+ if frozen_stages not in range(-1, 4):
+ raise ValueError('frozen_stages must be in range(-1, 4). '
+ f'But received {frozen_stages}')
+ self.out_indices = out_indices
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.act_cfg = act_cfg
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ if widen_factor == 0.5:
+ channels = [48, 96, 192, 1024]
+ elif widen_factor == 1.0:
+ channels = [116, 232, 464, 1024]
+ elif widen_factor == 1.5:
+ channels = [176, 352, 704, 1024]
+ elif widen_factor == 2.0:
+ channels = [244, 488, 976, 2048]
+ else:
+ raise ValueError('widen_factor must be in [0.5, 1.0, 1.5, 2.0]. '
+ f'But received {widen_factor}')
+
+ self.in_channels = 24
+ self.conv1 = ConvModule(
+ in_channels=3,
+ out_channels=self.in_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+
+ self.layers = nn.ModuleList()
+ for i, num_blocks in enumerate(self.stage_blocks):
+ layer = self._make_layer(channels[i], num_blocks)
+ self.layers.append(layer)
+
+ output_channels = channels[-1]
+ self.layers.append(
+ ConvModule(
+ in_channels=self.in_channels,
+ out_channels=output_channels,
+ kernel_size=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+
+ def _make_layer(self, out_channels, num_blocks):
+ """Stack blocks to make a layer.
+
+ Args:
+ out_channels (int): out_channels of the block.
+ num_blocks (int): number of blocks.
+ """
+ layers = []
+ for i in range(num_blocks):
+ stride = 2 if i == 0 else 1
+ layers.append(
+ InvertedResidual(
+ in_channels=self.in_channels,
+ out_channels=out_channels,
+ stride=stride,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=self.act_cfg,
+ with_cp=self.with_cp))
+ self.in_channels = out_channels
+
+ return nn.Sequential(*layers)
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ for param in self.conv1.parameters():
+ param.requires_grad = False
+
+ for i in range(self.frozen_stages):
+ m = self.layers[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for name, m in self.named_modules():
+ if isinstance(m, nn.Conv2d):
+ if 'conv1' in name:
+ normal_init(m, mean=0, std=0.01)
+ else:
+ normal_init(m, mean=0, std=1.0 / m.weight.shape[1])
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m.weight, val=1, bias=0.0001)
+ if isinstance(m, _BatchNorm):
+ if m.running_mean is not None:
+ nn.init.constant_(m.running_mean, 0)
+ else:
+ raise TypeError('pretrained must be a str or None. But received '
+ f'{type(pretrained)}')
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.maxpool(x)
+
+ outs = []
+ for i, layer in enumerate(self.layers):
+ x = layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, nn.BatchNorm2d):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/swin.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/swin.py
new file mode 100644
index 0000000000000000000000000000000000000000..2449cdca591bc0bbf601295bde11efe834b49f8a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/swin.py
@@ -0,0 +1,733 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import OrderedDict
+from copy import deepcopy
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as cp
+from mmcv.cnn import build_norm_layer, constant_init, trunc_normal_init
+from mmcv.cnn.bricks.transformer import FFN, build_dropout
+from mmcv.cnn.utils.weight_init import trunc_normal_
+from mmcv.runner import _load_checkpoint
+from mmcv.utils import to_2tuple
+
+from ...utils import get_root_logger
+from ..builder import BACKBONES
+from ..utils.transformer import PatchEmbed, PatchMerging
+from .base_backbone import BaseBackbone
+from .utils.ckpt_convert import swin_converter
+
+
+class WindowMSA(nn.Module):
+ """Window based multi-head self-attention (W-MSA) module with relative
+ position bias.
+
+ Args:
+ embed_dims (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (tuple[int]): The height and width of the window.
+ qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.
+ Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ attn_drop_rate (float, optional): Dropout ratio of attention weight.
+ Default: 0.0
+ proj_drop_rate (float, optional): Dropout ratio of output. Default: 0.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ window_size,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop_rate=0.,
+ proj_drop_rate=0.):
+
+ super().__init__()
+ self.embed_dims = embed_dims
+ self.window_size = window_size # Wh, Ww
+ self.num_heads = num_heads
+ head_embed_dims = embed_dims // num_heads
+ self.scale = qk_scale or head_embed_dims**-0.5
+
+ # define a parameter table of relative position bias
+ self.relative_position_bias_table = nn.Parameter(
+ torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1),
+ num_heads)) # 2*Wh-1 * 2*Ww-1, nH
+
+ # About 2x faster than original impl
+ Wh, Ww = self.window_size
+ rel_index_coords = self.double_step_seq(2 * Ww - 1, Wh, 1, Ww)
+ rel_position_index = rel_index_coords + rel_index_coords.T
+ rel_position_index = rel_position_index.flip(1).contiguous()
+ self.register_buffer('relative_position_index', rel_position_index)
+
+ self.qkv = nn.Linear(embed_dims, embed_dims * 3, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop_rate)
+ self.proj = nn.Linear(embed_dims, embed_dims)
+ self.proj_drop = nn.Dropout(proj_drop_rate)
+
+ self.softmax = nn.Softmax(dim=-1)
+
+ def init_weights(self):
+ trunc_normal_(self.relative_position_bias_table, std=0.02)
+
+ def forward(self, x, mask=None):
+ """
+ Args:
+
+ x (tensor): input features with shape of (num_windows*B, N, C)
+ mask (tensor | None, Optional): mask with shape of (num_windows,
+ Wh*Ww, Wh*Ww), value should be between (-inf, 0].
+ """
+ B, N, C = x.shape
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads,
+ C // self.num_heads).permute(2, 0, 3, 1, 4)
+ # make torchscript happy (cannot use tensor as tuple)
+ q, k, v = qkv[0], qkv[1], qkv[2]
+
+ q = q * self.scale
+ attn = (q @ k.transpose(-2, -1))
+
+ relative_position_bias = self.relative_position_bias_table[
+ self.relative_position_index.view(-1)].view(
+ self.window_size[0] * self.window_size[1],
+ self.window_size[0] * self.window_size[1],
+ -1) # Wh*Ww,Wh*Ww,nH
+ relative_position_bias = relative_position_bias.permute(
+ 2, 0, 1).contiguous() # nH, Wh*Ww, Wh*Ww
+ attn = attn + relative_position_bias.unsqueeze(0)
+
+ if mask is not None:
+ nW = mask.shape[0]
+ attn = attn.view(B // nW, nW, self.num_heads, N,
+ N) + mask.unsqueeze(1).unsqueeze(0)
+ attn = attn.view(-1, self.num_heads, N, N)
+ attn = self.softmax(attn)
+
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+ @staticmethod
+ def double_step_seq(step1, len1, step2, len2):
+ seq1 = torch.arange(0, step1 * len1, step1)
+ seq2 = torch.arange(0, step2 * len2, step2)
+ return (seq1[:, None] + seq2[None, :]).reshape(1, -1)
+
+
+class ShiftWindowMSA(nn.Module):
+ """Shifted Window Multihead Self-Attention Module.
+
+ Args:
+ embed_dims (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ window_size (int): The height and width of the window.
+ shift_size (int, optional): The shift step of each window towards
+ right-bottom. If zero, act as regular window-msa. Defaults to 0.
+ qkv_bias (bool, optional): If True, add a learnable bias to q, k, v.
+ Default: True
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Defaults: None.
+ attn_drop_rate (float, optional): Dropout ratio of attention weight.
+ Defaults: 0.
+ proj_drop_rate (float, optional): Dropout ratio of output.
+ Defaults: 0.
+ dropout_layer (dict, optional): The dropout_layer used before output.
+ Defaults: dict(type='DropPath', drop_prob=0.).
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ window_size,
+ shift_size=0,
+ qkv_bias=True,
+ qk_scale=None,
+ attn_drop_rate=0,
+ proj_drop_rate=0,
+ dropout_layer=dict(type='DropPath', drop_prob=0.)):
+ super().__init__()
+
+ self.window_size = window_size
+ self.shift_size = shift_size
+ assert 0 <= self.shift_size < self.window_size
+
+ self.w_msa = WindowMSA(
+ embed_dims=embed_dims,
+ num_heads=num_heads,
+ window_size=to_2tuple(window_size),
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop_rate=attn_drop_rate,
+ proj_drop_rate=proj_drop_rate)
+
+ self.drop = build_dropout(dropout_layer)
+
+ def forward(self, query, hw_shape):
+ B, L, C = query.shape
+ H, W = hw_shape
+ assert L == H * W, 'input feature has wrong size'
+ query = query.view(B, H, W, C)
+
+ # pad feature maps to multiples of window size
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
+ query = F.pad(query, (0, 0, 0, pad_r, 0, pad_b))
+ H_pad, W_pad = query.shape[1], query.shape[2]
+
+ # cyclic shift
+ if self.shift_size > 0:
+ shifted_query = torch.roll(
+ query,
+ shifts=(-self.shift_size, -self.shift_size),
+ dims=(1, 2))
+
+ # calculate attention mask for SW-MSA
+ img_mask = torch.zeros((1, H_pad, W_pad, 1), device=query.device)
+ h_slices = (slice(0, -self.window_size),
+ slice(-self.window_size,
+ -self.shift_size), slice(-self.shift_size, None))
+ w_slices = (slice(0, -self.window_size),
+ slice(-self.window_size,
+ -self.shift_size), slice(-self.shift_size, None))
+ cnt = 0
+ for h in h_slices:
+ for w in w_slices:
+ img_mask[:, h, w, :] = cnt
+ cnt += 1
+
+ # nW, window_size, window_size, 1
+ mask_windows = self.window_partition(img_mask)
+ mask_windows = mask_windows.view(
+ -1, self.window_size * self.window_size)
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
+ attn_mask = attn_mask.masked_fill(attn_mask != 0,
+ float(-100.0)).masked_fill(
+ attn_mask == 0, float(0.0))
+ else:
+ shifted_query = query
+ attn_mask = None
+
+ # nW*B, window_size, window_size, C
+ query_windows = self.window_partition(shifted_query)
+ # nW*B, window_size*window_size, C
+ query_windows = query_windows.view(-1, self.window_size**2, C)
+
+ # W-MSA/SW-MSA (nW*B, window_size*window_size, C)
+ attn_windows = self.w_msa(query_windows, mask=attn_mask)
+
+ # merge windows
+ attn_windows = attn_windows.view(-1, self.window_size,
+ self.window_size, C)
+
+ # B H' W' C
+ shifted_x = self.window_reverse(attn_windows, H_pad, W_pad)
+ # reverse cyclic shift
+ if self.shift_size > 0:
+ x = torch.roll(
+ shifted_x,
+ shifts=(self.shift_size, self.shift_size),
+ dims=(1, 2))
+ else:
+ x = shifted_x
+
+ if pad_r > 0 or pad_b:
+ x = x[:, :H, :W, :].contiguous()
+
+ x = x.view(B, H * W, C)
+
+ x = self.drop(x)
+ return x
+
+ def window_reverse(self, windows, H, W):
+ """
+ Args:
+ windows: (num_windows*B, window_size, window_size, C)
+ H (int): Height of image
+ W (int): Width of image
+ Returns:
+ x: (B, H, W, C)
+ """
+ window_size = self.window_size
+ B = int(windows.shape[0] / (H * W / window_size / window_size))
+ x = windows.view(B, H // window_size, W // window_size, window_size,
+ window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1)
+ return x
+
+ def window_partition(self, x):
+ """
+ Args:
+ x: (B, H, W, C)
+ Returns:
+ windows: (num_windows*B, window_size, window_size, C)
+ """
+ B, H, W, C = x.shape
+ window_size = self.window_size
+ x = x.view(B, H // window_size, window_size, W // window_size,
+ window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous()
+ windows = windows.view(-1, window_size, window_size, C)
+ return windows
+
+
+class SwinBlock(nn.Module):
+ """"
+ Args:
+ embed_dims (int): The feature dimension.
+ num_heads (int): Parallel attention heads.
+ feedforward_channels (int): The hidden dimension for FFNs.
+ window_size (int, optional): The local window scale. Default: 7.
+ shift (bool, optional): whether to shift window or not. Default False.
+ qkv_bias (bool, optional): enable bias for qkv if True. Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop_rate (float, optional): Dropout rate. Default: 0.
+ attn_drop_rate (float, optional): Attention dropout rate. Default: 0.
+ drop_path_rate (float, optional): Stochastic depth rate. Default: 0.
+ act_cfg (dict, optional): The config dict of activation function.
+ Default: dict(type='GELU').
+ norm_cfg (dict, optional): The config dict of normalization.
+ Default: dict(type='LN').
+ with_cp (bool, optional): Use checkpoint or not. Using checkpoint
+ will save some memory while slowing down the training speed.
+ Default: False.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ feedforward_channels,
+ window_size=7,
+ shift=False,
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='LN'),
+ with_cp=False):
+
+ super(SwinBlock, self).__init__()
+
+ self.with_cp = with_cp
+
+ self.norm1 = build_norm_layer(norm_cfg, embed_dims)[1]
+ self.attn = ShiftWindowMSA(
+ embed_dims=embed_dims,
+ num_heads=num_heads,
+ window_size=window_size,
+ shift_size=window_size // 2 if shift else 0,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop_rate=attn_drop_rate,
+ proj_drop_rate=drop_rate,
+ dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate))
+
+ self.norm2 = build_norm_layer(norm_cfg, embed_dims)[1]
+ self.ffn = FFN(
+ embed_dims=embed_dims,
+ feedforward_channels=feedforward_channels,
+ num_fcs=2,
+ ffn_drop=drop_rate,
+ dropout_layer=dict(type='DropPath', drop_prob=drop_path_rate),
+ act_cfg=act_cfg,
+ add_identity=True,
+ init_cfg=None)
+
+ def forward(self, x, hw_shape):
+
+ def _inner_forward(x):
+ identity = x
+ x = self.norm1(x)
+ x = self.attn(x, hw_shape)
+
+ x = x + identity
+
+ identity = x
+ x = self.norm2(x)
+ x = self.ffn(x, identity=identity)
+
+ return x
+
+ if self.with_cp and x.requires_grad:
+ x = cp.checkpoint(_inner_forward, x)
+ else:
+ x = _inner_forward(x)
+
+ return x
+
+
+class SwinBlockSequence(nn.Module):
+ """Implements one stage in Swin Transformer.
+
+ Args:
+ embed_dims (int): The feature dimension.
+ num_heads (int): Parallel attention heads.
+ feedforward_channels (int): The hidden dimension for FFNs.
+ depth (int): The number of blocks in this stage.
+ window_size (int, optional): The local window scale. Default: 7.
+ qkv_bias (bool, optional): enable bias for qkv if True. Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop_rate (float, optional): Dropout rate. Default: 0.
+ attn_drop_rate (float, optional): Attention dropout rate. Default: 0.
+ drop_path_rate (float | list[float], optional): Stochastic depth
+ rate. Default: 0.
+ downsample (nn.Module | None, optional): The downsample operation
+ module. Default: None.
+ act_cfg (dict, optional): The config dict of activation function.
+ Default: dict(type='GELU').
+ norm_cfg (dict, optional): The config dict of normalization.
+ Default: dict(type='LN').
+ with_cp (bool, optional): Use checkpoint or not. Using checkpoint
+ will save some memory while slowing down the training speed.
+ Default: False.
+ """
+
+ def __init__(self,
+ embed_dims,
+ num_heads,
+ feedforward_channels,
+ depth,
+ window_size=7,
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.,
+ downsample=None,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='LN'),
+ with_cp=False):
+ super().__init__()
+
+ if isinstance(drop_path_rate, list):
+ drop_path_rates = drop_path_rate
+ assert len(drop_path_rates) == depth
+ else:
+ drop_path_rates = [deepcopy(drop_path_rate) for _ in range(depth)]
+
+ self.blocks = nn.ModuleList()
+ for i in range(depth):
+ block = SwinBlock(
+ embed_dims=embed_dims,
+ num_heads=num_heads,
+ feedforward_channels=feedforward_channels,
+ window_size=window_size,
+ shift=False if i % 2 == 0 else True,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop_rate=drop_rate,
+ attn_drop_rate=attn_drop_rate,
+ drop_path_rate=drop_path_rates[i],
+ act_cfg=act_cfg,
+ norm_cfg=norm_cfg,
+ with_cp=with_cp)
+ self.blocks.append(block)
+
+ self.downsample = downsample
+
+ def forward(self, x, hw_shape):
+ for block in self.blocks:
+ x = block(x, hw_shape)
+
+ if self.downsample:
+ x_down, down_hw_shape = self.downsample(x, hw_shape)
+ return x_down, down_hw_shape, x, hw_shape
+ else:
+ return x, hw_shape, x, hw_shape
+
+
+@BACKBONES.register_module()
+class SwinTransformer(BaseBackbone):
+ """ Swin Transformer
+ A PyTorch implement of : `Swin Transformer:
+ Hierarchical Vision Transformer using Shifted Windows` -
+ https://arxiv.org/abs/2103.14030
+
+ Inspiration from
+ https://github.com/microsoft/Swin-Transformer
+
+ Args:
+ pretrain_img_size (int | tuple[int]): The size of input image when
+ pretrain. Defaults: 224.
+ in_channels (int): The num of input channels.
+ Defaults: 3.
+ embed_dims (int): The feature dimension. Default: 96.
+ patch_size (int | tuple[int]): Patch size. Default: 4.
+ window_size (int): Window size. Default: 7.
+ mlp_ratio (int): Ratio of mlp hidden dim to embedding dim.
+ Default: 4.
+ depths (tuple[int]): Depths of each Swin Transformer stage.
+ Default: (2, 2, 6, 2).
+ num_heads (tuple[int]): Parallel attention heads of each Swin
+ Transformer stage. Default: (3, 6, 12, 24).
+ strides (tuple[int]): The patch merging or patch embedding stride of
+ each Swin Transformer stage. (In swin, we set kernel size equal to
+ stride.) Default: (4, 2, 2, 2).
+ out_indices (tuple[int]): Output from which stages.
+ Default: (0, 1, 2, 3).
+ qkv_bias (bool, optional): If True, add a learnable bias to query, key,
+ value. Default: True
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ patch_norm (bool): If add a norm layer for patch embed and patch
+ merging. Default: True.
+ drop_rate (float): Dropout rate. Defaults: 0.
+ attn_drop_rate (float): Attention dropout rate. Default: 0.
+ drop_path_rate (float): Stochastic depth rate. Defaults: 0.1.
+ use_abs_pos_embed (bool): If True, add absolute position embedding to
+ the patch embedding. Defaults: False.
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='LN').
+ norm_cfg (dict): Config dict for normalization layer at
+ output of backone. Defaults: dict(type='LN').
+ with_cp (bool, optional): Use checkpoint or not. Using checkpoint
+ will save some memory while slowing down the training speed.
+ Default: False.
+ pretrained (str, optional): model pretrained path. Default: None.
+ convert_weights (bool): The flag indicates whether the
+ pre-trained model is from the original repo. We may need
+ to convert some keys to make it compatible.
+ Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ Default: -1 (-1 means not freezing any parameters).
+ """
+
+ def __init__(
+ self,
+ pretrain_img_size=224,
+ in_channels=3,
+ embed_dims=96,
+ patch_size=4,
+ window_size=7,
+ mlp_ratio=4,
+ depths=(2, 2, 6, 2),
+ num_heads=(3, 6, 12, 24),
+ strides=(4, 2, 2, 2),
+ out_indices=(0, 1, 2, 3),
+ qkv_bias=True,
+ qk_scale=None,
+ patch_norm=True,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.1,
+ use_abs_pos_embed=False,
+ act_cfg=dict(type='GELU'),
+ norm_cfg=dict(type='LN'),
+ with_cp=False,
+ convert_weights=False,
+ frozen_stages=-1,
+ ):
+ self.convert_weights = convert_weights
+ self.frozen_stages = frozen_stages
+ if isinstance(pretrain_img_size, int):
+ pretrain_img_size = to_2tuple(pretrain_img_size)
+ elif isinstance(pretrain_img_size, tuple):
+ if len(pretrain_img_size) == 1:
+ pretrain_img_size = to_2tuple(pretrain_img_size[0])
+ assert len(pretrain_img_size) == 2, \
+ f'The size of image should have length 1 or 2, ' \
+ f'but got {len(pretrain_img_size)}'
+
+ super(SwinTransformer, self).__init__()
+
+ num_layers = len(depths)
+ self.out_indices = out_indices
+ self.use_abs_pos_embed = use_abs_pos_embed
+
+ assert strides[0] == patch_size, 'Use non-overlapping patch embed.'
+
+ self.patch_embed = PatchEmbed(
+ in_channels=in_channels,
+ embed_dims=embed_dims,
+ conv_type='Conv2d',
+ kernel_size=patch_size,
+ stride=strides[0],
+ norm_cfg=norm_cfg if patch_norm else None,
+ init_cfg=None)
+
+ if self.use_abs_pos_embed:
+ patch_row = pretrain_img_size[0] // patch_size
+ patch_col = pretrain_img_size[1] // patch_size
+ num_patches = patch_row * patch_col
+ self.absolute_pos_embed = nn.Parameter(
+ torch.zeros((1, num_patches, embed_dims)))
+
+ self.drop_after_pos = nn.Dropout(p=drop_rate)
+
+ # set stochastic depth decay rule
+ total_depth = sum(depths)
+ dpr = [
+ x.item() for x in torch.linspace(0, drop_path_rate, total_depth)
+ ]
+
+ self.stages = nn.ModuleList()
+ in_channels = embed_dims
+ for i in range(num_layers):
+ if i < num_layers - 1:
+ downsample = PatchMerging(
+ in_channels=in_channels,
+ out_channels=2 * in_channels,
+ stride=strides[i + 1],
+ norm_cfg=norm_cfg if patch_norm else None,
+ init_cfg=None)
+ else:
+ downsample = None
+
+ stage = SwinBlockSequence(
+ embed_dims=in_channels,
+ num_heads=num_heads[i],
+ feedforward_channels=mlp_ratio * in_channels,
+ depth=depths[i],
+ window_size=window_size,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop_rate=drop_rate,
+ attn_drop_rate=attn_drop_rate,
+ drop_path_rate=dpr[sum(depths[:i]):sum(depths[:i + 1])],
+ downsample=downsample,
+ act_cfg=act_cfg,
+ norm_cfg=norm_cfg,
+ with_cp=with_cp)
+ self.stages.append(stage)
+ if downsample:
+ in_channels = downsample.out_channels
+
+ self.num_features = [int(embed_dims * 2**i) for i in range(num_layers)]
+ # Add a norm layer for each output
+ for i in out_indices:
+ layer = build_norm_layer(norm_cfg, self.num_features[i])[1]
+ layer_name = f'norm{i}'
+ self.add_module(layer_name, layer)
+
+ def train(self, mode=True):
+ """Convert the model into training mode while keep layers freezed."""
+ super(SwinTransformer, self).train(mode)
+ self._freeze_stages()
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+ if self.use_abs_pos_embed:
+ self.absolute_pos_embed.requires_grad = False
+ self.drop_after_pos.eval()
+
+ for i in range(1, self.frozen_stages + 1):
+
+ if (i - 1) in self.out_indices:
+ norm_layer = getattr(self, f'norm{i-1}')
+ norm_layer.eval()
+ for param in norm_layer.parameters():
+ param.requires_grad = False
+
+ m = self.stages[i - 1]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+ ckpt = _load_checkpoint(
+ pretrained, logger=logger, map_location='cpu')
+ if 'state_dict' in ckpt:
+ _state_dict = ckpt['state_dict']
+ elif 'model' in ckpt:
+ _state_dict = ckpt['model']
+ else:
+ _state_dict = ckpt
+ if self.convert_weights:
+ # supported loading weight from original repo,
+ _state_dict = swin_converter(_state_dict)
+
+ state_dict = OrderedDict()
+ for k, v in _state_dict.items():
+ if k.startswith('backbone.'):
+ state_dict[k[9:]] = v
+
+ # strip prefix of state_dict
+ if list(state_dict.keys())[0].startswith('module.'):
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
+
+ # reshape absolute position embedding
+ if state_dict.get('absolute_pos_embed') is not None:
+ absolute_pos_embed = state_dict['absolute_pos_embed']
+ N1, L, C1 = absolute_pos_embed.size()
+ N2, C2, H, W = self.absolute_pos_embed.size()
+ if N1 != N2 or C1 != C2 or L != H * W:
+ logger.warning('Error in loading absolute_pos_embed, pass')
+ else:
+ state_dict['absolute_pos_embed'] = absolute_pos_embed.view(
+ N2, H, W, C2).permute(0, 3, 1, 2).contiguous()
+
+ # interpolate position bias table if needed
+ relative_position_bias_table_keys = [
+ k for k in state_dict.keys()
+ if 'relative_position_bias_table' in k
+ ]
+ for table_key in relative_position_bias_table_keys:
+ table_pretrained = state_dict[table_key]
+ table_current = self.state_dict()[table_key]
+ L1, nH1 = table_pretrained.size()
+ L2, nH2 = table_current.size()
+ if nH1 != nH2:
+ logger.warning(f'Error in loading {table_key}, pass')
+ elif L1 != L2:
+ S1 = int(L1**0.5)
+ S2 = int(L2**0.5)
+ table_pretrained_resized = F.interpolate(
+ table_pretrained.permute(1, 0).reshape(1, nH1, S1, S1),
+ size=(S2, S2),
+ mode='bicubic')
+ state_dict[table_key] = table_pretrained_resized.view(
+ nH2, L2).permute(1, 0).contiguous()
+
+ # load state_dict
+ self.load_state_dict(state_dict, False)
+ elif pretrained is None:
+ if self.use_abs_pos_embed:
+ trunc_normal_(self.absolute_pos_embed, std=0.02)
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ constant_init(m, 1.0)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ x, hw_shape = self.patch_embed(x)
+
+ if self.use_abs_pos_embed:
+ x = x + self.absolute_pos_embed
+ x = self.drop_after_pos(x)
+
+ outs = []
+ for i, stage in enumerate(self.stages):
+ x, hw_shape, out, out_hw_shape = stage(x, hw_shape)
+ if i in self.out_indices:
+ norm_layer = getattr(self, f'norm{i}')
+ out = norm_layer(out)
+ out = out.view(-1, *out_hw_shape,
+ self.num_features[i]).permute(0, 3, 1,
+ 2).contiguous()
+ outs.append(out)
+
+ return outs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..a0805cdddd17bbba50bf203e2bc9012efd86ba03
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcformer.py
@@ -0,0 +1,283 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+
+import torch
+import torch.nn as nn
+from mmcv.cnn import (build_norm_layer, constant_init, normal_init,
+ trunc_normal_init)
+from mmcv.runner import _load_checkpoint, load_state_dict
+
+from ...utils import get_root_logger
+from ..builder import BACKBONES
+from ..utils import (PatchEmbed, TCFormerDynamicBlock, TCFormerRegularBlock,
+ TokenConv, cluster_dpc_knn, merge_tokens,
+ tcformer_convert, token2map)
+
+
+class CTM(nn.Module):
+ """Clustering-based Token Merging module in TCFormer.
+
+ Args:
+ sample_ratio (float): The sample ratio of tokens.
+ embed_dim (int): Input token feature dimension.
+ dim_out (int): Output token feature dimension.
+ k (int): number of the nearest neighbor used i DPC-knn algorithm.
+ """
+
+ def __init__(self, sample_ratio, embed_dim, dim_out, k=5):
+ super().__init__()
+ self.sample_ratio = sample_ratio
+ self.dim_out = dim_out
+ self.conv = TokenConv(
+ in_channels=embed_dim,
+ out_channels=dim_out,
+ kernel_size=3,
+ stride=2,
+ padding=1)
+ self.norm = nn.LayerNorm(self.dim_out)
+ self.score = nn.Linear(self.dim_out, 1)
+ self.k = k
+
+ def forward(self, token_dict):
+ token_dict = token_dict.copy()
+ x = self.conv(token_dict)
+ x = self.norm(x)
+ token_score = self.score(x)
+ token_weight = token_score.exp()
+
+ token_dict['x'] = x
+ B, N, C = x.shape
+ token_dict['token_score'] = token_score
+
+ cluster_num = max(math.ceil(N * self.sample_ratio), 1)
+ idx_cluster, cluster_num = cluster_dpc_knn(token_dict, cluster_num,
+ self.k)
+ down_dict = merge_tokens(token_dict, idx_cluster, cluster_num,
+ token_weight)
+
+ H, W = token_dict['map_size']
+ H = math.floor((H - 1) / 2 + 1)
+ W = math.floor((W - 1) / 2 + 1)
+ down_dict['map_size'] = [H, W]
+
+ return down_dict, token_dict
+
+
+@BACKBONES.register_module()
+class TCFormer(nn.Module):
+ """Token Clustering Transformer (TCFormer)
+
+ Implementation of `Not All Tokens Are Equal: Human-centric Visual
+ Analysis via Token Clustering Transformer
+ `
+
+ Args:
+ in_channels (int): Number of input channels. Default: 3.
+ embed_dims (list[int]): Embedding dimension. Default:
+ [64, 128, 256, 512].
+ num_heads (Sequence[int]): The attention heads of each transformer
+ encode layer. Default: [1, 2, 5, 8].
+ mlp_ratios (Sequence[int]): The ratio of the mlp hidden dim to the
+ embedding dim of each transformer block.
+ qkv_bias (bool): Enable bias for qkv if True. Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop_rate (float): Probability of an element to be zeroed.
+ Default 0.0.
+ attn_drop_rate (float): The drop out rate for attention layer.
+ Default 0.0.
+ drop_path_rate (float): stochastic depth rate. Default 0.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN', eps=1e-6).
+ num_layers (Sequence[int]): The layer number of each transformer encode
+ layer. Default: [3, 4, 6, 3].
+ sr_ratios (Sequence[int]): The spatial reduction rate of each
+ transformer block. Default: [8, 4, 2, 1].
+ num_stages (int): The num of stages. Default: 4.
+ pretrained (str, optional): model pretrained path. Default: None.
+ k (int): number of the nearest neighbor used for local density.
+ sample_ratios (list[float]): The sample ratios of CTM modules.
+ Default: [0.25, 0.25, 0.25]
+ return_map (bool): If True, transfer dynamic tokens to feature map at
+ last. Default: False
+ convert_weights (bool): The flag indicates whether the
+ pre-trained model is from the original repo. We may need
+ to convert some keys to make it compatible.
+ Default: True.
+ """
+
+ def __init__(self,
+ in_channels=3,
+ embed_dims=[64, 128, 256, 512],
+ num_heads=[1, 2, 4, 8],
+ mlp_ratios=[4, 4, 4, 4],
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.,
+ norm_cfg=dict(type='LN', eps=1e-6),
+ num_layers=[3, 4, 6, 3],
+ sr_ratios=[8, 4, 2, 1],
+ num_stages=4,
+ pretrained=None,
+ k=5,
+ sample_ratios=[0.25, 0.25, 0.25],
+ return_map=False,
+ convert_weights=True):
+ super().__init__()
+
+ self.num_layers = num_layers
+ self.num_stages = num_stages
+ self.grid_stride = sr_ratios[0]
+ self.embed_dims = embed_dims
+ self.sr_ratios = sr_ratios
+ self.mlp_ratios = mlp_ratios
+ self.sample_ratios = sample_ratios
+ self.return_map = return_map
+ self.convert_weights = convert_weights
+
+ # stochastic depth decay rule
+ dpr = [
+ x.item()
+ for x in torch.linspace(0, drop_path_rate, sum(num_layers))
+ ]
+ cur = 0
+
+ # In stage 1, use the standard transformer blocks
+ for i in range(1):
+ patch_embed = PatchEmbed(
+ in_channels=in_channels if i == 0 else embed_dims[i - 1],
+ embed_dims=embed_dims[i],
+ kernel_size=7,
+ stride=4,
+ padding=3,
+ bias=True,
+ norm_cfg=dict(type='LN', eps=1e-6))
+
+ block = nn.ModuleList([
+ TCFormerRegularBlock(
+ dim=embed_dims[i],
+ num_heads=num_heads[i],
+ mlp_ratio=mlp_ratios[i],
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop_rate,
+ attn_drop=attn_drop_rate,
+ drop_path=dpr[cur + j],
+ norm_cfg=norm_cfg,
+ sr_ratio=sr_ratios[i]) for j in range(num_layers[i])
+ ])
+ norm = build_norm_layer(norm_cfg, embed_dims[i])[1]
+
+ cur += num_layers[i]
+
+ setattr(self, f'patch_embed{i + 1}', patch_embed)
+ setattr(self, f'block{i + 1}', block)
+ setattr(self, f'norm{i + 1}', norm)
+
+ # In stage 2~4, use TCFormerDynamicBlock for dynamic tokens
+ for i in range(1, num_stages):
+ ctm = CTM(sample_ratios[i - 1], embed_dims[i - 1], embed_dims[i],
+ k)
+
+ block = nn.ModuleList([
+ TCFormerDynamicBlock(
+ dim=embed_dims[i],
+ num_heads=num_heads[i],
+ mlp_ratio=mlp_ratios[i],
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop_rate,
+ attn_drop=attn_drop_rate,
+ drop_path=dpr[cur + j],
+ norm_cfg=norm_cfg,
+ sr_ratio=sr_ratios[i]) for j in range(num_layers[i])
+ ])
+ norm = build_norm_layer(norm_cfg, embed_dims[i])[1]
+ cur += num_layers[i]
+
+ setattr(self, f'ctm{i}', ctm)
+ setattr(self, f'block{i + 1}', block)
+ setattr(self, f'norm{i + 1}', norm)
+
+ self.init_weights(pretrained)
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = get_root_logger()
+
+ checkpoint = _load_checkpoint(
+ pretrained, logger=logger, map_location='cpu')
+ logger.warning(f'Load pre-trained model for '
+ f'{self.__class__.__name__} from original repo')
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ elif 'model' in checkpoint:
+ state_dict = checkpoint['model']
+ else:
+ state_dict = checkpoint
+
+ if self.convert_weights:
+ # We need to convert pre-trained weights to match this
+ # implementation.
+ state_dict = tcformer_convert(state_dict)
+ load_state_dict(self, state_dict, strict=False, logger=logger)
+
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ constant_init(m, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[
+ 1] * m.out_channels
+ fan_out //= m.groups
+ normal_init(m, 0, math.sqrt(2.0 / fan_out))
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ outs = []
+
+ i = 0
+ patch_embed = getattr(self, f'patch_embed{i + 1}')
+ block = getattr(self, f'block{i + 1}')
+ norm = getattr(self, f'norm{i + 1}')
+ x, (H, W) = patch_embed(x)
+ for blk in block:
+ x = blk(x, H, W)
+ x = norm(x)
+
+ # init token dict
+ B, N, _ = x.shape
+ device = x.device
+ idx_token = torch.arange(N)[None, :].repeat(B, 1).to(device)
+ agg_weight = x.new_ones(B, N, 1)
+ token_dict = {
+ 'x': x,
+ 'token_num': N,
+ 'map_size': [H, W],
+ 'init_grid_size': [H, W],
+ 'idx_token': idx_token,
+ 'agg_weight': agg_weight
+ }
+ outs.append(token_dict.copy())
+
+ # stage 2~4
+ for i in range(1, self.num_stages):
+ ctm = getattr(self, f'ctm{i}')
+ block = getattr(self, f'block{i + 1}')
+ norm = getattr(self, f'norm{i + 1}')
+
+ token_dict = ctm(token_dict) # down sample
+ for j, blk in enumerate(block):
+ token_dict = blk(token_dict)
+
+ token_dict['x'] = norm(token_dict['x'])
+ outs.append(token_dict)
+
+ if self.return_map:
+ outs = [token2map(token_dict) for token_dict in outs]
+ return outs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcn.py
new file mode 100644
index 0000000000000000000000000000000000000000..deca2290aeb1830bc3e241b819157369371aaf27
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/tcn.py
@@ -0,0 +1,267 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+from mmcv.cnn import ConvModule, build_conv_layer, constant_init, kaiming_init
+from mmcv.utils.parrots_wrapper import _BatchNorm
+
+from mmpose.core import WeightNormClipHook
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class BasicTemporalBlock(nn.Module):
+ """Basic block for VideoPose3D.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ mid_channels (int): The output channels of conv1. Default: 1024.
+ kernel_size (int): Size of the convolving kernel. Default: 3.
+ dilation (int): Spacing between kernel elements. Default: 3.
+ dropout (float): Dropout rate. Default: 0.25.
+ causal (bool): Use causal convolutions instead of symmetric
+ convolutions (for real-time applications). Default: False.
+ residual (bool): Use residual connection. Default: True.
+ use_stride_conv (bool): Use optimized TCN that designed
+ specifically for single-frame batching, i.e. where batches have
+ input length = receptive field, and output length = 1. This
+ implementation replaces dilated convolutions with strided
+ convolutions to avoid generating unused intermediate results.
+ Default: False.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: dict(type='Conv1d').
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN1d').
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ mid_channels=1024,
+ kernel_size=3,
+ dilation=3,
+ dropout=0.25,
+ causal=False,
+ residual=True,
+ use_stride_conv=False,
+ conv_cfg=dict(type='Conv1d'),
+ norm_cfg=dict(type='BN1d')):
+ # Protect mutable default arguments
+ conv_cfg = copy.deepcopy(conv_cfg)
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.mid_channels = mid_channels
+ self.kernel_size = kernel_size
+ self.dilation = dilation
+ self.dropout = dropout
+ self.causal = causal
+ self.residual = residual
+ self.use_stride_conv = use_stride_conv
+
+ self.pad = (kernel_size - 1) * dilation // 2
+ if use_stride_conv:
+ self.stride = kernel_size
+ self.causal_shift = kernel_size // 2 if causal else 0
+ self.dilation = 1
+ else:
+ self.stride = 1
+ self.causal_shift = kernel_size // 2 * dilation if causal else 0
+
+ self.conv1 = nn.Sequential(
+ ConvModule(
+ in_channels,
+ mid_channels,
+ kernel_size=kernel_size,
+ stride=self.stride,
+ dilation=self.dilation,
+ bias='auto',
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg))
+ self.conv2 = nn.Sequential(
+ ConvModule(
+ mid_channels,
+ out_channels,
+ kernel_size=1,
+ bias='auto',
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg))
+
+ if residual and in_channels != out_channels:
+ self.short_cut = build_conv_layer(conv_cfg, in_channels,
+ out_channels, 1)
+ else:
+ self.short_cut = None
+
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else None
+
+ def forward(self, x):
+ """Forward function."""
+ if self.use_stride_conv:
+ assert self.causal_shift + self.kernel_size // 2 < x.shape[2]
+ else:
+ assert 0 <= self.pad + self.causal_shift < x.shape[2] - \
+ self.pad + self.causal_shift <= x.shape[2]
+
+ out = self.conv1(x)
+ if self.dropout is not None:
+ out = self.dropout(out)
+
+ out = self.conv2(out)
+ if self.dropout is not None:
+ out = self.dropout(out)
+
+ if self.residual:
+ if self.use_stride_conv:
+ res = x[:, :, self.causal_shift +
+ self.kernel_size // 2::self.kernel_size]
+ else:
+ res = x[:, :,
+ (self.pad + self.causal_shift):(x.shape[2] - self.pad +
+ self.causal_shift)]
+
+ if self.short_cut is not None:
+ res = self.short_cut(res)
+ out = out + res
+
+ return out
+
+
+@BACKBONES.register_module()
+class TCN(BaseBackbone):
+ """TCN backbone.
+
+ Temporal Convolutional Networks.
+ More details can be found in the
+ `paper `__ .
+
+ Args:
+ in_channels (int): Number of input channels, which equals to
+ num_keypoints * num_features.
+ stem_channels (int): Number of feature channels. Default: 1024.
+ num_blocks (int): NUmber of basic temporal convolutional blocks.
+ Default: 2.
+ kernel_sizes (Sequence[int]): Sizes of the convolving kernel of
+ each basic block. Default: ``(3, 3, 3)``.
+ dropout (float): Dropout rate. Default: 0.25.
+ causal (bool): Use causal convolutions instead of symmetric
+ convolutions (for real-time applications).
+ Default: False.
+ residual (bool): Use residual connection. Default: True.
+ use_stride_conv (bool): Use TCN backbone optimized for
+ single-frame batching, i.e. where batches have input length =
+ receptive field, and output length = 1. This implementation
+ replaces dilated convolutions with strided convolutions to avoid
+ generating unused intermediate results. The weights are
+ interchangeable with the reference implementation. Default: False
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: dict(type='Conv1d').
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN1d').
+ max_norm (float|None): if not None, the weight of convolution layers
+ will be clipped to have a maximum norm of max_norm.
+
+ Example:
+ >>> from mmpose.models import TCN
+ >>> import torch
+ >>> self = TCN(in_channels=34)
+ >>> self.eval()
+ >>> inputs = torch.rand(1, 34, 243)
+ >>> level_outputs = self.forward(inputs)
+ >>> for level_out in level_outputs:
+ ... print(tuple(level_out.shape))
+ (1, 1024, 235)
+ (1, 1024, 217)
+ """
+
+ def __init__(self,
+ in_channels,
+ stem_channels=1024,
+ num_blocks=2,
+ kernel_sizes=(3, 3, 3),
+ dropout=0.25,
+ causal=False,
+ residual=True,
+ use_stride_conv=False,
+ conv_cfg=dict(type='Conv1d'),
+ norm_cfg=dict(type='BN1d'),
+ max_norm=None):
+ # Protect mutable default arguments
+ conv_cfg = copy.deepcopy(conv_cfg)
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self.in_channels = in_channels
+ self.stem_channels = stem_channels
+ self.num_blocks = num_blocks
+ self.kernel_sizes = kernel_sizes
+ self.dropout = dropout
+ self.causal = causal
+ self.residual = residual
+ self.use_stride_conv = use_stride_conv
+ self.max_norm = max_norm
+
+ assert num_blocks == len(kernel_sizes) - 1
+ for ks in kernel_sizes:
+ assert ks % 2 == 1, 'Only odd filter widths are supported.'
+
+ self.expand_conv = ConvModule(
+ in_channels,
+ stem_channels,
+ kernel_size=kernel_sizes[0],
+ stride=kernel_sizes[0] if use_stride_conv else 1,
+ bias='auto',
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg)
+
+ dilation = kernel_sizes[0]
+ self.tcn_blocks = nn.ModuleList()
+ for i in range(1, num_blocks + 1):
+ self.tcn_blocks.append(
+ BasicTemporalBlock(
+ in_channels=stem_channels,
+ out_channels=stem_channels,
+ mid_channels=stem_channels,
+ kernel_size=kernel_sizes[i],
+ dilation=dilation,
+ dropout=dropout,
+ causal=causal,
+ residual=residual,
+ use_stride_conv=use_stride_conv,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg))
+ dilation *= kernel_sizes[i]
+
+ if self.max_norm is not None:
+ # Apply weight norm clip to conv layers
+ weight_clip = WeightNormClipHook(self.max_norm)
+ for module in self.modules():
+ if isinstance(module, nn.modules.conv._ConvNd):
+ weight_clip.register(module)
+
+ self.dropout = nn.Dropout(dropout) if dropout > 0 else None
+
+ def forward(self, x):
+ """Forward function."""
+ x = self.expand_conv(x)
+
+ if self.dropout is not None:
+ x = self.dropout(x)
+
+ outs = []
+ for i in range(self.num_blocks):
+ x = self.tcn_blocks[i](x)
+ outs.append(x)
+
+ return tuple(outs)
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights."""
+ super().init_weights(pretrained)
+ if pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.modules.conv._ConvNd):
+ kaiming_init(m, mode='fan_in', nonlinearity='relu')
+ elif isinstance(m, _BatchNorm):
+ constant_init(m, 1)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..52a30ca9f7c8e90b6c6fa2fd8a9705ca0403b259
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .channel_shuffle import channel_shuffle
+from .inverted_residual import InvertedResidual
+from .make_divisible import make_divisible
+from .se_layer import SELayer
+from .utils import load_checkpoint
+
+__all__ = [
+ 'channel_shuffle', 'make_divisible', 'InvertedResidual', 'SELayer',
+ 'load_checkpoint'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/channel_shuffle.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/channel_shuffle.py
new file mode 100644
index 0000000000000000000000000000000000000000..aedd826bee690d42d92ed8a7f538b221e5b069e2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/channel_shuffle.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+
+
+def channel_shuffle(x, groups):
+ """Channel Shuffle operation.
+
+ This function enables cross-group information flow for multiple groups
+ convolution layers.
+
+ Args:
+ x (Tensor): The input tensor.
+ groups (int): The number of groups to divide the input tensor
+ in the channel dimension.
+
+ Returns:
+ Tensor: The output tensor after channel shuffle operation.
+ """
+
+ batch_size, num_channels, height, width = x.size()
+ assert (num_channels % groups == 0), ('num_channels should be '
+ 'divisible by groups')
+ channels_per_group = num_channels // groups
+
+ x = x.view(batch_size, groups, channels_per_group, height, width)
+ x = torch.transpose(x, 1, 2).contiguous()
+ x = x.view(batch_size, groups * channels_per_group, height, width)
+
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/ckpt_convert.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/ckpt_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..14a43892c6630be31e915ed1f8b9164ba250e8bd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/ckpt_convert.py
@@ -0,0 +1,62 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+# This script consists of several convert functions which
+# can modify the weights of model in original repo to be
+# pre-trained weights.
+
+from collections import OrderedDict
+
+
+def swin_converter(ckpt):
+
+ new_ckpt = OrderedDict()
+
+ def correct_unfold_reduction_order(x):
+ out_channel, in_channel = x.shape
+ x = x.reshape(out_channel, 4, in_channel // 4)
+ x = x[:, [0, 2, 1, 3], :].transpose(1,
+ 2).reshape(out_channel, in_channel)
+ return x
+
+ def correct_unfold_norm_order(x):
+ in_channel = x.shape[0]
+ x = x.reshape(4, in_channel // 4)
+ x = x[[0, 2, 1, 3], :].transpose(0, 1).reshape(in_channel)
+ return x
+
+ for k, v in ckpt.items():
+ if k.startswith('head'):
+ continue
+ elif k.startswith('layers'):
+ new_v = v
+ if 'attn.' in k:
+ new_k = k.replace('attn.', 'attn.w_msa.')
+ elif 'mlp.' in k:
+ if 'mlp.fc1.' in k:
+ new_k = k.replace('mlp.fc1.', 'ffn.layers.0.0.')
+ elif 'mlp.fc2.' in k:
+ new_k = k.replace('mlp.fc2.', 'ffn.layers.1.')
+ else:
+ new_k = k.replace('mlp.', 'ffn.')
+ elif 'downsample' in k:
+ new_k = k
+ if 'reduction.' in k:
+ new_v = correct_unfold_reduction_order(v)
+ elif 'norm.' in k:
+ new_v = correct_unfold_norm_order(v)
+ else:
+ new_k = k
+ new_k = new_k.replace('layers', 'stages', 1)
+ elif k.startswith('patch_embed'):
+ new_v = v
+ if 'proj' in k:
+ new_k = k.replace('proj', 'projection')
+ else:
+ new_k = k
+ else:
+ new_v = v
+ new_k = k
+
+ new_ckpt['backbone.' + new_k] = new_v
+
+ return new_ckpt
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/inverted_residual.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/inverted_residual.py
new file mode 100644
index 0000000000000000000000000000000000000000..dff762c570550e4a738ae1833a4c82c18777115d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/inverted_residual.py
@@ -0,0 +1,128 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import ConvModule
+
+from .se_layer import SELayer
+
+
+class InvertedResidual(nn.Module):
+ """Inverted Residual Block.
+
+ Args:
+ in_channels (int): The input channels of this Module.
+ out_channels (int): The output channels of this Module.
+ mid_channels (int): The input channels of the depthwise convolution.
+ kernel_size (int): The kernel size of the depthwise convolution.
+ Default: 3.
+ groups (None or int): The group number of the depthwise convolution.
+ Default: None, which means group number = mid_channels.
+ stride (int): The stride of the depthwise convolution. Default: 1.
+ se_cfg (dict): Config dict for se layer. Default: None, which means no
+ se layer.
+ with_expand_conv (bool): Use expand conv or not. If set False,
+ mid_channels must be the same with in_channels.
+ Default: True.
+ conv_cfg (dict): Config dict for convolution layer. Default: None,
+ which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ act_cfg (dict): Config dict for activation layer.
+ Default: dict(type='ReLU').
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+
+ Returns:
+ Tensor: The output tensor.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ mid_channels,
+ kernel_size=3,
+ groups=None,
+ stride=1,
+ se_cfg=None,
+ with_expand_conv=True,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ act_cfg=dict(type='ReLU'),
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ act_cfg = copy.deepcopy(act_cfg)
+ super().__init__()
+ self.with_res_shortcut = (stride == 1 and in_channels == out_channels)
+ assert stride in [1, 2]
+ self.with_cp = with_cp
+ self.with_se = se_cfg is not None
+ self.with_expand_conv = with_expand_conv
+
+ if groups is None:
+ groups = mid_channels
+
+ if self.with_se:
+ assert isinstance(se_cfg, dict)
+ if not self.with_expand_conv:
+ assert mid_channels == in_channels
+
+ if self.with_expand_conv:
+ self.expand_conv = ConvModule(
+ in_channels=in_channels,
+ out_channels=mid_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ self.depthwise_conv = ConvModule(
+ in_channels=mid_channels,
+ out_channels=mid_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=kernel_size // 2,
+ groups=groups,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ if self.with_se:
+ self.se = SELayer(**se_cfg)
+ self.linear_conv = ConvModule(
+ in_channels=mid_channels,
+ out_channels=out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None)
+
+ def forward(self, x):
+
+ def _inner_forward(x):
+ out = x
+
+ if self.with_expand_conv:
+ out = self.expand_conv(out)
+
+ out = self.depthwise_conv(out)
+
+ if self.with_se:
+ out = self.se(out)
+
+ out = self.linear_conv(out)
+
+ if self.with_res_shortcut:
+ return x + out
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/make_divisible.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/make_divisible.py
new file mode 100644
index 0000000000000000000000000000000000000000..b7666be65939d5c76057e73927c230029cb1871d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/make_divisible.py
@@ -0,0 +1,25 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
+ """Make divisible function.
+
+ This function rounds the channel number down to the nearest value that can
+ be divisible by the divisor.
+
+ Args:
+ value (int): The original channel number.
+ divisor (int): The divisor to fully divide the channel number.
+ min_value (int, optional): The minimum value of the output channel.
+ Default: None, means that the minimum value equal to the divisor.
+ min_ratio (float, optional): The minimum ratio of the rounded channel
+ number to the original channel number. Default: 0.9.
+ Returns:
+ int: The modified output channel number
+ """
+
+ if min_value is None:
+ min_value = divisor
+ new_value = max(min_value, int(value + divisor / 2) // divisor * divisor)
+ # Make sure that round down does not go down by more than (1-min_ratio).
+ if new_value < min_ratio * value:
+ new_value += divisor
+ return new_value
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/se_layer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/se_layer.py
new file mode 100644
index 0000000000000000000000000000000000000000..07f70802eb1b98b1f22516ba62b1533557f428ed
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/se_layer.py
@@ -0,0 +1,54 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import mmcv
+import torch.nn as nn
+from mmcv.cnn import ConvModule
+
+
+class SELayer(nn.Module):
+ """Squeeze-and-Excitation Module.
+
+ Args:
+ channels (int): The input (and output) channels of the SE layer.
+ ratio (int): Squeeze ratio in SELayer, the intermediate channel will be
+ ``int(channels/ratio)``. Default: 16.
+ conv_cfg (None or dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ act_cfg (dict or Sequence[dict]): Config dict for activation layer.
+ If act_cfg is a dict, two activation layers will be configurated
+ by this dict. If act_cfg is a sequence of dicts, the first
+ activation layer will be configurated by the first dict and the
+ second activation layer will be configurated by the second dict.
+ Default: (dict(type='ReLU'), dict(type='Sigmoid'))
+ """
+
+ def __init__(self,
+ channels,
+ ratio=16,
+ conv_cfg=None,
+ act_cfg=(dict(type='ReLU'), dict(type='Sigmoid'))):
+ super().__init__()
+ if isinstance(act_cfg, dict):
+ act_cfg = (act_cfg, act_cfg)
+ assert len(act_cfg) == 2
+ assert mmcv.is_tuple_of(act_cfg, dict)
+ self.global_avgpool = nn.AdaptiveAvgPool2d(1)
+ self.conv1 = ConvModule(
+ in_channels=channels,
+ out_channels=int(channels / ratio),
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ act_cfg=act_cfg[0])
+ self.conv2 = ConvModule(
+ in_channels=int(channels / ratio),
+ out_channels=channels,
+ kernel_size=1,
+ stride=1,
+ conv_cfg=conv_cfg,
+ act_cfg=act_cfg[1])
+
+ def forward(self, x):
+ out = self.global_avgpool(x)
+ out = self.conv1(out)
+ out = self.conv2(out)
+ return x * out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a53c94a90a1802cc0c4dcfceba241711c989640
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/utils/utils.py
@@ -0,0 +1,612 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import OrderedDict
+
+from mmcv.runner.checkpoint import _load_checkpoint, load_state_dict
+
+
+# Copyright (c) Open-MMLab. All rights reserved.
+import io
+import os
+import os.path as osp
+import pkgutil
+import time
+import warnings
+from collections import OrderedDict
+from importlib import import_module
+from tempfile import TemporaryDirectory
+
+import torch
+import torchvision
+from torch.optim import Optimizer
+from torch.utils import model_zoo
+from torch.nn import functional as F
+
+import mmcv
+from mmcv.fileio import FileClient
+from mmcv.fileio import load as load_file
+from mmcv.parallel import is_module_wrapper
+from mmcv.utils import mkdir_or_exist
+from mmcv.runner import get_dist_info
+
+from scipy import interpolate
+import numpy as np
+import math
+
+ENV_MMCV_HOME = 'MMCV_HOME'
+ENV_XDG_CACHE_HOME = 'XDG_CACHE_HOME'
+DEFAULT_CACHE_DIR = '~/.cache'
+
+
+def _get_mmcv_home():
+ mmcv_home = os.path.expanduser(
+ os.getenv(
+ ENV_MMCV_HOME,
+ os.path.join(
+ os.getenv(ENV_XDG_CACHE_HOME, DEFAULT_CACHE_DIR), 'mmcv')))
+
+ mkdir_or_exist(mmcv_home)
+ return mmcv_home
+
+
+def load_state_dict(module, state_dict, strict=False, logger=None):
+ """Load state_dict to a module.
+ This method is modified from :meth:`torch.nn.Module.load_state_dict`.
+ Default value for ``strict`` is set to ``False`` and the message for
+ param mismatch will be shown even if strict is False.
+ Args:
+ module (Module): Module that receives the state_dict.
+ state_dict (OrderedDict): Weights.
+ strict (bool): whether to strictly enforce that the keys
+ in :attr:`state_dict` match the keys returned by this module's
+ :meth:`~torch.nn.Module.state_dict` function. Default: ``False``.
+ logger (:obj:`logging.Logger`, optional): Logger to log the error
+ message. If not specified, print function will be used.
+ """
+ unexpected_keys = []
+ all_missing_keys = []
+ err_msg = []
+
+ metadata = getattr(state_dict, '_metadata', None)
+ state_dict = state_dict.copy()
+ if metadata is not None:
+ state_dict._metadata = metadata
+
+ # use _load_from_state_dict to enable checkpoint version control
+ def load(module, prefix=''):
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_module_wrapper(module):
+ module = module.module
+ local_metadata = {} if metadata is None else metadata.get(
+ prefix[:-1], {})
+ module._load_from_state_dict(state_dict, prefix, local_metadata, True,
+ all_missing_keys, unexpected_keys,
+ err_msg)
+ for name, child in module._modules.items():
+ if child is not None:
+ load(child, prefix + name + '.')
+
+ load(module)
+ load = None # break load->load reference cycle
+
+ # ignore "num_batches_tracked" of BN layers
+ missing_keys = [
+ key for key in all_missing_keys if 'num_batches_tracked' not in key
+ ]
+
+ if unexpected_keys:
+ err_msg.append('unexpected key in source '
+ f'state_dict: {", ".join(unexpected_keys)}\n')
+ if missing_keys:
+ err_msg.append(
+ f'missing keys in source state_dict: {", ".join(missing_keys)}\n')
+
+ rank, _ = get_dist_info()
+ if len(err_msg) > 0 and rank == 0:
+ err_msg.insert(
+ 0, 'The model and loaded state dict do not match exactly\n')
+ err_msg = '\n'.join(err_msg)
+ if strict:
+ raise RuntimeError(err_msg)
+ elif logger is not None:
+ logger.warning(err_msg)
+ else:
+ print(err_msg)
+
+
+def load_url_dist(url, model_dir=None, map_location="cpu"):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ if rank == 0:
+ checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ checkpoint = model_zoo.load_url(url, model_dir=model_dir, map_location=map_location)
+ return checkpoint
+
+
+def load_pavimodel_dist(model_path, map_location=None):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ try:
+ from pavi import modelcloud
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ if rank == 0:
+ model = modelcloud.get(model_path)
+ with TemporaryDirectory() as tmp_dir:
+ downloaded_file = osp.join(tmp_dir, model.name)
+ model.download(downloaded_file)
+ checkpoint = torch.load(downloaded_file, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ model = modelcloud.get(model_path)
+ with TemporaryDirectory() as tmp_dir:
+ downloaded_file = osp.join(tmp_dir, model.name)
+ model.download(downloaded_file)
+ checkpoint = torch.load(
+ downloaded_file, map_location=map_location)
+ return checkpoint
+
+
+def load_fileclient_dist(filename, backend, map_location):
+ """In distributed setting, this function only download checkpoint at local
+ rank 0."""
+ rank, world_size = get_dist_info()
+ rank = int(os.environ.get('LOCAL_RANK', rank))
+ allowed_backends = ['ceph']
+ if backend not in allowed_backends:
+ raise ValueError(f'Load from Backend {backend} is not supported.')
+ if rank == 0:
+ fileclient = FileClient(backend=backend)
+ buffer = io.BytesIO(fileclient.get(filename))
+ checkpoint = torch.load(buffer, map_location=map_location)
+ if world_size > 1:
+ torch.distributed.barrier()
+ if rank > 0:
+ fileclient = FileClient(backend=backend)
+ buffer = io.BytesIO(fileclient.get(filename))
+ checkpoint = torch.load(buffer, map_location=map_location)
+ return checkpoint
+
+
+def get_torchvision_models():
+ model_urls = dict()
+ for _, name, ispkg in pkgutil.walk_packages(torchvision.models.__path__):
+ if ispkg:
+ continue
+ _zoo = import_module(f'torchvision.models.{name}')
+ if hasattr(_zoo, 'model_urls'):
+ _urls = getattr(_zoo, 'model_urls')
+ model_urls.update(_urls)
+ return model_urls
+
+
+def get_external_models():
+ mmcv_home = _get_mmcv_home()
+ default_json_path = osp.join(mmcv.__path__[0], 'model_zoo/open_mmlab.json')
+ default_urls = load_file(default_json_path)
+ assert isinstance(default_urls, dict)
+ external_json_path = osp.join(mmcv_home, 'open_mmlab.json')
+ if osp.exists(external_json_path):
+ external_urls = load_file(external_json_path)
+ assert isinstance(external_urls, dict)
+ default_urls.update(external_urls)
+
+ return default_urls
+
+
+def get_mmcls_models():
+ mmcls_json_path = osp.join(mmcv.__path__[0], 'model_zoo/mmcls.json')
+ mmcls_urls = load_file(mmcls_json_path)
+
+ return mmcls_urls
+
+
+def get_deprecated_model_names():
+ deprecate_json_path = osp.join(mmcv.__path__[0],
+ 'model_zoo/deprecated.json')
+ deprecate_urls = load_file(deprecate_json_path)
+ assert isinstance(deprecate_urls, dict)
+
+ return deprecate_urls
+
+
+def _process_mmcls_checkpoint(checkpoint):
+ state_dict = checkpoint['state_dict']
+ new_state_dict = OrderedDict()
+ for k, v in state_dict.items():
+ if k.startswith('backbone.'):
+ new_state_dict[k[9:]] = v
+ new_checkpoint = dict(state_dict=new_state_dict)
+
+ return new_checkpoint
+
+
+def _load_checkpoint(filename, map_location=None):
+ """Load checkpoint from somewhere (modelzoo, file, url).
+ Args:
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str | None): Same as :func:`torch.load`. Default: None.
+ Returns:
+ dict | OrderedDict: The loaded checkpoint. It can be either an
+ OrderedDict storing model weights or a dict containing other
+ information, which depends on the checkpoint.
+ """
+ if filename.startswith('modelzoo://'):
+ warnings.warn('The URL scheme of "modelzoo://" is deprecated, please '
+ 'use "torchvision://" instead')
+ model_urls = get_torchvision_models()
+ model_name = filename[11:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ elif filename.startswith('torchvision://'):
+ model_urls = get_torchvision_models()
+ model_name = filename[14:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ elif filename.startswith('open-mmlab://'):
+ model_urls = get_external_models()
+ model_name = filename[13:]
+ deprecated_urls = get_deprecated_model_names()
+ if model_name in deprecated_urls:
+ warnings.warn(f'open-mmlab://{model_name} is deprecated in favor '
+ f'of open-mmlab://{deprecated_urls[model_name]}')
+ model_name = deprecated_urls[model_name]
+ model_url = model_urls[model_name]
+ # check if is url
+ if model_url.startswith(('http://', 'https://')):
+ checkpoint = load_url_dist(model_url)
+ else:
+ filename = osp.join(_get_mmcv_home(), model_url)
+ if not osp.isfile(filename):
+ raise IOError(f'{filename} is not a checkpoint file')
+ checkpoint = torch.load(filename, map_location=map_location)
+ elif filename.startswith('mmcls://'):
+ model_urls = get_mmcls_models()
+ model_name = filename[8:]
+ checkpoint = load_url_dist(model_urls[model_name])
+ checkpoint = _process_mmcls_checkpoint(checkpoint)
+ elif filename.startswith(('http://', 'https://')):
+ checkpoint = load_url_dist(filename)
+ elif filename.startswith('pavi://'):
+ model_path = filename[7:]
+ checkpoint = load_pavimodel_dist(model_path, map_location=map_location)
+ elif filename.startswith('s3://'):
+ checkpoint = load_fileclient_dist(
+ filename, backend='ceph', map_location=map_location)
+ else:
+ if not osp.isfile(filename):
+ raise IOError(f'{filename} is not a checkpoint file')
+ checkpoint = torch.load(filename, map_location=map_location)
+ return checkpoint
+
+
+def cosine_scheduler(base_value, final_value, epochs, niter_per_ep, warmup_epochs=0,
+ start_warmup_value=0, warmup_steps=-1):
+ warmup_schedule = np.array([])
+ warmup_iters = warmup_epochs * niter_per_ep
+ if warmup_steps > 0:
+ warmup_iters = warmup_steps
+ print("Set warmup steps = %d" % warmup_iters)
+ if warmup_epochs > 0:
+ warmup_schedule = np.linspace(start_warmup_value, base_value, warmup_iters)
+
+ iters = np.arange(epochs * niter_per_ep - warmup_iters)
+ schedule = np.array(
+ [final_value + 0.5 * (base_value - final_value) * (1 + math.cos(math.pi * i / (len(iters)))) for i in iters])
+
+ schedule = np.concatenate((warmup_schedule, schedule))
+
+ assert len(schedule) == epochs * niter_per_ep
+ return schedule
+
+
+def load_checkpoint(model,
+ filename,
+ map_location='cpu',
+ strict=False,
+ logger=None,
+ patch_padding='pad',
+ ):
+ """Load checkpoint from a file or URI.
+ Args:
+ model (Module): Module to load checkpoint.
+ filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+ ``open-mmlab://xxx``. Please refer to ``docs/model_zoo.md`` for
+ details.
+ map_location (str): Same as :func:`torch.load`.
+ strict (bool): Whether to allow different params for the model and
+ checkpoint.
+ logger (:mod:`logging.Logger` or None): The logger for error message.
+ patch_padding (str): 'pad' or 'bilinear' or 'bicubic', used for interpolate patch embed from 14x14 to 16x16
+ Returns:
+ dict or OrderedDict: The loaded checkpoint.
+ """
+ checkpoint = _load_checkpoint(filename, map_location)
+ # OrderedDict is a subclass of dict
+ if not isinstance(checkpoint, dict):
+ raise RuntimeError(
+ f'No state_dict found in checkpoint file {filename}')
+ # get state_dict from checkpoint
+ if 'state_dict' in checkpoint:
+ state_dict = checkpoint['state_dict']
+ elif 'model' in checkpoint:
+ state_dict = checkpoint['model']
+ elif 'module' in checkpoint:
+ state_dict = checkpoint['module']
+ else:
+ state_dict = checkpoint
+ # strip prefix of state_dict
+ if list(state_dict.keys())[0].startswith('module.'):
+ state_dict = {k[7:]: v for k, v in state_dict.items()}
+
+ # for MoBY, load model of online branch
+ if sorted(list(state_dict.keys()))[0].startswith('encoder'):
+ state_dict = {k.replace('encoder.', ''): v for k, v in state_dict.items() if k.startswith('encoder.')}
+
+ rank, _ = get_dist_info()
+
+ if 'patch_embed.proj.weight' in state_dict:
+ proj_weight = state_dict['patch_embed.proj.weight']
+ orig_size = proj_weight.shape[2:]
+ current_size = model.patch_embed.proj.weight.shape[2:]
+ padding_size = current_size[0] - orig_size[0]
+ padding_l = padding_size // 2
+ padding_r = padding_size - padding_l
+ if orig_size != current_size:
+ if 'pad' in patch_padding:
+ proj_weight = torch.nn.functional.pad(proj_weight, (padding_l, padding_r, padding_l, padding_r))
+ elif 'bilinear' in patch_padding:
+ proj_weight = torch.nn.functional.interpolate(proj_weight, size=current_size, mode='bilinear', align_corners=False)
+ elif 'bicubic' in patch_padding:
+ proj_weight = torch.nn.functional.interpolate(proj_weight, size=current_size, mode='bicubic', align_corners=False)
+ state_dict['patch_embed.proj.weight'] = proj_weight
+
+ if 'pos_embed' in state_dict:
+ pos_embed_checkpoint = state_dict['pos_embed']
+ embedding_size = pos_embed_checkpoint.shape[-1]
+ H, W = model.patch_embed.patch_shape
+ num_patches = model.patch_embed.num_patches
+ num_extra_tokens = model.pos_embed.shape[-2] - num_patches
+ # height (== width) for the checkpoint position embedding
+ orig_size = int((pos_embed_checkpoint.shape[-2] - num_extra_tokens) ** 0.5)
+ if rank == 0:
+ print("Position interpolate from %dx%d to %dx%d" % (orig_size, orig_size, H, W))
+ extra_tokens = pos_embed_checkpoint[:, :num_extra_tokens]
+ # only the position tokens are interpolated
+ pos_tokens = pos_embed_checkpoint[:, num_extra_tokens:]
+ pos_tokens = pos_tokens.reshape(-1, orig_size, orig_size, embedding_size).permute(0, 3, 1, 2)
+ pos_tokens = torch.nn.functional.interpolate(
+ pos_tokens, size=(H, W), mode='bicubic', align_corners=False)
+ pos_tokens = pos_tokens.permute(0, 2, 3, 1).flatten(1, 2)
+ new_pos_embed = torch.cat((extra_tokens, pos_tokens), dim=1)
+ state_dict['pos_embed'] = new_pos_embed
+
+ # load state_dict
+ load_state_dict(model, state_dict, strict, logger)
+ return checkpoint
+
+
+def weights_to_cpu(state_dict):
+ """Copy a model state_dict to cpu.
+ Args:
+ state_dict (OrderedDict): Model weights on GPU.
+ Returns:
+ OrderedDict: Model weights on GPU.
+ """
+ state_dict_cpu = OrderedDict()
+ for key, val in state_dict.items():
+ state_dict_cpu[key] = val.cpu()
+ return state_dict_cpu
+
+
+def _save_to_state_dict(module, destination, prefix, keep_vars):
+ """Saves module state to `destination` dictionary.
+ This method is modified from :meth:`torch.nn.Module._save_to_state_dict`.
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (dict): A dict where state will be stored.
+ prefix (str): The prefix for parameters and buffers used in this
+ module.
+ """
+ for name, param in module._parameters.items():
+ if param is not None:
+ destination[prefix + name] = param if keep_vars else param.detach()
+ for name, buf in module._buffers.items():
+ # remove check of _non_persistent_buffers_set to allow nn.BatchNorm2d
+ if buf is not None:
+ destination[prefix + name] = buf if keep_vars else buf.detach()
+
+
+def get_state_dict(module, destination=None, prefix='', keep_vars=False):
+ """Returns a dictionary containing a whole state of the module.
+ Both parameters and persistent buffers (e.g. running averages) are
+ included. Keys are corresponding parameter and buffer names.
+ This method is modified from :meth:`torch.nn.Module.state_dict` to
+ recursively check parallel module in case that the model has a complicated
+ structure, e.g., nn.Module(nn.Module(DDP)).
+ Args:
+ module (nn.Module): The module to generate state_dict.
+ destination (OrderedDict): Returned dict for the state of the
+ module.
+ prefix (str): Prefix of the key.
+ keep_vars (bool): Whether to keep the variable property of the
+ parameters. Default: False.
+ Returns:
+ dict: A dictionary containing a whole state of the module.
+ """
+ # recursively check parallel module in case that the model has a
+ # complicated structure, e.g., nn.Module(nn.Module(DDP))
+ if is_module_wrapper(module):
+ module = module.module
+
+ # below is the same as torch.nn.Module.state_dict()
+ if destination is None:
+ destination = OrderedDict()
+ destination._metadata = OrderedDict()
+ destination._metadata[prefix[:-1]] = local_metadata = dict(
+ version=module._version)
+ _save_to_state_dict(module, destination, prefix, keep_vars)
+ for name, child in module._modules.items():
+ if child is not None:
+ get_state_dict(
+ child, destination, prefix + name + '.', keep_vars=keep_vars)
+ for hook in module._state_dict_hooks.values():
+ hook_result = hook(module, destination, prefix, local_metadata)
+ if hook_result is not None:
+ destination = hook_result
+ return destination
+
+
+def save_checkpoint(model, filename, optimizer=None, meta=None):
+ """Save checkpoint to file.
+ The checkpoint will have 3 fields: ``meta``, ``state_dict`` and
+ ``optimizer``. By default ``meta`` will contain version and time info.
+ Args:
+ model (Module): Module whose params are to be saved.
+ filename (str): Checkpoint filename.
+ optimizer (:obj:`Optimizer`, optional): Optimizer to be saved.
+ meta (dict, optional): Metadata to be saved in checkpoint.
+ """
+ if meta is None:
+ meta = {}
+ elif not isinstance(meta, dict):
+ raise TypeError(f'meta must be a dict or None, but got {type(meta)}')
+ meta.update(mmcv_version=mmcv.__version__, time=time.asctime())
+
+ if is_module_wrapper(model):
+ model = model.module
+
+ if hasattr(model, 'CLASSES') and model.CLASSES is not None:
+ # save class name to the meta
+ meta.update(CLASSES=model.CLASSES)
+
+ checkpoint = {
+ 'meta': meta,
+ 'state_dict': weights_to_cpu(get_state_dict(model))
+ }
+ # save optimizer state dict in the checkpoint
+ if isinstance(optimizer, Optimizer):
+ checkpoint['optimizer'] = optimizer.state_dict()
+ elif isinstance(optimizer, dict):
+ checkpoint['optimizer'] = {}
+ for name, optim in optimizer.items():
+ checkpoint['optimizer'][name] = optim.state_dict()
+
+ if filename.startswith('pavi://'):
+ try:
+ from pavi import modelcloud
+ from pavi.exception import NodeNotFoundError
+ except ImportError:
+ raise ImportError(
+ 'Please install pavi to load checkpoint from modelcloud.')
+ model_path = filename[7:]
+ root = modelcloud.Folder()
+ model_dir, model_name = osp.split(model_path)
+ try:
+ model = modelcloud.get(model_dir)
+ except NodeNotFoundError:
+ model = root.create_training_model(model_dir)
+ with TemporaryDirectory() as tmp_dir:
+ checkpoint_file = osp.join(tmp_dir, model_name)
+ with open(checkpoint_file, 'wb') as f:
+ torch.save(checkpoint, f)
+ f.flush()
+ model.create_file(checkpoint_file, name=model_name)
+ else:
+ mmcv.mkdir_or_exist(osp.dirname(filename))
+ # immediately flush buffer
+ with open(filename, 'wb') as f:
+ torch.save(checkpoint, f)
+ f.flush()
+
+
+# def load_checkpoint(model,
+# filename,
+# map_location='cpu',
+# strict=False,
+# logger=None):
+# """Load checkpoint from a file or URI.
+#
+# Args:
+# model (Module): Module to load checkpoint.
+# filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+# ``open-mmlab://xxx``.
+# map_location (str): Same as :func:`torch.load`.
+# strict (bool): Whether to allow different params for the model and
+# checkpoint.
+# logger (:mod:`logging.Logger` or None): The logger for error message.
+#
+# Returns:
+# dict or OrderedDict: The loaded checkpoint.
+# """
+# checkpoint = _load_checkpoint(filename, map_location)
+# # OrderedDict is a subclass of dict
+# if not isinstance(checkpoint, dict):
+# raise RuntimeError(
+# f'No state_dict found in checkpoint file {filename}')
+# # get state_dict from checkpoint
+# if 'state_dict' in checkpoint:
+# state_dict_tmp = checkpoint['state_dict']
+# else:
+# state_dict_tmp = checkpoint
+#
+# state_dict = OrderedDict()
+# # strip prefix of state_dict
+# for k, v in state_dict_tmp.items():
+# if k.startswith('module.backbone.'):
+# state_dict[k[16:]] = v
+# elif k.startswith('module.'):
+# state_dict[k[7:]] = v
+# elif k.startswith('backbone.'):
+# state_dict[k[9:]] = v
+# else:
+# state_dict[k] = v
+# # load state_dict
+# load_state_dict(model, state_dict, strict, logger)
+# return checkpoint
+#
+#
+# def get_state_dict(filename, map_location='cpu'):
+# """Get state_dict from a file or URI.
+#
+# Args:
+# filename (str): Accept local filepath, URL, ``torchvision://xxx``,
+# ``open-mmlab://xxx``.
+# map_location (str): Same as :func:`torch.load`.
+#
+# Returns:
+# OrderedDict: The state_dict.
+# """
+# checkpoint = _load_checkpoint(filename, map_location)
+# # OrderedDict is a subclass of dict
+# if not isinstance(checkpoint, dict):
+# raise RuntimeError(
+# f'No state_dict found in checkpoint file {filename}')
+# # get state_dict from checkpoint
+# if 'state_dict' in checkpoint:
+# state_dict_tmp = checkpoint['state_dict']
+# else:
+# state_dict_tmp = checkpoint
+#
+# state_dict = OrderedDict()
+# # strip prefix of state_dict
+# for k, v in state_dict_tmp.items():
+# if k.startswith('module.backbone.'):
+# state_dict[k[16:]] = v
+# elif k.startswith('module.'):
+# state_dict[k[7:]] = v
+# elif k.startswith('backbone.'):
+# state_dict[k[9:]] = v
+# else:
+# state_dict[k] = v
+#
+# return state_dict
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/v2v_net.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/v2v_net.py
new file mode 100644
index 0000000000000000000000000000000000000000..99462af711069a34c13628364e2c466163507861
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/v2v_net.py
@@ -0,0 +1,257 @@
+# ------------------------------------------------------------------------------
+# Copyright and License Information
+# Adapted from
+# https://github.com/microsoft/voxelpose-pytorch/blob/main/lib/models/v2v_net.py
+# Original Licence: MIT License
+# ------------------------------------------------------------------------------
+
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import ConvModule
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class Basic3DBlock(nn.Module):
+ """A basic 3D convolutional block.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ kernel_size (int): Kernel size of the convolution operation
+ conv_cfg (dict): Dictionary to construct and config conv layer.
+ Default: dict(type='Conv3d')
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+ Default: dict(type='BN3d')
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ kernel_size,
+ conv_cfg=dict(type='Conv3d'),
+ norm_cfg=dict(type='BN3d')):
+ super(Basic3DBlock, self).__init__()
+ self.block = ConvModule(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride=1,
+ padding=((kernel_size - 1) // 2),
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ bias=True)
+
+ def forward(self, x):
+ """Forward function."""
+ return self.block(x)
+
+
+class Res3DBlock(nn.Module):
+ """A residual 3D convolutional block.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ kernel_size (int): Kernel size of the convolution operation
+ Default: 3
+ conv_cfg (dict): Dictionary to construct and config conv layer.
+ Default: dict(type='Conv3d')
+ norm_cfg (dict): Dictionary to construct and config norm layer.
+ Default: dict(type='BN3d')
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ conv_cfg=dict(type='Conv3d'),
+ norm_cfg=dict(type='BN3d')):
+ super(Res3DBlock, self).__init__()
+ self.res_branch = nn.Sequential(
+ ConvModule(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride=1,
+ padding=((kernel_size - 1) // 2),
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ bias=True),
+ ConvModule(
+ out_channels,
+ out_channels,
+ kernel_size,
+ stride=1,
+ padding=((kernel_size - 1) // 2),
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None,
+ bias=True))
+
+ if in_channels == out_channels:
+ self.skip_con = nn.Sequential()
+ else:
+ self.skip_con = ConvModule(
+ in_channels,
+ out_channels,
+ 1,
+ stride=1,
+ padding=0,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=None,
+ bias=True)
+
+ def forward(self, x):
+ """Forward function."""
+ res = self.res_branch(x)
+ skip = self.skip_con(x)
+ return F.relu(res + skip, True)
+
+
+class Pool3DBlock(nn.Module):
+ """A 3D max-pool block.
+
+ Args:
+ pool_size (int): Pool size of the 3D max-pool layer
+ """
+
+ def __init__(self, pool_size):
+ super(Pool3DBlock, self).__init__()
+ self.pool_size = pool_size
+
+ def forward(self, x):
+ """Forward function."""
+ return F.max_pool3d(
+ x, kernel_size=self.pool_size, stride=self.pool_size)
+
+
+class Upsample3DBlock(nn.Module):
+ """A 3D upsample block.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ kernel_size (int): Kernel size of the transposed convolution operation.
+ Default: 2
+ stride (int): Kernel size of the transposed convolution operation.
+ Default: 2
+ """
+
+ def __init__(self, in_channels, out_channels, kernel_size=2, stride=2):
+ super(Upsample3DBlock, self).__init__()
+ assert kernel_size == 2
+ assert stride == 2
+ self.block = nn.Sequential(
+ nn.ConvTranspose3d(
+ in_channels,
+ out_channels,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=0,
+ output_padding=0), nn.BatchNorm3d(out_channels), nn.ReLU(True))
+
+ def forward(self, x):
+ """Forward function."""
+ return self.block(x)
+
+
+class EncoderDecorder(nn.Module):
+ """An encoder-decoder block.
+
+ Args:
+ in_channels (int): Input channels of this block
+ """
+
+ def __init__(self, in_channels=32):
+ super(EncoderDecorder, self).__init__()
+
+ self.encoder_pool1 = Pool3DBlock(2)
+ self.encoder_res1 = Res3DBlock(in_channels, in_channels * 2)
+ self.encoder_pool2 = Pool3DBlock(2)
+ self.encoder_res2 = Res3DBlock(in_channels * 2, in_channels * 4)
+
+ self.mid_res = Res3DBlock(in_channels * 4, in_channels * 4)
+
+ self.decoder_res2 = Res3DBlock(in_channels * 4, in_channels * 4)
+ self.decoder_upsample2 = Upsample3DBlock(in_channels * 4,
+ in_channels * 2, 2, 2)
+ self.decoder_res1 = Res3DBlock(in_channels * 2, in_channels * 2)
+ self.decoder_upsample1 = Upsample3DBlock(in_channels * 2, in_channels,
+ 2, 2)
+
+ self.skip_res1 = Res3DBlock(in_channels, in_channels)
+ self.skip_res2 = Res3DBlock(in_channels * 2, in_channels * 2)
+
+ def forward(self, x):
+ """Forward function."""
+ skip_x1 = self.skip_res1(x)
+ x = self.encoder_pool1(x)
+ x = self.encoder_res1(x)
+
+ skip_x2 = self.skip_res2(x)
+ x = self.encoder_pool2(x)
+ x = self.encoder_res2(x)
+
+ x = self.mid_res(x)
+
+ x = self.decoder_res2(x)
+ x = self.decoder_upsample2(x)
+ x = x + skip_x2
+
+ x = self.decoder_res1(x)
+ x = self.decoder_upsample1(x)
+ x = x + skip_x1
+
+ return x
+
+
+@BACKBONES.register_module()
+class V2VNet(BaseBackbone):
+ """V2VNet.
+
+ Please refer to the `paper `
+ for details.
+
+ Args:
+ input_channels (int):
+ Number of channels of the input feature volume.
+ output_channels (int):
+ Number of channels of the output volume.
+ mid_channels (int):
+ Input and output channels of the encoder-decoder block.
+ """
+
+ def __init__(self, input_channels, output_channels, mid_channels=32):
+ super(V2VNet, self).__init__()
+
+ self.front_layers = nn.Sequential(
+ Basic3DBlock(input_channels, mid_channels // 2, 7),
+ Res3DBlock(mid_channels // 2, mid_channels),
+ )
+
+ self.encoder_decoder = EncoderDecorder(in_channels=mid_channels)
+
+ self.output_layer = nn.Conv3d(
+ mid_channels, output_channels, kernel_size=1, stride=1, padding=0)
+
+ self._initialize_weights()
+
+ def forward(self, x):
+ """Forward function."""
+ x = self.front_layers(x)
+ x = self.encoder_decoder(x)
+ x = self.output_layer(x)
+
+ return x
+
+ def _initialize_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv3d):
+ nn.init.normal_(m.weight, 0, 0.001)
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.ConvTranspose3d):
+ nn.init.normal_(m.weight, 0, 0.001)
+ nn.init.constant_(m.bias, 0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vgg.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vgg.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7d467017a5520f399c84b1235ec64c99b805b42
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vgg.py
@@ -0,0 +1,193 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.nn as nn
+from mmcv.cnn import ConvModule, constant_init, kaiming_init, normal_init
+from mmcv.utils.parrots_wrapper import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+def make_vgg_layer(in_channels,
+ out_channels,
+ num_blocks,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=dict(type='ReLU'),
+ dilation=1,
+ with_norm=False,
+ ceil_mode=False):
+ layers = []
+ for _ in range(num_blocks):
+ layer = ConvModule(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=3,
+ dilation=dilation,
+ padding=dilation,
+ bias=True,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg)
+ layers.append(layer)
+ in_channels = out_channels
+ layers.append(nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=ceil_mode))
+
+ return layers
+
+
+@BACKBONES.register_module()
+class VGG(BaseBackbone):
+ """VGG backbone.
+
+ Args:
+ depth (int): Depth of vgg, from {11, 13, 16, 19}.
+ with_norm (bool): Use BatchNorm or not.
+ num_classes (int): number of classes for classification.
+ num_stages (int): VGG stages, normally 5.
+ dilations (Sequence[int]): Dilation of each stage.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. When it is None, the default behavior depends on
+ whether num_classes is specified. If num_classes <= 0, the default
+ value is (4, ), outputting the last feature map before classifier.
+ If num_classes > 0, the default value is (5, ), outputting the
+ classification score. Default: None.
+ frozen_stages (int): Stages to be frozen (all param fixed). -1 means
+ not freezing any parameters.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ ceil_mode (bool): Whether to use ceil_mode of MaxPool. Default: False.
+ with_last_pool (bool): Whether to keep the last pooling before
+ classifier. Default: True.
+ """
+
+ # Parameters to build layers. Each element specifies the number of conv in
+ # each stage. For example, VGG11 contains 11 layers with learnable
+ # parameters. 11 is computed as 11 = (1 + 1 + 2 + 2 + 2) + 3,
+ # where 3 indicates the last three fully-connected layers.
+ arch_settings = {
+ 11: (1, 1, 2, 2, 2),
+ 13: (2, 2, 2, 2, 2),
+ 16: (2, 2, 3, 3, 3),
+ 19: (2, 2, 4, 4, 4)
+ }
+
+ def __init__(self,
+ depth,
+ num_classes=-1,
+ num_stages=5,
+ dilations=(1, 1, 1, 1, 1),
+ out_indices=None,
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=dict(type='ReLU'),
+ norm_eval=False,
+ ceil_mode=False,
+ with_last_pool=True):
+ super().__init__()
+ if depth not in self.arch_settings:
+ raise KeyError(f'invalid depth {depth} for vgg')
+ assert num_stages >= 1 and num_stages <= 5
+ stage_blocks = self.arch_settings[depth]
+ self.stage_blocks = stage_blocks[:num_stages]
+ assert len(dilations) == num_stages
+
+ self.num_classes = num_classes
+ self.frozen_stages = frozen_stages
+ self.norm_eval = norm_eval
+ with_norm = norm_cfg is not None
+
+ if out_indices is None:
+ out_indices = (5, ) if num_classes > 0 else (4, )
+ assert max(out_indices) <= num_stages
+ self.out_indices = out_indices
+
+ self.in_channels = 3
+ start_idx = 0
+ vgg_layers = []
+ self.range_sub_modules = []
+ for i, num_blocks in enumerate(self.stage_blocks):
+ num_modules = num_blocks + 1
+ end_idx = start_idx + num_modules
+ dilation = dilations[i]
+ out_channels = 64 * 2**i if i < 4 else 512
+ vgg_layer = make_vgg_layer(
+ self.in_channels,
+ out_channels,
+ num_blocks,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ dilation=dilation,
+ with_norm=with_norm,
+ ceil_mode=ceil_mode)
+ vgg_layers.extend(vgg_layer)
+ self.in_channels = out_channels
+ self.range_sub_modules.append([start_idx, end_idx])
+ start_idx = end_idx
+ if not with_last_pool:
+ vgg_layers.pop(-1)
+ self.range_sub_modules[-1][1] -= 1
+ self.module_name = 'features'
+ self.add_module(self.module_name, nn.Sequential(*vgg_layers))
+
+ if self.num_classes > 0:
+ self.classifier = nn.Sequential(
+ nn.Linear(512 * 7 * 7, 4096),
+ nn.ReLU(True),
+ nn.Dropout(),
+ nn.Linear(4096, 4096),
+ nn.ReLU(True),
+ nn.Dropout(),
+ nn.Linear(4096, num_classes),
+ )
+
+ def init_weights(self, pretrained=None):
+ super().init_weights(pretrained)
+ if pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, _BatchNorm):
+ constant_init(m, 1)
+ elif isinstance(m, nn.Linear):
+ normal_init(m, std=0.01)
+
+ def forward(self, x):
+ outs = []
+ vgg_layers = getattr(self, self.module_name)
+ for i in range(len(self.stage_blocks)):
+ for j in range(*self.range_sub_modules[i]):
+ vgg_layer = vgg_layers[j]
+ x = vgg_layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+ if self.num_classes > 0:
+ x = x.view(x.size(0), -1)
+ x = self.classifier(x)
+ outs.append(x)
+ if len(outs) == 1:
+ return outs[0]
+ else:
+ return tuple(outs)
+
+ def _freeze_stages(self):
+ vgg_layers = getattr(self, self.module_name)
+ for i in range(self.frozen_stages):
+ for j in range(*self.range_sub_modules[i]):
+ m = vgg_layers[j]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ # trick: eval have effect on BatchNorm only
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_mbv3.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_mbv3.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed990e3966b27301dbaf081e3ec0e908704dfc8b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_mbv3.py
@@ -0,0 +1,179 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+import logging
+
+import torch.nn as nn
+from mmcv.cnn import ConvModule
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from .utils import InvertedResidual, load_checkpoint
+
+
+@BACKBONES.register_module()
+class ViPNAS_MobileNetV3(BaseBackbone):
+ """ViPNAS_MobileNetV3 backbone.
+
+ "ViPNAS: Efficient Video Pose Estimation via Neural Architecture Search"
+ More details can be found in the `paper
+ `__ .
+
+ Args:
+ wid (list(int)): Searched width config for each stage.
+ expan (list(int)): Searched expansion ratio config for each stage.
+ dep (list(int)): Searched depth config for each stage.
+ ks (list(int)): Searched kernel size config for each stage.
+ group (list(int)): Searched group number config for each stage.
+ att (list(bool)): Searched attention config for each stage.
+ stride (list(int)): Stride config for each stage.
+ act (list(dict)): Activation config for each stage.
+ conv_cfg (dict): Config dict for convolution layer.
+ Default: None, which means using conv2d.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='BN').
+ frozen_stages (int): Stages to be frozen (all param fixed).
+ Default: -1, which means not freezing any parameters.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save
+ some memory while slowing down the training speed.
+ Default: False.
+ """
+
+ def __init__(self,
+ wid=[16, 16, 24, 40, 80, 112, 160],
+ expan=[None, 1, 5, 4, 5, 5, 6],
+ dep=[None, 1, 4, 4, 4, 4, 4],
+ ks=[3, 3, 7, 7, 5, 7, 5],
+ group=[None, 8, 120, 20, 100, 280, 240],
+ att=[None, True, True, False, True, True, True],
+ stride=[2, 1, 2, 2, 2, 1, 2],
+ act=[
+ 'HSwish', 'ReLU', 'ReLU', 'ReLU', 'HSwish', 'HSwish',
+ 'HSwish'
+ ],
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ frozen_stages=-1,
+ norm_eval=False,
+ with_cp=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ self.wid = wid
+ self.expan = expan
+ self.dep = dep
+ self.ks = ks
+ self.group = group
+ self.att = att
+ self.stride = stride
+ self.act = act
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.frozen_stages = frozen_stages
+ self.norm_eval = norm_eval
+ self.with_cp = with_cp
+
+ self.conv1 = ConvModule(
+ in_channels=3,
+ out_channels=self.wid[0],
+ kernel_size=self.ks[0],
+ stride=self.stride[0],
+ padding=self.ks[0] // 2,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=dict(type=self.act[0]))
+
+ self.layers = self._make_layer()
+
+ def _make_layer(self):
+ layers = []
+ layer_index = 0
+ for i, dep in enumerate(self.dep[1:]):
+ mid_channels = self.wid[i + 1] * self.expan[i + 1]
+
+ if self.att[i + 1]:
+ se_cfg = dict(
+ channels=mid_channels,
+ ratio=4,
+ act_cfg=(dict(type='ReLU'), dict(type='HSigmoid')))
+ else:
+ se_cfg = None
+
+ if self.expan[i + 1] == 1:
+ with_expand_conv = False
+ else:
+ with_expand_conv = True
+
+ for j in range(dep):
+ if j == 0:
+ stride = self.stride[i + 1]
+ in_channels = self.wid[i]
+ else:
+ stride = 1
+ in_channels = self.wid[i + 1]
+
+ layer = InvertedResidual(
+ in_channels=in_channels,
+ out_channels=self.wid[i + 1],
+ mid_channels=mid_channels,
+ kernel_size=self.ks[i + 1],
+ groups=self.group[i + 1],
+ stride=stride,
+ se_cfg=se_cfg,
+ with_expand_conv=with_expand_conv,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ act_cfg=dict(type=self.act[i + 1]),
+ with_cp=self.with_cp)
+ layer_index += 1
+ layer_name = f'layer{layer_index}'
+ self.add_module(layer_name, layer)
+ layers.append(layer_name)
+ return layers
+
+ def init_weights(self, pretrained=None):
+ if isinstance(pretrained, str):
+ logger = logging.getLogger()
+ load_checkpoint(self, pretrained, strict=False, logger=logger)
+ elif pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.normal_(m.weight, std=0.001)
+ for name, _ in m.named_parameters():
+ if name in ['bias']:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.BatchNorm2d):
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+ else:
+ raise TypeError('pretrained must be a str or None')
+
+ def forward(self, x):
+ x = self.conv1(x)
+
+ for i, layer_name in enumerate(self.layers):
+ layer = getattr(self, layer_name)
+ x = layer(x)
+
+ return x
+
+ def _freeze_stages(self):
+ if self.frozen_stages >= 0:
+ for param in self.conv1.parameters():
+ param.requires_grad = False
+ for i in range(1, self.frozen_stages + 1):
+ layer = getattr(self, f'layer{i}')
+ layer.eval()
+ for param in layer.parameters():
+ param.requires_grad = False
+
+ def train(self, mode=True):
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_resnet.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_resnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..81b028ed5f5caad5f59c68b7f82c1a4661cf4d6f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vipnas_resnet.py
@@ -0,0 +1,589 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy
+
+import torch.nn as nn
+import torch.utils.checkpoint as cp
+from mmcv.cnn import ConvModule, build_conv_layer, build_norm_layer
+from mmcv.cnn.bricks import ContextBlock
+from mmcv.utils.parrots_wrapper import _BatchNorm
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+
+
+class ViPNAS_Bottleneck(nn.Module):
+ """Bottleneck block for ViPNAS_ResNet.
+
+ Args:
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (int): The ratio of ``out_channels/mid_channels`` where
+ ``mid_channels`` is the input/output channels of conv2. Default: 4.
+ stride (int): stride of the block. Default: 1
+ dilation (int): dilation of convolution. Default: 1
+ downsample (nn.Module): downsample operation on identity branch.
+ Default: None.
+ style (str): ``"pytorch"`` or ``"caffe"``. If set to "pytorch", the
+ stride-two layer is the 3x3 conv layer, otherwise the stride-two
+ layer is the first 1x1 conv layer. Default: "pytorch".
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed.
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ kernel_size (int): kernel size of conv2 searched in ViPANS.
+ groups (int): group number of conv2 searched in ViPNAS.
+ attention (bool): whether to use attention module in the end of
+ the block.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ expansion=4,
+ stride=1,
+ dilation=1,
+ downsample=None,
+ style='pytorch',
+ with_cp=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ kernel_size=3,
+ groups=1,
+ attention=False):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ assert style in ['pytorch', 'caffe']
+
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.expansion = expansion
+ assert out_channels % expansion == 0
+ self.mid_channels = out_channels // expansion
+ self.stride = stride
+ self.dilation = dilation
+ self.style = style
+ self.with_cp = with_cp
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+
+ if self.style == 'pytorch':
+ self.conv1_stride = 1
+ self.conv2_stride = stride
+ else:
+ self.conv1_stride = stride
+ self.conv2_stride = 1
+
+ self.norm1_name, norm1 = build_norm_layer(
+ norm_cfg, self.mid_channels, postfix=1)
+ self.norm2_name, norm2 = build_norm_layer(
+ norm_cfg, self.mid_channels, postfix=2)
+ self.norm3_name, norm3 = build_norm_layer(
+ norm_cfg, out_channels, postfix=3)
+
+ self.conv1 = build_conv_layer(
+ conv_cfg,
+ in_channels,
+ self.mid_channels,
+ kernel_size=1,
+ stride=self.conv1_stride,
+ bias=False)
+ self.add_module(self.norm1_name, norm1)
+ self.conv2 = build_conv_layer(
+ conv_cfg,
+ self.mid_channels,
+ self.mid_channels,
+ kernel_size=kernel_size,
+ stride=self.conv2_stride,
+ padding=kernel_size // 2,
+ groups=groups,
+ dilation=dilation,
+ bias=False)
+
+ self.add_module(self.norm2_name, norm2)
+ self.conv3 = build_conv_layer(
+ conv_cfg,
+ self.mid_channels,
+ out_channels,
+ kernel_size=1,
+ bias=False)
+ self.add_module(self.norm3_name, norm3)
+
+ if attention:
+ self.attention = ContextBlock(out_channels,
+ max(1.0 / 16, 16.0 / out_channels))
+ else:
+ self.attention = None
+
+ self.relu = nn.ReLU(inplace=True)
+ self.downsample = downsample
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ @property
+ def norm2(self):
+ """nn.Module: the normalization layer named "norm2" """
+ return getattr(self, self.norm2_name)
+
+ @property
+ def norm3(self):
+ """nn.Module: the normalization layer named "norm3" """
+ return getattr(self, self.norm3_name)
+
+ def forward(self, x):
+ """Forward function."""
+
+ def _inner_forward(x):
+ identity = x
+
+ out = self.conv1(x)
+ out = self.norm1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.norm2(out)
+ out = self.relu(out)
+
+ out = self.conv3(out)
+ out = self.norm3(out)
+
+ if self.attention is not None:
+ out = self.attention(out)
+
+ if self.downsample is not None:
+ identity = self.downsample(x)
+
+ out += identity
+
+ return out
+
+ if self.with_cp and x.requires_grad:
+ out = cp.checkpoint(_inner_forward, x)
+ else:
+ out = _inner_forward(x)
+
+ out = self.relu(out)
+
+ return out
+
+
+def get_expansion(block, expansion=None):
+ """Get the expansion of a residual block.
+
+ The block expansion will be obtained by the following order:
+
+ 1. If ``expansion`` is given, just return it.
+ 2. If ``block`` has the attribute ``expansion``, then return
+ ``block.expansion``.
+ 3. Return the default value according the the block type:
+ 4 for ``ViPNAS_Bottleneck``.
+
+ Args:
+ block (class): The block class.
+ expansion (int | None): The given expansion ratio.
+
+ Returns:
+ int: The expansion of the block.
+ """
+ if isinstance(expansion, int):
+ assert expansion > 0
+ elif expansion is None:
+ if hasattr(block, 'expansion'):
+ expansion = block.expansion
+ elif issubclass(block, ViPNAS_Bottleneck):
+ expansion = 1
+ else:
+ raise TypeError(f'expansion is not specified for {block.__name__}')
+ else:
+ raise TypeError('expansion must be an integer or None')
+
+ return expansion
+
+
+class ViPNAS_ResLayer(nn.Sequential):
+ """ViPNAS_ResLayer to build ResNet style backbone.
+
+ Args:
+ block (nn.Module): Residual block used to build ViPNAS ResLayer.
+ num_blocks (int): Number of blocks.
+ in_channels (int): Input channels of this block.
+ out_channels (int): Output channels of this block.
+ expansion (int, optional): The expansion for BasicBlock/Bottleneck.
+ If not specified, it will firstly be obtained via
+ ``block.expansion``. If the block has no attribute "expansion",
+ the following default values will be used: 1 for BasicBlock and
+ 4 for Bottleneck. Default: None.
+ stride (int): stride of the first block. Default: 1.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False
+ conv_cfg (dict): dictionary to construct and config conv layer.
+ Default: None
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ downsample_first (bool): Downsample at the first block or last block.
+ False for Hourglass, True for ResNet. Default: True
+ kernel_size (int): Kernel Size of the corresponding convolution layer
+ searched in the block.
+ groups (int): Group number of the corresponding convolution layer
+ searched in the block.
+ attention (bool): Whether to use attention module in the end of the
+ block.
+ """
+
+ def __init__(self,
+ block,
+ num_blocks,
+ in_channels,
+ out_channels,
+ expansion=None,
+ stride=1,
+ avg_down=False,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN'),
+ downsample_first=True,
+ kernel_size=3,
+ groups=1,
+ attention=False,
+ **kwargs):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ self.block = block
+ self.expansion = get_expansion(block, expansion)
+
+ downsample = None
+ if stride != 1 or in_channels != out_channels:
+ downsample = []
+ conv_stride = stride
+ if avg_down and stride != 1:
+ conv_stride = 1
+ downsample.append(
+ nn.AvgPool2d(
+ kernel_size=stride,
+ stride=stride,
+ ceil_mode=True,
+ count_include_pad=False))
+ downsample.extend([
+ build_conv_layer(
+ conv_cfg,
+ in_channels,
+ out_channels,
+ kernel_size=1,
+ stride=conv_stride,
+ bias=False),
+ build_norm_layer(norm_cfg, out_channels)[1]
+ ])
+ downsample = nn.Sequential(*downsample)
+
+ layers = []
+ if downsample_first:
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=stride,
+ downsample=downsample,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ kernel_size=kernel_size,
+ groups=groups,
+ attention=attention,
+ **kwargs))
+ in_channels = out_channels
+ for _ in range(1, num_blocks):
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ kernel_size=kernel_size,
+ groups=groups,
+ attention=attention,
+ **kwargs))
+ else: # downsample_first=False is for HourglassModule
+ for i in range(0, num_blocks - 1):
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ expansion=self.expansion,
+ stride=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ kernel_size=kernel_size,
+ groups=groups,
+ attention=attention,
+ **kwargs))
+ layers.append(
+ block(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ expansion=self.expansion,
+ stride=stride,
+ downsample=downsample,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ kernel_size=kernel_size,
+ groups=groups,
+ attention=attention,
+ **kwargs))
+
+ super().__init__(*layers)
+
+
+@BACKBONES.register_module()
+class ViPNAS_ResNet(BaseBackbone):
+ """ViPNAS_ResNet backbone.
+
+ "ViPNAS: Efficient Video Pose Estimation via Neural Architecture Search"
+ More details can be found in the `paper
+ `__ .
+
+ Args:
+ depth (int): Network depth, from {18, 34, 50, 101, 152}.
+ in_channels (int): Number of input image channels. Default: 3.
+ num_stages (int): Stages of the network. Default: 4.
+ strides (Sequence[int]): Strides of the first block of each stage.
+ Default: ``(1, 2, 2, 2)``.
+ dilations (Sequence[int]): Dilation of each stage.
+ Default: ``(1, 1, 1, 1)``.
+ out_indices (Sequence[int]): Output from which stages. If only one
+ stage is specified, a single tensor (feature map) is returned,
+ otherwise multiple stages are specified, a tuple of tensors will
+ be returned. Default: ``(3, )``.
+ style (str): `pytorch` or `caffe`. If set to "pytorch", the stride-two
+ layer is the 3x3 conv layer, otherwise the stride-two layer is
+ the first 1x1 conv layer.
+ deep_stem (bool): Replace 7x7 conv in input stem with 3 3x3 conv.
+ Default: False.
+ avg_down (bool): Use AvgPool instead of stride conv when
+ downsampling in the bottleneck. Default: False.
+ frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
+ -1 means not freezing any parameters. Default: -1.
+ conv_cfg (dict | None): The config dict for conv layers. Default: None.
+ norm_cfg (dict): The config dict for norm layers.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ with_cp (bool): Use checkpoint or not. Using checkpoint will save some
+ memory while slowing down the training speed. Default: False.
+ zero_init_residual (bool): Whether to use zero init for last norm layer
+ in resblocks to let them behave as identity. Default: True.
+ wid (list(int)): Searched width config for each stage.
+ expan (list(int)): Searched expansion ratio config for each stage.
+ dep (list(int)): Searched depth config for each stage.
+ ks (list(int)): Searched kernel size config for each stage.
+ group (list(int)): Searched group number config for each stage.
+ att (list(bool)): Searched attention config for each stage.
+ """
+
+ arch_settings = {
+ 50: ViPNAS_Bottleneck,
+ }
+
+ def __init__(self,
+ depth,
+ in_channels=3,
+ num_stages=4,
+ strides=(1, 2, 2, 2),
+ dilations=(1, 1, 1, 1),
+ out_indices=(3, ),
+ style='pytorch',
+ deep_stem=False,
+ avg_down=False,
+ frozen_stages=-1,
+ conv_cfg=None,
+ norm_cfg=dict(type='BN', requires_grad=True),
+ norm_eval=False,
+ with_cp=False,
+ zero_init_residual=True,
+ wid=[48, 80, 160, 304, 608],
+ expan=[None, 1, 1, 1, 1],
+ dep=[None, 4, 6, 7, 3],
+ ks=[7, 3, 5, 5, 5],
+ group=[None, 16, 16, 16, 16],
+ att=[None, True, False, True, True]):
+ # Protect mutable default arguments
+ norm_cfg = copy.deepcopy(norm_cfg)
+ super().__init__()
+ if depth not in self.arch_settings:
+ raise KeyError(f'invalid depth {depth} for resnet')
+ self.depth = depth
+ self.stem_channels = dep[0]
+ self.num_stages = num_stages
+ assert 1 <= num_stages <= 4
+ self.strides = strides
+ self.dilations = dilations
+ assert len(strides) == len(dilations) == num_stages
+ self.out_indices = out_indices
+ assert max(out_indices) < num_stages
+ self.style = style
+ self.deep_stem = deep_stem
+ self.avg_down = avg_down
+ self.frozen_stages = frozen_stages
+ self.conv_cfg = conv_cfg
+ self.norm_cfg = norm_cfg
+ self.with_cp = with_cp
+ self.norm_eval = norm_eval
+ self.zero_init_residual = zero_init_residual
+ self.block = self.arch_settings[depth]
+ self.stage_blocks = dep[1:1 + num_stages]
+
+ self._make_stem_layer(in_channels, wid[0], ks[0])
+
+ self.res_layers = []
+ _in_channels = wid[0]
+ for i, num_blocks in enumerate(self.stage_blocks):
+ expansion = get_expansion(self.block, expan[i + 1])
+ _out_channels = wid[i + 1] * expansion
+ stride = strides[i]
+ dilation = dilations[i]
+ res_layer = self.make_res_layer(
+ block=self.block,
+ num_blocks=num_blocks,
+ in_channels=_in_channels,
+ out_channels=_out_channels,
+ expansion=expansion,
+ stride=stride,
+ dilation=dilation,
+ style=self.style,
+ avg_down=self.avg_down,
+ with_cp=with_cp,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ kernel_size=ks[i + 1],
+ groups=group[i + 1],
+ attention=att[i + 1])
+ _in_channels = _out_channels
+ layer_name = f'layer{i + 1}'
+ self.add_module(layer_name, res_layer)
+ self.res_layers.append(layer_name)
+
+ self._freeze_stages()
+
+ self.feat_dim = res_layer[-1].out_channels
+
+ def make_res_layer(self, **kwargs):
+ """Make a ViPNAS ResLayer."""
+ return ViPNAS_ResLayer(**kwargs)
+
+ @property
+ def norm1(self):
+ """nn.Module: the normalization layer named "norm1" """
+ return getattr(self, self.norm1_name)
+
+ def _make_stem_layer(self, in_channels, stem_channels, kernel_size):
+ """Make stem layer."""
+ if self.deep_stem:
+ self.stem = nn.Sequential(
+ ConvModule(
+ in_channels,
+ stem_channels // 2,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True),
+ ConvModule(
+ stem_channels // 2,
+ stem_channels // 2,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True),
+ ConvModule(
+ stem_channels // 2,
+ stem_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ conv_cfg=self.conv_cfg,
+ norm_cfg=self.norm_cfg,
+ inplace=True))
+ else:
+ self.conv1 = build_conv_layer(
+ self.conv_cfg,
+ in_channels,
+ stem_channels,
+ kernel_size=kernel_size,
+ stride=2,
+ padding=kernel_size // 2,
+ bias=False)
+ self.norm1_name, norm1 = build_norm_layer(
+ self.norm_cfg, stem_channels, postfix=1)
+ self.add_module(self.norm1_name, norm1)
+ self.relu = nn.ReLU(inplace=True)
+ self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
+
+ def _freeze_stages(self):
+ """Freeze parameters."""
+ if self.frozen_stages >= 0:
+ if self.deep_stem:
+ self.stem.eval()
+ for param in self.stem.parameters():
+ param.requires_grad = False
+ else:
+ self.norm1.eval()
+ for m in [self.conv1, self.norm1]:
+ for param in m.parameters():
+ param.requires_grad = False
+
+ for i in range(1, self.frozen_stages + 1):
+ m = getattr(self, f'layer{i}')
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize model weights."""
+ super().init_weights(pretrained)
+ if pretrained is None:
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ nn.init.normal_(m.weight, std=0.001)
+ for name, _ in m.named_parameters():
+ if name in ['bias']:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.BatchNorm2d):
+ nn.init.constant_(m.weight, 1)
+ nn.init.constant_(m.bias, 0)
+
+ def forward(self, x):
+ """Forward function."""
+ if self.deep_stem:
+ x = self.stem(x)
+ else:
+ x = self.conv1(x)
+ x = self.norm1(x)
+ x = self.relu(x)
+ x = self.maxpool(x)
+ outs = []
+ for i, layer_name in enumerate(self.res_layers):
+ res_layer = getattr(self, layer_name)
+ x = res_layer(x)
+ if i in self.out_indices:
+ outs.append(x)
+ if len(outs) == 1:
+ return outs[0]
+ return tuple(outs)
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self._freeze_stages()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ # trick: eval have effect on BatchNorm only
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vit.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vit.py
new file mode 100644
index 0000000000000000000000000000000000000000..8306e35624837301ef3376eae143f4f728746a1e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/backbones/vit.py
@@ -0,0 +1,327 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+
+import torch
+from functools import partial
+import torch.nn as nn
+import torch.nn.functional as F
+import torch.utils.checkpoint as checkpoint
+
+from timm.models.layers import drop_path, to_2tuple, trunc_normal_
+
+from ..builder import BACKBONES
+from .base_backbone import BaseBackbone
+from einops import repeat
+
+class DropPath(nn.Module):
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
+ """
+
+ def __init__(self, drop_prob=None):
+ super(DropPath, self).__init__()
+ self.drop_prob = drop_prob
+
+ def forward(self, x):
+ return drop_path(x, self.drop_prob, self.training)
+
+ def extra_repr(self):
+ return 'p={}'.format(self.drop_prob)
+
+
+class Mlp(nn.Module):
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class Attention(nn.Module):
+ def __init__(
+ self, dim, num_heads=8, qkv_bias=False, qk_scale=None, attn_drop=0.,
+ proj_drop=0., attn_head_dim=None, ):
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.dim = dim
+
+ if attn_head_dim is not None:
+ head_dim = attn_head_dim
+ all_head_dim = head_dim * self.num_heads
+
+ self.scale = qk_scale or head_dim ** -0.5
+
+ self.qkv = nn.Linear(dim, all_head_dim * 3, bias=qkv_bias)
+
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(all_head_dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ def forward(self, x):
+ B, N, C = x.shape
+ qkv = self.qkv(x)
+ qkv = qkv.reshape(B, N, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
+ q, k, v = qkv[0], qkv[1], qkv[2] # make torchscript happy (cannot use tensor as tuple)
+
+ q = q * self.scale
+ attn = (q @ k.transpose(-2, -1))
+
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, -1)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+
+ return x
+
+
+class Block(nn.Module):
+
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, qk_scale=None,
+ drop=0., attn_drop=0., drop_path=0., act_layer=nn.GELU,
+ norm_layer=nn.LayerNorm, attn_head_dim=None
+ ):
+ super().__init__()
+
+ self.norm1 = norm_layer(dim)
+ self.attn = Attention(
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, qk_scale=qk_scale,
+ attn_drop=attn_drop, proj_drop=drop, attn_head_dim=attn_head_dim
+ )
+
+ # NOTE: drop path for stochastic depth, we shall see if this is better than dropout here
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
+ self.norm2 = norm_layer(dim)
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
+
+ def forward(self, x):
+ x = x + self.drop_path(self.attn(self.norm1(x)))
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
+ return x
+
+
+class PatchEmbed(nn.Module):
+ """ Image to Patch Embedding
+ """
+
+ def __init__(self, img_size=224, patch_size=16, in_chans=3, embed_dim=768, ratio=1):
+ super().__init__()
+ img_size = to_2tuple(img_size)
+ patch_size = to_2tuple(patch_size)
+ num_patches = (img_size[1] // patch_size[1]) * (img_size[0] // patch_size[0]) * (ratio ** 2)
+ self.patch_shape = (int(img_size[0] // patch_size[0] * ratio), int(img_size[1] // patch_size[1] * ratio))
+ self.origin_patch_shape = (int(img_size[0] // patch_size[0]), int(img_size[1] // patch_size[1]))
+ self.img_size = img_size
+ self.patch_size = patch_size
+ self.num_patches = num_patches
+
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=(patch_size[0] // ratio),
+ padding=4 + 2 * (ratio // 2 - 1))
+
+ def forward(self, x, **kwargs):
+ B, C, H, W = x.shape
+ x = self.proj(x)
+ Hp, Wp = x.shape[2], x.shape[3]
+
+ x = x.flatten(2).transpose(1, 2)
+ return x, (Hp, Wp)
+
+
+class HybridEmbed(nn.Module):
+ """ CNN Feature Map Embedding
+ Extract feature map from CNN, flatten, project to embedding dim.
+ """
+
+ def __init__(self, backbone, img_size=224, feature_size=None, in_chans=3, embed_dim=768):
+ super().__init__()
+ assert isinstance(backbone, nn.Module)
+ img_size = to_2tuple(img_size)
+ self.img_size = img_size
+ self.backbone = backbone
+ if feature_size is None:
+ with torch.no_grad():
+ training = backbone.training
+ if training:
+ backbone.eval()
+ o = self.backbone(torch.zeros(1, in_chans, img_size[0], img_size[1]))[-1]
+ feature_size = o.shape[-2:]
+ feature_dim = o.shape[1]
+ backbone.train(training)
+ else:
+ feature_size = to_2tuple(feature_size)
+ feature_dim = self.backbone.feature_info.channels()[-1]
+ self.num_patches = feature_size[0] * feature_size[1]
+ self.proj = nn.Linear(feature_dim, embed_dim)
+
+ def forward(self, x):
+ x = self.backbone(x)[-1]
+ x = x.flatten(2).transpose(1, 2)
+ x = self.proj(x)
+ return x
+
+
+@BACKBONES.register_module()
+class ViT(BaseBackbone):
+
+ def __init__(self,
+ img_size=(256, 192), patch_size=16, in_chans=3, num_classes=80, embed_dim=1024, depth=24,
+ num_heads=16, mlp_ratio=4., qkv_bias=True, qk_scale=None, drop_rate=0., attn_drop_rate=0.,
+ drop_path_rate=0.5, hybrid_backbone=None, norm_layer=nn.LayerNorm, use_checkpoint=False,
+ frozen_stages=-1, ratio=1, last_norm=True,
+ patch_padding='pad', freeze_attn=False, freeze_ffn=False, task_tokens_num=1+1+2+2+25
+ ):
+ # Protect mutable default arguments
+ super(ViT, self).__init__()
+ norm_layer = norm_layer or partial(nn.LayerNorm, eps=1e-6)
+ self.num_classes = num_classes
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
+ self.frozen_stages = frozen_stages
+ self.use_checkpoint = use_checkpoint
+ self.patch_padding = patch_padding
+ self.freeze_attn = freeze_attn
+ self.freeze_ffn = freeze_ffn
+ self.depth = depth
+ self.task_tokens_num = task_tokens_num
+
+ if hybrid_backbone is not None:
+ self.patch_embed = HybridEmbed(
+ hybrid_backbone, img_size=img_size, in_chans=in_chans, embed_dim=embed_dim)
+ else:
+ self.patch_embed = PatchEmbed(
+ img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim, ratio=ratio)
+ num_patches = self.patch_embed.num_patches
+
+ # task tokens for HPS estimation
+ self.task_tokens = nn.Parameter(torch.zeros(1, task_tokens_num, embed_dim))
+ trunc_normal_(self.task_tokens, std=.02)
+
+ # since the pretraining model has class token
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + 1, embed_dim))
+
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
+
+ self.blocks = nn.ModuleList([
+ Block(
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, qk_scale=qk_scale,
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
+ )
+ for i in range(depth)])
+
+ self.last_norm = norm_layer(embed_dim) if last_norm else nn.Identity()
+
+ if self.pos_embed is not None:
+ trunc_normal_(self.pos_embed, std=.02)
+
+ self._freeze_stages()
+
+ def _freeze_stages(self):
+ """Freeze parameters."""
+ if self.frozen_stages >= 0:
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+
+ for i in range(1, self.frozen_stages + 1):
+ m = self.blocks[i]
+ m.eval()
+ for param in m.parameters():
+ param.requires_grad = False
+
+ if self.freeze_attn:
+ for i in range(0, self.depth):
+ m = self.blocks[i]
+ m.attn.eval()
+ m.norm1.eval()
+ for param in m.attn.parameters():
+ param.requires_grad = False
+ for param in m.norm1.parameters():
+ param.requires_grad = False
+
+ if self.freeze_ffn:
+ self.pos_embed.requires_grad = False
+ self.patch_embed.eval()
+ for param in self.patch_embed.parameters():
+ param.requires_grad = False
+ for i in range(0, self.depth):
+ m = self.blocks[i]
+ m.mlp.eval()
+ m.norm2.eval()
+ for param in m.mlp.parameters():
+ param.requires_grad = False
+ for param in m.norm2.parameters():
+ param.requires_grad = False
+
+ def init_weights(self, pretrained=None):
+ """Initialize the weights in backbone.
+ Args:
+ pretrained (str, optional): Path to pre-trained weights.
+ Defaults to None.
+ """
+ super().init_weights(pretrained, patch_padding=self.patch_padding)
+
+ if pretrained is None:
+ def _init_weights(m):
+ if isinstance(m, nn.Linear):
+ trunc_normal_(m.weight, std=.02)
+ if isinstance(m, nn.Linear) and m.bias is not None:
+ nn.init.constant_(m.bias, 0)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+
+ self.apply(_init_weights)
+
+ def get_num_layers(self):
+ return len(self.blocks)
+
+ @torch.jit.ignore
+ def no_weight_decay(self):
+ return {'pos_embed', 'cls_token'}
+
+ def forward_features(self, x):
+ B, C, H, W = x.shape
+ x, (Hp, Wp) = self.patch_embed(x)
+ task_tokens = repeat(self.task_tokens, '() n d -> b n d', b=B)
+ if self.pos_embed is not None:
+ # fit for multiple GPU training
+ # since the first element for pos embed (sin-cos manner) is zero, it will cause no difference
+ x = x + self.pos_embed[:, 1:] + self.pos_embed[:, :1]
+
+ x = torch.cat((task_tokens, x), dim=1)
+
+ for blk in self.blocks:
+ if self.use_checkpoint:
+ x = checkpoint.checkpoint(blk, x)
+ else:
+ x = blk(x)
+
+ x = self.last_norm(x)
+
+ task_tokens = x[:, :self.task_tokens_num] # [N,J,C]
+ # task_tokens = torch.cat(task_tokens_, dim=-1)
+ xp = x[:, self.task_tokens_num:] # [N,Hp*Wp,C]
+
+ xp = xp.permute(0, 2, 1).reshape(B, -1, Hp, Wp).contiguous()
+
+ return xp, task_tokens
+
+ def forward(self, x):
+ x = self.forward_features(x)
+ return x
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self._freeze_stages()
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/builder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/builder.py
new file mode 100644
index 0000000000000000000000000000000000000000..47f0a53121633fb6185a4d514c05a5862a9d74cf
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/builder.py
@@ -0,0 +1,49 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.cnn import MODELS as MMCV_MODELS
+from mmcv.cnn import build_model_from_cfg
+from mmcv.utils import Registry, build_from_cfg
+
+MODELS = Registry(
+ 'models', build_func=build_model_from_cfg, parent=MMCV_MODELS)
+
+BACKBONES = MODELS
+NECKS = MODELS
+HEADS = MODELS
+LOSSES = MODELS
+POSENETS = MODELS
+MESH_MODELS = MODELS
+TRANSFORMER = Registry('Transformer')
+
+
+def build_backbone(cfg):
+ """Build backbone."""
+ return BACKBONES.build(cfg)
+
+
+def build_neck(cfg):
+ """Build neck."""
+ return NECKS.build(cfg)
+
+
+def build_head(cfg):
+ """Build head."""
+ return HEADS.build(cfg)
+
+
+def build_loss(cfg):
+ """Build loss."""
+ return LOSSES.build(cfg)
+
+
+def build_posenet(cfg):
+ """Build posenet."""
+ return POSENETS.build(cfg)
+
+
+def build_mesh_model(cfg):
+ """Build mesh model."""
+ return MESH_MODELS.build(cfg)
+
+def build_transformer(cfg, default_args=None):
+ """Builder for Transformer."""
+ return build_from_cfg(cfg, TRANSFORMER, default_args)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..823cd5d52c2723c6a537765a7f083a444016e8f7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/__init__.py
@@ -0,0 +1,7 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .top_down import TopDown
+from .poseur import Poseur
+
+__all__ = [
+ 'TopDown', 'Poseur'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/base.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/base.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d459b42de66012c88ff37d7d845265d06efebc7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/base.py
@@ -0,0 +1,131 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+from collections import OrderedDict
+
+import torch
+import torch.distributed as dist
+import torch.nn as nn
+
+
+class BasePose(nn.Module, metaclass=ABCMeta):
+ """Base class for pose detectors.
+
+ All recognizers should subclass it.
+ All subclass should overwrite:
+ Methods:`forward_train`, supporting to forward when training.
+ Methods:`forward_test`, supporting to forward when testing.
+
+ Args:
+ backbone (dict): Backbone modules to extract feature.
+ head (dict): Head modules to give output.
+ train_cfg (dict): Config for training. Default: None.
+ test_cfg (dict): Config for testing. Default: None.
+ """
+
+ @abstractmethod
+ def forward_train(self, img, img_metas, **kwargs):
+ """Defines the computation performed at training."""
+
+ @abstractmethod
+ def forward_test(self, img, img_metas, **kwargs):
+ """Defines the computation performed at testing."""
+
+ @abstractmethod
+ def forward(self, img, img_metas, return_loss=True, **kwargs):
+ """Forward function."""
+
+ @staticmethod
+ def _parse_losses(losses):
+ """Parse the raw outputs (losses) of the network.
+
+ Args:
+ losses (dict): Raw output of the network, which usually contain
+ losses and other necessary information.
+
+ Returns:
+ tuple[Tensor, dict]: (loss, log_vars), loss is the loss tensor \
+ which may be a weighted sum of all losses, log_vars \
+ contains all the variables to be sent to the logger.
+ """
+ log_vars = OrderedDict()
+ for loss_name, loss_value in losses.items():
+ if isinstance(loss_value, torch.Tensor):
+ log_vars[loss_name] = loss_value.mean()
+ elif isinstance(loss_value, float):
+ log_vars[loss_name] = loss_value
+ elif isinstance(loss_value, list):
+ log_vars[loss_name] = sum(_loss.mean() for _loss in loss_value)
+ else:
+ raise TypeError(
+ f'{loss_name} is not a tensor or list of tensors or float')
+
+ loss = sum(_value for _key, _value in log_vars.items()
+ if 'loss' in _key)
+
+ log_vars['loss'] = loss
+ for loss_name, loss_value in log_vars.items():
+ # reduce loss when distributed training
+ if not isinstance(loss_value, float):
+ if dist.is_available() and dist.is_initialized():
+ loss_value = loss_value.data.clone()
+ dist.all_reduce(loss_value.div_(dist.get_world_size()))
+ log_vars[loss_name] = loss_value.item()
+ else:
+ log_vars[loss_name] = loss_value
+
+ return loss, log_vars
+
+ def train_step(self, data_batch, optimizer, **kwargs):
+ """The iteration step during training.
+
+ This method defines an iteration step during training, except for the
+ back propagation and optimizer updating, which are done in an optimizer
+ hook. Note that in some complicated cases or models, the whole process
+ including back propagation and optimizer updating is also defined in
+ this method, such as GAN.
+
+ Args:
+ data_batch (dict): The output of dataloader.
+ optimizer (:obj:`torch.optim.Optimizer` | dict): The optimizer of
+ runner is passed to ``train_step()``. This argument is unused
+ and reserved.
+
+ Returns:
+ dict: It should contain at least 3 keys: ``loss``, ``log_vars``,
+ ``num_samples``.
+ ``loss`` is a tensor for back propagation, which can be a
+ weighted sum of multiple losses.
+ ``log_vars`` contains all the variables to be sent to the
+ logger.
+ ``num_samples`` indicates the batch size (when the model is
+ DDP, it means the batch size on each GPU), which is used for
+ averaging the logs.
+ """
+ losses = self.forward(**data_batch)
+
+ loss, log_vars = self._parse_losses(losses)
+
+ outputs = dict(
+ loss=loss,
+ log_vars=log_vars,
+ num_samples=len(next(iter(data_batch.values()))))
+
+ return outputs
+
+ def val_step(self, data_batch, optimizer, **kwargs):
+ """The iteration step during validation.
+
+ This method shares the same signature as :func:`train_step`, but used
+ during val epochs. Note that the evaluation after training epochs is
+ not implemented with this method, but an evaluation hook.
+ """
+ results = self.forward(return_loss=False, **data_batch)
+
+ outputs = dict(results=results)
+
+ return outputs
+
+ @abstractmethod
+ def show_result(self, **kwargs):
+ """Visualize the results."""
+ raise NotImplementedError
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/poseur.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/poseur.py
new file mode 100644
index 0000000000000000000000000000000000000000..b5c98ea95af4ee114e2dc731bf1b3e83489b8563
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/poseur.py
@@ -0,0 +1,278 @@
+import warnings
+
+import mmcv
+import numpy as np
+from mmcv.image import imwrite
+from mmcv.visualization.image import imshow
+
+from mmpose.core import imshow_keypoints
+from .. import builder
+from ..builder import POSENETS
+from .base import BasePose
+import torch
+from config import cfg
+
+try:
+ from mmcv.runner import auto_fp16
+except ImportError:
+ warnings.warn('auto_fp16 from mmpose will be deprecated from v0.15.0'
+ 'Please install mmcv>=1.1.4')
+ from mmpose.core import auto_fp16
+
+from .top_down import TopDown
+
+
+@POSENETS.register_module()
+class Poseur(TopDown):
+ def __init__(self, *args, **kwargs):
+ if 'filp_fuse_type' in kwargs:
+ self.filp_fuse_type = kwargs.pop('filp_fuse_type')
+ else:
+ self.filp_fuse_type = 'default'
+ super().__init__(*args, **kwargs)
+
+ def init_weights(self, pretrained=None):
+ """Weight initialization for model."""
+ self.backbone.init_weights(pretrained)
+ if self.with_neck:
+ self.neck.init_weights()
+ if self.with_keypoint:
+ self.keypoint_head.init_weights()
+
+ @auto_fp16(apply_to=('img',))
+ def forward(self,
+ img,
+ coord_target=None,
+ coord_target_weight=None,
+ bbox_target=None,
+ bbox_target_weight=None,
+ hp_target=None,
+ hp_target_weight=None,
+ img_metas=None,
+ return_loss=True,
+ return_heatmap=False,
+ coord_init=None,
+ query_init=None,
+ **kwargs):
+ """Calls either forward_train or forward_test depending on whether
+ return_loss=True. Note this setting will change the expected inputs.
+ When `return_loss=True`, img and img_meta are single-nested (i.e.
+ Tensor and List[dict]), and when `resturn_loss=False`, img and img_meta
+ should be double nested (i.e. List[Tensor], List[List[dict]]), with
+ the outer list indicating test time augmentations.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ num_img_channel: C (Default: 3)
+ img height: imgH
+ img weight: imgW
+ heatmaps height: H
+ heatmaps weight: W
+
+ Args:
+ img (torch.Tensor[NxCximgHximgW]): Input images.
+ target (torch.Tensor[NxKxHxW]): Target heatmaps.
+ target_weight (torch.Tensor[NxKx1]): Weights across
+ different joint types.
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ return_loss (bool): Option to `return loss`. `return loss=True`
+ for training, `return loss=False` for validation & test.
+ return_heatmap (bool) : Option to return heatmap.
+
+ Returns:
+ dict|tuple: if `return loss` is true, then return losses.
+ Otherwise, return predicted poses, boxes, image paths
+ and heatmaps.
+ """
+ return self.forward_mesh_recovery(img, coord_init=coord_init, query_init=query_init,
+ **kwargs)
+ # if return_loss:
+ # return self.forward_train(img,
+ # coord_target, coord_target_weight,
+ # hp_target, hp_target_weight, img_metas,
+ # **kwargs)
+ # return self.forward_test(
+ # img, img_metas, return_heatmap=return_heatmap, **kwargs)
+
+ def forward_train(self, img, coord_target, coord_target_weight,
+ hp_target, hp_target_weight, img_metas, **kwargs):
+ """
+ :param img:
+ :param coord_target: [2, 17, 2]
+ :param coord_target_weight: [2, 17, 2]
+ :param hp_target: [2, 4, 17, 64, 48]
+ :param hp_target_weight: [2, 4, 17, 1]
+ :param img_metas:
+ :param kwargs:
+ :return:
+ """
+ """Defines the computation performed at every call when training."""
+ output = self.backbone(img)
+ img_feat = output[-1]
+ if self.with_neck:
+ output = self.neck(output)
+ if self.with_keypoint:
+ # output = self.keypoint_head(output, img_metas)
+ enc_output, dec_output = self.keypoint_head(output)
+
+ return img_feat, enc_output, dec_output, None
+
+ def seperate_sigma_from_score(self, score):
+ if score.shape[2] == 3:
+ sigma = score[:, :, [1, 2]]
+ score = score[:, :, [0]]
+ return score, sigma
+ elif score.shape[2] == 1:
+ return score, None
+ else:
+ raise
+
+ def forward_mesh_recovery(self, output, coord_init=None, query_init=None, **kwargs):
+ """
+ :param img:
+ :param coord_target: [2, 17, 2]
+ :param coord_target_weight: [2, 17, 2]
+ :param hp_target: [2, 4, 17, 64, 48]
+ :param hp_target_weight: [2, 4, 17, 1]
+ :param img_metas:
+ :param kwargs:
+ :return:
+ """
+ """Defines the computation performed at every call when training."""
+ # output = self.backbone(img)
+ img_feat = output[-1]
+ # print(len(output))
+ if self.with_neck:
+ output = self.neck(output)
+ if self.with_keypoint:
+ # output = self.keypoint_head(output, img_metas)
+ enc_output, dec_output = self.keypoint_head(output, coord_init=coord_init, query_init=query_init)
+
+ return dec_output.feat[-1]
+
+ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs):
+ """Defines the computation performed at every call when testing."""
+ assert img.size(0) == len(img_metas)
+ batch_size, _, img_height, img_width = img.shape
+ if batch_size > 1:
+ assert 'bbox_id' in img_metas[0]
+
+ result = {}
+
+ features = self.backbone(img)
+ if self.with_neck:
+ features = self.neck(features)
+ if self.with_keypoint:
+ output_regression, output_regression_score = self.keypoint_head.inference_model(
+ features, flip_pairs=None)
+ output_regression_score, output_regression_sigma = self.seperate_sigma_from_score(output_regression_score)
+
+ if self.test_cfg['flip_test']:
+ img_flipped = img.flip(3)
+ features_flipped = self.backbone(img_flipped)
+ if self.with_neck:
+ features_flipped = self.neck(features_flipped)
+ if self.with_keypoint:
+ output_regression_flipped, output_regression_score_flipped = self.keypoint_head.inference_model(
+ features_flipped, img_metas[0]['flip_pairs'])
+ output_regression_score_flipped, output_regression_sigma_flipped = \
+ self.seperate_sigma_from_score(output_regression_score_flipped)
+ if self.filp_fuse_type == 'default':
+ output_regression = (output_regression +
+ output_regression_flipped) * 0.5
+
+ output_regression_score = (output_regression_score +
+ output_regression_score_flipped) * 0.5
+ elif self.filp_fuse_type == 'type1':
+ # output_regression = (output_regression * output_regression_score + output_regression_flipped * output_regression_score_flipped)\
+ # /(output_regression_score + output_regression_score_flipped+1e-9)
+ output_regression, output_regression_flipped = \
+ torch.from_numpy(output_regression), torch.from_numpy(output_regression_flipped)
+
+ output_regression_score, output_regression_score_flipped = \
+ torch.from_numpy(output_regression_score), torch.from_numpy(output_regression_score_flipped)
+
+ output_regression = (
+ output_regression * output_regression_score + output_regression_flipped * output_regression_score_flipped) \
+ / (output_regression_score + output_regression_score_flipped + 1e-9)
+
+ diff = 1 - (output_regression_score - output_regression_score_flipped).abs()
+ output_regression_score = (output_regression_score * output_regression_score_flipped * diff) ** 2
+
+ output_regression = output_regression.numpy()
+ output_regression_score = output_regression_score.numpy()
+ elif self.filp_fuse_type == 'type2':
+ # output_regression = (output_regression * output_regression_score + output_regression_flipped * output_regression_score_flipped)\
+ # /(output_regression_score + output_regression_score_flipped+1e-9)
+ output_regression, output_regression_flipped = \
+ torch.from_numpy(output_regression), torch.from_numpy(output_regression_flipped)
+
+ output_regression_sigma, output_regression_sigma_flipped = \
+ torch.from_numpy(output_regression_sigma), torch.from_numpy(output_regression_sigma_flipped)
+
+ output_regression_p, output_regression_p_flipped = \
+ self.get_p(output_regression_sigma), self.get_p(output_regression_sigma_flipped)
+
+ p_to_coord_index = 5
+ output_regression = (
+ output_regression * output_regression_p ** p_to_coord_index + output_regression_flipped * output_regression_p_flipped ** p_to_coord_index) \
+ / (
+ output_regression_p ** p_to_coord_index + output_regression_p_flipped ** p_to_coord_index + 1e-10)
+
+ output_regression_score = (output_regression_p + output_regression_p_flipped) * 0.5
+
+ output_regression = output_regression.numpy()
+ output_regression_score = output_regression_score.numpy()
+ else:
+ NotImplementedError
+
+ if self.with_keypoint:
+ keypoint_result = self.keypoint_head.decode_keypoints(
+ img_metas, output_regression, output_regression_score, [img_width, img_height])
+ result.update(keypoint_result)
+
+ if not return_heatmap:
+ output_heatmap = None
+
+ result['output_heatmap'] = output_heatmap
+
+ return result
+
+ def get_p(self, output_regression_sigma, p_x=0.2):
+ output_regression_p = (1 - np.exp(-(p_x / output_regression_sigma)))
+ output_regression_p = output_regression_p[:, :, 0] * output_regression_p[:, :, 1]
+ output_regression_p = output_regression_p[:, :, None]
+ return output_regression_p * 0.7
+ # 0.2 0.7 7421
+ # 0.2 0.7 7610
+ # 0.17 0.7
+
+ def forward_dummy(self, img):
+ """Used for computing network FLOPs.
+
+ See ``tools/get_flops.py``.
+
+ Args:
+ img (torch.Tensor): Input image.
+
+ Returns:
+ Tensor: Output heatmaps.
+ """
+ output = self.backbone(img)
+ if self.with_neck:
+ output = self.neck(output)
+ if self.with_keypoint:
+ img_h, img_w = 256, 192
+ img_metas = [{}]
+ img_metas[0]['batch_input_shape'] = (img_h, img_w)
+ img_metas[0]['img_shape'] = (img_h, img_w, 3)
+ # output = self.keypoint_head(output, img_metas)
+ output = self.keypoint_head(output)
+ return output
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/top_down.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/top_down.py
new file mode 100644
index 0000000000000000000000000000000000000000..99215ec70b2381fbc01be6e448e30a09f83cda2b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/detectors/top_down.py
@@ -0,0 +1,311 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+import mmcv
+import numpy as np
+from mmcv.image import imwrite
+from mmcv.utils.misc import deprecated_api_warning
+from mmcv.visualization.image import imshow
+
+from mmpose.core import imshow_bboxes, imshow_keypoints
+from .. import builder
+from ..builder import POSENETS
+from .base import BasePose
+
+try:
+ from mmcv.runner import auto_fp16
+except ImportError:
+ warnings.warn('auto_fp16 from mmpose will be deprecated from v0.15.0'
+ 'Please install mmcv>=1.1.4')
+ from mmpose.core import auto_fp16
+
+
+@POSENETS.register_module()
+class TopDown(BasePose):
+ """Top-down pose detectors.
+
+ Args:
+ backbone (dict): Backbone modules to extract feature.
+ keypoint_head (dict): Keypoint head to process feature.
+ train_cfg (dict): Config for training. Default: None.
+ test_cfg (dict): Config for testing. Default: None.
+ pretrained (str): Path to the pretrained models.
+ loss_pose (None): Deprecated arguments. Please use
+ `loss_keypoint` for heads instead.
+ """
+
+ def __init__(self,
+ backbone,
+ neck=None,
+ keypoint_head=None,
+ train_cfg=None,
+ test_cfg=None,
+ pretrained=None,
+ loss_pose=None):
+ super().__init__()
+ self.fp16_enabled = False
+
+ self.backbone = builder.build_backbone(backbone)
+
+ self.train_cfg = train_cfg
+ self.test_cfg = test_cfg
+
+ if neck is not None:
+ self.neck = builder.build_neck(neck)
+
+ if keypoint_head is not None:
+ keypoint_head['train_cfg'] = train_cfg
+ keypoint_head['test_cfg'] = test_cfg
+
+ if 'loss_keypoint' not in keypoint_head and loss_pose is not None:
+ warnings.warn(
+ '`loss_pose` for TopDown is deprecated, '
+ 'use `loss_keypoint` for heads instead. See '
+ 'https://github.com/open-mmlab/mmpose/pull/382'
+ ' for more information.', DeprecationWarning)
+ keypoint_head['loss_keypoint'] = loss_pose
+
+ self.keypoint_head = builder.build_head(keypoint_head)
+ self.pretrained = pretrained
+ self.init_weights()
+
+ @property
+ def with_neck(self):
+ """Check if has neck."""
+ return hasattr(self, 'neck')
+
+ @property
+ def with_keypoint(self):
+ """Check if has keypoint_head."""
+ return hasattr(self, 'keypoint_head')
+
+ def init_weights(self, pretrained=None):
+ """Weight initialization for model."""
+ if pretrained is not None:
+ self.pretrained = pretrained
+ self.backbone.init_weights(self.pretrained)
+ if self.with_neck:
+ self.neck.init_weights()
+ if self.with_keypoint:
+ self.keypoint_head.init_weights()
+
+ @auto_fp16(apply_to=('img', ))
+ def forward(self,
+ img,
+ target=None,
+ target_weight=None,
+ img_metas=None,
+ return_loss=True,
+ return_heatmap=False,
+ **kwargs):
+ """Calls either forward_train or forward_test depending on whether
+ return_loss=True. Note this setting will change the expected inputs.
+ When `return_loss=True`, img and img_meta are single-nested (i.e.
+ Tensor and List[dict]), and when `resturn_loss=False`, img and img_meta
+ should be double nested (i.e. List[Tensor], List[List[dict]]), with
+ the outer list indicating test time augmentations.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - num_img_channel: C (Default: 3)
+ - img height: imgH
+ - img width: imgW
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ img (torch.Tensor[NxCximgHximgW]): Input images.
+ target (torch.Tensor[NxKxHxW]): Target heatmaps.
+ target_weight (torch.Tensor[NxKx1]): Weights across
+ different joint types.
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ return_loss (bool): Option to `return loss`. `return loss=True`
+ for training, `return loss=False` for validation & test.
+ return_heatmap (bool) : Option to return heatmap.
+
+ Returns:
+ dict|tuple: if `return loss` is true, then return losses. \
+ Otherwise, return predicted poses, boxes, image paths \
+ and heatmaps.
+ """
+ if return_loss:
+ return self.forward_train(img, target, target_weight, img_metas,
+ **kwargs)
+ return self.forward_test(
+ img, img_metas, return_heatmap=return_heatmap, **kwargs)
+
+ def forward_train(self, img, target, target_weight, img_metas, **kwargs):
+ """Defines the computation performed at every call when training."""
+ output = self.backbone(img)
+ if self.with_neck:
+ output = self.neck(output)
+ if self.with_keypoint:
+ output = self.keypoint_head(output)
+
+ # if return loss
+ losses = dict()
+ if self.with_keypoint:
+ keypoint_losses = self.keypoint_head.get_loss(
+ output, target, target_weight)
+ losses.update(keypoint_losses)
+ keypoint_accuracy = self.keypoint_head.get_accuracy(
+ output, target, target_weight)
+ losses.update(keypoint_accuracy)
+
+ return losses
+
+ def forward_test(self, img, img_metas, return_heatmap=False, **kwargs):
+ """Defines the computation performed at every call when testing."""
+ assert img.size(0) == len(img_metas)
+ batch_size, _, img_height, img_width = img.shape
+ if batch_size > 1:
+ assert 'bbox_id' in img_metas[0]
+
+ result = {}
+
+ features = self.backbone(img)
+ if self.with_neck:
+ features = self.neck(features)
+ if self.with_keypoint:
+ output_heatmap = self.keypoint_head.inference_model(
+ features, flip_pairs=None)
+
+ if self.test_cfg.get('flip_test', True):
+ img_flipped = img.flip(3)
+ features_flipped = self.backbone(img_flipped)
+ if self.with_neck:
+ features_flipped = self.neck(features_flipped)
+ if self.with_keypoint:
+ output_flipped_heatmap = self.keypoint_head.inference_model(
+ features_flipped, img_metas[0]['flip_pairs'])
+ output_heatmap = (output_heatmap + output_flipped_heatmap)
+ if self.test_cfg.get('regression_flip_shift', False):
+ output_heatmap[..., 0] -= 1.0 / img_width
+ output_heatmap = output_heatmap / 2
+
+ if self.with_keypoint:
+ keypoint_result = self.keypoint_head.decode(
+ img_metas, output_heatmap, img_size=[img_width, img_height])
+ result.update(keypoint_result)
+
+ if not return_heatmap:
+ output_heatmap = None
+
+ result['output_heatmap'] = output_heatmap
+
+ return result
+
+ def forward_dummy(self, img):
+ """Used for computing network FLOPs.
+
+ See ``tools/get_flops.py``.
+
+ Args:
+ img (torch.Tensor): Input image.
+
+ Returns:
+ Tensor: Output heatmaps.
+ """
+ output = self.backbone(img)
+ if self.with_neck:
+ output = self.neck(output)
+ if self.with_keypoint:
+ output = self.keypoint_head(output)
+ return output
+
+ @deprecated_api_warning({'pose_limb_color': 'pose_link_color'},
+ cls_name='TopDown')
+ def show_result(self,
+ img,
+ result,
+ skeleton=None,
+ kpt_score_thr=0.3,
+ bbox_color='green',
+ pose_kpt_color=None,
+ pose_link_color=None,
+ text_color='white',
+ radius=4,
+ thickness=1,
+ font_scale=0.5,
+ bbox_thickness=1,
+ win_name='',
+ show=False,
+ show_keypoint_weight=False,
+ wait_time=0,
+ out_file=None):
+ """Draw `result` over `img`.
+
+ Args:
+ img (str or Tensor): The image to be displayed.
+ result (list[dict]): The results to draw over `img`
+ (bbox_result, pose_result).
+ skeleton (list[list]): The connection of keypoints.
+ skeleton is 0-based indexing.
+ kpt_score_thr (float, optional): Minimum score of keypoints
+ to be shown. Default: 0.3.
+ bbox_color (str or tuple or :obj:`Color`): Color of bbox lines.
+ pose_kpt_color (np.array[Nx3]`): Color of N keypoints.
+ If None, do not draw keypoints.
+ pose_link_color (np.array[Mx3]): Color of M links.
+ If None, do not draw links.
+ text_color (str or tuple or :obj:`Color`): Color of texts.
+ radius (int): Radius of circles.
+ thickness (int): Thickness of lines.
+ font_scale (float): Font scales of texts.
+ win_name (str): The window name.
+ show (bool): Whether to show the image. Default: False.
+ show_keypoint_weight (bool): Whether to change the transparency
+ using the predicted confidence scores of keypoints.
+ wait_time (int): Value of waitKey param.
+ Default: 0.
+ out_file (str or None): The filename to write the image.
+ Default: None.
+
+ Returns:
+ Tensor: Visualized img, only if not `show` or `out_file`.
+ """
+ img = mmcv.imread(img)
+ img = img.copy()
+
+ bbox_result = []
+ bbox_labels = []
+ pose_result = []
+ for res in result:
+ if 'bbox' in res:
+ bbox_result.append(res['bbox'])
+ bbox_labels.append(res.get('label', None))
+ pose_result.append(res['keypoints'])
+
+ if bbox_result:
+ bboxes = np.vstack(bbox_result)
+ # draw bounding boxes
+ imshow_bboxes(
+ img,
+ bboxes,
+ labels=bbox_labels,
+ colors=bbox_color,
+ text_color=text_color,
+ thickness=bbox_thickness,
+ font_scale=font_scale,
+ show=False)
+
+ if pose_result:
+ imshow_keypoints(img, pose_result, skeleton, kpt_score_thr,
+ pose_kpt_color, pose_link_color, radius,
+ thickness)
+
+ if show:
+ imshow(img, win_name, wait_time)
+
+ if out_file is not None:
+ imwrite(img, out_file)
+
+ return img
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..80c1be50a9bb91eb9e0f97c6bbcca70cf1478a87
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .topdown_heatmap_base_head import TopdownHeatmapBaseHead
+from .topdown_heatmap_multi_stage_head import (TopdownHeatmapMSMUHead,
+ TopdownHeatmapMultiStageHead)
+from .topdown_heatmap_simple_head import TopdownHeatmapSimpleHead
+from .poseur_head import Poseur_noise_sample
+
+__all__ = [
+ 'TopdownHeatmapSimpleHead', 'TopdownHeatmapMultiStageHead',
+ 'TopdownHeatmapMSMUHead', 'TopdownHeatmapBaseHead',
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/poseur_head.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/poseur_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..d01232247db1d687144d8fff2a3b226dd66fdcf5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/poseur_head.py
@@ -0,0 +1,759 @@
+import numpy as np
+import torch
+import torch.nn as nn
+import copy
+import math
+import warnings
+from mmcv.cnn import build_upsample_layer, Linear, bias_init_with_prob, constant_init, normal_init
+import torch.nn.functional as F
+from mmcv.cnn import normal_init
+
+from mmpose.core.evaluation import (keypoint_pck_accuracy,
+ keypoints_from_regression)
+from mmpose.core.post_processing import fliplr_regression
+from mmpose.models.builder import build_loss, HEADS, build_transformer
+from mmpose.core.evaluation import pose_pck_accuracy
+from mmpose.models.utils.transformer import inverse_sigmoid
+from mmcv.cnn import Conv2d, build_activation_layer
+from mmcv.cnn.bricks.transformer import Linear, FFN, build_positional_encoding
+from mmcv.cnn import ConvModule
+import torch.distributions as distributions
+from .rle_regression_head import nets, nett, RealNVP, nets3d, nett3d
+from easydict import EasyDict
+from mmpose.models.losses.regression_loss import L1Loss
+from mmpose.models.losses.rle_loss import RLELoss_poseur, RLEOHKMLoss
+from config import cfg
+from utils.human_models import smpl_x
+from torch.distributions.utils import lazy_property
+
+from torch.distributions import MultivariateNormal
+
+
+def fliplr_rle_regression(regression,
+ regression_score,
+ flip_pairs,
+ center_mode='static',
+ center_x=0.5,
+ center_index=0):
+ """Flip human joints horizontally.
+
+ Note:
+ batch_size: N
+ num_keypoint: K
+ Args:
+ regression (np.ndarray([..., K, C])): Coordinates of keypoints, where K
+ is the joint number and C is the dimension. Example shapes are:
+ - [N, K, C]: a batch of keypoints where N is the batch size.
+ - [N, T, K, C]: a batch of pose sequences, where T is the frame
+ number.
+ flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored
+ (for example, left ear -- right ear).
+ center_mode (str): The mode to set the center location on the x-axis
+ to flip around. Options are:
+ - static: use a static x value (see center_x also)
+ - root: use a root joint (see center_index also)
+ center_x (float): Set the x-axis location of the flip center. Only used
+ when center_mode=static.
+ center_index (int): Set the index of the root joint, whose x location
+ will be used as the flip center. Only used when center_mode=root.
+
+ Returns:
+ tuple: Flipped human joints.
+
+ - regression_flipped (np.ndarray([..., K, C])): Flipped joints.
+ """
+ assert regression.ndim >= 2, f'Invalid pose shape {regression.shape}'
+
+ allowed_center_mode = {'static', 'root'}
+ assert center_mode in allowed_center_mode, 'Get invalid center_mode ' \
+ f'{center_mode}, allowed choices are {allowed_center_mode}'
+
+ if center_mode == 'static':
+ x_c = center_x
+ elif center_mode == 'root':
+ assert regression.shape[-2] > center_index
+ x_c = regression[..., center_index:center_index + 1, 0]
+
+ regression_flipped = regression.copy()
+ regression_score_flipped = regression_score.copy()
+
+ # Swap left-right parts
+ for left, right in flip_pairs:
+ regression_flipped[..., left, :] = regression[..., right, :]
+ regression_flipped[..., right, :] = regression[..., left, :]
+ regression_score_flipped[..., left, :] = regression_score[..., right, :]
+ regression_score_flipped[..., right, :] = regression_score[..., left, :]
+
+ # Flip horizontally
+ regression_flipped[..., 0] = x_c * 2 - regression_flipped[..., 0]
+ return regression_flipped, regression_score_flipped
+
+
+class Linear_with_norm(nn.Module):
+ def __init__(self, in_channel, out_channel, bias=True, norm=True):
+ super(Linear_with_norm, self).__init__()
+ self.bias = bias
+ self.norm = norm
+ self.linear = nn.Linear(in_channel, out_channel, bias)
+ nn.init.xavier_uniform_(self.linear.weight, gain=0.01)
+
+ def forward(self, x):
+ y = x.matmul(self.linear.weight.t())
+
+ if self.norm:
+ x_norm = torch.norm(x, dim=-1, keepdim=True)
+ y = y / x_norm
+
+ if self.bias:
+ y = y + self.linear.bias
+ return y
+
+def deepapply(obj, fn):
+ r"""Applies `fn` to all tensors referenced in `obj`"""
+
+ if torch.is_tensor(obj):
+ obj = fn(obj)
+ elif isinstance(obj, dict):
+ for key, value in obj.items():
+ obj[key] = deepapply(value, fn)
+ elif isinstance(obj, list):
+ for i, value in enumerate(obj):
+ obj[i] = deepapply(value, fn)
+ elif isinstance(obj, tuple):
+ obj = tuple(
+ deepapply(value, fn)
+ for value in obj
+ )
+ elif hasattr(obj, '__dict__'):
+ deepapply(obj.__dict__, fn)
+
+ return obj
+
+
+__init__ = MultivariateNormal.__init__
+
+
+def init(self, *args, **kwargs):
+ __init__(self, *args, **kwargs)
+
+ self.__class__ = type(
+ self.__class__.__name__,
+ (self.__class__, nn.Module),
+ {},
+ )
+
+ nn.Module.__init__(self)
+
+
+MultivariateNormal.__init__ = init
+MultivariateNormal._apply = deepapply
+
+
+@HEADS.register_module()
+class Poseur_noise_sample(nn.Module):
+ """
+ rle loss for transformer_utils
+ """
+
+ def __init__(self,
+ in_channels,
+ num_queries=17,
+ num_reg_fcs=2,
+ positional_encoding=dict(
+ type='SinePositionalEncoding',
+ num_feats=128,
+ normalize=True),
+ transformer=None,
+ with_box_refine=False,
+ as_two_stage=False,
+ heatmap_size=[64, 48],
+ num_joints=17,
+ loss_coord_enc=None,
+ loss_coord_dec=None,
+ loss_hp_keypoint=None,
+ use_heatmap_loss=True,
+ train_cfg=None,
+ test_cfg=None,
+ use_udp=False,
+ ):
+ super().__init__()
+ self.use_udp = use_udp
+ self.num_queries = num_queries
+ self.num_reg_fcs = num_reg_fcs
+ self.in_channels = in_channels
+ self.act_cfg = transformer.get('act_cfg', dict(type='ReLU', inplace=True))
+ self.activate = build_activation_layer(self.act_cfg)
+ self.positional_encoding = build_positional_encoding(positional_encoding)
+ self.with_box_refine = with_box_refine
+ self.as_two_stage = as_two_stage
+ if self.as_two_stage:
+ transformer['as_two_stage'] = self.as_two_stage
+ self.transformer = build_transformer(transformer)
+ self.embed_dims = self.transformer.embed_dims
+ assert 'num_feats' in positional_encoding
+ num_feats = positional_encoding['num_feats']
+ assert num_feats * 2 == self.embed_dims, 'embed_dims should' \
+ f' be exactly 2 times of num_feats. Found {self.embed_dims}' \
+ f' and {num_feats}.'
+
+ self.num_joints = num_joints
+ # self.num_joints = len(smpl_x.pos_joint_part['rhand'])
+ self.heatmap_size = heatmap_size
+ self.loss_coord_enc = build_loss(loss_coord_enc)
+ self.loss_coord_dec = build_loss(loss_coord_dec)
+
+ self.use_dec_rle_loss = isinstance(self.loss_coord_dec, RLELoss_poseur) or isinstance(self.loss_coord_dec,
+ RLEOHKMLoss)
+ self.use_heatmap_loss = use_heatmap_loss
+ if self.use_heatmap_loss:
+ self.loss_hp = build_loss(loss_hp_keypoint)
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+
+ enc_prior = MultivariateNormal(torch.zeros(2), torch.eye(2))
+ dec_prior = MultivariateNormal(torch.zeros(2), torch.eye(2))
+ masks = torch.from_numpy(np.array([[0, 1], [1, 0]] * 3).astype(np.float32))
+
+ enc_prior3d = MultivariateNormal(torch.zeros(3), torch.eye(3))
+ dec_prior3d = MultivariateNormal(torch.zeros(3), torch.eye(3))
+ masks3d = torch.from_numpy(np.array([[0, 0, 1], [1, 1, 0]] * 3).astype(np.float32))
+
+ self.enc_flow2d = RealNVP(nets, nett, masks, enc_prior)
+ self.enc_flow3d = RealNVP(nets3d, nett3d, masks3d, enc_prior3d)
+
+ if self.use_dec_rle_loss:
+ self.dec_flow2d = RealNVP(nets, nett, masks, dec_prior)
+ self.dec_flow3d = RealNVP(nets3d, nett3d, masks3d, dec_prior3d)
+
+ self._init_layers()
+
+ def _init_layers(self):
+ """Initialize classification branch and regression branch of head."""
+
+ fc_coord_branch = []
+ for _ in range(self.num_reg_fcs):
+ fc_coord_branch.append(Linear(self.embed_dims, self.embed_dims))
+ fc_coord_branch.append(nn.ReLU())
+ fc_coord_branch.append(Linear(self.embed_dims, 3))
+ fc_coord_branch = nn.Sequential(*fc_coord_branch)
+
+ if self.use_dec_rle_loss:
+ fc_sigma_branch = []
+ for _ in range(self.num_reg_fcs):
+ fc_sigma_branch.append(Linear(self.embed_dims, self.embed_dims))
+ fc_sigma_branch.append(Linear_with_norm(self.embed_dims, 3, norm=False))
+ fc_sigma_branch = nn.Sequential(*fc_sigma_branch)
+
+ def _get_clones(module, N):
+ return nn.ModuleList([copy.deepcopy(module) for i in range(N)])
+
+ num_pred = self.transformer.decoder.num_layers
+
+ if self.with_box_refine:
+ self.fc_coord_branches = _get_clones(fc_coord_branch, num_pred)
+ self.fc_coord_output_branches = _get_clones(fc_coord_branch, num_pred)
+ if self.use_dec_rle_loss:
+ self.fc_sigma_branches = _get_clones(fc_sigma_branch, num_pred)
+ else:
+ self.fc_coord_branches = nn.ModuleList(
+ [fc_coord_branch for _ in range(num_pred)])
+ if isinstance(self.loss_coord_dec, RLELoss) or isinstance(self.loss_coord_dec, RLEOHKMLoss):
+ self.fc_sigma_branches = nn.ModuleList([fc_sigma_branch for _ in range(1)])
+
+ if self.as_two_stage:
+ self.query_embedding = None
+ else:
+ self.query_embedding = nn.Embedding(self.num_queries,
+ self.embed_dims * 2)
+
+ if self.use_heatmap_loss:
+ from mmcv.cnn import build_upsample_layer
+ # simplebaseline style
+ num_layers = 3
+ num_kernels = [4, 4, 4]
+ num_filters = [256, 256, 256]
+
+ layers = []
+ for i in range(num_layers):
+ kernel, padding, output_padding = \
+ self._get_deconv_cfg(num_kernels[i])
+
+ planes = num_filters[i]
+ if i == 0:
+ layers.append(
+ build_upsample_layer(
+ dict(type='deconv'),
+ in_channels=self.embed_dims,
+ out_channels=planes,
+ kernel_size=kernel,
+ stride=2,
+ padding=padding,
+ output_padding=output_padding,
+ bias=False))
+ else:
+ layers.append(
+ build_upsample_layer(
+ dict(type='deconv'),
+ in_channels=planes,
+ out_channels=planes,
+ kernel_size=kernel,
+ stride=2,
+ padding=padding,
+ output_padding=output_padding,
+ bias=False))
+
+ layers.append(nn.BatchNorm2d(planes))
+ layers.append(nn.ReLU(inplace=True))
+ self.in_channels = planes
+
+ self.deconv_layer = nn.Sequential(*layers)
+ self.final_layer = nn.Sequential(
+ ConvModule(
+ self.embed_dims,
+ self.num_joints,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=None,
+ act_cfg=None,
+ inplace=False)
+ )
+
+ @staticmethod
+ def _get_deconv_cfg(deconv_kernel):
+ """Get configurations for deconv layers."""
+ if deconv_kernel == 4:
+ padding = 1
+ output_padding = 0
+ elif deconv_kernel == 3:
+ padding = 1
+ output_padding = 1
+ elif deconv_kernel == 2:
+ padding = 0
+ output_padding = 0
+ else:
+ raise ValueError(f'Not supported num_kernels ({deconv_kernel}).')
+
+ return deconv_kernel, padding, output_padding
+
+ def init_weights(self):
+ """Initialize weights of the DeformDETR head."""
+ self.transformer.init_weights()
+
+ # for m in [self.fc_coord_branches, self.fc_sigma_branches]:
+ for m in [self.fc_coord_branches]:
+ for mm in m:
+ if isinstance(mm, nn.Linear):
+ nn.init.xavier_uniform_(mm.weight, gain=0.01)
+
+ for m in [self.fc_coord_output_branches]:
+ for mm in m:
+ if isinstance(mm, nn.Linear):
+ nn.init.xavier_uniform_(mm.weight, gain=0.01)
+
+ if self.use_heatmap_loss:
+ for _, m in self.deconv_layer.named_modules():
+ if isinstance(m, nn.ConvTranspose2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ for m in self.final_layer.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001, bias=0)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+
+ def forward(self, mlvl_feats, coord_init=None, query_init=None):
+
+ batch_size = mlvl_feats[0].size(0)
+ img_w, img_h = self.train_cfg['image_size']
+ img_masks = mlvl_feats[0].new_ones(
+ (batch_size, img_h, img_w))
+ for img_id in range(batch_size):
+ img_masks[img_id, :img_h, :img_w] = 0
+
+ mlvl_masks = []
+ mlvl_positional_encodings = []
+ for feat in mlvl_feats:
+ mlvl_masks.append(F.interpolate(img_masks[None], size=feat.shape[-2:]).to(torch.bool).squeeze(0))
+ mlvl_positional_encodings.append(
+ self.positional_encoding(mlvl_masks[-1]))
+
+ query_embeds = None
+ if not self.as_two_stage:
+ query_embeds = self.query_embedding.weight
+
+ memory, spatial_shapes, level_start_index, hs, init_reference, inter_references, \
+ enc_outputs = self.transformer(
+ mlvl_feats,
+ mlvl_masks,
+ query_embeds,
+ mlvl_positional_encodings,
+ reg_branches=self.fc_coord_branches if self.with_box_refine else None, # noqa:E501
+ cls_branches=None, # noqa:E501
+ coord_init=coord_init,
+ query_init=query_init,
+ )
+ hs = hs.permute(0, 2, 1, 3)
+ outputs_coords = []
+
+ dec_outputs = EasyDict(pred_jts=outputs_coords, feat=hs)
+
+ return enc_outputs, dec_outputs
+
+ def get_loss(self, enc_output, dec_output, coord_target, coord_target_weight, hp_target, hp_target_weight):
+ losses = dict()
+ if self.as_two_stage and enc_output is not None:
+ enc_rle_loss = self.get_enc_rle_loss(enc_output, coord_target, coord_target_weight)
+ losses.update(enc_rle_loss)
+
+ dec_rle_loss = self.get_dec_rle_loss(dec_output, coord_target, coord_target_weight)
+ losses.update(dec_rle_loss)
+
+ return losses
+
+ def get_enc_rle_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+ Note:
+ batch_size: N
+ num_keypoints: K
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+ assert not isinstance(self.loss_coord_enc, nn.Sequential)
+ assert target.dim() == 3 and target_weight.dim() == 3
+
+ BATCH_SIZE = output.sigma.size(0)
+ gt_uvd = target.reshape(output.pred_jts.shape)
+ gt_uvd_weight = target_weight.reshape(output.pred_jts.shape)
+ gt_3d_mask = gt_uvd_weight[:, :, 2].reshape(-1)
+
+ assert output.pred_jts.shape == output.sigma.shape, (output.pred_jts.shape, output.sigma.shape)
+ bar_mu = (output.pred_jts - gt_uvd) / output.sigma
+ bar_mu = bar_mu.reshape(-1, 3)
+ bar_mu_3d = bar_mu[gt_3d_mask > 0]
+ bar_mu_2d = bar_mu[gt_3d_mask < 1][:, :2]
+ # (B, K, 3)
+ log_phi_3d = self.enc_flow3d.log_prob(bar_mu_3d)
+ log_phi_2d = self.enc_flow2d.log_prob(bar_mu_2d)
+ log_phi = torch.zeros_like(bar_mu[:, 0])
+ # print(gt_3d_mask)
+ log_phi[gt_3d_mask > 0] = log_phi_3d
+ log_phi[gt_3d_mask < 1] = log_phi_2d
+ log_phi = log_phi.reshape(BATCH_SIZE, self.num_joints, 1)
+
+ output.nf_loss = torch.log(output.sigma) - log_phi
+ losses['enc_rle_loss'] = self.loss_coord_enc(output, target, target_weight)
+
+ return losses
+
+ def get_enc_rle_loss_old(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+ Note:
+ batch_size: N
+ num_keypoints: K
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+ assert not isinstance(self.loss_coord_enc, nn.Sequential)
+ assert target.dim() == 3 and target_weight.dim() == 3
+
+ BATCH_SIZE = output.sigma.size(0)
+ gt_uv = target.reshape(output.pred_jts.shape)
+ bar_mu = (output.pred_jts - gt_uv) / output.sigma
+ # (B, K, 1)
+ log_phi = self.enc_flow.log_prob(bar_mu.reshape(-1, 2)).reshape(BATCH_SIZE, self.num_joints, 1)
+ output.nf_loss = torch.log(output.sigma) - log_phi
+ losses['enc_rle_loss'] = self.loss_coord_enc(output, target, target_weight)
+
+ return losses
+
+ def get_dec_rle_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+ assert not isinstance(self.loss_coord_dec, nn.Sequential)
+ assert target.dim() == 3 and target_weight.dim() == 3
+ target = target.repeat(1, self.transformer.num_noise_sample + 1, 1)
+ target_weight = target_weight.repeat(1, self.transformer.num_noise_sample + 1, 1)
+
+ if self.with_box_refine:
+ if self.use_dec_rle_loss:
+ for i in range(len(output.pred_jts)):
+ pred_jts, sigma = output.pred_jts[i], output.sigma[i]
+ output_i = EasyDict(
+ pred_jts=pred_jts,
+ sigma=sigma
+ )
+ BATCH_SIZE = output_i.sigma.size(0)
+ gt_uvd = target.reshape(output_i.pred_jts.shape)
+ gt_uvd_weight = target_weight.reshape(pred_jts.shape)
+ gt_3d_mask = gt_uvd_weight[:, :, 2].reshape(-1)
+
+ assert pred_jts.shape == sigma.shape, (pred_jts.shape, sigma.shape)
+ bar_mu = (output_i.pred_jts - gt_uvd) / output_i.sigma
+ bar_mu = bar_mu.reshape(-1, 3)
+ bar_mu_3d = bar_mu[gt_3d_mask > 0]
+ bar_mu_2d = bar_mu[gt_3d_mask < 1][:, :2]
+ # (B, K, 3)
+ log_phi_3d = self.dec_flow3d.log_prob(bar_mu_3d)
+ log_phi_2d = self.dec_flow2d.log_prob(bar_mu_2d)
+ log_phi = torch.zeros_like(bar_mu[:, 0])
+ log_phi[gt_3d_mask > 0] = log_phi_3d
+ log_phi[gt_3d_mask < 1] = log_phi_2d
+ log_phi = log_phi.reshape(BATCH_SIZE, self.num_joints * (self.transformer.num_noise_sample + 1), 1)
+ output_i.nf_loss = torch.log(output_i.sigma) - log_phi
+ losses['dec_rle_loss_{}'.format(i)] = self.loss_coord_dec(output_i, target, target_weight)
+ else:
+ for i, pred_jts in enumerate(output.pred_jts):
+ losses['dec_rle_loss_{}'.format(i)] = self.loss_coord_dec(pred_jts, target, target_weight)
+ else:
+ if self.use_dec_rle_loss:
+ BATCH_SIZE = output.sigma.size(0)
+ gt_uv = target.reshape(output.pred_jts.shape)
+ bar_mu = (output.pred_jts - gt_uv) / output.sigma
+ # (B, K, 1)
+ log_phi = self.dec_flow.log_prob(bar_mu.reshape(-1, 2)).reshape(BATCH_SIZE, self.num_joints, 1)
+ output.nf_loss = torch.log(output.sigma) - log_phi
+ losses['dec_rle_loss'] = self.loss_coord_dec(output, target, target_weight) * 0
+ else:
+ losses['dec_rle_loss'] = self.loss_coord_dec(output.pred_jts, target + 0.5, target_weight) * 0
+
+ return losses
+
+ def get_hp_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ heatmaps height: H
+ heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[NxKxHxW]): Output heatmaps.
+ target (torch.Tensor[NxKxHxW]): Target heatmaps.
+ target_weight (torch.Tensor[NxKx1]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+
+ if isinstance(self.loss_hp, nn.Sequential):
+ if not isinstance(output, dict):
+ assert len(self.loss_hp) == output.size(0)
+ assert target.dim() == 5 and target_weight.dim() == 4
+ num_hp_layers = output.size(0)
+ for i in range(num_hp_layers):
+ target_i = target[:, i, :, :, :]
+ target_weight_i = target_weight[:, i, :, :]
+ losses['mse_loss_{}'.format(i)] = self.loss_hp[i](output[i], target_i, target_weight_i)
+ else:
+ out_hp_backbone = output['backbone']
+ num_hp_layers = out_hp_backbone.size(0)
+ for i in range(num_hp_layers):
+ target_i = target[:, i, :, :, :]
+ target_weight_i = target_weight[:, i, :, :]
+ losses['mse_loss_backbone_{}'.format(i)] = self.loss_hp[i](out_hp_backbone[i], target_i,
+ target_weight_i)
+
+ out_hp_enc = output['enc']
+ for lvl in range(len(out_hp_enc)):
+ if lvl == 2 or lvl == 5:
+ # if lvl == 5:
+ for i in range(3):
+ target_i = target[:, i + 1, :, :, :]
+ target_weight_i = target_weight[:, i + 1, :, :]
+ # losses['reg_loss'] += self.loss(output[i], target, target_weight).sum()
+ if lvl == 2:
+ loss_weight = 0.1
+ elif lvl == 5:
+ loss_weight = 1.0
+
+ losses['mse_loss_enc_layer{}_c{}'.format(lvl, i + 3)] = loss_weight * self.loss_hp[i + 1](
+ out_hp_enc[lvl][i], target_i, target_weight_i)
+ else:
+
+ assert target.dim() == 4 and target_weight.dim() == 3
+ losses['mse_loss'] = self.loss_hp(output, target, target_weight)
+
+ return losses
+
+ def get_accuracy(self, enc_output, dec_output, coord_target, coord_target_weight, hp_target, hp_target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+ # coord_output = output["coord"]
+ if self.as_two_stage and enc_output is not None:
+ coord_output = enc_output.pred_jts
+ N = coord_output.shape[0]
+
+ _, avg_acc, cnt = keypoint_pck_accuracy(
+ coord_output.detach().cpu().numpy(),
+ coord_target.detach().cpu().numpy(),
+ coord_target_weight[:, :, 0].detach().cpu().numpy() > 0,
+ thr=0.05,
+ normalize=np.ones((N, 2), dtype=np.float32))
+ accuracy['enc_coord_acc'] = avg_acc
+
+ coord_output = dec_output.pred_jts
+ if coord_output.dim() == 4:
+ coord_output = coord_output[-1]
+ N = coord_output.shape[0]
+
+ if not self.use_dec_rle_loss:
+ coord_target += 0.5
+ # self.num_joints
+ _, avg_acc, cnt = keypoint_pck_accuracy(
+ coord_output[:, :self.num_joints].detach().cpu().numpy(),
+ coord_target.detach().cpu().numpy(),
+ coord_target_weight[:, :, 0].detach().cpu().numpy() > 0,
+ thr=0.05,
+ normalize=np.ones((N, 2), dtype=np.float32))
+ accuracy['dec_coord_acc'] = avg_acc
+
+ # if self.use_heatmap_loss and self.use_multi_stage_memory:
+ # assert hp_target.dim() == 5 and hp_target_weight.dim() == 4
+ # _, avg_acc, _ = pose_pck_accuracy(
+ # hp_output_backbone[0].detach().cpu().numpy(),
+ # hp_target[:, 0, ...].detach().cpu().numpy(),
+ # hp_target_weight[:, 0,
+ # ...].detach().cpu().numpy().squeeze(-1) > 0)
+ # accuracy['hp_acc_backbone'] = float(avg_acc)
+
+ # _, avg_acc, _ = pose_pck_accuracy(
+ # hp_output_enc[-1][0].detach().cpu().numpy(),
+ # hp_target[:, 1, ...].detach().cpu().numpy(),
+ # hp_target_weight[:, 1,
+ # ...].detach().cpu().numpy().squeeze(-1) > 0)
+ # accuracy['hp_acc_enc'] = float(avg_acc)
+
+ # else:
+ if self.use_heatmap_loss:
+ hp_output = dec_output["hp"]
+ _, avg_acc, _ = pose_pck_accuracy(
+ hp_output.detach().cpu().numpy(),
+ hp_target.detach().cpu().numpy(),
+ hp_target_weight.detach().cpu().numpy().squeeze(-1) > 0)
+ accuracy['hp_acc'] = float(avg_acc)
+
+ return accuracy
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_regression (np.ndarray): Output regression.
+
+ Args:
+ x (torch.Tensor[N, K, 2]): Input features.
+ flip_pairs (None | list[tuple()):
+ Pairs of keypoints which are mirrored.
+ """
+ output_enc, output_dec = self.forward(x)
+ output_regression, output_regression_score = output_dec.pred_jts.detach().cpu().numpy(), output_dec.maxvals.detach().cpu().numpy()
+ output_sigma = output_dec.sigma.detach().cpu().numpy()
+ output_sigma = output_sigma[-1]
+ output_regression_score = np.concatenate([output_regression_score, output_sigma], axis=2)
+
+ if output_regression.ndim == 4:
+ output_regression = output_regression[-1]
+
+ if flip_pairs is not None:
+
+ output_regression, output_regression_score = fliplr_rle_regression(
+ output_regression, output_regression_score, flip_pairs)
+
+ return output_regression, output_regression_score
+
+ def decode_keypoints(self, img_metas, output_regression, output_regression_score, img_size):
+ """Decode keypoints from output regression.
+
+ Args:
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ output_regression (np.ndarray[N, K, 2]): model
+ predicted regression vector.
+ img_size (tuple(img_width, img_height)): model input image size.
+ """
+ batch_size = len(img_metas)
+
+ if 'bbox_id' in img_metas[0]:
+ bbox_ids = []
+ else:
+ bbox_ids = None
+
+ c = np.zeros((batch_size, 2), dtype=np.float32)
+ s = np.zeros((batch_size, 2), dtype=np.float32)
+ image_paths = []
+ score = np.ones(batch_size)
+ for i in range(batch_size):
+ c[i, :] = img_metas[i]['center']
+ s[i, :] = img_metas[i]['scale']
+ image_paths.append(img_metas[i]['image_file'])
+
+ if 'bbox_score' in img_metas[i]:
+ score[i] = np.array(img_metas[i]['bbox_score']).reshape(-1)
+
+ if bbox_ids is not None:
+ bbox_ids.append(img_metas[i]['bbox_id'])
+
+ preds, maxvals = keypoints_from_regression(output_regression, c, s,
+ img_size)
+
+ all_preds = np.zeros((batch_size, preds.shape[1], 3), dtype=np.float32)
+ all_boxes = np.zeros((batch_size, 6), dtype=np.float32)
+ all_preds[:, :, 0:2] = preds[:, :, 0:2]
+ # all_preds[:, :, 2:3] = maxvals
+ all_preds[:, :, 2:3] = output_regression_score
+ all_boxes[:, 0:2] = c[:, 0:2]
+ all_boxes[:, 2:4] = s[:, 0:2]
+ all_boxes[:, 4] = np.prod(s * 200.0, axis=1)
+ all_boxes[:, 5] = score
+
+ result = {}
+
+ result['preds'] = all_preds
+ result['boxes'] = all_boxes
+ result['image_paths'] = image_paths
+ result['bbox_ids'] = bbox_ids
+
+ return result
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/rle_regression_head.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/rle_regression_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..b96a19155f6ec13f86e069d75d15ea4b70f133fa
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/rle_regression_head.py
@@ -0,0 +1,426 @@
+import numpy as np
+import torch.nn as nn
+from mmcv.cnn import normal_init
+
+from mmpose.core.evaluation import (keypoint_pck_accuracy,
+ keypoints_from_regression)
+from mmpose.core.post_processing import fliplr_regression
+from mmpose.models.builder import HEADS, build_loss
+
+import torch
+import torch.nn as nn
+import torch.distributions as distributions
+from easydict import EasyDict
+
+def rle_fliplr_regression(regression,
+ regression_score,
+ flip_pairs,
+ center_mode='static',
+ center_x=0.5,
+ center_index=0,
+ shift=True):
+ """Flip human joints horizontally.
+
+ Note:
+ batch_size: N
+ num_keypoint: K
+ Args:
+ regression (np.ndarray([..., K, C])): Coordinates of keypoints, where K
+ is the joint number and C is the dimension. Example shapes are:
+ - [N, K, C]: a batch of keypoints where N is the batch size.
+ - [N, T, K, C]: a batch of pose sequences, where T is the frame
+ number.
+ flip_pairs (list[tuple()]): Pairs of keypoints which are mirrored
+ (for example, left ear -- right ear).
+ center_mode (str): The mode to set the center location on the x-axis
+ to flip around. Options are:
+ - static: use a static x value (see center_x also)
+ - root: use a root joint (see center_index also)
+ center_x (float): Set the x-axis location of the flip center. Only used
+ when center_mode=static.
+ center_index (int): Set the index of the root joint, whose x location
+ will be used as the flip center. Only used when center_mode=root.
+
+ Returns:
+ tuple: Flipped human joints.
+
+ - regression_flipped (np.ndarray([..., K, C])): Flipped joints.
+ """
+ assert regression.ndim >= 2, f'Invalid pose shape {regression.shape}'
+
+ # flip
+ # width_dim = 48
+ # if shift:
+ # regression[:, :, 0] = - regression[:, :, 0] - 1 / (width_dim * 4)
+ # else:
+ # regression[:, :, 0] = -1 / width_dim - regression[:, :, 0]
+
+ allowed_center_mode = {'static', 'root'}
+ assert center_mode in allowed_center_mode, 'Get invalid center_mode ' \
+ f'{center_mode}, allowed choices are {allowed_center_mode}'
+
+ if center_mode == 'static':
+ x_c = center_x
+ elif center_mode == 'root':
+ assert regression.shape[-2] > center_index
+ x_c = regression[..., center_index:center_index + 1, 0]
+
+ regression_flipped = regression.copy()
+ regression_score_flipped = regression_score.copy()
+
+ # Swap left-right parts
+ for left, right in flip_pairs:
+ regression_flipped[..., left, :] = regression[..., right, :]
+ regression_flipped[..., right, :] = regression[..., left, :]
+ regression_score_flipped[..., left, :] = regression_score[..., right, :]
+ regression_score_flipped[..., right, :] = regression_score[..., left, :]
+
+ # Flip horizontally
+ regression_flipped[..., 0] = x_c * 2 - regression_flipped[..., 0]
+ return regression_flipped, regression_score_flipped
+
+
+def nets():
+ return nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, 2), nn.Tanh())
+
+def nets3d():
+ return nn.Sequential(nn.Linear(3, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, 3), nn.Tanh())
+ # return nn.Sequential(nn.Linear(3, 256), nn.LeakyReLU(), nn.Linear(256, 2), nn.Tanh())
+
+def nett():
+ return nn.Sequential(nn.Linear(2, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, 2))
+
+def nett3d():
+ return nn.Sequential(nn.Linear(3, 64), nn.LeakyReLU(), nn.Linear(64, 64), nn.LeakyReLU(), nn.Linear(64, 3))
+ # return nn.Sequential(nn.Linear(3, 256), nn.LeakyReLU(), nn.Linear(256, 2))
+
+
+class Linear(nn.Module):
+ def __init__(self, in_channel, out_channel, bias=True, norm=True):
+ super(Linear, self).__init__()
+ self.bias = bias
+ self.norm = norm
+ self.linear = nn.Linear(in_channel, out_channel, bias)
+ nn.init.xavier_uniform_(self.linear.weight, gain=0.01)
+
+ def forward(self, x):
+ y = x.matmul(self.linear.weight.t())
+
+ if self.norm:
+ x_norm = torch.norm(x, dim=1, keepdim=True)
+ y = y / x_norm
+
+ if self.bias:
+ y = y + self.linear.bias
+ return y
+
+
+class RealNVP(nn.Module):
+ def __init__(self, nets, nett, mask, prior):
+ super(RealNVP, self).__init__()
+
+ self.prior = prior
+ self.register_buffer('mask', mask)
+ self.t = torch.nn.ModuleList([nett() for _ in range(len(mask))])
+ self.s = torch.nn.ModuleList([nets() for _ in range(len(mask))])
+
+ def _init(self):
+ for m in self.t:
+ for mm in m.modules():
+ if isinstance(mm, nn.Linear):
+ nn.init.xavier_uniform_(mm.weight, gain=0.01)
+ for m in self.s:
+ for mm in m.modules():
+ if isinstance(mm, nn.Linear):
+ nn.init.xavier_uniform_(mm.weight, gain=0.01)
+
+ def forward_p(self, z):
+ x = z
+ for i in range(len(self.t)):
+ x_ = x * self.mask[i]
+ s = self.s[i](x_) * (1 - self.mask[i])
+ t = self.t[i](x_) * (1 - self.mask[i])
+ x = x_ + (1 - self.mask[i]) * (x * torch.exp(s) + t)
+ return x
+
+ def backward_p(self, x):
+ log_det_J, z = x.new_zeros(x.shape[0]), x
+ for i in reversed(range(len(self.t))):
+ z_ = self.mask[i] * z
+ s = self.s[i](z_) * (1 - self.mask[i])
+ t = self.t[i](z_) * (1 - self.mask[i])
+ z = (1 - self.mask[i]) * (z - t) * torch.exp(-s) + z_
+ log_det_J -= s.sum(dim=1)
+ return z, log_det_J
+
+ def log_prob(self, x):
+ DEVICE = x.device
+ if self.prior.loc.device != DEVICE:
+ self.prior.loc = self.prior.loc.to(DEVICE)
+ self.prior.scale_tril = self.prior.scale_tril.to(DEVICE)
+ self.prior._unbroadcasted_scale_tril = self.prior._unbroadcasted_scale_tril.to(DEVICE)
+ self.prior.covariance_matrix = self.prior.covariance_matrix.to(DEVICE)
+ self.prior.precision_matrix = self.prior.precision_matrix.to(DEVICE)
+
+ z, logp = self.backward_p(x)
+ return self.prior.log_prob(z) + logp
+
+ def sample(self, batchSize):
+ z = self.prior.sample((batchSize, 1))
+ x = self.forward_p(z)
+ return x
+
+ def forward(self, x):
+ return self.log_prob(x)
+
+
+@HEADS.register_module()
+class RLERegressionHead(nn.Module):
+ """Deeppose regression head with fully connected layers.
+
+ paper ref: Alexander Toshev and Christian Szegedy,
+ ``DeepPose: Human Pose Estimation via Deep Neural Networks.''.
+
+ Args:
+ in_channels (int): Number of input channels
+ num_joints (int): Number of joints
+ loss_keypoint (dict): Config for keypoint loss. Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ num_joints,
+ loss_keypoint=None,
+ train_cfg=None,
+ test_cfg=None):
+ super().__init__()
+
+ self.in_channels = in_channels
+ self.num_joints = num_joints
+
+ self.loss = build_loss(loss_keypoint)
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+
+ # self.fc = nn.Linear(self.in_channels, self.num_joints * 2)
+ # self.avg_pool = nn.AdaptiveAvgPool2d(1)
+ # self.fcs, out_channel = self._make_fc_layer()
+
+ # self.fc_coord = Linear(self.in_channels, self.num_joints * 2)
+ # self.fc_sigma = Linear(self.in_channels, self.num_joints * 2, norm=False)
+ self.fc_coord = Linear(self.in_channels, self.num_joints * 3)
+ self.fc_sigma = Linear(self.in_channels, self.num_joints * 3, norm=False)
+
+ self.fc_layers = [self.fc_coord, self.fc_sigma]
+
+ self.share_flow = True
+
+ prior = distributions.MultivariateNormal(torch.zeros(2), torch.eye(2))
+ masks = torch.from_numpy(np.array([[0, 1], [1, 0]] * 3).astype(np.float32))
+
+ prior3d = distributions.MultivariateNormal(torch.zeros(3), torch.eye(3))
+ masks3d = torch.from_numpy(np.array([[0, 0, 1], [1, 1, 0]] * 3).astype(np.float32))
+
+ self.flow2d = RealNVP(nets, nett, masks, prior)
+ self.flow3d = RealNVP(nets3d, nett3d, masks3d, prior3d)
+
+
+ # def _make_fc_layer(self):
+ # fc_layers = []
+ # num_deconv = len(self.fc_dim)
+ # input_channel = self.feature_channel
+ # for i in range(num_deconv):
+ # if self.fc_dim[i] > 0:
+ # fc = nn.Linear(input_channel, self.fc_dim[i])
+ # bn = nn.BatchNorm1d(self.fc_dim[i])
+ # fc_layers.append(fc)
+ # fc_layers.append(bn)
+ # fc_layers.append(nn.ReLU(inplace=True))
+ # input_channel = self.fc_dim[i]
+ # else:
+ # fc_layers.append(nn.Identity())
+ #
+ # return nn.Sequential(*fc_layers), input_channel
+
+
+ def forward(self, x):
+ """Forward function."""
+ # output = self.fc(x)
+ # N, C = output.shape
+ # return output.reshape([N, C // 2, 2])
+ BATCH_SIZE = x.shape[0]
+ out_coord = self.fc_coord(x).reshape(BATCH_SIZE, self.num_joints, 3)
+ assert out_coord.shape[2] == 3
+
+ out_sigma = self.fc_sigma(x).reshape(BATCH_SIZE, self.num_joints, -1)
+
+ # (B, N, 3)
+ pred_jts = out_coord.reshape(BATCH_SIZE, self.num_joints, 3)
+ sigma = out_sigma.reshape(BATCH_SIZE, self.num_joints, -1).sigmoid() + 1e-9
+ scores = 1 - sigma
+ # (B, N, 1)
+ scores = torch.mean(scores, dim=2, keepdim=True)
+
+ output = EasyDict(
+ pred_jts=pred_jts,
+ sigma=sigma,
+ maxvals=scores.float(),
+ )
+ return output
+
+ def get_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+ assert not isinstance(self.loss, nn.Sequential)
+ assert target.dim() == 3 and target_weight.dim() == 3
+
+ BATCH_SIZE = output.sigma.size(0)
+ gt_uvd = target.reshape(output.pred_jts.shape)
+ bar_mu = (output.pred_jts - gt_uvd) / output.sigma
+ # (B, K, 1)
+ log_phi = self.flow.log_prob(bar_mu.reshape(-1, 2)).reshape(BATCH_SIZE, self.num_joints, 1)
+ output.nf_loss = torch.log(output.sigma) - log_phi
+ losses['reg_loss'] = self.loss(output, target, target_weight)
+
+ return losses
+
+ def get_accuracy(self, output, target, target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output keypoints.
+ target (torch.Tensor[N, K, 2]): Target keypoints.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+
+ N = output.pred_jts.shape[0]
+
+ _, avg_acc, cnt = keypoint_pck_accuracy(
+ output.pred_jts.detach().cpu().numpy(),
+ target.detach().cpu().numpy(),
+ target_weight[:, :, 0].detach().cpu().numpy() > 0,
+ thr=0.05,
+ normalize=np.ones((N, 2), dtype=np.float32))
+ accuracy['acc_pose'] = avg_acc
+
+ return accuracy
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_regression (np.ndarray): Output regression.
+
+ Args:
+ x (torch.Tensor[N, K, 2]): Input features.
+ flip_pairs (None | list[tuple()):
+ Pairs of keypoints which are mirrored.
+ """
+ output = self.forward(x)
+
+ if flip_pairs is not None:
+ output_regression, output_regression_score = rle_fliplr_regression(
+ output.pred_jts.detach().cpu().numpy(), output.maxvals.detach().cpu().numpy(), flip_pairs, center_x=0.0)
+ else:
+ output_regression = output.pred_jts.detach().cpu().numpy()
+ output_regression_score = output.maxvals.detach().cpu().numpy()
+
+ output_regression += 0.5
+ # output = EasyDict(
+ # preds=output_regression,
+ # maxvals=output_regression_score,
+ # )
+ return output_regression
+
+ def decode(self, img_metas, output, pixel_std=200.0, **kwargs):
+ """Decode the keypoints from output regression.
+
+ Args:
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ output (np.ndarray[N, K, 2]): predicted regression vector.
+ kwargs: dict contains 'img_size'.
+ img_size (tuple(img_width, img_height)): input image size.
+ """
+ batch_size = len(img_metas)
+
+ if 'bbox_id' in img_metas[0]:
+ bbox_ids = []
+ else:
+ bbox_ids = None
+
+ c = np.zeros((batch_size, 2), dtype=np.float32)
+ s = np.zeros((batch_size, 2), dtype=np.float32)
+ image_paths = []
+ score = np.ones(batch_size)
+ for i in range(batch_size):
+ c[i, :] = img_metas[i]['center']
+ s[i, :] = img_metas[i]['scale']
+ image_paths.append(img_metas[i]['image_file'])
+
+ if 'bbox_score' in img_metas[i]:
+ score[i] = np.array(img_metas[i]['bbox_score']).reshape(-1)
+ if bbox_ids is not None:
+ bbox_ids.append(img_metas[i]['bbox_id'])
+
+ preds, maxvals = keypoints_from_regression(output, c, s, kwargs['img_size'], pixel_std)
+ # maxvals = output.maxvals
+
+ all_preds = np.zeros((batch_size, preds.shape[1], 3), dtype=np.float32)
+ all_boxes = np.zeros((batch_size, 6), dtype=np.float32)
+ all_preds[:, :, 0:2] = preds[:, :, 0:2]
+ all_preds[:, :, 2:3] = maxvals
+ all_boxes[:, 0:2] = c[:, 0:2]
+ all_boxes[:, 2:4] = s[:, 0:2]
+ all_boxes[:, 4] = np.prod(s * pixel_std, axis=1)
+ all_boxes[:, 5] = score
+
+ result = {}
+ result['preds'] = all_preds
+ result['boxes'] = all_boxes
+ result['image_paths'] = image_paths
+ result['bbox_ids'] = bbox_ids
+
+ return result
+
+ def init_weights(self):
+ for m in self.fc_layers:
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight, gain=0.01)
+
+
+ # for m in self.flow.t:
+ # for mm in m.modules():
+ # if isinstance(mm, nn.Linear):
+ # nn.init.xavier_uniform_(mm.weight, gain=0.01)
+
+ # for m in self.flow.s:
+ # for mm in m.modules():
+ # if isinstance(mm, nn.Linear):
+ # nn.init.xavier_uniform_(mm.weight, gain=0.01)
+ # normal_init(self.fc, mean=0, std=0.01, bias=0)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_base_head.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_base_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..09646ead353fb054f066b9fc6816748a43287e2c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_base_head.py
@@ -0,0 +1,120 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from abc import ABCMeta, abstractmethod
+
+import numpy as np
+import torch.nn as nn
+
+from mmpose.core.evaluation.top_down_eval import keypoints_from_heatmaps
+
+
+class TopdownHeatmapBaseHead(nn.Module):
+ """Base class for top-down heatmap heads.
+
+ All top-down heatmap heads should subclass it.
+ All subclass should overwrite:
+
+ Methods:`get_loss`, supporting to calculate loss.
+ Methods:`get_accuracy`, supporting to calculate accuracy.
+ Methods:`forward`, supporting to forward model.
+ Methods:`inference_model`, supporting to inference model.
+ """
+
+ __metaclass__ = ABCMeta
+
+ @abstractmethod
+ def get_loss(self, **kwargs):
+ """Gets the loss."""
+
+ @abstractmethod
+ def get_accuracy(self, **kwargs):
+ """Gets the accuracy."""
+
+ @abstractmethod
+ def forward(self, **kwargs):
+ """Forward function."""
+
+ @abstractmethod
+ def inference_model(self, **kwargs):
+ """Inference function."""
+
+ def decode(self, img_metas, output, **kwargs):
+ """Decode keypoints from heatmaps.
+
+ Args:
+ img_metas (list(dict)): Information about data augmentation
+ By default this includes:
+
+ - "image_file: path to the image file
+ - "center": center of the bbox
+ - "scale": scale of the bbox
+ - "rotation": rotation of the bbox
+ - "bbox_score": score of bbox
+ output (np.ndarray[N, K, H, W]): model predicted heatmaps.
+ """
+ batch_size = len(img_metas)
+
+ if 'bbox_id' in img_metas[0]:
+ bbox_ids = []
+ else:
+ bbox_ids = None
+
+ c = np.zeros((batch_size, 2), dtype=np.float32)
+ s = np.zeros((batch_size, 2), dtype=np.float32)
+ image_paths = []
+ score = np.ones(batch_size)
+ for i in range(batch_size):
+ c[i, :] = img_metas[i]['center']
+ s[i, :] = img_metas[i]['scale']
+ image_paths.append(img_metas[i]['image_file'])
+
+ if 'bbox_score' in img_metas[i]:
+ score[i] = np.array(img_metas[i]['bbox_score']).reshape(-1)
+ if bbox_ids is not None:
+ bbox_ids.append(img_metas[i]['bbox_id'])
+
+ preds, maxvals = keypoints_from_heatmaps(
+ output,
+ c,
+ s,
+ unbiased=self.test_cfg.get('unbiased_decoding', False),
+ post_process=self.test_cfg.get('post_process', 'default'),
+ kernel=self.test_cfg.get('modulate_kernel', 11),
+ valid_radius_factor=self.test_cfg.get('valid_radius_factor',
+ 0.0546875),
+ use_udp=self.test_cfg.get('use_udp', False),
+ target_type=self.test_cfg.get('target_type', 'GaussianHeatmap'))
+
+ all_preds = np.zeros((batch_size, preds.shape[1], 3), dtype=np.float32)
+ all_boxes = np.zeros((batch_size, 6), dtype=np.float32)
+ all_preds[:, :, 0:2] = preds[:, :, 0:2]
+ all_preds[:, :, 2:3] = maxvals
+ all_boxes[:, 0:2] = c[:, 0:2]
+ all_boxes[:, 2:4] = s[:, 0:2]
+ all_boxes[:, 4] = np.prod(s * 200.0, axis=1)
+ all_boxes[:, 5] = score
+
+ result = {}
+
+ result['preds'] = all_preds
+ result['boxes'] = all_boxes
+ result['image_paths'] = image_paths
+ result['bbox_ids'] = bbox_ids
+
+ return result
+
+ @staticmethod
+ def _get_deconv_cfg(deconv_kernel):
+ """Get configurations for deconv layers."""
+ if deconv_kernel == 4:
+ padding = 1
+ output_padding = 0
+ elif deconv_kernel == 3:
+ padding = 1
+ output_padding = 1
+ elif deconv_kernel == 2:
+ padding = 0
+ output_padding = 0
+ else:
+ raise ValueError(f'Not supported num_kernels ({deconv_kernel}).')
+
+ return deconv_kernel, padding, output_padding
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_multi_stage_head.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_multi_stage_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..c439f5b6332d72a66db75bf599035411c4e1e0d1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_multi_stage_head.py
@@ -0,0 +1,572 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import copy as cp
+
+import torch.nn as nn
+from mmcv.cnn import (ConvModule, DepthwiseSeparableConvModule, Linear,
+ build_activation_layer, build_conv_layer,
+ build_norm_layer, build_upsample_layer, constant_init,
+ kaiming_init, normal_init)
+
+from mmpose.core.evaluation import pose_pck_accuracy
+from mmpose.core.post_processing import flip_back
+from mmpose.models.builder import build_loss
+from ..builder import HEADS
+from .topdown_heatmap_base_head import TopdownHeatmapBaseHead
+
+
+@HEADS.register_module()
+class TopdownHeatmapMultiStageHead(TopdownHeatmapBaseHead):
+ """Top-down heatmap multi-stage head.
+
+ TopdownHeatmapMultiStageHead is consisted of multiple branches,
+ each of which has num_deconv_layers(>=0) number of deconv layers
+ and a simple conv2d layer.
+
+ Args:
+ in_channels (int): Number of input channels.
+ out_channels (int): Number of output channels.
+ num_stages (int): Number of stages.
+ num_deconv_layers (int): Number of deconv layers.
+ num_deconv_layers should >= 0. Note that 0 means
+ no deconv layers.
+ num_deconv_filters (list|tuple): Number of filters.
+ If num_deconv_layers > 0, the length of
+ num_deconv_kernels (list|tuple): Kernel sizes.
+ loss_keypoint (dict): Config for keypoint loss. Default: None.
+ """
+
+ def __init__(self,
+ in_channels=512,
+ out_channels=17,
+ num_stages=1,
+ num_deconv_layers=3,
+ num_deconv_filters=(256, 256, 256),
+ num_deconv_kernels=(4, 4, 4),
+ extra=None,
+ loss_keypoint=None,
+ train_cfg=None,
+ test_cfg=None):
+ super().__init__()
+
+ self.in_channels = in_channels
+ self.num_stages = num_stages
+ self.loss = build_loss(loss_keypoint)
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+ self.target_type = self.test_cfg.get('target_type', 'GaussianHeatmap')
+
+ if extra is not None and not isinstance(extra, dict):
+ raise TypeError('extra should be dict or None.')
+
+ # build multi-stage deconv layers
+ self.multi_deconv_layers = nn.ModuleList([])
+ for _ in range(self.num_stages):
+ if num_deconv_layers > 0:
+ deconv_layers = self._make_deconv_layer(
+ num_deconv_layers,
+ num_deconv_filters,
+ num_deconv_kernels,
+ )
+ elif num_deconv_layers == 0:
+ deconv_layers = nn.Identity()
+ else:
+ raise ValueError(
+ f'num_deconv_layers ({num_deconv_layers}) should >= 0.')
+ self.multi_deconv_layers.append(deconv_layers)
+
+ identity_final_layer = False
+ if extra is not None and 'final_conv_kernel' in extra:
+ assert extra['final_conv_kernel'] in [0, 1, 3]
+ if extra['final_conv_kernel'] == 3:
+ padding = 1
+ elif extra['final_conv_kernel'] == 1:
+ padding = 0
+ else:
+ # 0 for Identity mapping.
+ identity_final_layer = True
+ kernel_size = extra['final_conv_kernel']
+ else:
+ kernel_size = 1
+ padding = 0
+
+ # build multi-stage final layers
+ self.multi_final_layers = nn.ModuleList([])
+ for i in range(self.num_stages):
+ if identity_final_layer:
+ final_layer = nn.Identity()
+ else:
+ final_layer = build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=num_deconv_filters[-1]
+ if num_deconv_layers > 0 else in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=1,
+ padding=padding)
+ self.multi_final_layers.append(final_layer)
+
+ def get_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - num_outputs: O
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]):
+ Output heatmaps.
+ target (torch.Tensor[N,K,H,W]):
+ Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+
+ assert isinstance(output, list)
+ assert target.dim() == 4 and target_weight.dim() == 3
+
+ if isinstance(self.loss, nn.Sequential):
+ assert len(self.loss) == len(output)
+ for i in range(len(output)):
+ target_i = target
+ target_weight_i = target_weight
+ if isinstance(self.loss, nn.Sequential):
+ loss_func = self.loss[i]
+ else:
+ loss_func = self.loss
+ loss_i = loss_func(output[i], target_i, target_weight_i)
+ if 'heatmap_loss' not in losses:
+ losses['heatmap_loss'] = loss_i
+ else:
+ losses['heatmap_loss'] += loss_i
+
+ return losses
+
+ def get_accuracy(self, output, target, target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+
+ if self.target_type == 'GaussianHeatmap':
+ _, avg_acc, _ = pose_pck_accuracy(
+ output[-1].detach().cpu().numpy(),
+ target.detach().cpu().numpy(),
+ target_weight.detach().cpu().numpy().squeeze(-1) > 0)
+ accuracy['acc_pose'] = float(avg_acc)
+
+ return accuracy
+
+ def forward(self, x):
+ """Forward function.
+
+ Returns:
+ out (list[Tensor]): a list of heatmaps from multiple stages.
+ """
+ out = []
+ assert isinstance(x, list)
+ for i in range(self.num_stages):
+ y = self.multi_deconv_layers[i](x[i])
+ y = self.multi_final_layers[i](y)
+ out.append(y)
+ return out
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_heatmap (np.ndarray): Output heatmaps.
+
+ Args:
+ x (List[torch.Tensor[NxKxHxW]]): Input features.
+ flip_pairs (None | list[tuple()):
+ Pairs of keypoints which are mirrored.
+ """
+ output = self.forward(x)
+ assert isinstance(output, list)
+ output = output[-1]
+
+ if flip_pairs is not None:
+ # perform flip
+ output_heatmap = flip_back(
+ output.detach().cpu().numpy(),
+ flip_pairs,
+ target_type=self.target_type)
+ # feature is not aligned, shift flipped heatmap for higher accuracy
+ if self.test_cfg.get('shift_heatmap', False):
+ output_heatmap[:, :, :, 1:] = output_heatmap[:, :, :, :-1]
+ else:
+ output_heatmap = output.detach().cpu().numpy()
+
+ return output_heatmap
+
+ def _make_deconv_layer(self, num_layers, num_filters, num_kernels):
+ """Make deconv layers."""
+ if num_layers != len(num_filters):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_filters({len(num_filters)})'
+ raise ValueError(error_msg)
+ if num_layers != len(num_kernels):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_kernels({len(num_kernels)})'
+ raise ValueError(error_msg)
+
+ layers = []
+ for i in range(num_layers):
+ kernel, padding, output_padding = \
+ self._get_deconv_cfg(num_kernels[i])
+
+ planes = num_filters[i]
+ layers.append(
+ build_upsample_layer(
+ dict(type='deconv'),
+ in_channels=self.in_channels,
+ out_channels=planes,
+ kernel_size=kernel,
+ stride=2,
+ padding=padding,
+ output_padding=output_padding,
+ bias=False))
+ layers.append(nn.BatchNorm2d(planes))
+ layers.append(nn.ReLU(inplace=True))
+ self.in_channels = planes
+
+ return nn.Sequential(*layers)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for _, m in self.multi_deconv_layers.named_modules():
+ if isinstance(m, nn.ConvTranspose2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ for m in self.multi_final_layers.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001, bias=0)
+
+
+class PredictHeatmap(nn.Module):
+ """Predict the heat map for an input feature.
+
+ Args:
+ unit_channels (int): Number of input channels.
+ out_channels (int): Number of output channels.
+ out_shape (tuple): Shape of the output heatmap.
+ use_prm (bool): Whether to use pose refine machine. Default: False.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self,
+ unit_channels,
+ out_channels,
+ out_shape,
+ use_prm=False,
+ norm_cfg=dict(type='BN')):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.unit_channels = unit_channels
+ self.out_channels = out_channels
+ self.out_shape = out_shape
+ self.use_prm = use_prm
+ if use_prm:
+ self.prm = PRM(out_channels, norm_cfg=norm_cfg)
+ self.conv_layers = nn.Sequential(
+ ConvModule(
+ unit_channels,
+ unit_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=norm_cfg,
+ inplace=False),
+ ConvModule(
+ unit_channels,
+ out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ norm_cfg=norm_cfg,
+ act_cfg=None,
+ inplace=False))
+
+ def forward(self, feature):
+ feature = self.conv_layers(feature)
+ output = nn.functional.interpolate(
+ feature, size=self.out_shape, mode='bilinear', align_corners=True)
+ if self.use_prm:
+ output = self.prm(output)
+ return output
+
+
+class PRM(nn.Module):
+ """Pose Refine Machine.
+
+ Please refer to "Learning Delicate Local Representations
+ for Multi-Person Pose Estimation" (ECCV 2020).
+
+ Args:
+ out_channels (int): Channel number of the output. Equals to
+ the number of key points.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ """
+
+ def __init__(self, out_channels, norm_cfg=dict(type='BN')):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+ self.out_channels = out_channels
+ self.global_pooling = nn.AdaptiveAvgPool2d((1, 1))
+ self.middle_path = nn.Sequential(
+ Linear(self.out_channels, self.out_channels),
+ build_norm_layer(dict(type='BN1d'), out_channels)[1],
+ build_activation_layer(dict(type='ReLU')),
+ Linear(self.out_channels, self.out_channels),
+ build_norm_layer(dict(type='BN1d'), out_channels)[1],
+ build_activation_layer(dict(type='ReLU')),
+ build_activation_layer(dict(type='Sigmoid')))
+
+ self.bottom_path = nn.Sequential(
+ ConvModule(
+ self.out_channels,
+ self.out_channels,
+ kernel_size=1,
+ stride=1,
+ padding=0,
+ norm_cfg=norm_cfg,
+ inplace=False),
+ DepthwiseSeparableConvModule(
+ self.out_channels,
+ 1,
+ kernel_size=9,
+ stride=1,
+ padding=4,
+ norm_cfg=norm_cfg,
+ inplace=False), build_activation_layer(dict(type='Sigmoid')))
+ self.conv_bn_relu_prm_1 = ConvModule(
+ self.out_channels,
+ self.out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ norm_cfg=norm_cfg,
+ inplace=False)
+
+ def forward(self, x):
+ out = self.conv_bn_relu_prm_1(x)
+ out_1 = out
+
+ out_2 = self.global_pooling(out_1)
+ out_2 = out_2.view(out_2.size(0), -1)
+ out_2 = self.middle_path(out_2)
+ out_2 = out_2.unsqueeze(2)
+ out_2 = out_2.unsqueeze(3)
+
+ out_3 = self.bottom_path(out_1)
+ out = out_1 * (1 + out_2 * out_3)
+
+ return out
+
+
+@HEADS.register_module()
+class TopdownHeatmapMSMUHead(TopdownHeatmapBaseHead):
+ """Heads for multi-stage multi-unit heads used in Multi-Stage Pose
+ estimation Network (MSPN), and Residual Steps Networks (RSN).
+
+ Args:
+ unit_channels (int): Number of input channels.
+ out_channels (int): Number of output channels.
+ out_shape (tuple): Shape of the output heatmap.
+ num_stages (int): Number of stages.
+ num_units (int): Number of units in each stage.
+ use_prm (bool): Whether to use pose refine machine (PRM).
+ Default: False.
+ norm_cfg (dict): dictionary to construct and config norm layer.
+ Default: dict(type='BN')
+ loss_keypoint (dict): Config for keypoint loss. Default: None.
+ """
+
+ def __init__(self,
+ out_shape,
+ unit_channels=256,
+ out_channels=17,
+ num_stages=4,
+ num_units=4,
+ use_prm=False,
+ norm_cfg=dict(type='BN'),
+ loss_keypoint=None,
+ train_cfg=None,
+ test_cfg=None):
+ # Protect mutable default arguments
+ norm_cfg = cp.deepcopy(norm_cfg)
+ super().__init__()
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+ self.target_type = self.test_cfg.get('target_type', 'GaussianHeatmap')
+
+ self.out_shape = out_shape
+ self.unit_channels = unit_channels
+ self.out_channels = out_channels
+ self.num_stages = num_stages
+ self.num_units = num_units
+
+ self.loss = build_loss(loss_keypoint)
+
+ self.predict_layers = nn.ModuleList([])
+ for i in range(self.num_stages):
+ for j in range(self.num_units):
+ self.predict_layers.append(
+ PredictHeatmap(
+ unit_channels,
+ out_channels,
+ out_shape,
+ use_prm,
+ norm_cfg=norm_cfg))
+
+ def get_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - num_outputs: O
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,O,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,O,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,O,K,1]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+
+ assert isinstance(output, list)
+ assert target.dim() == 5 and target_weight.dim() == 4
+ assert target.size(1) == len(output)
+
+ if isinstance(self.loss, nn.Sequential):
+ assert len(self.loss) == len(output)
+ for i in range(len(output)):
+ target_i = target[:, i, :, :, :]
+ target_weight_i = target_weight[:, i, :, :]
+
+ if isinstance(self.loss, nn.Sequential):
+ loss_func = self.loss[i]
+ else:
+ loss_func = self.loss
+
+ loss_i = loss_func(output[i], target_i, target_weight_i)
+ if 'heatmap_loss' not in losses:
+ losses['heatmap_loss'] = loss_i
+ else:
+ losses['heatmap_loss'] += loss_i
+
+ return losses
+
+ def get_accuracy(self, output, target, target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+
+ if self.target_type == 'GaussianHeatmap':
+ assert isinstance(output, list)
+ assert target.dim() == 5 and target_weight.dim() == 4
+ _, avg_acc, _ = pose_pck_accuracy(
+ output[-1].detach().cpu().numpy(),
+ target[:, -1, ...].detach().cpu().numpy(),
+ target_weight[:, -1,
+ ...].detach().cpu().numpy().squeeze(-1) > 0)
+ accuracy['acc_pose'] = float(avg_acc)
+
+ return accuracy
+
+ def forward(self, x):
+ """Forward function.
+
+ Returns:
+ out (list[Tensor]): a list of heatmaps from multiple stages
+ and units.
+ """
+ out = []
+ assert isinstance(x, list)
+ assert len(x) == self.num_stages
+ assert isinstance(x[0], list)
+ assert len(x[0]) == self.num_units
+ assert x[0][0].shape[1] == self.unit_channels
+ for i in range(self.num_stages):
+ for j in range(self.num_units):
+ y = self.predict_layers[i * self.num_units + j](x[i][j])
+ out.append(y)
+
+ return out
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_heatmap (np.ndarray): Output heatmaps.
+
+ Args:
+ x (list[torch.Tensor[N,K,H,W]]): Input features.
+ flip_pairs (None | list[tuple]):
+ Pairs of keypoints which are mirrored.
+ """
+ output = self.forward(x)
+ assert isinstance(output, list)
+ output = output[-1]
+ if flip_pairs is not None:
+ output_heatmap = flip_back(
+ output.detach().cpu().numpy(),
+ flip_pairs,
+ target_type=self.target_type)
+ # feature is not aligned, shift flipped heatmap for higher accuracy
+ if self.test_cfg.get('shift_heatmap', False):
+ output_heatmap[:, :, :, 1:] = output_heatmap[:, :, :, :-1]
+ else:
+ output_heatmap = output.detach().cpu().numpy()
+ return output_heatmap
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for m in self.predict_layers.modules():
+ if isinstance(m, nn.Conv2d):
+ kaiming_init(m)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ elif isinstance(m, nn.Linear):
+ normal_init(m, std=0.01)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_simple_head.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_simple_head.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ddc058d5634a5c63970a1efb8eaa66b158da1ec
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/heads/topdown_heatmap_simple_head.py
@@ -0,0 +1,339 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+from mmcv.cnn import (build_conv_layer, build_norm_layer, build_upsample_layer,
+ constant_init, normal_init)
+
+from mmpose.core.evaluation import pose_pck_accuracy
+from mmpose.core.post_processing import flip_back
+from mmpose.models.builder import build_loss
+from mmpose.models.utils.ops import resize
+from ..builder import HEADS
+from .topdown_heatmap_base_head import TopdownHeatmapBaseHead
+
+
+@HEADS.register_module()
+class TopdownHeatmapSimpleHead(TopdownHeatmapBaseHead):
+ """Top-down heatmap simple head. paper ref: Bin Xiao et al. ``Simple
+ Baselines for Human Pose Estimation and Tracking``.
+
+ TopdownHeatmapSimpleHead is consisted of (>=0) number of deconv layers
+ and a simple conv2d layer.
+
+ Args:
+ in_channels (int): Number of input channels
+ out_channels (int): Number of output channels
+ num_deconv_layers (int): Number of deconv layers.
+ num_deconv_layers should >= 0. Note that 0 means
+ no deconv layers.
+ num_deconv_filters (list|tuple): Number of filters.
+ If num_deconv_layers > 0, the length of
+ num_deconv_kernels (list|tuple): Kernel sizes.
+ in_index (int|Sequence[int]): Input feature index. Default: 0
+ input_transform (str|None): Transformation type of input features.
+ Options: 'resize_concat', 'multiple_select', None.
+ Default: None.
+
+ - 'resize_concat': Multiple feature maps will be resized to the
+ same size as the first one and then concat together.
+ Usually used in FCN head of HRNet.
+ - 'multiple_select': Multiple feature maps will be bundle into
+ a list and passed into decode head.
+ - None: Only one select feature map is allowed.
+ align_corners (bool): align_corners argument of F.interpolate.
+ Default: False.
+ loss_keypoint (dict): Config for keypoint loss. Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ num_deconv_layers=3,
+ num_deconv_filters=(256, 256, 256),
+ num_deconv_kernels=(4, 4, 4),
+ extra=None,
+ in_index=0,
+ input_transform=None,
+ align_corners=False,
+ loss_keypoint=None,
+ train_cfg=None,
+ test_cfg=None):
+ super().__init__()
+
+ self.in_channels = in_channels
+ self.loss = build_loss(loss_keypoint)
+
+ self.train_cfg = {} if train_cfg is None else train_cfg
+ self.test_cfg = {} if test_cfg is None else test_cfg
+ self.target_type = self.test_cfg.get('target_type', 'GaussianHeatmap')
+
+ self._init_inputs(in_channels, in_index, input_transform)
+ self.in_index = in_index
+ self.align_corners = align_corners
+
+ if extra is not None and not isinstance(extra, dict):
+ raise TypeError('extra should be dict or None.')
+
+ if num_deconv_layers > 0:
+ self.deconv_layers = self._make_deconv_layer(
+ num_deconv_layers,
+ num_deconv_filters,
+ num_deconv_kernels,
+ )
+ elif num_deconv_layers == 0:
+ self.deconv_layers = nn.Identity()
+ else:
+ raise ValueError(
+ f'num_deconv_layers ({num_deconv_layers}) should >= 0.')
+
+ identity_final_layer = False
+ if extra is not None and 'final_conv_kernel' in extra:
+ assert extra['final_conv_kernel'] in [0, 1, 3]
+ if extra['final_conv_kernel'] == 3:
+ padding = 1
+ elif extra['final_conv_kernel'] == 1:
+ padding = 0
+ else:
+ # 0 for Identity mapping.
+ identity_final_layer = True
+ kernel_size = extra['final_conv_kernel']
+ else:
+ kernel_size = 1
+ padding = 0
+
+ if identity_final_layer:
+ self.final_layer = nn.Identity()
+ else:
+ conv_channels = num_deconv_filters[
+ -1] if num_deconv_layers > 0 else self.in_channels
+
+ layers = []
+ if extra is not None:
+ num_conv_layers = extra.get('num_conv_layers', 0)
+ num_conv_kernels = extra.get('num_conv_kernels',
+ [1] * num_conv_layers)
+
+ for i in range(num_conv_layers):
+ layers.append(
+ build_conv_layer(
+ dict(type='Conv2d'),
+ in_channels=conv_channels,
+ out_channels=conv_channels,
+ kernel_size=num_conv_kernels[i],
+ stride=1,
+ padding=(num_conv_kernels[i] - 1) // 2))
+ layers.append(
+ build_norm_layer(dict(type='BN'), conv_channels)[1])
+ layers.append(nn.ReLU(inplace=True))
+
+ layers.append(
+ build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=conv_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=1,
+ padding=padding))
+
+ if len(layers) > 1:
+ self.final_layer = nn.Sequential(*layers)
+ else:
+ self.final_layer = layers[0]
+
+ def get_loss(self, output, target, target_weight):
+ """Calculate top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ losses = dict()
+
+ assert not isinstance(self.loss, nn.Sequential)
+ assert target.dim() == 4 and target_weight.dim() == 3
+ losses['heatmap_loss'] = self.loss(output, target, target_weight)
+
+ return losses
+
+ def get_accuracy(self, output, target, target_weight):
+ """Calculate accuracy for top-down keypoint loss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - heatmaps height: H
+ - heatmaps weight: W
+
+ Args:
+ output (torch.Tensor[N,K,H,W]): Output heatmaps.
+ target (torch.Tensor[N,K,H,W]): Target heatmaps.
+ target_weight (torch.Tensor[N,K,1]):
+ Weights across different joint types.
+ """
+
+ accuracy = dict()
+
+ if self.target_type == 'GaussianHeatmap':
+ _, avg_acc, _ = pose_pck_accuracy(
+ output.detach().cpu().numpy(),
+ target.detach().cpu().numpy(),
+ target_weight.detach().cpu().numpy().squeeze(-1) > 0)
+ accuracy['acc_pose'] = float(avg_acc)
+
+ return accuracy
+
+ def forward(self, x):
+ """Forward function."""
+ x = self._transform_inputs(x)
+ x = self.deconv_layers(x)
+ x = self.final_layer(x)
+ return x
+
+ def inference_model(self, x, flip_pairs=None):
+ """Inference function.
+
+ Returns:
+ output_heatmap (np.ndarray): Output heatmaps.
+
+ Args:
+ x (torch.Tensor[N,K,H,W]): Input features.
+ flip_pairs (None | list[tuple]):
+ Pairs of keypoints which are mirrored.
+ """
+ output = self.forward(x)
+
+ if flip_pairs is not None:
+ output_heatmap = flip_back(
+ output.detach().cpu().numpy(),
+ flip_pairs,
+ target_type=self.target_type)
+ # feature is not aligned, shift flipped heatmap for higher accuracy
+ if self.test_cfg.get('shift_heatmap', False):
+ output_heatmap[:, :, :, 1:] = output_heatmap[:, :, :, :-1]
+ else:
+ output_heatmap = output.detach().cpu().numpy()
+ return output_heatmap
+
+ def _init_inputs(self, in_channels, in_index, input_transform):
+ """Check and initialize input transforms.
+
+ The in_channels, in_index and input_transform must match.
+ Specifically, when input_transform is None, only single feature map
+ will be selected. So in_channels and in_index must be of type int.
+ When input_transform is not None, in_channels and in_index must be
+ list or tuple, with the same length.
+
+ Args:
+ in_channels (int|Sequence[int]): Input channels.
+ in_index (int|Sequence[int]): Input feature index.
+ input_transform (str|None): Transformation type of input features.
+ Options: 'resize_concat', 'multiple_select', None.
+
+ - 'resize_concat': Multiple feature maps will be resize to the
+ same size as first one and than concat together.
+ Usually used in FCN head of HRNet.
+ - 'multiple_select': Multiple feature maps will be bundle into
+ a list and passed into decode head.
+ - None: Only one select feature map is allowed.
+ """
+
+ if input_transform is not None:
+ assert input_transform in ['resize_concat', 'multiple_select']
+ self.input_transform = input_transform
+ self.in_index = in_index
+ if input_transform is not None:
+ assert isinstance(in_channels, (list, tuple))
+ assert isinstance(in_index, (list, tuple))
+ assert len(in_channels) == len(in_index)
+ if input_transform == 'resize_concat':
+ self.in_channels = sum(in_channels)
+ else:
+ self.in_channels = in_channels
+ else:
+ assert isinstance(in_channels, int)
+ assert isinstance(in_index, int)
+ self.in_channels = in_channels
+
+ def _transform_inputs(self, inputs):
+ """Transform inputs for decoder.
+
+ Args:
+ inputs (list[Tensor] | Tensor): multi-level img features.
+
+ Returns:
+ Tensor: The transformed inputs
+ """
+ if not isinstance(inputs, list):
+ return inputs
+
+ if self.input_transform == 'resize_concat':
+ inputs = [inputs[i] for i in self.in_index]
+ upsampled_inputs = [
+ resize(
+ input=x,
+ size=inputs[0].shape[2:],
+ mode='bilinear',
+ align_corners=self.align_corners) for x in inputs
+ ]
+ inputs = torch.cat(upsampled_inputs, dim=1)
+ elif self.input_transform == 'multiple_select':
+ inputs = [inputs[i] for i in self.in_index]
+ else:
+ inputs = inputs[self.in_index]
+
+ return inputs
+
+ def _make_deconv_layer(self, num_layers, num_filters, num_kernels):
+ """Make deconv layers."""
+ if num_layers != len(num_filters):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_filters({len(num_filters)})'
+ raise ValueError(error_msg)
+ if num_layers != len(num_kernels):
+ error_msg = f'num_layers({num_layers}) ' \
+ f'!= length of num_kernels({len(num_kernels)})'
+ raise ValueError(error_msg)
+
+ layers = []
+ for i in range(num_layers):
+ kernel, padding, output_padding = \
+ self._get_deconv_cfg(num_kernels[i])
+
+ planes = num_filters[i]
+ layers.append(
+ build_upsample_layer(
+ dict(type='deconv'),
+ in_channels=self.in_channels,
+ out_channels=planes,
+ kernel_size=kernel,
+ stride=2,
+ padding=padding,
+ output_padding=output_padding,
+ bias=False))
+ layers.append(nn.BatchNorm2d(planes))
+ layers.append(nn.ReLU(inplace=True))
+ self.in_channels = planes
+
+ return nn.Sequential(*layers)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for _, m in self.deconv_layers.named_modules():
+ if isinstance(m, nn.ConvTranspose2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
+ for m in self.final_layer.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001, bias=0)
+ elif isinstance(m, nn.BatchNorm2d):
+ constant_init(m, 1)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..6502f7b19e8ab71cbdca028cd8b14bffde24cf20
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/__init__.py
@@ -0,0 +1,17 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .classfication_loss import BCELoss
+from .heatmap_loss import AdaptiveWingLoss
+from .mesh_loss import GANLoss, MeshLoss
+from .mse_loss import JointsMSELoss, JointsOHKMMSELoss
+from .multi_loss_factory import AELoss, HeatmapLoss, MultiLossFactory
+from .regression_loss import (BoneLoss, L1Loss, MPJPELoss, MSELoss, RLELoss,
+ SemiSupervisionLoss, SmoothL1Loss, SoftWingLoss,
+ WingLoss)
+from .rle_loss import RLELoss_poseur
+
+__all__ = [
+ 'JointsMSELoss', 'JointsOHKMMSELoss', 'HeatmapLoss', 'AELoss',
+ 'MultiLossFactory', 'MeshLoss', 'GANLoss', 'SmoothL1Loss', 'WingLoss',
+ 'MPJPELoss', 'MSELoss', 'L1Loss', 'BCELoss', 'BoneLoss',
+ 'SemiSupervisionLoss', 'SoftWingLoss', 'AdaptiveWingLoss', 'RLELoss'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/classfication_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/classfication_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..b79b69d035611f75f10e8722aaea4362659509e2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/classfication_loss.py
@@ -0,0 +1,41 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ..builder import LOSSES
+
+
+@LOSSES.register_module()
+class BCELoss(nn.Module):
+ """Binary Cross Entropy loss."""
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.criterion = F.binary_cross_entropy
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_labels: K
+
+ Args:
+ output (torch.Tensor[N, K]): Output classification.
+ target (torch.Tensor[N, K]): Target classification.
+ target_weight (torch.Tensor[N, K] or torch.Tensor[N]):
+ Weights across different labels.
+ """
+
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output, target, reduction='none')
+ if target_weight.dim() == 1:
+ target_weight = target_weight[:, None]
+ loss = (loss * target_weight).mean()
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/heatmap_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/heatmap_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..9471457ca0da2d43441da1d394bc45b3e8ca3ee7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/heatmap_loss.py
@@ -0,0 +1,86 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+
+from ..builder import LOSSES
+
+
+@LOSSES.register_module()
+class AdaptiveWingLoss(nn.Module):
+ """Adaptive wing loss. paper ref: 'Adaptive Wing Loss for Robust Face
+ Alignment via Heatmap Regression' Wang et al. ICCV'2019.
+
+ Args:
+ alpha (float), omega (float), epsilon (float), theta (float)
+ are hyper-parameters.
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self,
+ alpha=2.1,
+ omega=14,
+ epsilon=1,
+ theta=0.5,
+ use_target_weight=False,
+ loss_weight=1.):
+ super().__init__()
+ self.alpha = float(alpha)
+ self.omega = float(omega)
+ self.epsilon = float(epsilon)
+ self.theta = float(theta)
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def criterion(self, pred, target):
+ """Criterion of wingloss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ pred (torch.Tensor[NxKxHxW]): Predicted heatmaps.
+ target (torch.Tensor[NxKxHxW]): Target heatmaps.
+ """
+ H, W = pred.shape[2:4]
+ delta = (target - pred).abs()
+
+ A = self.omega * (
+ 1 / (1 + torch.pow(self.theta / self.epsilon, self.alpha - target))
+ ) * (self.alpha - target) * (torch.pow(
+ self.theta / self.epsilon,
+ self.alpha - target - 1)) * (1 / self.epsilon)
+ C = self.theta * A - self.omega * torch.log(
+ 1 + torch.pow(self.theta / self.epsilon, self.alpha - target))
+
+ losses = torch.where(
+ delta < self.theta,
+ self.omega *
+ torch.log(1 +
+ torch.pow(delta / self.epsilon, self.alpha - target)),
+ A * delta - C)
+
+ return torch.mean(losses)
+
+ def forward(self, output, target, target_weight):
+ """Forward function.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+
+ Args:
+ output (torch.Tensor[NxKxHxW]): Output heatmaps.
+ target (torch.Tensor[NxKxHxW]): Target heatmaps.
+ target_weight (torch.Tensor[NxKx1]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ loss = self.criterion(output * target_weight.unsqueeze(-1),
+ target * target_weight.unsqueeze(-1))
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mesh_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mesh_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9d18bd7296a189ec2f24c422cc05a19035d3224
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mesh_loss.py
@@ -0,0 +1,340 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+
+from ..builder import LOSSES
+from ..utils.geometry import batch_rodrigues
+
+
+def perspective_projection(points, rotation, translation, focal_length,
+ camera_center):
+ """This function computes the perspective projection of a set of 3D points.
+
+ Note:
+ - batch size: B
+ - point number: N
+
+ Args:
+ points (Tensor([B, N, 3])): A set of 3D points
+ rotation (Tensor([B, 3, 3])): Camera rotation matrix
+ translation (Tensor([B, 3])): Camera translation
+ focal_length (Tensor([B,])): Focal length
+ camera_center (Tensor([B, 2])): Camera center
+
+ Returns:
+ projected_points (Tensor([B, N, 2])): Projected 2D
+ points in image space.
+ """
+
+ batch_size = points.shape[0]
+ K = torch.zeros([batch_size, 3, 3], device=points.device)
+ K[:, 0, 0] = focal_length
+ K[:, 1, 1] = focal_length
+ K[:, 2, 2] = 1.
+ K[:, :-1, -1] = camera_center
+
+ # Transform points
+ points = torch.einsum('bij,bkj->bki', rotation, points)
+ points = points + translation.unsqueeze(1)
+
+ # Apply perspective distortion
+ projected_points = points / points[:, :, -1].unsqueeze(-1)
+
+ # Apply camera intrinsics
+ projected_points = torch.einsum('bij,bkj->bki', K, projected_points)
+ projected_points = projected_points[:, :, :-1]
+ return projected_points
+
+
+@LOSSES.register_module()
+class MeshLoss(nn.Module):
+ """Mix loss for 3D human mesh. It is composed of loss on 2D joints, 3D
+ joints, mesh vertices and smpl parameters (if any).
+
+ Args:
+ joints_2d_loss_weight (float): Weight for loss on 2D joints.
+ joints_3d_loss_weight (float): Weight for loss on 3D joints.
+ vertex_loss_weight (float): Weight for loss on 3D verteices.
+ smpl_pose_loss_weight (float): Weight for loss on SMPL
+ pose parameters.
+ smpl_beta_loss_weight (float): Weight for loss on SMPL
+ shape parameters.
+ img_res (int): Input image resolution.
+ focal_length (float): Focal length of camera model. Default=5000.
+ """
+
+ def __init__(self,
+ joints_2d_loss_weight,
+ joints_3d_loss_weight,
+ vertex_loss_weight,
+ smpl_pose_loss_weight,
+ smpl_beta_loss_weight,
+ img_res,
+ focal_length=5000):
+
+ super().__init__()
+ # Per-vertex loss on the mesh
+ self.criterion_vertex = nn.L1Loss(reduction='none')
+
+ # Joints (2D and 3D) loss
+ self.criterion_joints_2d = nn.SmoothL1Loss(reduction='none')
+ self.criterion_joints_3d = nn.SmoothL1Loss(reduction='none')
+
+ # Loss for SMPL parameter regression
+ self.criterion_regr = nn.MSELoss(reduction='none')
+
+ self.joints_2d_loss_weight = joints_2d_loss_weight
+ self.joints_3d_loss_weight = joints_3d_loss_weight
+ self.vertex_loss_weight = vertex_loss_weight
+ self.smpl_pose_loss_weight = smpl_pose_loss_weight
+ self.smpl_beta_loss_weight = smpl_beta_loss_weight
+ self.focal_length = focal_length
+ self.img_res = img_res
+
+ def joints_2d_loss(self, pred_joints_2d, gt_joints_2d, joints_2d_visible):
+ """Compute 2D reprojection loss on the joints.
+
+ The loss is weighted by joints_2d_visible.
+ """
+ conf = joints_2d_visible.float()
+ loss = (conf *
+ self.criterion_joints_2d(pred_joints_2d, gt_joints_2d)).mean()
+ return loss
+
+ def joints_3d_loss(self, pred_joints_3d, gt_joints_3d, joints_3d_visible):
+ """Compute 3D joints loss for the examples that 3D joint annotations
+ are available.
+
+ The loss is weighted by joints_3d_visible.
+ """
+ conf = joints_3d_visible.float()
+ if len(gt_joints_3d) > 0:
+ gt_pelvis = (gt_joints_3d[:, 2, :] + gt_joints_3d[:, 3, :]) / 2
+ gt_joints_3d = gt_joints_3d - gt_pelvis[:, None, :]
+ pred_pelvis = (pred_joints_3d[:, 2, :] +
+ pred_joints_3d[:, 3, :]) / 2
+ pred_joints_3d = pred_joints_3d - pred_pelvis[:, None, :]
+ return (
+ conf *
+ self.criterion_joints_3d(pred_joints_3d, gt_joints_3d)).mean()
+ return pred_joints_3d.sum() * 0
+
+ def vertex_loss(self, pred_vertices, gt_vertices, has_smpl):
+ """Compute 3D vertex loss for the examples that 3D human mesh
+ annotations are available.
+
+ The loss is weighted by the has_smpl.
+ """
+ conf = has_smpl.float()
+ loss_vertex = self.criterion_vertex(pred_vertices, gt_vertices)
+ loss_vertex = (conf[:, None, None] * loss_vertex).mean()
+ return loss_vertex
+
+ def smpl_losses(self, pred_rotmat, pred_betas, gt_pose, gt_betas,
+ has_smpl):
+ """Compute SMPL parameters loss for the examples that SMPL parameter
+ annotations are available.
+
+ The loss is weighted by has_smpl.
+ """
+ conf = has_smpl.float()
+ gt_rotmat = batch_rodrigues(gt_pose.view(-1, 3)).view(-1, 24, 3, 3)
+ loss_regr_pose = self.criterion_regr(pred_rotmat, gt_rotmat)
+ loss_regr_betas = self.criterion_regr(pred_betas, gt_betas)
+ loss_regr_pose = (conf[:, None, None, None] * loss_regr_pose).mean()
+ loss_regr_betas = (conf[:, None] * loss_regr_betas).mean()
+ return loss_regr_pose, loss_regr_betas
+
+ def project_points(self, points_3d, camera):
+ """Perform orthographic projection of 3D points using the camera
+ parameters, return projected 2D points in image plane.
+
+ Note:
+ - batch size: B
+ - point number: N
+
+ Args:
+ points_3d (Tensor([B, N, 3])): 3D points.
+ camera (Tensor([B, 3])): camera parameters with the
+ 3 channel as (scale, translation_x, translation_y)
+
+ Returns:
+ Tensor([B, N, 2]): projected 2D points \
+ in image space.
+ """
+ batch_size = points_3d.shape[0]
+ device = points_3d.device
+ cam_t = torch.stack([
+ camera[:, 1], camera[:, 2], 2 * self.focal_length /
+ (self.img_res * camera[:, 0] + 1e-9)
+ ],
+ dim=-1)
+ camera_center = camera.new_zeros([batch_size, 2])
+ rot_t = torch.eye(
+ 3, device=device,
+ dtype=points_3d.dtype).unsqueeze(0).expand(batch_size, -1, -1)
+ joints_2d = perspective_projection(
+ points_3d,
+ rotation=rot_t,
+ translation=cam_t,
+ focal_length=self.focal_length,
+ camera_center=camera_center)
+ return joints_2d
+
+ def forward(self, output, target):
+ """Forward function.
+
+ Args:
+ output (dict): dict of network predicted results.
+ Keys: 'vertices', 'joints_3d', 'camera',
+ 'pose'(optional), 'beta'(optional)
+ target (dict): dict of ground-truth labels.
+ Keys: 'vertices', 'joints_3d', 'joints_3d_visible',
+ 'joints_2d', 'joints_2d_visible', 'pose', 'beta',
+ 'has_smpl'
+
+ Returns:
+ dict: dict of losses.
+ """
+ losses = {}
+
+ # Per-vertex loss for the shape
+ pred_vertices = output['vertices']
+
+ gt_vertices = target['vertices']
+ has_smpl = target['has_smpl']
+ loss_vertex = self.vertex_loss(pred_vertices, gt_vertices, has_smpl)
+ losses['vertex_loss'] = loss_vertex * self.vertex_loss_weight
+
+ # Compute loss on SMPL parameters, if available
+ if 'pose' in output.keys() and 'beta' in output.keys():
+ pred_rotmat = output['pose']
+ pred_betas = output['beta']
+ gt_pose = target['pose']
+ gt_betas = target['beta']
+ loss_regr_pose, loss_regr_betas = self.smpl_losses(
+ pred_rotmat, pred_betas, gt_pose, gt_betas, has_smpl)
+ losses['smpl_pose_loss'] = \
+ loss_regr_pose * self.smpl_pose_loss_weight
+ losses['smpl_beta_loss'] = \
+ loss_regr_betas * self.smpl_beta_loss_weight
+
+ # Compute 3D joints loss
+ pred_joints_3d = output['joints_3d']
+ gt_joints_3d = target['joints_3d']
+ joints_3d_visible = target['joints_3d_visible']
+ loss_joints_3d = self.joints_3d_loss(pred_joints_3d, gt_joints_3d,
+ joints_3d_visible)
+ losses['joints_3d_loss'] = loss_joints_3d * self.joints_3d_loss_weight
+
+ # Compute 2D reprojection loss for the 2D joints
+ pred_camera = output['camera']
+ gt_joints_2d = target['joints_2d']
+ joints_2d_visible = target['joints_2d_visible']
+ pred_joints_2d = self.project_points(pred_joints_3d, pred_camera)
+
+ # Normalize keypoints to [-1,1]
+ # The coordinate origin of pred_joints_2d is
+ # the center of the input image.
+ pred_joints_2d = 2 * pred_joints_2d / (self.img_res - 1)
+ # The coordinate origin of gt_joints_2d is
+ # the top left corner of the input image.
+ gt_joints_2d = 2 * gt_joints_2d / (self.img_res - 1) - 1
+ loss_joints_2d = self.joints_2d_loss(pred_joints_2d, gt_joints_2d,
+ joints_2d_visible)
+ losses['joints_2d_loss'] = loss_joints_2d * self.joints_2d_loss_weight
+
+ return losses
+
+
+@LOSSES.register_module()
+class GANLoss(nn.Module):
+ """Define GAN loss.
+
+ Args:
+ gan_type (str): Support 'vanilla', 'lsgan', 'wgan', 'hinge'.
+ real_label_val (float): The value for real label. Default: 1.0.
+ fake_label_val (float): The value for fake label. Default: 0.0.
+ loss_weight (float): Loss weight. Default: 1.0.
+ Note that loss_weight is only for generators; and it is always 1.0
+ for discriminators.
+ """
+
+ def __init__(self,
+ gan_type,
+ real_label_val=1.0,
+ fake_label_val=0.0,
+ loss_weight=1.0):
+ super().__init__()
+ self.gan_type = gan_type
+ self.loss_weight = loss_weight
+ self.real_label_val = real_label_val
+ self.fake_label_val = fake_label_val
+
+ if self.gan_type == 'vanilla':
+ self.loss = nn.BCEWithLogitsLoss()
+ elif self.gan_type == 'lsgan':
+ self.loss = nn.MSELoss()
+ elif self.gan_type == 'wgan':
+ self.loss = self._wgan_loss
+ elif self.gan_type == 'hinge':
+ self.loss = nn.ReLU()
+ else:
+ raise NotImplementedError(
+ f'GAN type {self.gan_type} is not implemented.')
+
+ @staticmethod
+ def _wgan_loss(input, target):
+ """wgan loss.
+
+ Args:
+ input (Tensor): Input tensor.
+ target (bool): Target label.
+
+ Returns:
+ Tensor: wgan loss.
+ """
+ return -input.mean() if target else input.mean()
+
+ def get_target_label(self, input, target_is_real):
+ """Get target label.
+
+ Args:
+ input (Tensor): Input tensor.
+ target_is_real (bool): Whether the target is real or fake.
+
+ Returns:
+ (bool | Tensor): Target tensor. Return bool for wgan, \
+ otherwise, return Tensor.
+ """
+
+ if self.gan_type == 'wgan':
+ return target_is_real
+ target_val = (
+ self.real_label_val if target_is_real else self.fake_label_val)
+ return input.new_ones(input.size()) * target_val
+
+ def forward(self, input, target_is_real, is_disc=False):
+ """
+ Args:
+ input (Tensor): The input for the loss module, i.e., the network
+ prediction.
+ target_is_real (bool): Whether the targe is real or fake.
+ is_disc (bool): Whether the loss for discriminators or not.
+ Default: False.
+
+ Returns:
+ Tensor: GAN loss value.
+ """
+ target_label = self.get_target_label(input, target_is_real)
+ if self.gan_type == 'hinge':
+ if is_disc: # for discriminators in hinge-gan
+ input = -input if target_is_real else input
+ loss = self.loss(1 + input).mean()
+ else: # for generators in hinge-gan
+ loss = -input.mean()
+ else: # other gan types
+ loss = self.loss(input, target_label)
+
+ # loss_weight is always 1.0 for discriminators
+ return loss if is_disc else loss * self.loss_weight
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mse_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mse_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..f972efadfdfe0093c9ae1b308c6f82a9ccd72f73
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/mse_loss.py
@@ -0,0 +1,153 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+
+from ..builder import LOSSES
+
+
+@LOSSES.register_module()
+class JointsMSELoss(nn.Module):
+ """MSE loss for heatmaps.
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.criterion = nn.MSELoss()
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight):
+ """Forward function."""
+ batch_size = output.size(0)
+ num_joints = output.size(1)
+
+ heatmaps_pred = output.reshape(
+ (batch_size, num_joints, -1)).split(1, 1)
+ heatmaps_gt = target.reshape((batch_size, num_joints, -1)).split(1, 1)
+
+ loss = 0.
+
+ for idx in range(num_joints):
+ heatmap_pred = heatmaps_pred[idx].squeeze(1)
+ heatmap_gt = heatmaps_gt[idx].squeeze(1)
+ if self.use_target_weight:
+ loss += self.criterion(heatmap_pred * target_weight[:, idx],
+ heatmap_gt * target_weight[:, idx])
+ else:
+ loss += self.criterion(heatmap_pred, heatmap_gt)
+
+ return loss / num_joints * self.loss_weight
+
+
+@LOSSES.register_module()
+class CombinedTargetMSELoss(nn.Module):
+ """MSE loss for combined target.
+ CombinedTarget: The combination of classification target
+ (response map) and regression target (offset map).
+ Paper ref: Huang et al. The Devil is in the Details: Delving into
+ Unbiased Data Processing for Human Pose Estimation (CVPR 2020).
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, use_target_weight, loss_weight=1.):
+ super().__init__()
+ self.criterion = nn.MSELoss(reduction='mean')
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight):
+ batch_size = output.size(0)
+ num_channels = output.size(1)
+ heatmaps_pred = output.reshape(
+ (batch_size, num_channels, -1)).split(1, 1)
+ heatmaps_gt = target.reshape(
+ (batch_size, num_channels, -1)).split(1, 1)
+ loss = 0.
+ num_joints = num_channels // 3
+ for idx in range(num_joints):
+ heatmap_pred = heatmaps_pred[idx * 3].squeeze()
+ heatmap_gt = heatmaps_gt[idx * 3].squeeze()
+ offset_x_pred = heatmaps_pred[idx * 3 + 1].squeeze()
+ offset_x_gt = heatmaps_gt[idx * 3 + 1].squeeze()
+ offset_y_pred = heatmaps_pred[idx * 3 + 2].squeeze()
+ offset_y_gt = heatmaps_gt[idx * 3 + 2].squeeze()
+ if self.use_target_weight:
+ heatmap_pred = heatmap_pred * target_weight[:, idx]
+ heatmap_gt = heatmap_gt * target_weight[:, idx]
+ # classification loss
+ loss += 0.5 * self.criterion(heatmap_pred, heatmap_gt)
+ # regression loss
+ loss += 0.5 * self.criterion(heatmap_gt * offset_x_pred,
+ heatmap_gt * offset_x_gt)
+ loss += 0.5 * self.criterion(heatmap_gt * offset_y_pred,
+ heatmap_gt * offset_y_gt)
+ return loss / num_joints * self.loss_weight
+
+
+@LOSSES.register_module()
+class JointsOHKMMSELoss(nn.Module):
+ """MSE loss with online hard keypoint mining.
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ topk (int): Only top k joint losses are kept.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, use_target_weight=False, topk=8, loss_weight=1.):
+ super().__init__()
+ assert topk > 0
+ self.criterion = nn.MSELoss(reduction='none')
+ self.use_target_weight = use_target_weight
+ self.topk = topk
+ self.loss_weight = loss_weight
+
+ def _ohkm(self, loss):
+ """Online hard keypoint mining."""
+ ohkm_loss = 0.
+ N = len(loss)
+ for i in range(N):
+ sub_loss = loss[i]
+ _, topk_idx = torch.topk(
+ sub_loss, k=self.topk, dim=0, sorted=False)
+ tmp_loss = torch.gather(sub_loss, 0, topk_idx)
+ ohkm_loss += torch.sum(tmp_loss) / self.topk
+ ohkm_loss /= N
+ return ohkm_loss
+
+ def forward(self, output, target, target_weight):
+ """Forward function."""
+ batch_size = output.size(0)
+ num_joints = output.size(1)
+ if num_joints < self.topk:
+ raise ValueError(f'topk ({self.topk}) should not '
+ f'larger than num_joints ({num_joints}).')
+ heatmaps_pred = output.reshape(
+ (batch_size, num_joints, -1)).split(1, 1)
+ heatmaps_gt = target.reshape((batch_size, num_joints, -1)).split(1, 1)
+
+ losses = []
+ for idx in range(num_joints):
+ heatmap_pred = heatmaps_pred[idx].squeeze(1)
+ heatmap_gt = heatmaps_gt[idx].squeeze(1)
+ if self.use_target_weight:
+ losses.append(
+ self.criterion(heatmap_pred * target_weight[:, idx],
+ heatmap_gt * target_weight[:, idx]))
+ else:
+ losses.append(self.criterion(heatmap_pred, heatmap_gt))
+
+ losses = [loss.mean(dim=1).unsqueeze(dim=1) for loss in losses]
+ losses = torch.cat(losses, dim=1)
+
+ return self._ohkm(losses) * self.loss_weight
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/multi_loss_factory.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/multi_loss_factory.py
new file mode 100644
index 0000000000000000000000000000000000000000..65f90a761d0e5f94309023288f0d3ec848ec82dd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/multi_loss_factory.py
@@ -0,0 +1,281 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/HRNet/HigherHRNet-Human-Pose-Estimation
+# Original licence: Copyright (c) Microsoft, under the MIT License.
+# ------------------------------------------------------------------------------
+
+import torch
+import torch.nn as nn
+
+from ..builder import LOSSES
+
+
+def _make_input(t, requires_grad=False, device=torch.device('cpu')):
+ """Make zero inputs for AE loss.
+
+ Args:
+ t (torch.Tensor): input
+ requires_grad (bool): Option to use requires_grad.
+ device: torch device
+
+ Returns:
+ torch.Tensor: zero input.
+ """
+ inp = torch.autograd.Variable(t, requires_grad=requires_grad)
+ inp = inp.sum()
+ inp = inp.to(device)
+ return inp
+
+
+@LOSSES.register_module()
+class HeatmapLoss(nn.Module):
+ """Accumulate the heatmap loss for each image in the batch.
+
+ Args:
+ supervise_empty (bool): Whether to supervise empty channels.
+ """
+
+ def __init__(self, supervise_empty=True):
+ super().__init__()
+ self.supervise_empty = supervise_empty
+
+ def forward(self, pred, gt, mask):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - heatmaps weight: W
+ - heatmaps height: H
+ - max_num_people: M
+ - num_keypoints: K
+
+ Args:
+ pred (torch.Tensor[N,K,H,W]):heatmap of output.
+ gt (torch.Tensor[N,K,H,W]): target heatmap.
+ mask (torch.Tensor[N,H,W]): mask of target.
+ """
+ assert pred.size() == gt.size(
+ ), f'pred.size() is {pred.size()}, gt.size() is {gt.size()}'
+
+ if not self.supervise_empty:
+ empty_mask = (gt.sum(dim=[2, 3], keepdim=True) > 0).float()
+ loss = ((pred - gt)**2) * empty_mask.expand_as(
+ pred) * mask[:, None, :, :].expand_as(pred)
+ else:
+ loss = ((pred - gt)**2) * mask[:, None, :, :].expand_as(pred)
+ loss = loss.mean(dim=3).mean(dim=2).mean(dim=1)
+ return loss
+
+
+@LOSSES.register_module()
+class AELoss(nn.Module):
+ """Associative Embedding loss.
+
+ `Associative Embedding: End-to-End Learning for Joint Detection and
+ Grouping `_.
+ """
+
+ def __init__(self, loss_type):
+ super().__init__()
+ self.loss_type = loss_type
+
+ def singleTagLoss(self, pred_tag, joints):
+ """Associative embedding loss for one image.
+
+ Note:
+ - heatmaps weight: W
+ - heatmaps height: H
+ - max_num_people: M
+ - num_keypoints: K
+
+ Args:
+ pred_tag (torch.Tensor[KxHxW,1]): tag of output for one image.
+ joints (torch.Tensor[M,K,2]): joints information for one image.
+ """
+ tags = []
+ pull = 0
+ for joints_per_person in joints:
+ tmp = []
+ for joint in joints_per_person:
+ if joint[1] > 0:
+ tmp.append(pred_tag[joint[0]])
+ if len(tmp) == 0:
+ continue
+ tmp = torch.stack(tmp)
+ tags.append(torch.mean(tmp, dim=0))
+ pull = pull + torch.mean((tmp - tags[-1].expand_as(tmp))**2)
+
+ num_tags = len(tags)
+ if num_tags == 0:
+ return (
+ _make_input(torch.zeros(1).float(), device=pred_tag.device),
+ _make_input(torch.zeros(1).float(), device=pred_tag.device))
+ elif num_tags == 1:
+ return (_make_input(
+ torch.zeros(1).float(), device=pred_tag.device), pull)
+
+ tags = torch.stack(tags)
+
+ size = (num_tags, num_tags)
+ A = tags.expand(*size)
+ B = A.permute(1, 0)
+
+ diff = A - B
+
+ if self.loss_type == 'exp':
+ diff = torch.pow(diff, 2)
+ push = torch.exp(-diff)
+ push = torch.sum(push) - num_tags
+ elif self.loss_type == 'max':
+ diff = 1 - torch.abs(diff)
+ push = torch.clamp(diff, min=0).sum() - num_tags
+ else:
+ raise ValueError('Unknown ae loss type')
+
+ push_loss = push / ((num_tags - 1) * num_tags) * 0.5
+ pull_loss = pull / (num_tags)
+
+ return push_loss, pull_loss
+
+ def forward(self, tags, joints):
+ """Accumulate the tag loss for each image in the batch.
+
+ Note:
+ - batch_size: N
+ - heatmaps weight: W
+ - heatmaps height: H
+ - max_num_people: M
+ - num_keypoints: K
+
+ Args:
+ tags (torch.Tensor[N,KxHxW,1]): tag channels of output.
+ joints (torch.Tensor[N,M,K,2]): joints information.
+ """
+ pushes, pulls = [], []
+ joints = joints.cpu().data.numpy()
+ batch_size = tags.size(0)
+ for i in range(batch_size):
+ push, pull = self.singleTagLoss(tags[i], joints[i])
+ pushes.append(push)
+ pulls.append(pull)
+ return torch.stack(pushes), torch.stack(pulls)
+
+
+@LOSSES.register_module()
+class MultiLossFactory(nn.Module):
+ """Loss for bottom-up models.
+
+ Args:
+ num_joints (int): Number of keypoints.
+ num_stages (int): Number of stages.
+ ae_loss_type (str): Type of ae loss.
+ with_ae_loss (list[bool]): Use ae loss or not in multi-heatmap.
+ push_loss_factor (list[float]):
+ Parameter of push loss in multi-heatmap.
+ pull_loss_factor (list[float]):
+ Parameter of pull loss in multi-heatmap.
+ with_heatmap_loss (list[bool]):
+ Use heatmap loss or not in multi-heatmap.
+ heatmaps_loss_factor (list[float]):
+ Parameter of heatmap loss in multi-heatmap.
+ supervise_empty (bool): Whether to supervise empty channels.
+ """
+
+ def __init__(self,
+ num_joints,
+ num_stages,
+ ae_loss_type,
+ with_ae_loss,
+ push_loss_factor,
+ pull_loss_factor,
+ with_heatmaps_loss,
+ heatmaps_loss_factor,
+ supervise_empty=True):
+ super().__init__()
+
+ assert isinstance(with_heatmaps_loss, (list, tuple)), \
+ 'with_heatmaps_loss should be a list or tuple'
+ assert isinstance(heatmaps_loss_factor, (list, tuple)), \
+ 'heatmaps_loss_factor should be a list or tuple'
+ assert isinstance(with_ae_loss, (list, tuple)), \
+ 'with_ae_loss should be a list or tuple'
+ assert isinstance(push_loss_factor, (list, tuple)), \
+ 'push_loss_factor should be a list or tuple'
+ assert isinstance(pull_loss_factor, (list, tuple)), \
+ 'pull_loss_factor should be a list or tuple'
+
+ self.num_joints = num_joints
+ self.num_stages = num_stages
+ self.ae_loss_type = ae_loss_type
+ self.with_ae_loss = with_ae_loss
+ self.push_loss_factor = push_loss_factor
+ self.pull_loss_factor = pull_loss_factor
+ self.with_heatmaps_loss = with_heatmaps_loss
+ self.heatmaps_loss_factor = heatmaps_loss_factor
+
+ self.heatmaps_loss = \
+ nn.ModuleList(
+ [
+ HeatmapLoss(supervise_empty)
+ if with_heatmaps_loss else None
+ for with_heatmaps_loss in self.with_heatmaps_loss
+ ]
+ )
+
+ self.ae_loss = \
+ nn.ModuleList(
+ [
+ AELoss(self.ae_loss_type) if with_ae_loss else None
+ for with_ae_loss in self.with_ae_loss
+ ]
+ )
+
+ def forward(self, outputs, heatmaps, masks, joints):
+ """Forward function to calculate losses.
+
+ Note:
+ - batch_size: N
+ - heatmaps weight: W
+ - heatmaps height: H
+ - max_num_people: M
+ - num_keypoints: K
+ - output_channel: C C=2K if use ae loss else K
+
+ Args:
+ outputs (list(torch.Tensor[N,C,H,W])): outputs of stages.
+ heatmaps (list(torch.Tensor[N,K,H,W])): target of heatmaps.
+ masks (list(torch.Tensor[N,H,W])): masks of heatmaps.
+ joints (list(torch.Tensor[N,M,K,2])): joints of ae loss.
+ """
+ heatmaps_losses = []
+ push_losses = []
+ pull_losses = []
+ for idx in range(len(outputs)):
+ offset_feat = 0
+ if self.heatmaps_loss[idx]:
+ heatmaps_pred = outputs[idx][:, :self.num_joints]
+ offset_feat = self.num_joints
+ heatmaps_loss = self.heatmaps_loss[idx](heatmaps_pred,
+ heatmaps[idx],
+ masks[idx])
+ heatmaps_loss = heatmaps_loss * self.heatmaps_loss_factor[idx]
+ heatmaps_losses.append(heatmaps_loss)
+ else:
+ heatmaps_losses.append(None)
+
+ if self.ae_loss[idx]:
+ tags_pred = outputs[idx][:, offset_feat:]
+ batch_size = tags_pred.size()[0]
+ tags_pred = tags_pred.contiguous().view(batch_size, -1, 1)
+
+ push_loss, pull_loss = self.ae_loss[idx](tags_pred,
+ joints[idx])
+ push_loss = push_loss * self.push_loss_factor[idx]
+ pull_loss = pull_loss * self.pull_loss_factor[idx]
+
+ push_losses.append(push_loss)
+ pull_losses.append(pull_loss)
+ else:
+ push_losses.append(None)
+ pull_losses.append(None)
+
+ return heatmaps_losses, push_losses, pull_losses
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/regression_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/regression_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc7aa33847d8fdc8c6e096b7e3467759024af053
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/regression_loss.py
@@ -0,0 +1,530 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ..builder import LOSSES
+from ..utils.realnvp import RealNVP
+
+
+@LOSSES.register_module()
+class RLELoss(nn.Module):
+ """RLE Loss.
+
+ `Human Pose Regression With Residual Log-Likelihood Estimation
+ arXiv: `_.
+
+ Code is modified from `the official implementation
+ `_.
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ size_average (bool): Option to average the loss by the batch_size.
+ residual (bool): Option to add L1 loss and let the flow
+ learn the residual error distribution.
+ q_dis (string): Option for the identity Q(error) distribution,
+ Options: "laplace" or "gaussian"
+ """
+
+ def __init__(self,
+ use_target_weight=False,
+ size_average=True,
+ residual=True,
+ q_dis='laplace'):
+ super(RLELoss, self).__init__()
+ self.size_average = size_average
+ self.use_target_weight = use_target_weight
+ self.residual = residual
+ self.q_dis = q_dis
+
+ self.flow_model = RealNVP()
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D*2]): Output regression,
+ including coords and sigmas.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N, K, D]):
+ Weights across different joint types.
+ """
+ pred = output[:, :, :2]
+ sigma = output[:, :, 2:4].sigmoid()
+
+ error = (pred - target) / (sigma + 1e-9)
+ # (B, K, 2)
+ log_phi = self.flow_model.log_prob(error.reshape(-1, 2))
+ log_phi = log_phi.reshape(target.shape[0], target.shape[1], 1)
+ log_sigma = torch.log(sigma).reshape(target.shape[0], target.shape[1],
+ 2)
+ nf_loss = log_sigma - log_phi
+
+ if self.residual:
+ assert self.q_dis in ['laplace', 'gaussian', 'strict']
+ if self.q_dis == 'laplace':
+ loss_q = torch.log(sigma * 2) + torch.abs(error)
+ else:
+ loss_q = torch.log(
+ sigma * math.sqrt(2 * math.pi)) + 0.5 * error**2
+
+ loss = nf_loss + loss_q
+ else:
+ loss = nf_loss
+
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss *= target_weight
+
+ if self.size_average:
+ loss /= len(loss)
+
+ return loss.sum()
+
+
+@LOSSES.register_module()
+class SmoothL1Loss(nn.Module):
+ """SmoothL1Loss loss.
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.criterion = F.smooth_l1_loss
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N, K, D]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output * target_weight,
+ target * target_weight)
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class WingLoss(nn.Module):
+ """Wing Loss. paper ref: 'Wing Loss for Robust Facial Landmark Localisation
+ with Convolutional Neural Networks' Feng et al. CVPR'2018.
+
+ Args:
+ omega (float): Also referred to as width.
+ epsilon (float): Also referred to as curvature.
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self,
+ omega=10.0,
+ epsilon=2.0,
+ use_target_weight=False,
+ loss_weight=1.):
+ super().__init__()
+ self.omega = omega
+ self.epsilon = epsilon
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ # constant that smoothly links the piecewise-defined linear
+ # and nonlinear parts
+ self.C = self.omega * (1.0 - math.log(1.0 + self.omega / self.epsilon))
+
+ def criterion(self, pred, target):
+ """Criterion of wingloss.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ pred (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ """
+ delta = (target - pred).abs()
+ losses = torch.where(
+ delta < self.omega,
+ self.omega * torch.log(1.0 + delta / self.epsilon), delta - self.C)
+ return torch.mean(torch.sum(losses, dim=[1, 2]), dim=0)
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N,K,D]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output * target_weight,
+ target * target_weight)
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class SoftWingLoss(nn.Module):
+ """Soft Wing Loss 'Structure-Coherent Deep Feature Learning for Robust Face
+ Alignment' Lin et al. TIP'2021.
+
+ loss =
+ 1. |x| , if |x| < omega1
+ 2. omega2*ln(1+|x|/epsilon) + B, if |x| >= omega1
+
+ Args:
+ omega1 (float): The first threshold.
+ omega2 (float): The second threshold.
+ epsilon (float): Also referred to as curvature.
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self,
+ omega1=2.0,
+ omega2=20.0,
+ epsilon=0.5,
+ use_target_weight=False,
+ loss_weight=1.):
+ super().__init__()
+ self.omega1 = omega1
+ self.omega2 = omega2
+ self.epsilon = epsilon
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ # constant that smoothly links the piecewise-defined linear
+ # and nonlinear parts
+ self.B = self.omega1 - self.omega2 * math.log(1.0 + self.omega1 /
+ self.epsilon)
+
+ def criterion(self, pred, target):
+ """Criterion of wingloss.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ pred (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ """
+ delta = (target - pred).abs()
+ losses = torch.where(
+ delta < self.omega1, delta,
+ self.omega2 * torch.log(1.0 + delta / self.epsilon) + self.B)
+ return torch.mean(torch.sum(losses, dim=[1, 2]), dim=0)
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ batch_size: N
+ num_keypoints: K
+ dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N, K, D]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output * target_weight,
+ target * target_weight)
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class MPJPELoss(nn.Module):
+ """MPJPE (Mean Per Joint Position Error) loss.
+
+ Args:
+ use_target_weight (bool): Option to use weighted MSE loss.
+ Different joint types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N,K,D]):
+ Weights across different joint types.
+ """
+
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = torch.mean(
+ torch.norm((output - target) * target_weight, dim=-1))
+ else:
+ loss = torch.mean(torch.norm(output - target, dim=-1))
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class L1Loss(nn.Module):
+ """L1Loss loss ."""
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.criterion = F.l1_loss
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output regression.
+ target (torch.Tensor[N, K, 2]): Target regression.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output * target_weight,
+ target * target_weight)
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class MSELoss(nn.Module):
+ """MSE loss for coordinate regression."""
+
+ def __init__(self, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.criterion = F.mse_loss
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+
+ Args:
+ output (torch.Tensor[N, K, 2]): Output regression.
+ target (torch.Tensor[N, K, 2]): Target regression.
+ target_weight (torch.Tensor[N, K, 2]):
+ Weights across different joint types.
+ """
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = self.criterion(output * target_weight,
+ target * target_weight)
+ else:
+ loss = self.criterion(output, target)
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class BoneLoss(nn.Module):
+ """Bone length loss.
+
+ Args:
+ joint_parents (list): Indices of each joint's parent joint.
+ use_target_weight (bool): Option to use weighted bone loss.
+ Different bone types may have different target weights.
+ loss_weight (float): Weight of the loss. Default: 1.0.
+ """
+
+ def __init__(self, joint_parents, use_target_weight=False, loss_weight=1.):
+ super().__init__()
+ self.joint_parents = joint_parents
+ self.use_target_weight = use_target_weight
+ self.loss_weight = loss_weight
+
+ self.non_root_indices = []
+ for i in range(len(self.joint_parents)):
+ if i != self.joint_parents[i]:
+ self.non_root_indices.append(i)
+
+ def forward(self, output, target, target_weight=None):
+ """Forward function.
+
+ Note:
+ - batch_size: N
+ - num_keypoints: K
+ - dimension of keypoints: D (D=2 or D=3)
+
+ Args:
+ output (torch.Tensor[N, K, D]): Output regression.
+ target (torch.Tensor[N, K, D]): Target regression.
+ target_weight (torch.Tensor[N, K-1]):
+ Weights across different bone types.
+ """
+ output_bone = torch.norm(
+ output - output[:, self.joint_parents, :],
+ dim=-1)[:, self.non_root_indices]
+ target_bone = torch.norm(
+ target - target[:, self.joint_parents, :],
+ dim=-1)[:, self.non_root_indices]
+ if self.use_target_weight:
+ assert target_weight is not None
+ loss = torch.mean(
+ torch.abs((output_bone * target_weight).mean(dim=0) -
+ (target_bone * target_weight).mean(dim=0)))
+ else:
+ loss = torch.mean(
+ torch.abs(output_bone.mean(dim=0) - target_bone.mean(dim=0)))
+
+ return loss * self.loss_weight
+
+
+@LOSSES.register_module()
+class SemiSupervisionLoss(nn.Module):
+ """Semi-supervision loss for unlabeled data. It is composed of projection
+ loss and bone loss.
+
+ Paper ref: `3D human pose estimation in video with temporal convolutions
+ and semi-supervised training` Dario Pavllo et al. CVPR'2019.
+
+ Args:
+ joint_parents (list): Indices of each joint's parent joint.
+ projection_loss_weight (float): Weight for projection loss.
+ bone_loss_weight (float): Weight for bone loss.
+ warmup_iterations (int): Number of warmup iterations. In the first
+ `warmup_iterations` iterations, the model is trained only on
+ labeled data, and semi-supervision loss will be 0.
+ This is a workaround since currently we cannot access
+ epoch number in loss functions. Note that the iteration number in
+ an epoch can be changed due to different GPU numbers in multi-GPU
+ settings. So please set this parameter carefully.
+ warmup_iterations = dataset_size // samples_per_gpu // gpu_num
+ * warmup_epochs
+ """
+
+ def __init__(self,
+ joint_parents,
+ projection_loss_weight=1.,
+ bone_loss_weight=1.,
+ warmup_iterations=0):
+ super().__init__()
+ self.criterion_projection = MPJPELoss(
+ loss_weight=projection_loss_weight)
+ self.criterion_bone = BoneLoss(
+ joint_parents, loss_weight=bone_loss_weight)
+ self.warmup_iterations = warmup_iterations
+ self.num_iterations = 0
+
+ @staticmethod
+ def project_joints(x, intrinsics):
+ """Project 3D joint coordinates to 2D image plane using camera
+ intrinsic parameters.
+
+ Args:
+ x (torch.Tensor[N, K, 3]): 3D joint coordinates.
+ intrinsics (torch.Tensor[N, 4] | torch.Tensor[N, 9]): Camera
+ intrinsics: f (2), c (2), k (3), p (2).
+ """
+ while intrinsics.dim() < x.dim():
+ intrinsics.unsqueeze_(1)
+ f = intrinsics[..., :2]
+ c = intrinsics[..., 2:4]
+ _x = torch.clamp(x[:, :, :2] / x[:, :, 2:], -1, 1)
+ if intrinsics.shape[-1] == 9:
+ k = intrinsics[..., 4:7]
+ p = intrinsics[..., 7:9]
+
+ r2 = torch.sum(_x[:, :, :2]**2, dim=-1, keepdim=True)
+ radial = 1 + torch.sum(
+ k * torch.cat((r2, r2**2, r2**3), dim=-1),
+ dim=-1,
+ keepdim=True)
+ tan = torch.sum(p * _x, dim=-1, keepdim=True)
+ _x = _x * (radial + tan) + p * r2
+ _x = f * _x + c
+ return _x
+
+ def forward(self, output, target):
+ losses = dict()
+
+ self.num_iterations += 1
+ if self.num_iterations <= self.warmup_iterations:
+ return losses
+
+ labeled_pose = output['labeled_pose']
+ unlabeled_pose = output['unlabeled_pose']
+ unlabeled_traj = output['unlabeled_traj']
+ unlabeled_target_2d = target['unlabeled_target_2d']
+ intrinsics = target['intrinsics']
+
+ # projection loss
+ unlabeled_output = unlabeled_pose + unlabeled_traj
+ unlabeled_output_2d = self.project_joints(unlabeled_output, intrinsics)
+ loss_proj = self.criterion_projection(unlabeled_output_2d,
+ unlabeled_target_2d, None)
+ losses['proj_loss'] = loss_proj
+
+ # bone loss
+ loss_bone = self.criterion_bone(unlabeled_pose, labeled_pose, None)
+ losses['bone_loss'] = loss_bone
+
+ return losses
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/rle_loss.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/rle_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..5973da8df59dd4804af746bd7fb83a23fbb78c35
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/losses/rle_loss.py
@@ -0,0 +1,180 @@
+import math
+import mmcv
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ..builder import LOSSES
+
+
+@LOSSES.register_module()
+class RLELoss_poseur_old(nn.Module):
+ ''' RLE Regression Loss
+ '''
+
+ def __init__(self, OUTPUT_3D=False, use_target_weight=True, size_average=True):
+ super(RLELoss_poseur_old, self).__init__()
+ self.size_average = size_average
+ self.amp = 1 / math.sqrt(2 * math.pi)
+
+ def logQ(self, gt_uv, pred_jts, sigma):
+ return torch.log(sigma / self.amp) + torch.abs(gt_uv - pred_jts) / (math.sqrt(2) * sigma + 1e-9)
+
+ def forward(self, output, target_uv, target_uv_weight):
+
+ pred_jts = output.pred_jts
+ sigma = output.sigma
+ gt_uv = target_uv.reshape(pred_jts.shape)
+ gt_uv_weight = target_uv_weight.reshape(pred_jts.shape)
+
+
+
+ nf_loss = output.nf_loss * gt_uv_weight[:, :, :1]
+ # print(gt_uv.min(), gt_uv.max())
+
+ residual = True
+ if residual:
+ Q_logprob = self.logQ(gt_uv, pred_jts, sigma) * gt_uv_weight
+ loss = nf_loss + Q_logprob
+
+ if self.size_average and gt_uv_weight.sum() > 0:
+ return loss.sum() / len(loss)
+ else:
+ return loss.sum()
+
+@LOSSES.register_module()
+class RLELoss_poseur(nn.Module):
+ ''' RLE Regression Loss
+ '''
+
+ def __init__(self, OUTPUT_3D=False, use_target_weight=True, size_average=True):
+ super(RLELoss_poseur, self).__init__()
+ self.size_average = size_average
+ self.amp = 1 / math.sqrt(2 * math.pi)
+
+ def logQ(self, gt_uv, pred_jts, sigma):
+ return torch.log(sigma / self.amp) + torch.abs(gt_uv - pred_jts) / (math.sqrt(2) * sigma + 1e-9)
+
+ def forward(self, output, target_uvd, target_uvd_weight):
+
+ pred_jts = output.pred_jts
+ sigma = output.sigma
+ gt_uv = target_uvd.reshape(pred_jts.shape)
+ gt_uv_weight = target_uvd_weight.reshape(pred_jts.shape)
+
+ # nf_loss = output.nf_loss * gt_uv_weight[:, :, :1]
+ nf_loss = output.nf_loss * gt_uv_weight
+
+ residual = True
+ if residual:
+ Q_logprob = self.logQ(gt_uv, pred_jts, sigma) * gt_uv_weight
+ loss = nf_loss + Q_logprob
+
+ if self.size_average and gt_uv_weight.sum() > 0:
+ return loss.sum() / len(loss)
+ else:
+ return loss.sum()
+
+@LOSSES.register_module()
+class RLEOHKMLoss(nn.Module):
+ ''' RLE Regression Loss
+ '''
+
+ def __init__(self, OUTPUT_3D=False, use_target_weight=True, size_average=True, topk=8,
+ ori_weight = 1.0, ohkm_weight = 0.0):
+ super(RLEOHKMLoss, self).__init__()
+ self.size_average = size_average
+ self.amp = 1 / math.sqrt(2 * math.pi)
+ self.topk = topk
+ self.ori_weight = ori_weight
+ self.ohkm_weight = ohkm_weight
+ self.neg_inf = -float("Inf")
+
+ def logQ(self, gt_uv, pred_jts, sigma):
+ return torch.log(sigma / self.amp) + torch.abs(gt_uv - pred_jts) / (math.sqrt(2) * sigma + 1e-9)
+
+ def ohkm(self, loss, weight):
+ # mask = weight == 0
+ loss_value = loss.clone().detach()
+ loss_value[weight == 0] = self.neg_inf
+ _, topk_idx = torch.topk(
+ loss_value, k=self.topk, dim=1, sorted=False)
+ tmp_loss = torch.gather(loss, 1, topk_idx)
+ tmp_weight = torch.gather(weight, 1, topk_idx)
+ # tmp_loss[tmp_loss==-float("Inf")] = 0
+ tmp_loss = tmp_loss * tmp_weight
+ tmp_loss = tmp_loss.flatten(start_dim=1).sum(dim = 1)
+ # tmp_weight = tmp_weight.flatten(start_dim=1).sum(dim = 1)
+ # tmp_loss = tmp_loss / tmp_weight
+
+ return tmp_loss.mean()
+
+ def ori(self, loss, weight):
+ # mask = weight == 0
+ loss = loss * weight
+ loss = loss.flatten(start_dim=1).sum(dim = 1)
+ # weight = weight.flatten(start_dim=1).sum(dim = 1)
+
+ return loss.mean()
+
+ def forward(self, output, target_uv, target_uv_weight):
+
+ pred_jts = output.pred_jts
+ sigma = output.sigma
+ gt_uv = target_uv.reshape(pred_jts.shape)
+ gt_uv_weight = target_uv_weight.reshape(pred_jts.shape)
+
+ # gt_uv_weight = gt_uv_weight[:, :, :1]
+ nf_loss = output.nf_loss
+ q_loss = self.logQ(gt_uv, pred_jts, sigma)
+
+ # nf_loss_ohkm = self.ohkm(nf_loss, gt_uv_weight)
+ # q_loss_ohkm = self.ohkm(q_loss, gt_uv_weight)
+
+ ori_loss = nf_loss + q_loss
+ ohkm_loss = self.ohkm(ori_loss, gt_uv_weight)
+ ori_loss = self.ori(ori_loss, gt_uv_weight)
+
+ loss = self.ori_weight * ori_loss + self.ohkm_weight * ohkm_loss
+ return loss #TODO mean?
+
+
+ # nf_loss = output.nf_loss * gt_uv_weight
+
+
+ # Q_logprob = self.logQ(gt_uv, pred_jts, sigma) * gt_uv_weight
+ # loss = nf_loss + Q_logprob
+
+ # return loss.sum() / len(loss)
+
+
+@LOSSES.register_module()
+class RLELoss3D(nn.Module):
+ ''' RLE Regression Loss 3D
+ '''
+
+ def __init__(self, OUTPUT_3D=False, size_average=True):
+ super(RLELoss3D, self).__init__()
+ self.size_average = size_average
+ self.amp = 1 / math.sqrt(2 * math.pi)
+
+ def logQ(self, gt_uv, pred_jts, sigma):
+ return torch.log(sigma / self.amp) + torch.abs(gt_uv - pred_jts) / (math.sqrt(2) * sigma + 1e-9)
+
+ def forward(self, output, labels):
+ nf_loss = output.nf_loss
+ pred_jts = output.pred_jts
+ sigma = output.sigma
+ gt_uv = labels['target_uvd'].reshape(pred_jts.shape)
+ gt_uv_weight = labels['target_uvd_weight'].reshape(pred_jts.shape)
+ nf_loss = nf_loss * gt_uv_weight
+
+ residual = True
+ if residual:
+ Q_logprob = self.logQ(gt_uv, pred_jts, sigma) * gt_uv_weight
+ loss = nf_loss + Q_logprob
+
+ if self.size_average and gt_uv_weight.sum() > 0:
+ return loss.sum() / len(loss)
+ else:
+ return loss.sum()
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ef101fec61e72abc0eb90266d453b5b22331378d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/__init__.py
@@ -0,0 +1 @@
+# Copyright (c) OpenMMLab. All rights reserved.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/discriminator.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/discriminator.py
new file mode 100644
index 0000000000000000000000000000000000000000..712f0a8b566e3dcbc0cd13206610d3c750b942ab
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/misc/discriminator.py
@@ -0,0 +1,307 @@
+# ------------------------------------------------------------------------------
+# Adapted from https://github.com/akanazawa/hmr
+# Original licence: Copyright (c) 2018 akanazawa, under the MIT License.
+# ------------------------------------------------------------------------------
+
+from abc import abstractmethod
+
+import torch
+import torch.nn as nn
+from mmcv.cnn import normal_init, xavier_init
+
+from mmpose.models.utils.geometry import batch_rodrigues
+
+
+class BaseDiscriminator(nn.Module):
+ """Base linear module for SMPL parameter discriminator.
+
+ Args:
+ fc_layers (Tuple): Tuple of neuron count,
+ such as (9, 32, 32, 1)
+ use_dropout (Tuple): Tuple of bool define use dropout or not
+ for each layer, such as (True, True, False)
+ drop_prob (Tuple): Tuple of float defined the drop prob,
+ such as (0.5, 0.5, 0)
+ use_activation(Tuple): Tuple of bool define use active function
+ or not, such as (True, True, False)
+ """
+
+ def __init__(self, fc_layers, use_dropout, drop_prob, use_activation):
+ super().__init__()
+ self.fc_layers = fc_layers
+ self.use_dropout = use_dropout
+ self.drop_prob = drop_prob
+ self.use_activation = use_activation
+ self._check()
+ self.create_layers()
+
+ def _check(self):
+ """Check input to avoid ValueError."""
+ if not isinstance(self.fc_layers, tuple):
+ raise TypeError(f'fc_layers require tuple, '
+ f'get {type(self.fc_layers)}')
+
+ if not isinstance(self.use_dropout, tuple):
+ raise TypeError(f'use_dropout require tuple, '
+ f'get {type(self.use_dropout)}')
+
+ if not isinstance(self.drop_prob, tuple):
+ raise TypeError(f'drop_prob require tuple, '
+ f'get {type(self.drop_prob)}')
+
+ if not isinstance(self.use_activation, tuple):
+ raise TypeError(f'use_activation require tuple, '
+ f'get {type(self.use_activation)}')
+
+ l_fc_layer = len(self.fc_layers)
+ l_use_drop = len(self.use_dropout)
+ l_drop_prob = len(self.drop_prob)
+ l_use_activation = len(self.use_activation)
+
+ pass_check = (
+ l_fc_layer >= 2 and l_use_drop < l_fc_layer
+ and l_drop_prob < l_fc_layer and l_use_activation < l_fc_layer
+ and l_drop_prob == l_use_drop)
+
+ if not pass_check:
+ msg = 'Wrong BaseDiscriminator parameters!'
+ raise ValueError(msg)
+
+ def create_layers(self):
+ """Create layers."""
+ l_fc_layer = len(self.fc_layers)
+ l_use_drop = len(self.use_dropout)
+ l_use_activation = len(self.use_activation)
+
+ self.fc_blocks = nn.Sequential()
+
+ for i in range(l_fc_layer - 1):
+ self.fc_blocks.add_module(
+ name=f'regressor_fc_{i}',
+ module=nn.Linear(
+ in_features=self.fc_layers[i],
+ out_features=self.fc_layers[i + 1]))
+
+ if i < l_use_activation and self.use_activation[i]:
+ self.fc_blocks.add_module(
+ name=f'regressor_af_{i}', module=nn.ReLU())
+
+ if i < l_use_drop and self.use_dropout[i]:
+ self.fc_blocks.add_module(
+ name=f'regressor_fc_dropout_{i}',
+ module=nn.Dropout(p=self.drop_prob[i]))
+
+ @abstractmethod
+ def forward(self, inputs):
+ """Forward function."""
+ msg = 'the base class [BaseDiscriminator] is not callable!'
+ raise NotImplementedError(msg)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for m in self.fc_blocks.named_modules():
+ if isinstance(m, nn.Linear):
+ xavier_init(m, gain=0.01)
+
+
+class ShapeDiscriminator(BaseDiscriminator):
+ """Discriminator for SMPL shape parameters, the inputs is (batch_size x 10)
+
+ Args:
+ fc_layers (Tuple): Tuple of neuron count, such as (10, 5, 1)
+ use_dropout (Tuple): Tuple of bool define use dropout or
+ not for each layer, such as (True, True, False)
+ drop_prob (Tuple): Tuple of float defined the drop prob,
+ such as (0.5, 0)
+ use_activation(Tuple): Tuple of bool define use active
+ function or not, such as (True, False)
+ """
+
+ def __init__(self, fc_layers, use_dropout, drop_prob, use_activation):
+ if fc_layers[-1] != 1:
+ msg = f'the neuron count of the last layer ' \
+ f'must be 1, but got {fc_layers[-1]}'
+ raise ValueError(msg)
+
+ super().__init__(fc_layers, use_dropout, drop_prob, use_activation)
+
+ def forward(self, inputs):
+ """Forward function."""
+ return self.fc_blocks(inputs)
+
+
+class PoseDiscriminator(nn.Module):
+ """Discriminator for SMPL pose parameters of each joint. It is composed of
+ discriminators for each joints. The inputs is (batch_size x joint_count x
+ 9)
+
+ Args:
+ channels (Tuple): Tuple of channel number,
+ such as (9, 32, 32, 1)
+ joint_count (int): Joint number, such as 23
+ """
+
+ def __init__(self, channels, joint_count):
+ super().__init__()
+ if channels[-1] != 1:
+ msg = f'the neuron count of the last layer ' \
+ f'must be 1, but got {channels[-1]}'
+ raise ValueError(msg)
+ self.joint_count = joint_count
+
+ self.conv_blocks = nn.Sequential()
+ len_channels = len(channels)
+ for idx in range(len_channels - 2):
+ self.conv_blocks.add_module(
+ name=f'conv_{idx}',
+ module=nn.Conv2d(
+ in_channels=channels[idx],
+ out_channels=channels[idx + 1],
+ kernel_size=1,
+ stride=1))
+
+ self.fc_layer = nn.ModuleList()
+ for idx in range(joint_count):
+ self.fc_layer.append(
+ nn.Linear(
+ in_features=channels[len_channels - 2], out_features=1))
+
+ def forward(self, inputs):
+ """Forward function.
+
+ The input is (batch_size x joint_count x 9).
+ """
+ # shape: batch_size x 9 x 1 x joint_count
+ inputs = inputs.transpose(1, 2).unsqueeze(2).contiguous()
+ # shape: batch_size x c x 1 x joint_count
+ internal_outputs = self.conv_blocks(inputs)
+ outputs = []
+ for idx in range(self.joint_count):
+ outputs.append(self.fc_layer[idx](internal_outputs[:, :, 0, idx]))
+
+ return torch.cat(outputs, 1), internal_outputs
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for m in self.conv_blocks:
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001, bias=0)
+ for m in self.fc_layer.named_modules():
+ if isinstance(m, nn.Linear):
+ xavier_init(m, gain=0.01)
+
+
+class FullPoseDiscriminator(BaseDiscriminator):
+ """Discriminator for SMPL pose parameters of all joints.
+
+ Args:
+ fc_layers (Tuple): Tuple of neuron count,
+ such as (736, 1024, 1024, 1)
+ use_dropout (Tuple): Tuple of bool define use dropout or not
+ for each layer, such as (True, True, False)
+ drop_prob (Tuple): Tuple of float defined the drop prob,
+ such as (0.5, 0.5, 0)
+ use_activation(Tuple): Tuple of bool define use active
+ function or not, such as (True, True, False)
+ """
+
+ def __init__(self, fc_layers, use_dropout, drop_prob, use_activation):
+ if fc_layers[-1] != 1:
+ msg = f'the neuron count of the last layer must be 1,' \
+ f' but got {fc_layers[-1]}'
+ raise ValueError(msg)
+
+ super().__init__(fc_layers, use_dropout, drop_prob, use_activation)
+
+ def forward(self, inputs):
+ """Forward function."""
+ return self.fc_blocks(inputs)
+
+
+class SMPLDiscriminator(nn.Module):
+ """Discriminator for SMPL pose and shape parameters. It is composed of a
+ discriminator for SMPL shape parameters, a discriminator for SMPL pose
+ parameters of all joints and a discriminator for SMPL pose parameters of
+ each joint.
+
+ Args:
+ beta_channel (tuple of int): Tuple of neuron count of the
+ discriminator of shape parameters. Defaults to (10, 5, 1)
+ per_joint_channel (tuple of int): Tuple of neuron count of the
+ discriminator of each joint. Defaults to (9, 32, 32, 1)
+ full_pose_channel (tuple of int): Tuple of neuron count of the
+ discriminator of full pose. Defaults to (23*32, 1024, 1024, 1)
+ """
+
+ def __init__(self,
+ beta_channel=(10, 5, 1),
+ per_joint_channel=(9, 32, 32, 1),
+ full_pose_channel=(23 * 32, 1024, 1024, 1)):
+ super().__init__()
+ self.joint_count = 23
+ # The count of SMPL shape parameter is 10.
+ assert beta_channel[0] == 10
+ # Use 3 x 3 rotation matrix as the pose parameters
+ # of each joint, so the input channel is 9.
+ assert per_joint_channel[0] == 9
+ assert self.joint_count * per_joint_channel[-2] \
+ == full_pose_channel[0]
+
+ self.beta_channel = beta_channel
+ self.per_joint_channel = per_joint_channel
+ self.full_pose_channel = full_pose_channel
+ self._create_sub_modules()
+
+ def _create_sub_modules(self):
+ """Create sub discriminators."""
+
+ # create theta discriminator for each joint
+ self.pose_discriminator = PoseDiscriminator(self.per_joint_channel,
+ self.joint_count)
+
+ # create full pose discriminator for total joints
+ fc_layers = self.full_pose_channel
+ use_dropout = tuple([False] * (len(fc_layers) - 1))
+ drop_prob = tuple([0.5] * (len(fc_layers) - 1))
+ use_activation = tuple([True] * (len(fc_layers) - 2) + [False])
+
+ self.full_pose_discriminator = FullPoseDiscriminator(
+ fc_layers, use_dropout, drop_prob, use_activation)
+
+ # create shape discriminator for betas
+ fc_layers = self.beta_channel
+ use_dropout = tuple([False] * (len(fc_layers) - 1))
+ drop_prob = tuple([0.5] * (len(fc_layers) - 1))
+ use_activation = tuple([True] * (len(fc_layers) - 2) + [False])
+ self.shape_discriminator = ShapeDiscriminator(fc_layers, use_dropout,
+ drop_prob,
+ use_activation)
+
+ def forward(self, thetas):
+ """Forward function."""
+ _, poses, shapes = thetas
+
+ batch_size = poses.shape[0]
+ shape_disc_value = self.shape_discriminator(shapes)
+
+ # The first rotation matrix is global rotation
+ # and is NOT used in discriminator.
+ if poses.dim() == 2:
+ rotate_matrixs = \
+ batch_rodrigues(poses.contiguous().view(-1, 3)
+ ).view(batch_size, 24, 9)[:, 1:, :]
+ else:
+ rotate_matrixs = poses.contiguous().view(batch_size, 24,
+ 9)[:, 1:, :].contiguous()
+ pose_disc_value, pose_inter_disc_value \
+ = self.pose_discriminator(rotate_matrixs)
+ full_pose_disc_value = self.full_pose_discriminator(
+ pose_inter_disc_value.contiguous().view(batch_size, -1))
+ return torch.cat(
+ (pose_disc_value, full_pose_disc_value, shape_disc_value), 1)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ self.full_pose_discriminator.init_weights()
+ self.pose_discriminator.init_weights()
+ self.shape_discriminator.init_weights()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..0593f61c01fa9968260b939f7ccd50311c058595
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/__init__.py
@@ -0,0 +1,8 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .fpn import FPN
+from .gap_neck import GlobalAveragePooling
+from .posewarper_neck import PoseWarperNeck
+from .tcformer_mta_neck import MTA
+from .channel_mapper import ChannelMapper
+
+__all__ = ['GlobalAveragePooling', 'PoseWarperNeck', 'FPN', 'MTA']
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/channel_mapper.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/channel_mapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..113d170e9d55b9e2d3984c6838a86e4c659fa75c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/channel_mapper.py
@@ -0,0 +1,76 @@
+import torch.nn as nn
+from mmcv.cnn import ConvModule, xavier_init
+
+from ..builder import NECKS
+
+
+@NECKS.register_module()
+class ChannelMapper(nn.Module):
+ r"""Channel Mapper to reduce/increase channels of backbone features.
+
+ This is used to reduce/increase channels of backbone features.
+
+ Args:
+ in_channels (List[int]): Number of input channels per scale.
+ out_channels (int): Number of output channels (used at each scale).
+ kernel_size (int, optional): kernel_size for reducing channels (used
+ at each scale). Default: 3.
+ conv_cfg (dict, optional): Config dict for convolution layer.
+ Default: None.
+ norm_cfg (dict, optional): Config dict for normalization layer.
+ Default: None.
+ act_cfg (dict, optional): Config dict for activation layer in
+ ConvModule. Default: dict(type='ReLU').
+
+ Example:
+ >>> import torch
+ >>> in_channels = [2, 3, 5, 7]
+ >>> scales = [340, 170, 84, 43]
+ >>> inputs = [torch.rand(1, c, s, s)
+ ... for c, s in zip(in_channels, scales)]
+ >>> self = ChannelMapper(in_channels, 11, 3).eval()
+ >>> outputs = self.forward(inputs)
+ >>> for i in range(len(outputs)):
+ ... print(f'outputs[{i}].shape = {outputs[i].shape}')
+ outputs[0].shape = torch.Size([1, 11, 340, 340])
+ outputs[1].shape = torch.Size([1, 11, 170, 170])
+ outputs[2].shape = torch.Size([1, 11, 84, 84])
+ outputs[3].shape = torch.Size([1, 11, 43, 43])
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ kernel_size=3,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=dict(type='ReLU')):
+ super(ChannelMapper, self).__init__()
+ assert isinstance(in_channels, list)
+
+ self.convs = nn.ModuleList()
+ for in_channel in in_channels:
+ self.convs.append(
+ ConvModule(
+ in_channel,
+ out_channels,
+ kernel_size,
+ padding=(kernel_size - 1) // 2,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg))
+
+ # default init_weights for conv(msra) and norm in ConvModule
+ def init_weights(self):
+ """Initialize the weights of ChannelMapper module."""
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ xavier_init(m, distribution='uniform')
+
+ def forward(self, inputs):
+ """Forward function."""
+
+
+ assert len(inputs) == len(self.convs)
+ outs = [self.convs[i](inputs[i]) for i in range(len(inputs))]
+ return tuple(outs)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/fpn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/fpn.py
new file mode 100644
index 0000000000000000000000000000000000000000..795a8af0b6904153a9b4e1a41d7b803381874162
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/fpn.py
@@ -0,0 +1,207 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import ConvModule, xavier_init
+from mmcv.runner import auto_fp16
+
+from ..builder import NECKS
+
+
+@NECKS.register_module()
+class FPN(nn.Module):
+ r"""Feature Pyramid Network.
+
+ This is an implementation of paper `Feature Pyramid Networks for Object
+ Detection `_.
+
+ Args:
+ in_channels (list[int]): Number of input channels per scale.
+ out_channels (int): Number of output channels (used at each scale).
+ num_outs (int): Number of output scales.
+ start_level (int): Index of the start input backbone level used to
+ build the feature pyramid. Default: 0.
+ end_level (int): Index of the end input backbone level (exclusive) to
+ build the feature pyramid. Default: -1, which means the last level.
+ add_extra_convs (bool | str): If bool, it decides whether to add conv
+ layers on top of the original feature maps. Default to False.
+ If True, it is equivalent to `add_extra_convs='on_input'`.
+ If str, it specifies the source feature map of the extra convs.
+ Only the following options are allowed
+
+ - 'on_input': Last feat map of neck inputs (i.e. backbone feature).
+ - 'on_lateral': Last feature map after lateral convs.
+ - 'on_output': The last output feature map after fpn convs.
+ relu_before_extra_convs (bool): Whether to apply relu before the extra
+ conv. Default: False.
+ no_norm_on_lateral (bool): Whether to apply norm on lateral.
+ Default: False.
+ conv_cfg (dict): Config dict for convolution layer. Default: None.
+ norm_cfg (dict): Config dict for normalization layer. Default: None.
+ act_cfg (dict): Config dict for activation layer in ConvModule.
+ Default: None.
+ upsample_cfg (dict): Config dict for interpolate layer.
+ Default: dict(mode='nearest').
+
+ Example:
+ >>> import torch
+ >>> in_channels = [2, 3, 5, 7]
+ >>> scales = [340, 170, 84, 43]
+ >>> inputs = [torch.rand(1, c, s, s)
+ ... for c, s in zip(in_channels, scales)]
+ >>> self = FPN(in_channels, 11, len(in_channels)).eval()
+ >>> outputs = self.forward(inputs)
+ >>> for i in range(len(outputs)):
+ ... print(f'outputs[{i}].shape = {outputs[i].shape}')
+ outputs[0].shape = torch.Size([1, 11, 340, 340])
+ outputs[1].shape = torch.Size([1, 11, 170, 170])
+ outputs[2].shape = torch.Size([1, 11, 84, 84])
+ outputs[3].shape = torch.Size([1, 11, 43, 43])
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ num_outs,
+ start_level=0,
+ end_level=-1,
+ add_extra_convs=False,
+ relu_before_extra_convs=False,
+ no_norm_on_lateral=False,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=None,
+ upsample_cfg=dict(mode='nearest')):
+ super().__init__()
+ assert isinstance(in_channels, list)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.num_ins = len(in_channels)
+ self.num_outs = num_outs
+ self.relu_before_extra_convs = relu_before_extra_convs
+ self.no_norm_on_lateral = no_norm_on_lateral
+ self.fp16_enabled = False
+ self.upsample_cfg = upsample_cfg.copy()
+
+ if end_level == -1 or end_level == self.num_ins - 1:
+ self.backbone_end_level = self.num_ins
+ assert num_outs >= self.num_ins - start_level
+ else:
+ # if end_level is not the last level, no extra level is allowed
+ self.backbone_end_level = end_level + 1
+ assert end_level < self.num_ins
+ assert num_outs == end_level - start_level + 1
+ self.start_level = start_level
+ self.end_level = end_level
+ self.add_extra_convs = add_extra_convs
+ assert isinstance(add_extra_convs, (str, bool))
+ if isinstance(add_extra_convs, str):
+ # Extra_convs_source choices: 'on_input', 'on_lateral', 'on_output'
+ assert add_extra_convs in ('on_input', 'on_lateral', 'on_output')
+ elif add_extra_convs: # True
+ self.add_extra_convs = 'on_input'
+
+ self.lateral_convs = nn.ModuleList()
+ self.fpn_convs = nn.ModuleList()
+
+ for i in range(self.start_level, self.backbone_end_level):
+ l_conv = ConvModule(
+ in_channels[i],
+ out_channels,
+ 1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,
+ act_cfg=act_cfg,
+ inplace=False)
+ fpn_conv = ConvModule(
+ out_channels,
+ out_channels,
+ 3,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ inplace=False)
+
+ self.lateral_convs.append(l_conv)
+ self.fpn_convs.append(fpn_conv)
+
+ # add extra conv layers (e.g., RetinaNet)
+ extra_levels = num_outs - self.backbone_end_level + self.start_level
+ if self.add_extra_convs and extra_levels >= 1:
+ for i in range(extra_levels):
+ if i == 0 and self.add_extra_convs == 'on_input':
+ in_channels = self.in_channels[self.backbone_end_level - 1]
+ else:
+ in_channels = out_channels
+ extra_fpn_conv = ConvModule(
+ in_channels,
+ out_channels,
+ 3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ inplace=False)
+ self.fpn_convs.append(extra_fpn_conv)
+
+ def init_weights(self):
+ """Initialize model weights."""
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ xavier_init(m, distribution='uniform')
+
+ @auto_fp16()
+ def forward(self, inputs):
+ """Forward function."""
+ assert len(inputs) == len(self.in_channels)
+
+ # build laterals
+ laterals = [
+ lateral_conv(inputs[i + self.start_level])
+ for i, lateral_conv in enumerate(self.lateral_convs)
+ ]
+
+ # build top-down path
+ used_backbone_levels = len(laterals)
+ for i in range(used_backbone_levels - 1, 0, -1):
+ # In some cases, fixing `scale factor` (e.g. 2) is preferred, but
+ # it cannot co-exist with `size` in `F.interpolate`.
+ if 'scale_factor' in self.upsample_cfg:
+ # fix runtime error of "+=" inplace operation in PyTorch 1.10
+ laterals[i - 1] = laterals[i - 1] + F.interpolate(
+ laterals[i], **self.upsample_cfg)
+ else:
+ prev_shape = laterals[i - 1].shape[2:]
+ laterals[i - 1] = laterals[i - 1] + F.interpolate(
+ laterals[i], size=prev_shape, **self.upsample_cfg)
+
+ # build outputs
+ # part 1: from original levels
+ outs = [
+ self.fpn_convs[i](laterals[i]) for i in range(used_backbone_levels)
+ ]
+ # part 2: add extra levels
+ if self.num_outs > len(outs):
+ # use max pool to get more levels on top of outputs
+ # (e.g., Faster R-CNN, Mask R-CNN)
+ if not self.add_extra_convs:
+ for i in range(self.num_outs - used_backbone_levels):
+ outs.append(F.max_pool2d(outs[-1], 1, stride=2))
+ # add conv layers on top of original feature maps (RetinaNet)
+ else:
+ if self.add_extra_convs == 'on_input':
+ extra_source = inputs[self.backbone_end_level - 1]
+ elif self.add_extra_convs == 'on_lateral':
+ extra_source = laterals[-1]
+ elif self.add_extra_convs == 'on_output':
+ extra_source = outs[-1]
+ else:
+ raise NotImplementedError
+ outs.append(self.fpn_convs[used_backbone_levels](extra_source))
+ for i in range(used_backbone_levels + 1, self.num_outs):
+ if self.relu_before_extra_convs:
+ outs.append(self.fpn_convs[i](F.relu(outs[-1])))
+ else:
+ outs.append(self.fpn_convs[i](outs[-1]))
+ return outs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/gap_neck.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/gap_neck.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e6ad68ec11110daaad3a66e09d67efb355c4b93
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/gap_neck.py
@@ -0,0 +1,37 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+
+from ..builder import NECKS
+
+
+@NECKS.register_module()
+class GlobalAveragePooling(nn.Module):
+ """Global Average Pooling neck.
+
+ Note that we use `view` to remove extra channel after pooling. We do not
+ use `squeeze` as it will also remove the batch dimension when the tensor
+ has a batch dimension of size 1, which can lead to unexpected errors.
+ """
+
+ def __init__(self):
+ super().__init__()
+ self.gap = nn.AdaptiveAvgPool2d((1, 1))
+
+ def init_weights(self):
+ pass
+
+ def forward(self, inputs):
+ if isinstance(inputs, tuple):
+ outs = tuple([self.gap(x) for x in inputs])
+ outs = tuple(
+ [out.view(x.size(0), -1) for out, x in zip(outs, inputs)])
+ elif isinstance(inputs, list):
+ outs = [self.gap(x) for x in inputs]
+ outs = [out.view(x.size(0), -1) for out, x in zip(outs, inputs)]
+ elif isinstance(inputs, torch.Tensor):
+ outs = self.gap(inputs)
+ outs = outs.view(inputs.size(0), -1)
+ else:
+ raise TypeError('neck inputs should be tuple or torch.tensor')
+ return outs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/posewarper_neck.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/posewarper_neck.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd4ddfbf8984857a6110f19b0a7d703b53f1c433
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/posewarper_neck.py
@@ -0,0 +1,329 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import mmcv
+import torch
+import torch.nn as nn
+from mmcv.cnn import (build_conv_layer, build_norm_layer, constant_init,
+ normal_init)
+from mmcv.utils import digit_version
+from torch.nn.modules.batchnorm import _BatchNorm
+
+from mmpose.models.utils.ops import resize
+from ..backbones.resnet import BasicBlock, Bottleneck
+from ..builder import NECKS
+
+try:
+ from mmcv.ops import DeformConv2d
+ has_mmcv_full = True
+except (ImportError, ModuleNotFoundError):
+ has_mmcv_full = False
+
+
+@NECKS.register_module()
+class PoseWarperNeck(nn.Module):
+ """PoseWarper neck.
+
+ `"Learning temporal pose estimation from sparsely-labeled videos"
+ `_.
+
+ Args:
+ in_channels (int): Number of input channels from backbone
+ out_channels (int): Number of output channels
+ inner_channels (int): Number of intermediate channels of the res block
+ deform_groups (int): Number of groups in the deformable conv
+ dilations (list|tuple): different dilations of the offset conv layers
+ trans_conv_kernel (int): the kernel of the trans conv layer, which is
+ used to get heatmap from the output of backbone. Default: 1
+ res_blocks_cfg (dict|None): config of residual blocks. If None,
+ use the default values. If not None, it should contain the
+ following keys:
+
+ - block (str): the type of residual block, Default: 'BASIC'.
+ - num_blocks (int): the number of blocks, Default: 20.
+
+ offsets_kernel (int): the kernel of offset conv layer.
+ deform_conv_kernel (int): the kernel of defomrable conv layer.
+ in_index (int|Sequence[int]): Input feature index. Default: 0
+ input_transform (str|None): Transformation type of input features.
+ Options: 'resize_concat', 'multiple_select', None.
+ Default: None.
+
+ - 'resize_concat': Multiple feature maps will be resize to \
+ the same size as first one and than concat together. \
+ Usually used in FCN head of HRNet.
+ - 'multiple_select': Multiple feature maps will be bundle into \
+ a list and passed into decode head.
+ - None: Only one select feature map is allowed.
+
+ freeze_trans_layer (bool): Whether to freeze the transition layer
+ (stop grad and set eval mode). Default: True.
+ norm_eval (bool): Whether to set norm layers to eval mode, namely,
+ freeze running stats (mean and var). Note: Effect on Batch Norm
+ and its variants only. Default: False.
+ im2col_step (int): the argument `im2col_step` in deformable conv,
+ Default: 80.
+ """
+ blocks_dict = {'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck}
+ minimum_mmcv_version = '1.3.17'
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ inner_channels,
+ deform_groups=17,
+ dilations=(3, 6, 12, 18, 24),
+ trans_conv_kernel=1,
+ res_blocks_cfg=None,
+ offsets_kernel=3,
+ deform_conv_kernel=3,
+ in_index=0,
+ input_transform=None,
+ freeze_trans_layer=True,
+ norm_eval=False,
+ im2col_step=80):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.inner_channels = inner_channels
+ self.deform_groups = deform_groups
+ self.dilations = dilations
+ self.trans_conv_kernel = trans_conv_kernel
+ self.res_blocks_cfg = res_blocks_cfg
+ self.offsets_kernel = offsets_kernel
+ self.deform_conv_kernel = deform_conv_kernel
+ self.in_index = in_index
+ self.input_transform = input_transform
+ self.freeze_trans_layer = freeze_trans_layer
+ self.norm_eval = norm_eval
+ self.im2col_step = im2col_step
+
+ identity_trans_layer = False
+
+ assert trans_conv_kernel in [0, 1, 3]
+ kernel_size = trans_conv_kernel
+ if kernel_size == 3:
+ padding = 1
+ elif kernel_size == 1:
+ padding = 0
+ else:
+ # 0 for Identity mapping.
+ identity_trans_layer = True
+
+ if identity_trans_layer:
+ self.trans_layer = nn.Identity()
+ else:
+ self.trans_layer = build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=in_channels,
+ out_channels=out_channels,
+ kernel_size=kernel_size,
+ stride=1,
+ padding=padding)
+
+ # build chain of residual blocks
+ if res_blocks_cfg is not None and not isinstance(res_blocks_cfg, dict):
+ raise TypeError('res_blocks_cfg should be dict or None.')
+
+ if res_blocks_cfg is None:
+ block_type = 'BASIC'
+ num_blocks = 20
+ else:
+ block_type = res_blocks_cfg.get('block', 'BASIC')
+ num_blocks = res_blocks_cfg.get('num_blocks', 20)
+
+ block = self.blocks_dict[block_type]
+
+ res_layers = []
+ downsample = nn.Sequential(
+ build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=out_channels,
+ out_channels=inner_channels,
+ kernel_size=1,
+ stride=1,
+ bias=False),
+ build_norm_layer(dict(type='BN'), inner_channels)[1])
+ res_layers.append(
+ block(
+ in_channels=out_channels,
+ out_channels=inner_channels,
+ downsample=downsample))
+
+ for _ in range(1, num_blocks):
+ res_layers.append(block(inner_channels, inner_channels))
+ self.offset_feats = nn.Sequential(*res_layers)
+
+ # build offset layers
+ self.num_offset_layers = len(dilations)
+ assert self.num_offset_layers > 0, 'Number of offset layers ' \
+ 'should be larger than 0.'
+
+ target_offset_channels = 2 * offsets_kernel**2 * deform_groups
+
+ offset_layers = [
+ build_conv_layer(
+ cfg=dict(type='Conv2d'),
+ in_channels=inner_channels,
+ out_channels=target_offset_channels,
+ kernel_size=offsets_kernel,
+ stride=1,
+ dilation=dilations[i],
+ padding=dilations[i],
+ bias=False,
+ ) for i in range(self.num_offset_layers)
+ ]
+ self.offset_layers = nn.ModuleList(offset_layers)
+
+ # build deformable conv layers
+ assert digit_version(mmcv.__version__) >= \
+ digit_version(self.minimum_mmcv_version), \
+ f'Current MMCV version: {mmcv.__version__}, ' \
+ f'but MMCV >= {self.minimum_mmcv_version} is required, see ' \
+ f'https://github.com/open-mmlab/mmcv/issues/1440, ' \
+ f'Please install the latest MMCV.'
+
+ if has_mmcv_full:
+ deform_conv_layers = [
+ DeformConv2d(
+ in_channels=out_channels,
+ out_channels=out_channels,
+ kernel_size=deform_conv_kernel,
+ stride=1,
+ padding=int(deform_conv_kernel / 2) * dilations[i],
+ dilation=dilations[i],
+ deform_groups=deform_groups,
+ im2col_step=self.im2col_step,
+ ) for i in range(self.num_offset_layers)
+ ]
+ else:
+ raise ImportError('Please install the full version of mmcv '
+ 'to use `DeformConv2d`.')
+
+ self.deform_conv_layers = nn.ModuleList(deform_conv_layers)
+
+ self.freeze_layers()
+
+ def freeze_layers(self):
+ if self.freeze_trans_layer:
+ self.trans_layer.eval()
+
+ for param in self.trans_layer.parameters():
+ param.requires_grad = False
+
+ def init_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Conv2d):
+ normal_init(m, std=0.001)
+ elif isinstance(m, (_BatchNorm, nn.GroupNorm)):
+ constant_init(m, 1)
+ elif isinstance(m, DeformConv2d):
+ filler = torch.zeros([
+ m.weight.size(0),
+ m.weight.size(1),
+ m.weight.size(2),
+ m.weight.size(3)
+ ],
+ dtype=torch.float32,
+ device=m.weight.device)
+ for k in range(m.weight.size(0)):
+ filler[k, k,
+ int(m.weight.size(2) / 2),
+ int(m.weight.size(3) / 2)] = 1.0
+ m.weight = torch.nn.Parameter(filler)
+ m.weight.requires_grad = True
+
+ # posewarper offset layer weight initialization
+ for m in self.offset_layers.modules():
+ constant_init(m, 0)
+
+ def _transform_inputs(self, inputs):
+ """Transform inputs for decoder.
+
+ Args:
+ inputs (list[Tensor] | Tensor): multi-level img features.
+
+ Returns:
+ Tensor: The transformed inputs
+ """
+ if not isinstance(inputs, list):
+ return inputs
+
+ if self.input_transform == 'resize_concat':
+ inputs = [inputs[i] for i in self.in_index]
+ upsampled_inputs = [
+ resize(
+ input=x,
+ size=inputs[0].shape[2:],
+ mode='bilinear',
+ align_corners=self.align_corners) for x in inputs
+ ]
+ inputs = torch.cat(upsampled_inputs, dim=1)
+ elif self.input_transform == 'multiple_select':
+ inputs = [inputs[i] for i in self.in_index]
+ else:
+ inputs = inputs[self.in_index]
+
+ return inputs
+
+ def forward(self, inputs, frame_weight):
+ assert isinstance(inputs, (list, tuple)), 'PoseWarperNeck inputs ' \
+ 'should be list or tuple, even though the length is 1, ' \
+ 'for unified processing.'
+
+ output_heatmap = 0
+ if len(inputs) > 1:
+ inputs = [self._transform_inputs(input) for input in inputs]
+ inputs = [self.trans_layer(input) for input in inputs]
+
+ # calculate difference features
+ diff_features = [
+ self.offset_feats(inputs[0] - input) for input in inputs
+ ]
+
+ for i in range(len(inputs)):
+ if frame_weight[i] == 0:
+ continue
+ warped_heatmap = 0
+ for j in range(self.num_offset_layers):
+ offset = (self.offset_layers[j](diff_features[i]))
+ warped_heatmap_tmp = self.deform_conv_layers[j](inputs[i],
+ offset)
+ warped_heatmap += warped_heatmap_tmp / \
+ self.num_offset_layers
+
+ output_heatmap += warped_heatmap * frame_weight[i]
+
+ else:
+ inputs = inputs[0]
+ inputs = self._transform_inputs(inputs)
+ inputs = self.trans_layer(inputs)
+
+ num_frames = len(frame_weight)
+ batch_size = inputs.size(0) // num_frames
+ ref_x = inputs[:batch_size]
+ ref_x_tiled = ref_x.repeat(num_frames, 1, 1, 1)
+
+ offset_features = self.offset_feats(ref_x_tiled - inputs)
+
+ warped_heatmap = 0
+ for j in range(self.num_offset_layers):
+ offset = self.offset_layers[j](offset_features)
+
+ warped_heatmap_tmp = self.deform_conv_layers[j](inputs, offset)
+ warped_heatmap += warped_heatmap_tmp / self.num_offset_layers
+
+ for i in range(num_frames):
+ if frame_weight[i] == 0:
+ continue
+ output_heatmap += warped_heatmap[i * batch_size:(i + 1) *
+ batch_size] * frame_weight[i]
+
+ return output_heatmap
+
+ def train(self, mode=True):
+ """Convert the model into training mode."""
+ super().train(mode)
+ self.freeze_layers()
+ if mode and self.norm_eval:
+ for m in self.modules():
+ if isinstance(m, _BatchNorm):
+ m.eval()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/tcformer_mta_neck.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/tcformer_mta_neck.py
new file mode 100644
index 0000000000000000000000000000000000000000..6723fb018e7799c1c0104868b1ca87c56cd28351
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/necks/tcformer_mta_neck.py
@@ -0,0 +1,224 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import ConvModule, constant_init, normal_init, trunc_normal_init
+from mmcv.runner import BaseModule
+
+from ..builder import NECKS
+from ..utils import TCFormerDynamicBlock, token2map, token_interp
+
+
+@NECKS.register_module()
+class MTA(BaseModule):
+ """Multi-stage Token feature Aggregation (MTA) module in TCFormer.
+
+ Args:
+ in_channels (list[int]): Number of input channels per stage.
+ Default: [64, 128, 256, 512].
+ out_channels (int): Number of output channels (used at each scale).
+ num_outs (int): Number of output scales. Default: 4.
+ start_level (int): Index of the start input backbone level used to
+ build the feature pyramid. Default: 0.
+ end_level (int): Index of the end input backbone level (exclusive) to
+ build the feature pyramid. Default: -1, which means the last level.
+ add_extra_convs (bool | str): If bool, it decides whether to add conv
+ layers on top of the original feature maps. Default to False.
+ If True, it is equivalent to `add_extra_convs='on_input'`.
+ If str, it specifies the source feature map of the extra convs.
+ Only the following options are allowed
+ - 'on_input': Last feat map of neck inputs (i.e. backbone feature).
+ - 'on_output': The last output feature map after fpn convs.
+ relu_before_extra_convs (bool): Whether to apply relu before the extra
+ conv. Default: False.
+ no_norm_on_lateral (bool): Whether to apply norm on lateral.
+ Default: False.
+ conv_cfg (dict): Config dict for convolution layer. Default: None.
+ norm_cfg (dict): Config dict for normalization layer. Default: None.
+ act_cfg (dict): Config dict for activation layer in ConvModule.
+ num_heads (Sequence[int]): The attention heads of each transformer
+ block. Default: [2, 2, 2, 2].
+ mlp_ratios (Sequence[int]): The ratio of the mlp hidden dim to the
+ embedding dim of each transformer block.
+ sr_ratios (Sequence[int]): The spatial reduction rate of each
+ transformer block. Default: [8, 4, 2, 1].
+ qkv_bias (bool): Enable bias for qkv if True. Default: True.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop_rate (float): Probability of an element to be zeroed.
+ Default 0.0.
+ attn_drop_rate (float): The drop out rate for attention layer.
+ Default 0.0.
+ drop_path_rate (float): stochastic depth rate. Default 0.
+ transformer_norm_cfg (dict): Config dict for normalization layer
+ in transformer blocks. Default: dict(type='LN').
+ use_sr_conv (bool): If True, use a conv layer for spatial reduction.
+ If False, use a pooling process for spatial reduction. Defaults:
+ False.
+ """
+
+ def __init__(
+ self,
+ in_channels=[64, 128, 256, 512],
+ out_channels=128,
+ num_outs=4,
+ start_level=0,
+ end_level=-1,
+ add_extra_convs=False,
+ relu_before_extra_convs=False,
+ no_norm_on_lateral=False,
+ conv_cfg=None,
+ norm_cfg=None,
+ act_cfg=None,
+ num_heads=[2, 2, 2, 2],
+ mlp_ratios=[4, 4, 4, 4],
+ sr_ratios=[8, 4, 2, 1],
+ qkv_bias=True,
+ qk_scale=None,
+ drop_rate=0.,
+ attn_drop_rate=0.,
+ drop_path_rate=0.,
+ transformer_norm_cfg=dict(type='LN'),
+ use_sr_conv=False,
+ ):
+ super().__init__()
+ assert isinstance(in_channels, list)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ self.num_ins = len(in_channels)
+ self.num_outs = num_outs
+ self.no_norm_on_lateral = no_norm_on_lateral
+ self.fp16_enabled = False
+ self.norm_cfg = norm_cfg
+ self.conv_cfg = conv_cfg
+ self.act_cfg = act_cfg
+ self.mlp_ratios = mlp_ratios
+
+ if end_level == -1 or end_level == self.num_ins - 1:
+ self.backbone_end_level = self.num_ins
+ assert num_outs >= self.num_ins - start_level
+ else:
+ # if end_level is not the last level, no extra level is allowed
+ self.backbone_end_level = end_level + 1
+ assert end_level < self.num_ins
+ assert num_outs == end_level - start_level + 1
+ self.start_level = start_level
+ self.end_level = end_level
+
+ self.lateral_convs = nn.ModuleList()
+ self.merge_blocks = nn.ModuleList()
+
+ for i in range(self.start_level, self.backbone_end_level):
+ l_conv = ConvModule(
+ in_channels[i],
+ out_channels,
+ 1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg if not self.no_norm_on_lateral else None,
+ act_cfg=act_cfg,
+ inplace=False)
+ self.lateral_convs.append(l_conv)
+
+ for i in range(self.start_level, self.backbone_end_level - 1):
+ merge_block = TCFormerDynamicBlock(
+ dim=out_channels,
+ num_heads=num_heads[i],
+ mlp_ratio=mlp_ratios[i],
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ drop=drop_rate,
+ attn_drop=attn_drop_rate,
+ drop_path=drop_path_rate,
+ norm_cfg=transformer_norm_cfg,
+ sr_ratio=sr_ratios[i],
+ use_sr_conv=use_sr_conv)
+ self.merge_blocks.append(merge_block)
+
+ # add extra conv layers (e.g., RetinaNet)
+ self.relu_before_extra_convs = relu_before_extra_convs
+
+ self.add_extra_convs = add_extra_convs
+ assert isinstance(add_extra_convs, (str, bool))
+ if isinstance(add_extra_convs, str):
+ # Extra_convs_source choices: 'on_input', 'on_output'
+ assert add_extra_convs in ('on_input', 'on_output')
+ elif add_extra_convs: # True
+ self.add_extra_convs = 'on_input'
+
+ self.extra_convs = nn.ModuleList()
+ extra_levels = num_outs - (self.end_level + 1 - self.start_level)
+ if self.add_extra_convs and extra_levels >= 1:
+ for i in range(extra_levels):
+ if i == 0 and self.add_extra_convs == 'on_input':
+ in_channels = self.in_channels[self.end_level]
+ else:
+ in_channels = out_channels
+ extra_fpn_conv = ConvModule(
+ in_channels,
+ out_channels,
+ 3,
+ stride=2,
+ padding=1,
+ conv_cfg=conv_cfg,
+ norm_cfg=norm_cfg,
+ act_cfg=act_cfg,
+ inplace=False)
+ self.extra_convs.append(extra_fpn_conv)
+
+ def init_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ constant_init(m, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ fan_out //= m.groups
+ normal_init(m, 0, math.sqrt(2.0 / fan_out))
+
+ def forward(self, inputs):
+ """Forward function."""
+ assert len(inputs) == len(self.in_channels)
+
+ # build lateral tokens
+ input_dicts = []
+ for i, lateral_conv in enumerate(self.lateral_convs):
+ tmp = inputs[i + self.start_level].copy()
+ tmp['x'] = lateral_conv(tmp['x'].unsqueeze(2).permute(
+ 0, 3, 1, 2)).permute(0, 2, 3, 1).squeeze(2)
+ input_dicts.append(tmp)
+
+ # merge from high level to low level
+ for i in range(len(input_dicts) - 2, -1, -1):
+ input_dicts[i]['x'] = input_dicts[i]['x'] + token_interp(
+ input_dicts[i], input_dicts[i + 1])
+ input_dicts[i] = self.merge_blocks[i](input_dicts[i])
+
+ # transform to feature map
+ outs = [token2map(token_dict) for token_dict in input_dicts]
+
+ # part 2: add extra levels
+ used_backbone_levels = len(outs)
+ if self.num_outs > len(outs):
+ # use max pool to get more levels on top of outputs
+ if not self.add_extra_convs:
+ for i in range(self.num_outs - used_backbone_levels):
+ outs.append(F.max_pool2d(outs[-1], 1, stride=2))
+ # add conv layers on top of original feature maps
+ else:
+ if self.add_extra_convs == 'on_input':
+ tmp = inputs[self.backbone_end_level - 1]
+ extra_source = token2map(tmp)
+ elif self.add_extra_convs == 'on_output':
+ extra_source = outs[-1]
+ else:
+ raise NotImplementedError
+
+ outs.append(self.extra_convs[0](extra_source))
+ for i in range(1, self.num_outs - used_backbone_levels):
+ if self.relu_before_extra_convs:
+ outs.append(self.extra_convs[i](F.relu(outs[-1])))
+ else:
+ outs.append(self.extra_convs[i](outs[-1]))
+ return outs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/registry.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/registry.py
new file mode 100644
index 0000000000000000000000000000000000000000..f354ae9e137262e2f375a64aef74c3af20baae63
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/registry.py
@@ -0,0 +1,13 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+from .builder import BACKBONES, HEADS, LOSSES, NECKS, POSENETS
+
+__all__ = ['BACKBONES', 'HEADS', 'LOSSES', 'NECKS', 'POSENETS']
+
+warnings.simplefilter('once', DeprecationWarning)
+warnings.warn(
+ 'Registries (BACKBONES, NECKS, HEADS, LOSSES, POSENETS) have '
+ 'been moved to mmpose.models.builder. Importing from '
+ 'mmpose.models.registry will be deprecated in the future.',
+ DeprecationWarning)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d7e8f6482ce3e2c06229a578f22536bd75e5260
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/__init__.py
@@ -0,0 +1,24 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .ckpt_convert import pvt_convert, tcformer_convert
+from .geometry import batch_rodrigues, quat_to_rotmat, rot6d_to_rotmat
+from .misc import torch_meshgrid_ij
+from .ops import resize
+from .realnvp import RealNVP
+from .smpl import SMPL
+from .tcformer_utils import (TCFormerDynamicBlock, TCFormerRegularBlock,
+ TokenConv, cluster_dpc_knn, merge_tokens,
+ token2map, token_interp)
+from .transformer import (PatchEmbed, PatchMerging, nchw_to_nlc, nlc_to_nchw,
+ PoseurTransformer_v3, DetrTransformerEncoder_zero_layer,
+ DeformableDetrTransformerDecoder, DetrTransformerDecoderLayer_grouped)
+
+from .positional_encoding import (LearnedPositionalEncoding,
+ SinePositionalEncoding)
+
+__all__ = [
+ 'SMPL', 'PatchEmbed', 'nchw_to_nlc', 'nlc_to_nchw', 'pvt_convert',
+ 'PatchMerging', 'batch_rodrigues', 'quat_to_rotmat', 'rot6d_to_rotmat',
+ 'resize', 'RealNVP', 'torch_meshgrid_ij', 'token2map', 'TokenConv',
+ 'TCFormerRegularBlock', 'TCFormerDynamicBlock', 'cluster_dpc_knn',
+ 'merge_tokens', 'token_interp', 'tcformer_convert'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ckpt_convert.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ckpt_convert.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5213937db3641bf7300156a2be3f2225326f02b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ckpt_convert.py
@@ -0,0 +1,94 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+
+# This script consists of several convert functions which
+# can modify the weights of model in original repo to be
+# pre-trained weights.
+
+from collections import OrderedDict
+
+import torch
+
+
+def pvt_convert(ckpt):
+ new_ckpt = OrderedDict()
+ # Process the concat between q linear weights and kv linear weights
+ use_abs_pos_embed = False
+ use_conv_ffn = False
+ for k in ckpt.keys():
+ if k.startswith('pos_embed'):
+ use_abs_pos_embed = True
+ if k.find('dwconv') >= 0:
+ use_conv_ffn = True
+ for k, v in ckpt.items():
+ if k.startswith('head'):
+ continue
+ if k.startswith('norm.'):
+ continue
+ if k.startswith('cls_token'):
+ continue
+ if k.startswith('pos_embed'):
+ stage_i = int(k.replace('pos_embed', ''))
+ new_k = k.replace(f'pos_embed{stage_i}',
+ f'layers.{stage_i - 1}.1.0.pos_embed')
+ if stage_i == 4 and v.size(1) == 50: # 1 (cls token) + 7 * 7
+ new_v = v[:, 1:, :] # remove cls token
+ else:
+ new_v = v
+ elif k.startswith('patch_embed'):
+ stage_i = int(k.split('.')[0].replace('patch_embed', ''))
+ new_k = k.replace(f'patch_embed{stage_i}',
+ f'layers.{stage_i - 1}.0')
+ new_v = v
+ if 'proj.' in new_k:
+ new_k = new_k.replace('proj.', 'projection.')
+ elif k.startswith('block'):
+ stage_i = int(k.split('.')[0].replace('block', ''))
+ layer_i = int(k.split('.')[1])
+ new_layer_i = layer_i + use_abs_pos_embed
+ new_k = k.replace(f'block{stage_i}.{layer_i}',
+ f'layers.{stage_i - 1}.1.{new_layer_i}')
+ new_v = v
+ if 'attn.q.' in new_k:
+ sub_item_k = k.replace('q.', 'kv.')
+ new_k = new_k.replace('q.', 'attn.in_proj_')
+ new_v = torch.cat([v, ckpt[sub_item_k]], dim=0)
+ elif 'attn.kv.' in new_k:
+ continue
+ elif 'attn.proj.' in new_k:
+ new_k = new_k.replace('proj.', 'attn.out_proj.')
+ elif 'attn.sr.' in new_k:
+ new_k = new_k.replace('sr.', 'sr.')
+ elif 'mlp.' in new_k:
+ string = f'{new_k}-'
+ new_k = new_k.replace('mlp.', 'ffn.layers.')
+ if 'fc1.weight' in new_k or 'fc2.weight' in new_k:
+ new_v = v.reshape((*v.shape, 1, 1))
+ new_k = new_k.replace('fc1.', '0.')
+ new_k = new_k.replace('dwconv.dwconv.', '1.')
+ if use_conv_ffn:
+ new_k = new_k.replace('fc2.', '4.')
+ else:
+ new_k = new_k.replace('fc2.', '3.')
+ string += f'{new_k} {v.shape}-{new_v.shape}'
+ elif k.startswith('norm'):
+ stage_i = int(k[4])
+ new_k = k.replace(f'norm{stage_i}', f'layers.{stage_i - 1}.2')
+ new_v = v
+ else:
+ new_k = k
+ new_v = v
+ new_ckpt[new_k] = new_v
+
+ return new_ckpt
+
+
+def tcformer_convert(ckpt):
+ new_ckpt = OrderedDict()
+ # Process the concat between q linear weights and kv linear weights
+ for k, v in ckpt.items():
+ if 'patch_embed' in k:
+ new_k = k.replace('.proj.', '.projection.')
+ else:
+ new_k = k
+ new_ckpt[new_k] = v
+ return new_ckpt
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/geometry.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ceadaec30cd2c9bb3fbada132e1ea674f2e8754
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/geometry.py
@@ -0,0 +1,68 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+from torch.nn import functional as F
+
+
+def rot6d_to_rotmat(x):
+ """Convert 6D rotation representation to 3x3 rotation matrix.
+
+ Based on Zhou et al., "On the Continuity of Rotation
+ Representations in Neural Networks", CVPR 2019
+ Input:
+ (B,6) Batch of 6-D rotation representations
+ Output:
+ (B,3,3) Batch of corresponding rotation matrices
+ """
+ x = x.view(-1, 3, 2)
+ a1 = x[:, :, 0]
+ a2 = x[:, :, 1]
+ b1 = F.normalize(a1)
+ b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)
+ b3 = torch.cross(b1, b2)
+ return torch.stack((b1, b2, b3), dim=-1)
+
+
+def batch_rodrigues(theta):
+ """Convert axis-angle representation to rotation matrix.
+ Args:
+ theta: size = [B, 3]
+ Returns:
+ Rotation matrix corresponding to the quaternion
+ -- size = [B, 3, 3]
+ """
+ l2norm = torch.norm(theta + 1e-8, p=2, dim=1)
+ angle = torch.unsqueeze(l2norm, -1)
+ normalized = torch.div(theta, angle)
+ angle = angle * 0.5
+ v_cos = torch.cos(angle)
+ v_sin = torch.sin(angle)
+ quat = torch.cat([v_cos, v_sin * normalized], dim=1)
+ return quat_to_rotmat(quat)
+
+
+def quat_to_rotmat(quat):
+ """Convert quaternion coefficients to rotation matrix.
+ Args:
+ quat: size = [B, 4] 4 <===>(w, x, y, z)
+ Returns:
+ Rotation matrix corresponding to the quaternion
+ -- size = [B, 3, 3]
+ """
+ norm_quat = quat
+ norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True)
+ w, x, y, z = norm_quat[:, 0], norm_quat[:, 1],\
+ norm_quat[:, 2], norm_quat[:, 3]
+
+ B = quat.size(0)
+
+ w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
+ wx, wy, wz = w * x, w * y, w * z
+ xy, xz, yz = x * y, x * z, y * z
+
+ rotMat = torch.stack([
+ w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz, 2 * wz + 2 * xy,
+ w2 - x2 + y2 - z2, 2 * yz - 2 * wx, 2 * xz - 2 * wy, 2 * wx + 2 * yz,
+ w2 - x2 - y2 + z2
+ ],
+ dim=1).view(B, 3, 3)
+ return rotMat
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/misc.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c784588ef0c0ef58badf5c68d0a9602e14d6079
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/misc.py
@@ -0,0 +1,13 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+from packaging import version
+
+_torch_version_meshgrid_indexing = version.parse(
+ torch.__version__) >= version.parse('1.10.0a0')
+
+
+def torch_meshgrid_ij(*tensors):
+ if _torch_version_meshgrid_indexing:
+ return torch.meshgrid(*tensors, indexing='ij')
+ else:
+ return torch.meshgrid(*tensors) # Uses indexing='ij' by default
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ops.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..858d0a92148a591d235e58bfce8990207632fb39
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/ops.py
@@ -0,0 +1,29 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import warnings
+
+import torch
+import torch.nn.functional as F
+
+
+def resize(input,
+ size=None,
+ scale_factor=None,
+ mode='nearest',
+ align_corners=None,
+ warning=True):
+ if warning:
+ if size is not None and align_corners:
+ input_h, input_w = tuple(int(x) for x in input.shape[2:])
+ output_h, output_w = tuple(int(x) for x in size)
+ if output_h > input_h or output_w > output_h:
+ if ((output_h > 1 and output_w > 1 and input_h > 1
+ and input_w > 1) and (output_h - 1) % (input_h - 1)
+ and (output_w - 1) % (input_w - 1)):
+ warnings.warn(
+ f'When align_corners={align_corners}, '
+ 'the output would more aligned if '
+ f'input size {(input_h, input_w)} is `x+1` and '
+ f'out size {(output_h, output_w)} is `nx+1`')
+ if isinstance(size, torch.Size):
+ size = tuple(int(x) for x in size)
+ return F.interpolate(input, size, scale_factor, mode, align_corners)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/positional_encoding.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/positional_encoding.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d3882cd515884794caeab3e06a40b22b6635b66
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/positional_encoding.py
@@ -0,0 +1,155 @@
+import math
+
+import torch
+import torch.nn as nn
+from mmcv.cnn.bricks.transformer import POSITIONAL_ENCODING
+from mmcv.runner import BaseModule
+
+
+@POSITIONAL_ENCODING.register_module()
+class SinePositionalEncoding(BaseModule):
+ """Position encoding with sine and cosine functions.
+ See `End-to-End Object Detection with Transformers
+ `_ for details.
+ Args:
+ num_feats (int): The feature dimension for each position
+ along x-axis or y-axis. Note the final returned dimension
+ for each position is 2 times of this value.
+ temperature (int, optional): The temperature used for scaling
+ the position embedding. Defaults to 10000.
+ normalize (bool, optional): Whether to normalize the position
+ embedding. Defaults to False.
+ scale (float, optional): A scale factor that scales the position
+ embedding. The scale will be used only when `normalize` is True.
+ Defaults to 2*pi.
+ eps (float, optional): A value added to the denominator for
+ numerical stability. Defaults to 1e-6.
+ offset (float): offset add to embed when do the normalization.
+ Defaults to 0.
+ init_cfg (dict or list[dict], optional): Initialization config dict.
+ Default: None
+ """
+
+ def __init__(self,
+ num_feats,
+ temperature=10000,
+ normalize=False,
+ scale=2 * math.pi,
+ eps=1e-6,
+ offset=0.,
+ init_cfg=None):
+ super(SinePositionalEncoding, self).__init__(init_cfg)
+ if normalize:
+ assert isinstance(scale, (float, int)), 'when normalize is set,' \
+ 'scale should be provided and in float or int type, ' \
+ f'found {type(scale)}'
+ self.num_feats = num_feats
+ self.temperature = temperature
+ self.normalize = normalize
+ self.scale = scale
+ self.eps = eps
+ self.offset = offset
+
+ def forward(self, mask):
+ """Forward function for `SinePositionalEncoding`.
+ Args:
+ mask (Tensor): ByteTensor mask. Non-zero values representing
+ ignored positions, while zero values means valid positions
+ for this image. Shape [bs, h, w].
+ Returns:
+ pos (Tensor): Returned position embedding with shape
+ [bs, num_feats*2, h, w].
+ """
+ # For convenience of exporting to ONNX, it's required to convert
+ # `masks` from bool to int.
+ mask = mask.to(torch.int)
+ not_mask = 1 - mask # logical_not
+ y_embed = not_mask.cumsum(1, dtype=torch.float32)
+ x_embed = not_mask.cumsum(2, dtype=torch.float32)
+ if self.normalize:
+ y_embed = (y_embed + self.offset) / \
+ (y_embed[:, -1:, :] + self.eps) * self.scale
+ x_embed = (x_embed + self.offset) / \
+ (x_embed[:, :, -1:] + self.eps) * self.scale
+ dim_t = torch.arange(
+ self.num_feats, dtype=torch.float32, device=mask.device)
+ dim_t = self.temperature**(2 * (dim_t // 2) / self.num_feats)
+ pos_x = x_embed[:, :, :, None] / dim_t
+ pos_y = y_embed[:, :, :, None] / dim_t
+ # use `view` instead of `flatten` for dynamically exporting to ONNX
+ B, H, W = mask.size()
+ pos_x = torch.stack(
+ (pos_x[:, :, :, 0::2].sin(), pos_x[:, :, :, 1::2].cos()),
+ dim=4).view(B, H, W, -1)
+ pos_y = torch.stack(
+ (pos_y[:, :, :, 0::2].sin(), pos_y[:, :, :, 1::2].cos()),
+ dim=4).view(B, H, W, -1)
+ pos = torch.cat((pos_y, pos_x), dim=3).permute(0, 3, 1, 2)
+ return pos
+
+ def __repr__(self):
+ """str: a string that describes the module"""
+ repr_str = self.__class__.__name__
+ repr_str += f'(num_feats={self.num_feats}, '
+ repr_str += f'temperature={self.temperature}, '
+ repr_str += f'normalize={self.normalize}, '
+ repr_str += f'scale={self.scale}, '
+ repr_str += f'eps={self.eps})'
+ return repr_str
+
+
+@POSITIONAL_ENCODING.register_module()
+class LearnedPositionalEncoding(BaseModule):
+ """Position embedding with learnable embedding weights.
+ Args:
+ num_feats (int): The feature dimension for each position
+ along x-axis or y-axis. The final returned dimension for
+ each position is 2 times of this value.
+ row_num_embed (int, optional): The dictionary size of row embeddings.
+ Default 50.
+ col_num_embed (int, optional): The dictionary size of col embeddings.
+ Default 50.
+ init_cfg (dict or list[dict], optional): Initialization config dict.
+ """
+
+ def __init__(self,
+ num_feats,
+ row_num_embed=50,
+ col_num_embed=50,
+ init_cfg=dict(type='Uniform', layer='Embedding')):
+ super(LearnedPositionalEncoding, self).__init__(init_cfg)
+ self.row_embed = nn.Embedding(row_num_embed, num_feats)
+ self.col_embed = nn.Embedding(col_num_embed, num_feats)
+ self.num_feats = num_feats
+ self.row_num_embed = row_num_embed
+ self.col_num_embed = col_num_embed
+
+ def forward(self, mask):
+ """Forward function for `LearnedPositionalEncoding`.
+ Args:
+ mask (Tensor): ByteTensor mask. Non-zero values representing
+ ignored positions, while zero values means valid positions
+ for this image. Shape [bs, h, w].
+ Returns:
+ pos (Tensor): Returned position embedding with shape
+ [bs, num_feats*2, h, w].
+ """
+ h, w = mask.shape[-2:]
+ x = torch.arange(w, device=mask.device)
+ y = torch.arange(h, device=mask.device)
+ x_embed = self.col_embed(x)
+ y_embed = self.row_embed(y)
+ pos = torch.cat(
+ (x_embed.unsqueeze(0).repeat(h, 1, 1), y_embed.unsqueeze(1).repeat(
+ 1, w, 1)),
+ dim=-1).permute(2, 0,
+ 1).unsqueeze(0).repeat(mask.shape[0], 1, 1, 1)
+ return pos
+
+ def __repr__(self):
+ """str: a string that describes the module"""
+ repr_str = self.__class__.__name__
+ repr_str += f'(num_feats={self.num_feats}, '
+ repr_str += f'row_num_embed={self.row_num_embed}, '
+ repr_str += f'col_num_embed={self.col_num_embed})'
+ return repr_str
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/realnvp.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/realnvp.py
new file mode 100644
index 0000000000000000000000000000000000000000..911953e8f9d1056d44a2d3538d750e89b9bd6a7a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/realnvp.py
@@ -0,0 +1,76 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import torch
+import torch.nn as nn
+from torch import distributions
+
+
+class RealNVP(nn.Module):
+ """RealNVP: a flow-based generative model
+
+ `Density estimation using Real NVP
+ arXiv: `_.
+
+ Code is modified from `the official implementation of RLE
+ `_.
+
+ See also `real-nvp-pytorch
+ `_.
+ """
+
+ @staticmethod
+ def get_scale_net():
+ """Get the scale model in a single invertable mapping."""
+ return nn.Sequential(
+ nn.Linear(2, 64), nn.LeakyReLU(), nn.Linear(64, 64),
+ nn.LeakyReLU(), nn.Linear(64, 2), nn.Tanh())
+
+ @staticmethod
+ def get_trans_net():
+ """Get the translation model in a single invertable mapping."""
+ return nn.Sequential(
+ nn.Linear(2, 64), nn.LeakyReLU(), nn.Linear(64, 64),
+ nn.LeakyReLU(), nn.Linear(64, 2))
+
+ @property
+ def prior(self):
+ """The prior distribution."""
+ return distributions.MultivariateNormal(self.loc, self.cov)
+
+ def __init__(self):
+ super(RealNVP, self).__init__()
+
+ self.register_buffer('loc', torch.zeros(2))
+ self.register_buffer('cov', torch.eye(2))
+ self.register_buffer(
+ 'mask', torch.tensor([[0, 1], [1, 0]] * 3, dtype=torch.float32))
+
+ self.s = torch.nn.ModuleList(
+ [self.get_scale_net() for _ in range(len(self.mask))])
+ self.t = torch.nn.ModuleList(
+ [self.get_trans_net() for _ in range(len(self.mask))])
+ self.init_weights()
+
+ def init_weights(self):
+ """Initialization model weights."""
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight, gain=0.01)
+
+ def backward_p(self, x):
+ """Apply mapping form the data space to the latent space and calculate
+ the log determinant of the Jacobian matrix."""
+
+ log_det_jacob, z = x.new_zeros(x.shape[0]), x
+ for i in reversed(range(len(self.t))):
+ z_ = self.mask[i] * z
+ s = self.s[i](z_) * (1 - self.mask[i]) # torch.exp(s): betas
+ t = self.t[i](z_) * (1 - self.mask[i]) # gammas
+ z = (1 - self.mask[i]) * (z - t) * torch.exp(-s) + z_
+ log_det_jacob -= s.sum(dim=1)
+ return z, log_det_jacob
+
+ def log_prob(self, x):
+ """Calculate the log probability of given sample in data space."""
+
+ z, log_det = self.backward_p(x)
+ return self.prior.log_prob(z) + log_det
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/smpl.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/smpl.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe723d483aadb7ce7e0e9f50ef8da7b10e7529e5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/smpl.py
@@ -0,0 +1,184 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import numpy as np
+import torch
+import torch.nn as nn
+
+from ..builder import MESH_MODELS
+
+try:
+ from smplx import SMPL as SMPL_
+ has_smpl = True
+except (ImportError, ModuleNotFoundError):
+ has_smpl = False
+
+
+@MESH_MODELS.register_module()
+class SMPL(nn.Module):
+ """SMPL 3d human mesh model of paper ref: Matthew Loper. ``SMPL: A skinned
+ multi-person linear model''. This module is based on the smplx project
+ (https://github.com/vchoutas/smplx).
+
+ Args:
+ smpl_path (str): The path to the folder where the model weights are
+ stored.
+ joints_regressor (str): The path to the file where the joints
+ regressor weight are stored.
+ """
+
+ def __init__(self, smpl_path, joints_regressor):
+ super().__init__()
+
+ assert has_smpl, 'Please install smplx to use SMPL.'
+
+ self.smpl_neutral = SMPL_(
+ model_path=smpl_path,
+ create_global_orient=False,
+ create_body_pose=False,
+ create_transl=False,
+ gender='neutral')
+
+ self.smpl_male = SMPL_(
+ model_path=smpl_path,
+ create_betas=False,
+ create_global_orient=False,
+ create_body_pose=False,
+ create_transl=False,
+ gender='male')
+
+ self.smpl_female = SMPL_(
+ model_path=smpl_path,
+ create_betas=False,
+ create_global_orient=False,
+ create_body_pose=False,
+ create_transl=False,
+ gender='female')
+
+ joints_regressor = torch.tensor(
+ np.load(joints_regressor), dtype=torch.float)[None, ...]
+ self.register_buffer('joints_regressor', joints_regressor)
+
+ self.num_verts = self.smpl_neutral.get_num_verts()
+ self.num_joints = self.joints_regressor.shape[1]
+
+ def smpl_forward(self, model, **kwargs):
+ """Apply a specific SMPL model with given model parameters.
+
+ Note:
+ B: batch size
+ V: number of vertices
+ K: number of joints
+
+ Returns:
+ outputs (dict): Dict with mesh vertices and joints.
+ - vertices: Tensor([B, V, 3]), mesh vertices
+ - joints: Tensor([B, K, 3]), 3d joints regressed
+ from mesh vertices.
+ """
+
+ betas = kwargs['betas']
+ batch_size = betas.shape[0]
+ device = betas.device
+ output = {}
+ if batch_size == 0:
+ output['vertices'] = betas.new_zeros([0, self.num_verts, 3])
+ output['joints'] = betas.new_zeros([0, self.num_joints, 3])
+ else:
+ smpl_out = model(**kwargs)
+ output['vertices'] = smpl_out.vertices
+ output['joints'] = torch.matmul(
+ self.joints_regressor.to(device), output['vertices'])
+ return output
+
+ def get_faces(self):
+ """Return mesh faces.
+
+ Note:
+ F: number of faces
+
+ Returns:
+ faces: np.ndarray([F, 3]), mesh faces
+ """
+ return self.smpl_neutral.faces
+
+ def forward(self,
+ betas,
+ body_pose,
+ global_orient,
+ transl=None,
+ gender=None):
+ """Forward function.
+
+ Note:
+ B: batch size
+ J: number of controllable joints of model, for smpl model J=23
+ K: number of joints
+
+ Args:
+ betas: Tensor([B, 10]), human body shape parameters of SMPL model.
+ body_pose: Tensor([B, J*3] or [B, J, 3, 3]), human body pose
+ parameters of SMPL model. It should be axis-angle vector
+ ([B, J*3]) or rotation matrix ([B, J, 3, 3)].
+ global_orient: Tensor([B, 3] or [B, 1, 3, 3]), global orientation
+ of human body. It should be axis-angle vector ([B, 3]) or
+ rotation matrix ([B, 1, 3, 3)].
+ transl: Tensor([B, 3]), global translation of human body.
+ gender: Tensor([B]), gender parameters of human body. -1 for
+ neutral, 0 for male , 1 for female.
+
+ Returns:
+ outputs (dict): Dict with mesh vertices and joints.
+ - vertices: Tensor([B, V, 3]), mesh vertices
+ - joints: Tensor([B, K, 3]), 3d joints regressed from
+ mesh vertices.
+ """
+
+ batch_size = betas.shape[0]
+ pose2rot = True if body_pose.dim() == 2 else False
+ if batch_size > 0 and gender is not None:
+ output = {
+ 'vertices': betas.new_zeros([batch_size, self.num_verts, 3]),
+ 'joints': betas.new_zeros([batch_size, self.num_joints, 3])
+ }
+
+ mask = gender < 0
+ _out = self.smpl_forward(
+ self.smpl_neutral,
+ betas=betas[mask],
+ body_pose=body_pose[mask],
+ global_orient=global_orient[mask],
+ transl=transl[mask] if transl is not None else None,
+ pose2rot=pose2rot)
+ output['vertices'][mask] = _out['vertices']
+ output['joints'][mask] = _out['joints']
+
+ mask = gender == 0
+ _out = self.smpl_forward(
+ self.smpl_male,
+ betas=betas[mask],
+ body_pose=body_pose[mask],
+ global_orient=global_orient[mask],
+ transl=transl[mask] if transl is not None else None,
+ pose2rot=pose2rot)
+ output['vertices'][mask] = _out['vertices']
+ output['joints'][mask] = _out['joints']
+
+ mask = gender == 1
+ _out = self.smpl_forward(
+ self.smpl_male,
+ betas=betas[mask],
+ body_pose=body_pose[mask],
+ global_orient=global_orient[mask],
+ transl=transl[mask] if transl is not None else None,
+ pose2rot=pose2rot)
+ output['vertices'][mask] = _out['vertices']
+ output['joints'][mask] = _out['joints']
+ else:
+ return self.smpl_forward(
+ self.smpl_neutral,
+ betas=betas,
+ body_pose=body_pose,
+ global_orient=global_orient,
+ transl=transl,
+ pose2rot=pose2rot)
+
+ return output
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/tcformer_utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/tcformer_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d3a28534c83d60e52ed0382f54a4d9f4902e018
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/tcformer_utils.py
@@ -0,0 +1,995 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import build_norm_layer, trunc_normal_init
+from mmcv.cnn.bricks.transformer import build_dropout
+
+try:
+ from torch.cuda.amp import autocast
+ WITH_AUTOCAST = True
+except ImportError:
+ WITH_AUTOCAST = False
+
+
+def get_grid_index(init_grid_size, map_size, device):
+ """For every initial grid, get its index in the feature map.
+ Note:
+ [H_init, W_init]: shape of initial grid
+ [H, W]: shape of feature map
+ N_init: numbers of initial token
+
+ Args:
+ init_grid_size (list[int] or tuple[int]): initial grid resolution in
+ format [H_init, W_init].
+ map_size (list[int] or tuple[int]): feature map resolution in format
+ [H, W].
+ device: the device of output
+
+ Returns:
+ idx (torch.LongTensor[B, N_init]): index in flattened feature map.
+ """
+ H_init, W_init = init_grid_size
+ H, W = map_size
+ idx = torch.arange(H * W, device=device).reshape(1, 1, H, W)
+ idx = F.interpolate(idx.float(), [H_init, W_init], mode='nearest').long()
+ return idx.flatten()
+
+
+def index_points(points, idx):
+ """Sample features following the index.
+ Note:
+ B: batch size
+ N: point number
+ C: channel number of each point
+ Ns: sampled point number
+
+ Args:
+ points (torch.Tensor[B, N, C]): input points data
+ idx (torch.LongTensor[B, S]): sample index
+
+ Returns:
+ new_points (torch.Tensor[B, Ns, C]):, indexed points data
+ """
+ device = points.device
+ B = points.shape[0]
+ view_shape = list(idx.shape)
+ view_shape[1:] = [1] * (len(view_shape) - 1)
+ repeat_shape = list(idx.shape)
+ repeat_shape[0] = 1
+ batch_indices = torch.arange(
+ B, dtype=torch.long).to(device).view(view_shape).repeat(repeat_shape)
+ new_points = points[batch_indices, idx, :]
+ return new_points
+
+
+def token2map(token_dict):
+ """Transform vision tokens to feature map. This function only works when
+ the resolution of the feature map is not higher than the initial grid
+ structure.
+
+ Note:
+ B: batch size
+ C: channel number of each token
+ [H, W]: shape of feature map
+ N_init: numbers of initial token
+
+ Args:
+ token_dict (dict): dict for token information.
+
+ Returns:
+ x_out (Tensor[B, C, H, W]): feature map.
+ """
+
+ x = token_dict['x']
+ H, W = token_dict['map_size']
+ H_init, W_init = token_dict['init_grid_size']
+ idx_token = token_dict['idx_token']
+ B, N, C = x.shape
+ N_init = H_init * W_init
+ device = x.device
+
+ if N_init == N and N == H * W:
+ # for the initial tokens with grid structure, just reshape
+ return x.reshape(B, H, W, C).permute(0, 3, 1, 2).contiguous()
+
+ # for each initial grid, get the corresponding index in
+ # the flattened feature map.
+ idx_hw = get_grid_index([H_init, W_init], [H, W],
+ device=device)[None, :].expand(B, -1)
+ idx_batch = torch.arange(B, device=device)[:, None].expand(B, N_init)
+ value = x.new_ones(B * N_init)
+
+ # choose the way with fewer flops.
+ if N_init < N * H * W:
+ # use sparse matrix multiplication
+ # Flops: B * N_init * (C+2)
+ idx_hw = idx_hw + idx_batch * H * W
+ idx_tokens = idx_token + idx_batch * N
+ coor = torch.stack([idx_hw, idx_tokens], dim=0).reshape(2, B * N_init)
+
+ # torch.sparse do not support gradient for
+ # sparse tensor, so we detach it
+ value = value.detach().to(torch.float32)
+
+ # build a sparse matrix with the shape [B * H * W, B * N]
+ A = torch.sparse.FloatTensor(coor, value,
+ torch.Size([B * H * W, B * N]))
+
+ # normalize the weight for each row
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ all_weight = A @ x.new_ones(B * N, 1).type(
+ torch.float32) + 1e-6
+ else:
+ all_weight = A @ x.new_ones(B * N, 1).type(torch.float32) + 1e-6
+ value = value / all_weight[idx_hw.reshape(-1), 0]
+
+ # update the matrix with normalize weight
+ A = torch.sparse.FloatTensor(coor, value,
+ torch.Size([B * H * W, B * N]))
+
+ # sparse matrix multiplication
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ x_out = A @ x.reshape(B * N, C).to(torch.float32) # [B*H*W, C]
+ else:
+ x_out = A @ x.reshape(B * N, C).to(torch.float32) # [B*H*W, C]
+
+ else:
+ # use dense matrix multiplication
+ # Flops: B * N * H * W * (C+2)
+ coor = torch.stack([idx_batch, idx_hw, idx_token],
+ dim=0).reshape(3, B * N_init)
+
+ # build a matrix with shape [B, H*W, N]
+ A = torch.sparse.FloatTensor(coor, value, torch.Size([B, H * W,
+ N])).to_dense()
+ # normalize the weight
+ A = A / (A.sum(dim=-1, keepdim=True) + 1e-6)
+
+ x_out = A @ x # [B, H*W, C]
+
+ x_out = x_out.type(x.dtype)
+ x_out = x_out.reshape(B, H, W, C).permute(0, 3, 1, 2).contiguous()
+ return x_out
+
+
+def map2token(feature_map, token_dict):
+ """Transform feature map to vision tokens. This function only works when
+ the resolution of the feature map is not higher than the initial grid
+ structure.
+
+ Note:
+ B: batch size
+ C: channel number
+ [H, W]: shape of feature map
+ N_init: numbers of initial token
+
+ Args:
+ feature_map (Tensor[B, C, H, W]): feature map.
+ token_dict (dict): dict for token information.
+
+ Returns:
+ out (Tensor[B, N, C]): token features.
+ """
+ idx_token = token_dict['idx_token']
+ N = token_dict['token_num']
+ H_init, W_init = token_dict['init_grid_size']
+ N_init = H_init * W_init
+
+ B, C, H, W = feature_map.shape
+ device = feature_map.device
+
+ if N_init == N and N == H * W:
+ # for the initial tokens with grid structure, just reshape
+ return feature_map.flatten(2).permute(0, 2, 1).contiguous()
+
+ idx_hw = get_grid_index([H_init, W_init], [H, W],
+ device=device)[None, :].expand(B, -1)
+
+ idx_batch = torch.arange(B, device=device)[:, None].expand(B, N_init)
+ value = feature_map.new_ones(B * N_init)
+
+ # choose the way with fewer flops.
+ if N_init < N * H * W:
+ # use sparse matrix multiplication
+ # Flops: B * N_init * (C+2)
+ idx_token = idx_token + idx_batch * N
+ idx_hw = idx_hw + idx_batch * H * W
+ indices = torch.stack([idx_token, idx_hw], dim=0).reshape(2, -1)
+
+ # sparse mm do not support gradient for sparse matrix
+ value = value.detach().to(torch.float32)
+ # build a sparse matrix with shape [B*N, B*H*W]
+ A = torch.sparse_coo_tensor(indices, value, (B * N, B * H * W))
+ # normalize the matrix
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ all_weight = A @ torch.ones(
+ [B * H * W, 1], device=device, dtype=torch.float32) + 1e-6
+ else:
+ all_weight = A @ torch.ones(
+ [B * H * W, 1], device=device, dtype=torch.float32) + 1e-6
+ value = value / all_weight[idx_token.reshape(-1), 0]
+
+ A = torch.sparse_coo_tensor(indices, value, (B * N, B * H * W))
+ # out: [B*N, C]
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ out = A @ feature_map.permute(0, 2, 3, 1).contiguous().reshape(
+ B * H * W, C).float()
+ else:
+ out = A @ feature_map.permute(0, 2, 3, 1).contiguous().reshape(
+ B * H * W, C).float()
+ else:
+ # use dense matrix multiplication
+ # Flops: B * N * H * W * (C+2)
+ indices = torch.stack([idx_batch, idx_token, idx_hw],
+ dim=0).reshape(3, -1)
+ value = value.detach() # To reduce the training time, we detach here.
+ A = torch.sparse_coo_tensor(indices, value, (B, N, H * W)).to_dense()
+ # normalize the matrix
+ A = A / (A.sum(dim=-1, keepdim=True) + 1e-6)
+
+ out = A @ feature_map.permute(0, 2, 3, 1).reshape(B, H * W,
+ C).contiguous()
+
+ out = out.type(feature_map.dtype)
+ out = out.reshape(B, N, C)
+ return out
+
+
+def token_interp(target_dict, source_dict):
+ """Transform token features between different distribution.
+
+ Note:
+ B: batch size
+ N: token number
+ C: channel number
+
+ Args:
+ target_dict (dict): dict for target token information
+ source_dict (dict): dict for source token information.
+
+ Returns:
+ x_out (Tensor[B, N, C]): token features.
+ """
+
+ x_s = source_dict['x']
+ idx_token_s = source_dict['idx_token']
+ idx_token_t = target_dict['idx_token']
+ T = target_dict['token_num']
+ B, S, C = x_s.shape
+ N_init = idx_token_s.shape[1]
+
+ weight = target_dict['agg_weight'] if 'agg_weight' in target_dict.keys(
+ ) else None
+ if weight is None:
+ weight = x_s.new_ones(B, N_init, 1)
+ weight = weight.reshape(-1)
+
+ # choose the way with fewer flops.
+ if N_init < T * S:
+ # use sparse matrix multiplication
+ # Flops: B * N_init * (C+2)
+ idx_token_t = idx_token_t + torch.arange(
+ B, device=x_s.device)[:, None] * T
+ idx_token_s = idx_token_s + torch.arange(
+ B, device=x_s.device)[:, None] * S
+ coor = torch.stack([idx_token_t, idx_token_s],
+ dim=0).reshape(2, B * N_init)
+
+ # torch.sparse does not support grad for sparse matrix
+ weight = weight.float().detach().to(torch.float32)
+ # build a matrix with shape [B*T, B*S]
+ A = torch.sparse.FloatTensor(coor, weight, torch.Size([B * T, B * S]))
+ # normalize the matrix
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ all_weight = A.type(torch.float32) @ x_s.new_ones(
+ B * S, 1).type(torch.float32) + 1e-6
+ else:
+ all_weight = A.type(torch.float32) @ x_s.new_ones(B * S, 1).type(
+ torch.float32) + 1e-6
+ weight = weight / all_weight[idx_token_t.reshape(-1), 0]
+ A = torch.sparse.FloatTensor(coor, weight, torch.Size([B * T, B * S]))
+ # sparse matmul
+ if WITH_AUTOCAST:
+ with autocast(enabled=False):
+ x_out = A.type(torch.float32) @ x_s.reshape(B * S, C).type(
+ torch.float32)
+ else:
+ x_out = A.type(torch.float32) @ x_s.reshape(B * S, C).type(
+ torch.float32)
+ else:
+ # use dense matrix multiplication
+ # Flops: B * T * S * (C+2)
+ idx_batch = torch.arange(
+ B, device=x_s.device)[:, None].expand(B, N_init)
+ coor = torch.stack([idx_batch, idx_token_t, idx_token_s],
+ dim=0).reshape(3, B * N_init)
+ weight = weight.detach() # detach to reduce training time
+ # build a matrix with shape [B, T, S]
+ A = torch.sparse.FloatTensor(coor, weight, torch.Size([B, T,
+ S])).to_dense()
+ # normalize the matrix
+ A = A / (A.sum(dim=-1, keepdim=True) + 1e-6)
+ # dense matmul
+ x_out = A @ x_s
+
+ x_out = x_out.reshape(B, T, C).type(x_s.dtype)
+ return x_out
+
+
+def cluster_dpc_knn(token_dict, cluster_num, k=5, token_mask=None):
+ """Cluster tokens with DPC-KNN algorithm.
+
+ Note:
+ B: batch size
+ N: token number
+ C: channel number
+
+ Args:
+ token_dict (dict): dict for token information
+ cluster_num (int): cluster number
+ k (int): number of the nearest neighbor used for local density.
+ token_mask (Tensor[B, N]): mask indicating which token is the
+ padded empty token. Non-zero value means the token is meaningful,
+ zero value means the token is an empty token. If set to None, all
+ tokens are regarded as meaningful.
+
+ Return:
+ idx_cluster (Tensor[B, N]): cluster index of each token.
+ cluster_num (int): actual cluster number. In this function, it equals
+ to the input cluster number.
+ """
+
+ with torch.no_grad():
+ x = token_dict['x']
+ B, N, C = x.shape
+
+ dist_matrix = torch.cdist(x, x) / (C**0.5)
+
+ if token_mask is not None:
+ token_mask = token_mask > 0
+ # in order to not affect the local density, the
+ # distance between empty tokens and any other
+ # tokens should be the maximal distance.
+ dist_matrix = \
+ dist_matrix * token_mask[:, None, :] +\
+ (dist_matrix.max() + 1) * (~token_mask[:, None, :])
+
+ # get local density
+ dist_nearest, index_nearest = torch.topk(
+ dist_matrix, k=k, dim=-1, largest=False)
+
+ density = (-(dist_nearest**2).mean(dim=-1)).exp()
+ # add a little noise to ensure no tokens have the same density.
+ density = density + torch.rand(
+ density.shape, device=density.device, dtype=density.dtype) * 1e-6
+
+ if token_mask is not None:
+ # the density of empty token should be 0
+ density = density * token_mask
+
+ # get distance indicator
+ mask = density[:, None, :] > density[:, :, None]
+ mask = mask.type(x.dtype)
+ dist_max = dist_matrix.flatten(1).max(dim=-1)[0][:, None, None]
+ dist, index_parent = (dist_matrix * mask + dist_max *
+ (1 - mask)).min(dim=-1)
+
+ # select clustering center according to score
+ score = dist * density
+ _, index_down = torch.topk(score, k=cluster_num, dim=-1)
+
+ # assign tokens to the nearest center
+ dist_matrix = index_points(dist_matrix, index_down)
+
+ idx_cluster = dist_matrix.argmin(dim=1)
+
+ # make sure cluster center merge to itself
+ idx_batch = torch.arange(
+ B, device=x.device)[:, None].expand(B, cluster_num)
+ idx_tmp = torch.arange(
+ cluster_num, device=x.device)[None, :].expand(B, cluster_num)
+ idx_cluster[idx_batch.reshape(-1),
+ index_down.reshape(-1)] = idx_tmp.reshape(-1)
+
+ return idx_cluster, cluster_num
+
+
+def merge_tokens(token_dict, idx_cluster, cluster_num, token_weight=None):
+ """Merge tokens in the same cluster to a single cluster. Implemented by
+ torch.index_add(). Flops: B*N*(C+2)
+
+ Note:
+ B: batch size
+ N: token number
+ C: channel number
+
+ Args:
+ token_dict (dict): dict for input token information
+ idx_cluster (Tensor[B, N]): cluster index of each token.
+ cluster_num (int): cluster number
+ token_weight (Tensor[B, N, 1]): weight for each token.
+
+ Return:
+ out_dict (dict): dict for output token information
+ """
+
+ x = token_dict['x']
+ idx_token = token_dict['idx_token']
+ agg_weight = token_dict['agg_weight']
+
+ B, N, C = x.shape
+ if token_weight is None:
+ token_weight = x.new_ones(B, N, 1)
+
+ idx_batch = torch.arange(B, device=x.device)[:, None]
+ idx = idx_cluster + idx_batch * cluster_num
+
+ all_weight = token_weight.new_zeros(B * cluster_num, 1)
+ all_weight.index_add_(
+ dim=0, index=idx.reshape(B * N), source=token_weight.reshape(B * N, 1))
+ all_weight = all_weight + 1e-6
+ norm_weight = token_weight / all_weight[idx]
+
+ # average token features
+ x_merged = x.new_zeros(B * cluster_num, C)
+ source = x * norm_weight
+ x_merged.index_add_(
+ dim=0,
+ index=idx.reshape(B * N),
+ source=source.reshape(B * N, C).type(x.dtype))
+ x_merged = x_merged.reshape(B, cluster_num, C)
+
+ idx_token_new = index_points(idx_cluster[..., None], idx_token).squeeze(-1)
+ weight_t = index_points(norm_weight, idx_token)
+ agg_weight_new = agg_weight * weight_t
+ agg_weight_new / agg_weight_new.max(dim=1, keepdim=True)[0]
+
+ out_dict = {}
+ out_dict['x'] = x_merged
+ out_dict['token_num'] = cluster_num
+ out_dict['map_size'] = token_dict['map_size']
+ out_dict['init_grid_size'] = token_dict['init_grid_size']
+ out_dict['idx_token'] = idx_token_new
+ out_dict['agg_weight'] = agg_weight_new
+ return out_dict
+
+
+class MLP(nn.Module):
+ """FFN with Depthwise Conv of TCFormer.
+
+ Args:
+ in_features (int): The feature dimension.
+ hidden_features (int, optional): The hidden dimension of FFNs.
+ Defaults: The same as in_features.
+ out_features (int, optional): The output feature dimension.
+ Defaults: The same as in_features.
+ act_layer (nn.Module, optional): The activation config for FFNs.
+ Default: nn.GELU.
+ drop (float, optional): drop out rate. Default: 0.
+ """
+
+ def __init__(self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ drop=0.):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.dwconv = DWConv(hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def init_weights(self):
+ """init weights."""
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ fan_out //= m.groups
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
+ if m.bias is not None:
+ m.bias.data.zero_()
+
+ def forward(self, x, H, W):
+ x = self.fc1(x)
+ x = self.dwconv(x, H, W)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class DWConv(nn.Module):
+ """Depthwise Conv for regular grid-based tokens.
+
+ Args:
+ dim (int): The feature dimension.
+ """
+
+ def __init__(self, dim=768):
+ super(DWConv, self).__init__()
+ self.dwconv = nn.Conv2d(dim, dim, 3, 1, 1, bias=True, groups=dim)
+
+ def forward(self, x, H, W):
+ B, N, C = x.shape
+ x = x.transpose(1, 2).view(B, C, H, W)
+ x = self.dwconv(x)
+ x = x.flatten(2).transpose(1, 2)
+ return x
+
+
+class TCFormerRegularAttention(nn.Module):
+ """Spatial Reduction Attention for regular grid-based tokens.
+
+ Args:
+ dim (int): The feature dimension of tokens,
+ num_heads (int): Parallel attention heads.
+ qkv_bias (bool): enable bias for qkv if True. Default: False.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ attn_drop (float): A Dropout layer on attn_output_weights.
+ Default: 0.0.
+ proj_drop (float): A Dropout layer after attention process.
+ Default: 0.0.
+ sr_ratio (int): The ratio of spatial reduction of Spatial Reduction
+ Attention. Default: 1.
+ use_sr_conv (bool): If True, use a conv layer for spatial reduction.
+ If False, use a pooling process for spatial reduction. Defaults:
+ True.
+ """
+
+ def __init__(
+ self,
+ dim,
+ num_heads=8,
+ qkv_bias=False,
+ qk_scale=None,
+ attn_drop=0.,
+ proj_drop=0.,
+ sr_ratio=1,
+ use_sr_conv=True,
+ ):
+ super().__init__()
+ assert dim % num_heads == 0, \
+ f'dim {dim} should be divided by num_heads {num_heads}.'
+
+ self.dim = dim
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = qk_scale or head_dim**-0.5
+
+ self.q = nn.Linear(dim, dim, bias=qkv_bias)
+ self.kv = nn.Linear(dim, dim * 2, bias=qkv_bias)
+ self.attn_drop = nn.Dropout(attn_drop)
+ self.proj = nn.Linear(dim, dim)
+ self.proj_drop = nn.Dropout(proj_drop)
+
+ self.sr_ratio = sr_ratio
+ self.use_sr_conv = use_sr_conv
+ if sr_ratio > 1 and self.use_sr_conv:
+ self.sr = nn.Conv2d(
+ dim, dim, kernel_size=sr_ratio, stride=sr_ratio)
+ self.norm = nn.LayerNorm(dim)
+
+ def init_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ fan_out //= m.groups
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
+ if m.bias is not None:
+ m.bias.data.zero_()
+
+ def forward(self, x, H, W):
+ B, N, C = x.shape
+ q = self.q(x).reshape(B, N, self.num_heads,
+ C // self.num_heads).permute(0, 2, 1, 3)
+
+ if self.sr_ratio > 1:
+ kv = x.permute(0, 2, 1).reshape(B, C, H, W)
+ if self.use_sr_conv:
+ kv = self.sr(kv).reshape(B, C, -1).permute(0, 2,
+ 1).contiguous()
+ kv = self.norm(kv)
+ else:
+ kv = F.avg_pool2d(
+ kv, kernel_size=self.sr_ratio, stride=self.sr_ratio)
+ kv = kv.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+ else:
+ kv = x
+
+ kv = self.kv(kv).reshape(B, -1, 2, self.num_heads,
+ C // self.num_heads).permute(2, 0, 3, 1,
+ 4).contiguous()
+ k, v = kv[0], kv[1]
+
+ attn = (q * self.scale) @ k.transpose(-2, -1)
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, N, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+
+ return x
+
+
+class TCFormerRegularBlock(nn.Module):
+ """Transformer block for regular grid-based tokens.
+
+ Args:
+ dim (int): The feature dimension.
+ num_heads (int): Parallel attention heads.
+ mlp_ratio (int): The expansion ratio for the FFNs.
+ qkv_bias (bool): enable bias for qkv if True. Default: False.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop (float): Dropout layers after attention process and in FFN.
+ Default: 0.0.
+ attn_drop (float): A Dropout layer on attn_output_weights.
+ Default: 0.0.
+ drop_path (int, optional): The drop path rate of transformer block.
+ Default: 0.0
+ act_layer (nn.Module, optional): The activation config for FFNs.
+ Default: nn.GELU.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN').
+ sr_ratio (int): The ratio of spatial reduction of Spatial Reduction
+ Attention. Default: 1.
+ use_sr_conv (bool): If True, use a conv layer for spatial reduction.
+ If False, use a pooling process for spatial reduction. Defaults:
+ True.
+ """
+
+ def __init__(self,
+ dim,
+ num_heads,
+ mlp_ratio=4.,
+ qkv_bias=False,
+ qk_scale=None,
+ drop=0.,
+ attn_drop=0.,
+ drop_path=0.,
+ act_layer=nn.GELU,
+ norm_cfg=dict(type='LN'),
+ sr_ratio=1,
+ use_sr_conv=True):
+ super().__init__()
+ self.norm1 = build_norm_layer(norm_cfg, dim)[1]
+
+ self.attn = TCFormerRegularAttention(
+ dim,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ sr_ratio=sr_ratio,
+ use_sr_conv=use_sr_conv)
+ self.drop_path = build_dropout(
+ dict(type='DropPath', drop_prob=drop_path))
+
+ self.norm2 = build_norm_layer(norm_cfg, dim)[1]
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = MLP(
+ in_features=dim,
+ hidden_features=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=drop)
+
+ def init_weights(self):
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ fan_out //= m.groups
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
+ if m.bias is not None:
+ m.bias.data.zero_()
+
+ def forward(self, x, H, W):
+ x = x + self.drop_path(self.attn(self.norm1(x), H, W))
+ x = x + self.drop_path(self.mlp(self.norm2(x), H, W))
+ return x
+
+
+class TokenConv(nn.Conv2d):
+ """Conv layer for dynamic tokens.
+
+ A skip link is added between the input and output tokens to reserve detail
+ tokens.
+ """
+
+ def __init__(self, **kwargs):
+ super().__init__(**kwargs)
+ groups = kwargs['groups'] if 'groups' in kwargs.keys() else 1
+ self.skip = nn.Conv1d(
+ in_channels=kwargs['in_channels'],
+ out_channels=kwargs['out_channels'],
+ kernel_size=1,
+ bias=False,
+ groups=groups)
+
+ def forward(self, token_dict):
+ x = token_dict['x']
+ x = self.skip(x.permute(0, 2, 1)).permute(0, 2, 1)
+ x_map = token2map(token_dict)
+ x_map = super().forward(x_map)
+ x = x + map2token(x_map, token_dict)
+ return x
+
+
+class TCMLP(nn.Module):
+ """FFN with Depthwise Conv for dynamic tokens.
+
+ Args:
+ in_features (int): The feature dimension.
+ hidden_features (int, optional): The hidden dimension of FFNs.
+ Defaults: The same as in_features.
+ out_features (int, optional): The output feature dimension.
+ Defaults: The same as in_features.
+ act_layer (nn.Module, optional): The activation config for FFNs.
+ Default: nn.GELU.
+ drop (float, optional): drop out rate. Default: 0.
+ """
+
+ def __init__(self,
+ in_features,
+ hidden_features=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ drop=0.):
+ super().__init__()
+ out_features = out_features or in_features
+ hidden_features = hidden_features or in_features
+ self.fc1 = nn.Linear(in_features, hidden_features)
+ self.dwconv = TokenConv(
+ in_channels=hidden_features,
+ out_channels=hidden_features,
+ kernel_size=3,
+ padding=1,
+ stride=1,
+ bias=True,
+ groups=hidden_features)
+ self.act = act_layer()
+ self.fc2 = nn.Linear(hidden_features, out_features)
+ self.drop = nn.Dropout(drop)
+
+ def init_weights(self):
+ """init weights."""
+ for m in self.modules():
+ if isinstance(m, nn.Linear):
+ trunc_normal_init(m, std=.02, bias=0.)
+ elif isinstance(m, nn.LayerNorm):
+ nn.init.constant_(m.bias, 0)
+ nn.init.constant_(m.weight, 1.0)
+ elif isinstance(m, nn.Conv2d):
+ fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ fan_out //= m.groups
+ m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))
+ if m.bias is not None:
+ m.bias.data.zero_()
+
+ def forward(self, token_dict):
+ token_dict['x'] = self.fc1(token_dict['x'])
+ x = self.dwconv(token_dict)
+ x = self.act(x)
+ x = self.drop(x)
+ x = self.fc2(x)
+ x = self.drop(x)
+ return x
+
+
+class TCFormerDynamicAttention(TCFormerRegularAttention):
+ """Spatial Reduction Attention for dynamic tokens."""
+
+ def forward(self, q_dict, kv_dict):
+ """Attention process for dynamic tokens.
+ Dynamic tokens are represented by a dict with the following keys:
+ x (torch.Tensor[B, N, C]): token features.
+ token_num(int): token number.
+ map_size(list[int] or tuple[int]): feature map resolution in
+ format [H, W].
+ init_grid_size(list[int] or tuple[int]): initial grid resolution
+ in format [H_init, W_init].
+ idx_token(torch.LongTensor[B, N_init]): indicates which token
+ the initial grid belongs to.
+ agg_weight(torch.LongTensor[B, N_init] or None): weight for
+ aggregation. Indicates the weight of each token in its
+ cluster. If set to None, uniform weight is used.
+
+ Note:
+ B: batch size
+ N: token number
+ C: channel number
+ Ns: sampled point number
+ [H_init, W_init]: shape of initial grid
+ [H, W]: shape of feature map
+ N_init: numbers of initial token
+
+ Args:
+ q_dict (dict): dict for query token information
+ kv_dict (dict): dict for key and value token information
+
+ Return:
+ x (torch.Tensor[B, N, C]): output token features.
+ """
+
+ q = q_dict['x']
+ kv = kv_dict['x']
+ B, Nq, C = q.shape
+ Nkv = kv.shape[1]
+ conf_kv = kv_dict['token_score'] if 'token_score' in kv_dict.keys(
+ ) else kv.new_zeros(B, Nkv, 1)
+
+ q = self.q(q).reshape(B, Nq, self.num_heads,
+ C // self.num_heads).permute(0, 2, 1,
+ 3).contiguous()
+
+ if self.sr_ratio > 1:
+ tmp = torch.cat([kv, conf_kv], dim=-1)
+ tmp_dict = kv_dict.copy()
+ tmp_dict['x'] = tmp
+ tmp_dict['map_size'] = q_dict['map_size']
+ tmp = token2map(tmp_dict)
+
+ kv = tmp[:, :C]
+ conf_kv = tmp[:, C:]
+
+ if self.use_sr_conv:
+ kv = self.sr(kv)
+ _, _, h, w = kv.shape
+ kv = kv.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+ kv = self.norm(kv)
+ else:
+ kv = F.avg_pool2d(
+ kv, kernel_size=self.sr_ratio, stride=self.sr_ratio)
+ kv = kv.reshape(B, C, -1).permute(0, 2, 1).contiguous()
+
+ conf_kv = F.avg_pool2d(
+ conf_kv, kernel_size=self.sr_ratio, stride=self.sr_ratio)
+ conf_kv = conf_kv.reshape(B, 1, -1).permute(0, 2, 1).contiguous()
+
+ kv = self.kv(kv).reshape(B, -1, 2, self.num_heads,
+ C // self.num_heads).permute(2, 0, 3, 1,
+ 4).contiguous()
+ k, v = kv[0], kv[1]
+
+ attn = (q * self.scale) @ k.transpose(-2, -1)
+
+ conf_kv = conf_kv.squeeze(-1)[:, None, None, :]
+ attn = attn + conf_kv
+ attn = attn.softmax(dim=-1)
+ attn = self.attn_drop(attn)
+
+ x = (attn @ v).transpose(1, 2).reshape(B, Nq, C)
+ x = self.proj(x)
+ x = self.proj_drop(x)
+ return x
+
+
+# Transformer block for dynamic tokens
+class TCFormerDynamicBlock(TCFormerRegularBlock):
+ """Transformer block for dynamic tokens.
+
+ Args:
+ dim (int): The feature dimension.
+ num_heads (int): Parallel attention heads.
+ mlp_ratio (int): The expansion ratio for the FFNs.
+ qkv_bias (bool): enable bias for qkv if True. Default: False.
+ qk_scale (float | None, optional): Override default qk scale of
+ head_dim ** -0.5 if set. Default: None.
+ drop (float): Dropout layers after attention process and in FFN.
+ Default: 0.0.
+ attn_drop (float): A Dropout layer on attn_output_weights.
+ Default: 0.0.
+ drop_path (int, optional): The drop path rate of transformer block.
+ Default: 0.0
+ act_layer (nn.Module, optional): The activation config for FFNs.
+ Default: nn.GELU.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: dict(type='LN').
+ sr_ratio (int): The ratio of spatial reduction of Spatial Reduction
+ Attention. Default: 1.
+ use_sr_conv (bool): If True, use a conv layer for spatial reduction.
+ If False, use a pooling process for spatial reduction. Defaults:
+ True.
+ """
+
+ def __init__(self,
+ dim,
+ num_heads,
+ mlp_ratio=4.,
+ qkv_bias=False,
+ qk_scale=None,
+ drop=0.,
+ attn_drop=0.,
+ drop_path=0.,
+ act_layer=nn.GELU,
+ norm_cfg=dict(type='LN'),
+ sr_ratio=1,
+ use_sr_conv=True):
+ super(TCFormerRegularBlock, self).__init__()
+ self.norm1 = build_norm_layer(norm_cfg, dim)[1]
+
+ self.attn = TCFormerDynamicAttention(
+ dim,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ qk_scale=qk_scale,
+ attn_drop=attn_drop,
+ proj_drop=drop,
+ sr_ratio=sr_ratio,
+ use_sr_conv=use_sr_conv)
+ self.drop_path = build_dropout(
+ dict(type='DropPath', drop_prob=drop_path))
+
+ self.norm2 = build_norm_layer(norm_cfg, dim)[1]
+ mlp_hidden_dim = int(dim * mlp_ratio)
+ self.mlp = TCMLP(
+ in_features=dim,
+ hidden_features=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=drop)
+
+ def forward(self, inputs):
+ """Forward function.
+
+ Args:
+ inputs (dict or tuple[dict] or list[dict]): input dynamic
+ token information. If a single dict is provided, it's
+ regraded as query and key, value. If a tuple or list
+ of dict is provided, the first one is regarded as key
+ and the second one is regarded as key, value.
+
+ Return:
+ q_dict (dict): dict for output token information
+ """
+ if isinstance(inputs, tuple) or isinstance(inputs, list):
+ q_dict, kv_dict = inputs
+ else:
+ q_dict, kv_dict = inputs, None
+
+ x = q_dict['x']
+ # norm1
+ q_dict['x'] = self.norm1(q_dict['x'])
+ if kv_dict is None:
+ kv_dict = q_dict
+ else:
+ kv_dict['x'] = self.norm1(kv_dict['x'])
+
+ # attn
+ x = x + self.drop_path(self.attn(q_dict, kv_dict))
+
+ # mlp
+ q_dict['x'] = self.norm2(x)
+ x = x + self.drop_path(self.mlp(q_dict))
+ q_dict['x'] = x
+
+ return q_dict
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/transformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce8a7bb1b7b6bebb9c17c7483c5c052ec049518e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/models/utils/transformer.py
@@ -0,0 +1,1138 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import math
+from typing import Sequence
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from mmcv.cnn import build_conv_layer, build_norm_layer
+from mmcv.runner.base_module import BaseModule
+from mmcv.utils import to_2tuple
+from mmpose.models.builder import TRANSFORMER
+
+from easydict import EasyDict
+from einops import rearrange, repeat
+from mmcv.runner import force_fp32
+from mmcv.cnn.bricks.transformer import (BaseTransformerLayer,
+ TransformerLayerSequence,
+ build_transformer_layer_sequence)
+from mmcv.cnn.bricks.registry import (TRANSFORMER_LAYER,
+ TRANSFORMER_LAYER_SEQUENCE)
+import torch.distributions as distributions
+from mmcv.ops.multi_scale_deform_attn import MultiScaleDeformableAttention
+from torch.nn.init import normal_
+import copy
+import warnings
+from mmcv.cnn import build_activation_layer, build_norm_layer, xavier_init
+
+from utils.human_models import smpl_x
+
+from config import cfg
+
+
+def point_sample(input, point_coords, **kwargs):
+ """
+ A wrapper around :function:`torch.nn.functional.grid_sample` to support 3D point_coords tensors.
+ Unlike :function:`torch.nn.functional.grid_sample` it assumes `point_coords` to lie inside
+ [0, 1] x [0, 1] square.
+ Args:
+ input (Tensor): A tensor of shape (N, C, H, W) that contains features map on a H x W grid.
+ point_coords (Tensor): A tensor of shape (N, P, 2) or (N, Hgrid, Wgrid, 2) that contains
+ [0, 1] x [0, 1] normalized point coordinates.
+ Returns:
+ output (Tensor): A tensor of shape (N, C, P) or (N, C, Hgrid, Wgrid) that contains
+ features for points in `point_coords`. The features are obtained via bilinear
+ interplation from `input` the same way as :function:`torch.nn.functional.grid_sample`.
+ """
+ add_dim = False
+ if point_coords.dim() == 3:
+ add_dim = True
+ point_coords = point_coords.unsqueeze(2)
+ output = F.grid_sample(input, 2.0 * point_coords - 1.0, **kwargs)
+ if add_dim:
+ output = output.squeeze(3)
+ return output
+
+
+def nlc_to_nchw(x, hw_shape):
+ """Convert [N, L, C] shape tensor to [N, C, H, W] shape tensor.
+
+ Args:
+ x (Tensor): The input tensor of shape [N, L, C] before conversion.
+ hw_shape (Sequence[int]): The height and width of output feature map.
+
+ Returns:
+ Tensor: The output tensor of shape [N, C, H, W] after conversion.
+ """
+ H, W = hw_shape
+ assert len(x.shape) == 3
+ B, L, C = x.shape
+ assert L == H * W, 'The seq_len does not match H, W'
+ return x.transpose(1, 2).reshape(B, C, H, W).contiguous()
+
+
+def nchw_to_nlc(x):
+ """Flatten [N, C, H, W] shape tensor to [N, L, C] shape tensor.
+
+ Args:
+ x (Tensor): The input tensor of shape [N, C, H, W] before conversion.
+
+ Returns:
+ Tensor: The output tensor of shape [N, L, C] after conversion.
+ """
+ assert len(x.shape) == 4
+ return x.flatten(2).transpose(1, 2).contiguous()
+
+
+class AdaptivePadding(nn.Module):
+ """Applies padding to input (if needed) so that input can get fully covered
+ by filter you specified. It support two modes "same" and "corner". The
+ "same" mode is same with "SAME" padding mode in TensorFlow, pad zero around
+ input. The "corner" mode would pad zero to bottom right.
+
+ Args:
+ kernel_size (int | tuple): Size of the kernel:
+ stride (int | tuple): Stride of the filter. Default: 1:
+ dilation (int | tuple): Spacing between kernel elements.
+ Default: 1
+ padding (str): Support "same" and "corner", "corner" mode
+ would pad zero to bottom right, and "same" mode would
+ pad zero around input. Default: "corner".
+ Example:
+ >>> kernel_size = 16
+ >>> stride = 16
+ >>> dilation = 1
+ >>> input = torch.rand(1, 1, 15, 17)
+ >>> adap_pad = AdaptivePadding(
+ >>> kernel_size=kernel_size,
+ >>> stride=stride,
+ >>> dilation=dilation,
+ >>> padding="corner")
+ >>> out = adap_pad(input)
+ >>> assert (out.shape[2], out.shape[3]) == (16, 32)
+ >>> input = torch.rand(1, 1, 16, 17)
+ >>> out = adap_pad(input)
+ >>> assert (out.shape[2], out.shape[3]) == (16, 32)
+ """
+
+ def __init__(self, kernel_size=1, stride=1, dilation=1, padding='corner'):
+
+ super(AdaptivePadding, self).__init__()
+
+ assert padding in ('same', 'corner')
+
+ kernel_size = to_2tuple(kernel_size)
+ stride = to_2tuple(stride)
+ padding = to_2tuple(padding)
+ dilation = to_2tuple(dilation)
+
+ self.padding = padding
+ self.kernel_size = kernel_size
+ self.stride = stride
+ self.dilation = dilation
+
+ def get_pad_shape(self, input_shape):
+ input_h, input_w = input_shape
+ kernel_h, kernel_w = self.kernel_size
+ stride_h, stride_w = self.stride
+ output_h = math.ceil(input_h / stride_h)
+ output_w = math.ceil(input_w / stride_w)
+ pad_h = max((output_h - 1) * stride_h +
+ (kernel_h - 1) * self.dilation[0] + 1 - input_h, 0)
+ pad_w = max((output_w - 1) * stride_w +
+ (kernel_w - 1) * self.dilation[1] + 1 - input_w, 0)
+ return pad_h, pad_w
+
+ def forward(self, x):
+ pad_h, pad_w = self.get_pad_shape(x.size()[-2:])
+ if pad_h > 0 or pad_w > 0:
+ if self.padding == 'corner':
+ x = F.pad(x, [0, pad_w, 0, pad_h])
+ elif self.padding == 'same':
+ x = F.pad(x, [
+ pad_w // 2, pad_w - pad_w // 2, pad_h // 2,
+ pad_h - pad_h // 2
+ ])
+ return x
+
+
+class PatchEmbed(BaseModule):
+ """Image to Patch Embedding.
+
+ We use a conv layer to implement PatchEmbed.
+
+ Args:
+ in_channels (int): The num of input channels. Default: 3
+ embed_dims (int): The dimensions of embedding. Default: 768
+ conv_type (str): The config dict for embedding
+ conv layer type selection. Default: "Conv2d.
+ kernel_size (int): The kernel_size of embedding conv. Default: 16.
+ stride (int): The slide stride of embedding conv.
+ Default: None (Would be set as `kernel_size`).
+ padding (int | tuple | string ): The padding length of
+ embedding conv. When it is a string, it means the mode
+ of adaptive padding, support "same" and "corner" now.
+ Default: "corner".
+ dilation (int): The dilation rate of embedding conv. Default: 1.
+ bias (bool): Bias of embed conv. Default: True.
+ norm_cfg (dict, optional): Config dict for normalization layer.
+ Default: None.
+ input_size (int | tuple | None): The size of input, which will be
+ used to calculate the out size. Only work when `dynamic_size`
+ is False. Default: None.
+ init_cfg (`mmcv.ConfigDict`, optional): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(
+ self,
+ in_channels=3,
+ embed_dims=768,
+ conv_type='Conv2d',
+ kernel_size=16,
+ stride=16,
+ padding='corner',
+ dilation=1,
+ bias=True,
+ norm_cfg=None,
+ input_size=None,
+ init_cfg=None,
+ ):
+ super(PatchEmbed, self).__init__(init_cfg=init_cfg)
+
+ self.embed_dims = embed_dims
+ if stride is None:
+ stride = kernel_size
+
+ kernel_size = to_2tuple(kernel_size)
+ stride = to_2tuple(stride)
+ dilation = to_2tuple(dilation)
+
+ if isinstance(padding, str):
+ self.adap_padding = AdaptivePadding(
+ kernel_size=kernel_size,
+ stride=stride,
+ dilation=dilation,
+ padding=padding)
+ # disable the padding of conv
+ padding = 0
+ else:
+ self.adap_padding = None
+ padding = to_2tuple(padding)
+
+ self.projection = build_conv_layer(
+ dict(type=conv_type),
+ in_channels=in_channels,
+ out_channels=embed_dims,
+ kernel_size=kernel_size,
+ stride=stride,
+ padding=padding,
+ dilation=dilation,
+ bias=bias)
+
+ if norm_cfg is not None:
+ self.norm = build_norm_layer(norm_cfg, embed_dims)[1]
+ else:
+ self.norm = None
+
+ if input_size:
+ input_size = to_2tuple(input_size)
+ # `init_out_size` would be used outside to
+ # calculate the num_patches
+ # when `use_abs_pos_embed` outside
+ self.init_input_size = input_size
+ if self.adap_padding:
+ pad_h, pad_w = self.adap_padding.get_pad_shape(input_size)
+ input_h, input_w = input_size
+ input_h = input_h + pad_h
+ input_w = input_w + pad_w
+ input_size = (input_h, input_w)
+
+ # https://pytorch.org/docs/stable/generated/torch.nn.Conv2d.html
+ h_out = (input_size[0] + 2 * padding[0] - dilation[0] *
+ (kernel_size[0] - 1) - 1) // stride[0] + 1
+ w_out = (input_size[1] + 2 * padding[1] - dilation[1] *
+ (kernel_size[1] - 1) - 1) // stride[1] + 1
+ self.init_out_size = (h_out, w_out)
+ else:
+ self.init_input_size = None
+ self.init_out_size = None
+
+ def forward(self, x):
+ """
+ Args:
+ x (Tensor): Has shape (B, C, H, W). In most case, C is 3.
+
+ Returns:
+ tuple: Contains merged results and its spatial shape.
+
+ - x (Tensor): Has shape (B, out_h * out_w, embed_dims)
+ - out_size (tuple[int]): Spatial shape of x, arrange as
+ (out_h, out_w).
+ """
+
+ if self.adap_padding:
+ x = self.adap_padding(x)
+
+ x = self.projection(x)
+ out_size = (x.shape[2], x.shape[3])
+ x = x.flatten(2).transpose(1, 2)
+ if self.norm is not None:
+ x = self.norm(x)
+ return x, out_size
+
+
+class PatchMerging(BaseModule):
+ """Merge patch feature map.
+
+ This layer groups feature map by kernel_size, and applies norm and linear
+ layers to the grouped feature map. Our implementation uses `nn.Unfold` to
+ merge patch, which is about 25% faster than original implementation.
+ Instead, we need to modify pretrained models for compatibility.
+
+ Args:
+ in_channels (int): The num of input channels.
+ to gets fully covered by filter and stride you specified..
+ Default: True.
+ out_channels (int): The num of output channels.
+ kernel_size (int | tuple, optional): the kernel size in the unfold
+ layer. Defaults to 2.
+ stride (int | tuple, optional): the stride of the sliding blocks in the
+ unfold layer. Default: None. (Would be set as `kernel_size`)
+ padding (int | tuple | string ): The padding length of
+ embedding conv. When it is a string, it means the mode
+ of adaptive padding, support "same" and "corner" now.
+ Default: "corner".
+ dilation (int | tuple, optional): dilation parameter in the unfold
+ layer. Default: 1.
+ bias (bool, optional): Whether to add bias in linear layer or not.
+ Defaults: False.
+ norm_cfg (dict, optional): Config dict for normalization layer.
+ Default: dict(type='LN').
+ init_cfg (dict, optional): The extra config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ in_channels,
+ out_channels,
+ kernel_size=2,
+ stride=None,
+ padding='corner',
+ dilation=1,
+ bias=False,
+ norm_cfg=dict(type='LN'),
+ init_cfg=None):
+ super().__init__(init_cfg=init_cfg)
+ self.in_channels = in_channels
+ self.out_channels = out_channels
+ if stride:
+ stride = stride
+ else:
+ stride = kernel_size
+
+ kernel_size = to_2tuple(kernel_size)
+ stride = to_2tuple(stride)
+ dilation = to_2tuple(dilation)
+
+ if isinstance(padding, str):
+ self.adap_padding = AdaptivePadding(
+ kernel_size=kernel_size,
+ stride=stride,
+ dilation=dilation,
+ padding=padding)
+ # disable the padding of unfold
+ padding = 0
+ else:
+ self.adap_padding = None
+
+ padding = to_2tuple(padding)
+ self.sampler = nn.Unfold(
+ kernel_size=kernel_size,
+ dilation=dilation,
+ padding=padding,
+ stride=stride)
+
+ sample_dim = kernel_size[0] * kernel_size[1] * in_channels
+
+ if norm_cfg is not None:
+ self.norm = build_norm_layer(norm_cfg, sample_dim)[1]
+ else:
+ self.norm = None
+
+ self.reduction = nn.Linear(sample_dim, out_channels, bias=bias)
+
+ def forward(self, x, input_size):
+ """
+ Args:
+ x (Tensor): Has shape (B, H*W, C_in).
+ input_size (tuple[int]): The spatial shape of x, arrange as (H, W).
+ Default: None.
+
+ Returns:
+ tuple: Contains merged results and its spatial shape.
+
+ - x (Tensor): Has shape (B, Merged_H * Merged_W, C_out)
+ - out_size (tuple[int]): Spatial shape of x, arrange as
+ (Merged_H, Merged_W).
+ """
+ B, L, C = x.shape
+ assert isinstance(input_size, Sequence), f'Expect ' \
+ f'input_size is ' \
+ f'`Sequence` ' \
+ f'but get {input_size}'
+
+ H, W = input_size
+ assert L == H * W, 'input feature has wrong size'
+
+ x = x.view(B, H, W, C).permute([0, 3, 1, 2]) # B, C, H, W
+ # Use nn.Unfold to merge patch. About 25% faster than original method,
+ # but need to modify pretrained model for compatibility
+
+ if self.adap_padding:
+ x = self.adap_padding(x)
+ H, W = x.shape[-2:]
+
+ x = self.sampler(x)
+ # if kernel_size=2 and stride=2, x should has shape (B, 4*C, H/2*W/2)
+
+ out_h = (H + 2 * self.sampler.padding[0] - self.sampler.dilation[0] *
+ (self.sampler.kernel_size[0] - 1) -
+ 1) // self.sampler.stride[0] + 1
+ out_w = (W + 2 * self.sampler.padding[1] - self.sampler.dilation[1] *
+ (self.sampler.kernel_size[1] - 1) -
+ 1) // self.sampler.stride[1] + 1
+
+ output_size = (out_h, out_w)
+ x = x.transpose(1, 2) # B, H/2*W/2, 4*C
+ x = self.norm(x) if self.norm else x
+ x = self.reduction(x)
+ return x, output_size
+
+
+def inverse_sigmoid(x, eps=1e-5):
+ """Inverse function of sigmoid.
+ Args:
+ x (Tensor): The tensor to do the
+ inverse.
+ eps (float): EPS avoid numerical
+ overflow. Defaults 1e-5.
+ Returns:
+ Tensor: The x has passed the inverse
+ function of sigmoid, has same
+ shape with input.
+ """
+ x = x.clamp(min=0, max=1)
+ x1 = x.clamp(min=eps)
+ x2 = (1 - x).clamp(min=eps)
+ return torch.log(x1 / x2)
+
+
+@TRANSFORMER_LAYER_SEQUENCE.register_module()
+class DetrTransformerEncoder_zero_layer():
+ def __init__(self, *args, post_norm_cfg=dict(type='LN'), **kwargs):
+ pass
+
+ def __call__(self,
+ query,
+ key,
+ value,
+ query_pos=None,
+ key_pos=None,
+ attn_masks=None,
+ query_key_padding_mask=None,
+ key_padding_mask=None,
+ **kwargs):
+ query = query + query_pos
+ return query
+
+
+@TRANSFORMER_LAYER.register_module()
+class DetrTransformerDecoderLayer_grouped(BaseTransformerLayer):
+ def __init__(self,
+ attn_cfgs,
+ feedforward_channels,
+ ffn_dropout=0.0,
+ operation_order=None,
+ act_cfg=dict(type='ReLU', inplace=True),
+ norm_cfg=dict(type='LN'),
+ ffn_num_fcs=2,
+ num_joints=17,
+ **kwargs):
+ super(DetrTransformerDecoderLayer_grouped, self).__init__(
+ attn_cfgs=attn_cfgs,
+ feedforward_channels=feedforward_channels,
+ ffn_dropout=ffn_dropout,
+ operation_order=operation_order,
+ act_cfg=act_cfg,
+ norm_cfg=norm_cfg,
+ ffn_num_fcs=ffn_num_fcs,
+ **kwargs)
+ # assert len(operation_order) == 6
+ # assert set(operation_order) == set(
+ # ['self_attn', 'norm', 'cross_attn', 'ffn'])
+ self.num_joints = num_joints
+ # self.num_joints = len(smpl_x.pos_joint_part['rhand'])
+ # self.num_joints = len(smpl_x.pos_joint_part['body']) + len(smpl_x.pos_joint_part['rhand']) + len(smpl_x.pos_joint_part['lhand'])
+
+ def forward(self,
+ query,
+ key=None,
+ value=None,
+ query_pos=None,
+ key_pos=None,
+ attn_masks=None,
+ query_key_padding_mask=None,
+ key_padding_mask=None,
+ **kwargs):
+
+ norm_index = 0
+ attn_index = 0
+ ffn_index = 0
+ identity = query
+ if attn_masks is None:
+ attn_masks = [None for _ in range(self.num_attn)]
+ elif isinstance(attn_masks, torch.Tensor):
+ attn_masks = [
+ copy.deepcopy(attn_masks) for _ in range(self.num_attn)
+ ]
+ warnings.warn(f'Use same attn_mask in all attentions in '
+ f'{self.__class__.__name__} ')
+ else:
+ assert len(attn_masks) == self.num_attn, f'The length of ' \
+ f'attn_masks {len(attn_masks)} must be equal ' \
+ f'to the number of attention in ' \
+ f'operation_order {self.num_attn}'
+
+ for layer in self.operation_order:
+ if layer == 'self_attn':
+ # print(query.shape)
+ assert query.size(0) % self.num_joints == 0, f'query.shape: {query.shape}, num_joints: {self.num_joints}'
+ num_group = query.size(0) // self.num_joints
+ bs = query.size(1)
+
+ temp_query = rearrange(query, '(g k) b c -> k (g b) c',
+ g=num_group, k=self.num_joints)
+ temp_identity = rearrange(identity, '(g k) b c -> k (g b) c',
+ g=num_group, k=self.num_joints)
+ temp_query_pos = rearrange(query_pos, '(g k) b c -> k (g b) c',
+ g=num_group, k=self.num_joints)
+
+ temp_key = temp_value = temp_query
+ query = self.attentions[attn_index](
+ temp_query,
+ temp_key,
+ temp_value,
+ temp_identity if self.pre_norm else None,
+ query_pos=temp_query_pos,
+ key_pos=temp_query_pos,
+ attn_mask=attn_masks[attn_index],
+ key_padding_mask=query_key_padding_mask,
+ **kwargs)
+
+ query = rearrange(query, 'k (g b) c -> (g k) b c',
+ g=num_group, b=bs)
+
+ attn_index += 1
+ identity = query
+
+ elif layer == 'norm':
+ query = self.norms[norm_index](query)
+ norm_index += 1
+
+ elif layer == 'cross_attn':
+ query = self.attentions[attn_index](
+ query,
+ key,
+ value,
+ identity if self.pre_norm else None,
+ query_pos=query_pos,
+ key_pos=key_pos,
+ attn_mask=attn_masks[attn_index],
+ key_padding_mask=key_padding_mask,
+ **kwargs)
+ attn_index += 1
+ identity = query
+
+ elif layer == 'ffn':
+ query = self.ffns[ffn_index](
+ query, identity if self.pre_norm else None)
+ ffn_index += 1
+ if 'cross_attn' not in self.operation_order:
+ query = query + value.sum() * 0
+
+ return query
+
+
+@TRANSFORMER_LAYER_SEQUENCE.register_module()
+class DeformableDetrTransformerDecoder(TransformerLayerSequence):
+ """Implements the decoder in DETR transformer.
+ Args:
+ return_intermediate (bool): Whether to return intermediate outputs.
+ coder_norm_cfg (dict): Config of last normalization layer. Default:
+ `LN`.
+ """
+
+ def __init__(self, *args, return_intermediate=False, **kwargs):
+
+ super(DeformableDetrTransformerDecoder, self).__init__(*args, **kwargs)
+ self.return_intermediate = return_intermediate
+
+ def forward(self,
+ query,
+ *args,
+ reference_points=None,
+ valid_ratios=None,
+ reg_branches=None,
+ fc_coord=None,
+ **kwargs):
+ output = query
+ intermediate = []
+ intermediate_reference_points = []
+
+ for lid, layer in enumerate(self.layers):
+ if reference_points.shape[-1] == 4:
+ reference_points_input = reference_points[:, :, None] * \
+ torch.cat([valid_ratios, valid_ratios], -1)[:, None]
+ else:
+ assert reference_points.shape[-1] == 3
+ # print(reference_points.shape, valid_ratios.shape) # [48,65,3], [48,4,3]
+ reference_points_input = reference_points[:, :, None, :2] * \
+ valid_ratios[:, None]
+ # assert reference_points.shape[-1] == 2
+ # reference_points_input = reference_points[:, :, None] * \
+ # valid_ratios[:, None]
+ # print(output.shape, reference_points_input.shape)
+ output = layer(
+ output,
+ *args,
+ reference_points=reference_points_input,
+ **kwargs)
+ output = output.permute(1, 0, 2)
+
+ # if reg_branches is not None:
+ # tmp = reg_branches[lid](output)
+ #
+ # if fc_coord is not None:
+ # tmp = fc_coord(tmp)
+ #
+ # if reference_points.shape[-1] == 4:
+ # new_reference_points = tmp + inverse_sigmoid(
+ # reference_points)
+ # new_reference_points = new_reference_points.sigmoid()
+ # else:
+ # assert reference_points.shape[-1] == 3
+ # new_reference_points = tmp
+ # new_reference_points[..., :3] = tmp[
+ # ..., :3] + inverse_sigmoid(reference_points)
+ # new_reference_points = new_reference_points.sigmoid()
+ # # else:
+ # # assert reference_points.shape[-1] == 2
+ # # new_reference_points = tmp
+ # # new_reference_points[..., :2] = tmp[
+ # # ..., :2] + inverse_sigmoid(reference_points)
+ # # new_reference_points = new_reference_points.sigmoid()
+ # # # reference_points = new_reference_points.detach()
+ # # reference_points = new_reference_points
+ # reference_points = new_reference_points
+ output = output.permute(1, 0, 2)
+ if self.return_intermediate:
+ intermediate.append(output)
+ intermediate_reference_points.append(reference_points)
+
+ if self.return_intermediate:
+ return torch.stack(intermediate), torch.stack(
+ intermediate_reference_points)
+
+ return output, reference_points
+
+
+class Linear_with_norm(nn.Module):
+ def __init__(self, in_channel, out_channel, bias=True, norm=True):
+ super(Linear_with_norm, self).__init__()
+ self.bias = bias
+ self.norm = norm
+ self.linear = nn.Linear(in_channel, out_channel, bias)
+ nn.init.xavier_uniform_(self.linear.weight, gain=0.01)
+
+ def forward(self, x):
+ y = x.matmul(self.linear.weight.t())
+
+ if self.norm:
+ x_norm = torch.norm(x, dim=1, keepdim=True)
+ y = y / x_norm
+
+ if self.bias:
+ y = y + self.linear.bias
+ return y
+
+
+@TRANSFORMER.register_module()
+class Transformer(BaseModule):
+ """Implements the DETR transformer.
+ Following the official DETR implementation, this module copy-paste
+ from torch.nn.Transformer with modifications:
+ * positional encodings are passed in MultiheadAttention
+ * extra LN at the end of encoder is removed
+ * decoder returns a stack of activations from all decoding layers
+ See `paper: End-to-End Object Detection with Transformers
+ `_ for details.
+ Args:
+ encoder (`mmcv.ConfigDict` | Dict): Config of
+ TransformerEncoder. Defaults to None.
+ decoder ((`mmcv.ConfigDict` | Dict)): Config of
+ TransformerDecoder. Defaults to None
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Defaults to None.
+ """
+
+ def __init__(self, encoder=None, decoder=None, init_cfg=None):
+ super(Transformer, self).__init__(init_cfg=init_cfg)
+ self.encoder = build_transformer_layer_sequence(encoder)
+ self.decoder = build_transformer_layer_sequence(decoder)
+ # self.embed_dims = self.encoder.embed_dims
+
+ def init_weights(self):
+ # follow the official DETR to init parameters
+ for m in self.modules():
+ if hasattr(m, 'weight') and m.weight.dim() > 1:
+ xavier_init(m, distribution='uniform')
+ self._is_init = True
+
+ def forward(self, x, mask, query_embed, pos_embed):
+ """Forward function for `Transformer`.
+ Args:
+ x (Tensor): Input query with shape [bs, c, h, w] where
+ c = embed_dims.
+ mask (Tensor): The key_padding_mask used for encoder and decoder,
+ with shape [bs, h, w].
+ query_embed (Tensor): The query embedding for decoder, with shape
+ [num_query, c].
+ pos_embed (Tensor): The positional encoding for encoder and
+ decoder, with the same shape as `x`.
+ Returns:
+ tuple[Tensor]: results of decoder containing the following tensor.
+ - out_dec: Output from decoder. If return_intermediate_dec \
+ is True output has shape [num_dec_layers, bs,
+ num_query, embed_dims], else has shape [1, bs, \
+ num_query, embed_dims].
+ - memory: Output results from encoder, with shape \
+ [bs, embed_dims, h, w].
+ """
+ bs, c, h, w = x.shape
+ # use `view` instead of `flatten` for dynamically exporting to ONNX
+ x = x.view(bs, c, -1).permute(2, 0, 1) # [bs, c, h, w] -> [h*w, bs, c]
+ pos_embed = pos_embed.view(bs, c, -1).permute(2, 0, 1)
+ query_embed = query_embed.unsqueeze(1).repeat(
+ 1, bs, 1) # [num_query, dim] -> [num_query, bs, dim]
+ mask = mask.view(bs, -1) # [bs, h, w] -> [bs, h*w]
+ memory = self.encoder(
+ query=x,
+ key=None,
+ value=None,
+ query_pos=pos_embed,
+ query_key_padding_mask=mask)
+ target = torch.zeros_like(query_embed)
+ # out_dec: [num_layers, num_query, bs, dim]
+ out_dec = self.decoder(
+ query=target,
+ key=memory,
+ value=memory,
+ key_pos=pos_embed,
+ query_pos=query_embed,
+ key_padding_mask=mask)
+ out_dec = out_dec.transpose(1, 2)
+ memory = memory.permute(1, 2, 0).reshape(bs, c, h, w)
+ return out_dec, memory
+
+
+@TRANSFORMER.register_module()
+class PoseurTransformer_v3(Transformer):
+ """ add noise training """
+
+ def __init__(self,
+ as_two_stage=False,
+ num_feature_levels=4,
+ two_stage_num_proposals=300,
+ num_joints=17,
+ use_soft_argmax=False,
+ use_soft_argmax_def=False,
+ proposal_feature='backbone_s', # or encoder_memory
+ image_size=[192, 256],
+ init_q_sigmoid=False,
+ soft_arg_stride=4,
+ add_feat_2_query=False,
+ query_pose_emb=True,
+ num_noise_sample=3,
+ num_noise_point=4,
+ noise_sigma=0.2,
+ embed_dims=256,
+ **kwargs):
+ super(PoseurTransformer_v3, self).__init__(**kwargs)
+ assert query_pose_emb == True
+ # self.num_noise_sample = num_noise_sample
+ self.num_noise_sample = num_noise_sample
+ self.num_noise_point = num_noise_point
+ self.noise_sigma = noise_sigma
+ self.add_feat_2_query = add_feat_2_query
+ self.as_two_stage = as_two_stage
+ self.num_feature_levels = num_feature_levels
+ self.two_stage_num_proposals = two_stage_num_proposals
+ try:
+ self.embed_dims = self.encoder.embed_dims
+ except:
+ self.embed_dims = embed_dims
+ self.num_joints = num_joints
+ # self.num_joints = 17
+ # self.num_joints = len(smpl_x.pos_joint_part['rhand']) # body_joints+bboxes
+ # self.num_joints = len(smpl_x.pos_joint_part['body']) + len(smpl_x.pos_joint_part['rhand']) + len(smpl_x.pos_joint_part['lhand'])
+ self.use_soft_argmax = use_soft_argmax
+ self.use_soft_argmax_def = use_soft_argmax_def
+ assert not (self.use_soft_argmax & self.use_soft_argmax_def)
+ self.init_q_sigmoid = init_q_sigmoid
+ self.image_size = image_size
+ self.soft_arg_stride = soft_arg_stride
+ self.proposal_feature = proposal_feature
+ self.query_pose_emb = query_pose_emb
+ self.prior = distributions.MultivariateNormal(torch.zeros(2), torch.eye(2) * self.noise_sigma)
+ self.init_layers()
+
+ def init_layers(self):
+ """Initialize layers of the DeformableDetrTransformer."""
+ self.level_embeds = nn.Parameter(
+ torch.Tensor(self.num_feature_levels, self.embed_dims))
+
+ if self.as_two_stage:
+ self.avg_pool = nn.AdaptiveAvgPool2d(1)
+ # self.fc_sigma = Linear_with_norm(self.embed_dims, self.num_joints * 2, norm=False)
+ self.fc_sigma = Linear_with_norm(self.embed_dims, self.num_joints * 3, norm=False)
+ if self.use_soft_argmax:
+ self.soft_argmax_coord = Heatmap1DHead(in_channels=self.embed_dims, expand_ratio=2, hidden_dims=(512,),
+ image_size=self.image_size, stride=self.soft_arg_stride)
+ self.fc_layers = [self.fc_sigma]
+ elif self.use_soft_argmax_def:
+ self.soft_argmax_coord = Heatmap2DHead(in_channels=self.embed_dims,
+ image_size=self.image_size, stride=self.soft_arg_stride)
+ self.fc_layers = [self.fc_sigma]
+ else:
+ # self.fc_coord = Linear_with_norm(self.embed_dims, self.num_joints * 2)
+ self.fc_coord = Linear_with_norm(self.embed_dims, self.num_joints * 3)
+ self.fc_layers = [self.fc_coord, self.fc_sigma]
+
+ if self.query_pose_emb:
+ self.pos_trans = nn.Linear(self.embed_dims * 2,
+ self.embed_dims)
+ self.pos_trans_norm = nn.LayerNorm(self.embed_dims)
+ # self.pos_embed = nn.Embedding(17,self.embed_dims)
+ self.pos_embed = nn.Embedding(self.num_joints, self.embed_dims)
+ else:
+ self.pos_trans = nn.Linear(self.embed_dims * 2,
+ self.embed_dims * 2)
+ self.pos_trans_norm = nn.LayerNorm(self.embed_dims * 2)
+ else:
+ self.reference_points = nn.Linear(self.embed_dims, 2)
+ self.fp16_enabled = False
+
+ def init_weights(self):
+ """Initialize the transformer weights."""
+ for p in self.parameters():
+ if p.dim() > 1:
+ nn.init.xavier_uniform_(p)
+ for m in self.modules():
+ if isinstance(m, MultiScaleDeformableAttention):
+ m.init_weights()
+ if not self.as_two_stage:
+ xavier_init(self.reference_points, distribution='uniform', bias=0.)
+ normal_(self.level_embeds)
+ if self.use_soft_argmax:
+ self.soft_argmax_coord.init_weights()
+
+ if self.as_two_stage:
+ for m in self.fc_layers:
+ if isinstance(m, nn.Linear):
+ nn.init.xavier_uniform_(m.weight, gain=0.01)
+
+ def gen_encoder_output_proposals(self, memory, memory_padding_mask,
+ spatial_shapes):
+ """Generate proposals from encoded memory.
+ Args:
+ memory (Tensor) : The output of encoder,
+ has shape (bs, num_key, embed_dim). num_key is
+ equal the number of points on feature map from
+ all level.
+ memory_padding_mask (Tensor): Padding mask for memory.
+ has shape (bs, num_key).
+ spatial_shapes (Tensor): The shape of all feature maps.
+ has shape (num_level, 2).
+ Returns:
+ tuple: A tuple of feature map and bbox prediction.
+ - output_memory (Tensor): The input of decoder, \
+ has shape (bs, num_key, embed_dim). num_key is \
+ equal the number of points on feature map from \
+ all levels.
+ - output_proposals (Tensor): The normalized proposal \
+ after a inverse sigmoid, has shape \
+ (bs, num_keys, 4).
+ """
+
+ N, S, C = memory.shape
+ proposals = []
+ _cur = 0
+ for lvl, (H, W) in enumerate(spatial_shapes):
+ mask_flatten_ = memory_padding_mask[:, _cur:(_cur + H * W)].view(
+ N, H, W, 1)
+ valid_H = torch.sum(~mask_flatten_[:, :, 0, 0], 1)
+ valid_W = torch.sum(~mask_flatten_[:, 0, :, 0], 1)
+
+ grid_y, grid_x = torch.meshgrid(
+ torch.linspace(
+ 0, H - 1, H, dtype=torch.float32, device=memory.device),
+ torch.linspace(
+ 0, W - 1, W, dtype=torch.float32, device=memory.device))
+ grid = torch.cat([grid_x.unsqueeze(-1), grid_y.unsqueeze(-1)], -1)
+
+ scale = torch.cat([valid_W.unsqueeze(-1),
+ valid_H.unsqueeze(-1)], 1).view(N, 1, 1, 2)
+ grid = (grid.unsqueeze(0).expand(N, -1, -1, -1) + 0.5) / scale
+ wh = torch.ones_like(grid) * 0.05 * (2.0 ** lvl)
+ # proposal = torch.cat((grid, wh), -1).view(N, -1, 4)
+ proposal = grid.view(N, -1, 2)
+ proposals.append(proposal)
+ _cur += (H * W)
+ output_proposals = torch.cat(proposals, 1)
+ output_proposals_valid = ((output_proposals > 0.01) &
+ (output_proposals < 0.99)).all(
+ -1, keepdim=True)
+ output_proposals = torch.log(output_proposals / (1 - output_proposals))
+ output_proposals = output_proposals.masked_fill(
+ memory_padding_mask.unsqueeze(-1), float('inf'))
+ output_proposals = output_proposals.masked_fill(
+ ~output_proposals_valid, float('inf'))
+
+ output_memory = memory
+ output_memory = output_memory.masked_fill(
+ memory_padding_mask.unsqueeze(-1), float(0))
+ output_memory = output_memory.masked_fill(~output_proposals_valid,
+ float(0))
+ output_memory = self.enc_output_norm(self.enc_output(output_memory))
+ return output_memory, output_proposals
+
+ @staticmethod
+ def get_reference_points(spatial_shapes, valid_ratios, device):
+ """Get the reference points used in decoder.
+ Args:
+ spatial_shapes (Tensor): The shape of all
+ feature maps, has shape (num_level, 2).
+ valid_ratios (Tensor): The radios of valid
+ points on the feature map, has shape
+ (bs, num_levels, 2)
+ device (obj:`device`): The device where
+ reference_points should be.
+ Returns:
+ Tensor: reference points used in decoder, has \
+ shape (bs, num_keys, num_levels, 2).
+ """
+ # print(spatial_shapes)
+ reference_points_list = []
+ for lvl, (H, W) in enumerate(spatial_shapes):
+ # TODO check this 0.5
+ ref_y, ref_x = torch.meshgrid(
+ torch.linspace(
+ 0.5, H - 0.5, H, dtype=torch.float32, device=device),
+ torch.linspace(
+ 0.5, W - 0.5, W, dtype=torch.float32, device=device))
+ ref_y = ref_y.reshape(-1)[None] / (
+ valid_ratios[:, None, lvl, 1] * H)
+ ref_x = ref_x.reshape(-1)[None] / (
+ valid_ratios[:, None, lvl, 0] * W)
+ ref = torch.stack((ref_x, ref_y), -1)
+ reference_points_list.append(ref)
+ # print(reference_points_list[-1]) # range:(0,1)
+ # print(H, W) [8,6]
+ reference_points = torch.cat(reference_points_list, 1)
+ reference_points = reference_points[:, :, None] * valid_ratios[:, None]
+ return reference_points
+
+ def get_valid_ratio(self, mask):
+ """Get the valid radios of feature maps of all level."""
+ _, H, W = mask.shape
+ valid_H = torch.sum(~mask[:, :, 0], 1)
+ valid_W = torch.sum(~mask[:, 0, :], 1)
+ valid_ratio_h = valid_H.float() / H
+ valid_ratio_w = valid_W.float() / W
+ valid_ratio = torch.stack([valid_ratio_w, valid_ratio_h], -1)
+ return valid_ratio
+
+ def get_proposal_pos_embed(self,
+ proposals,
+ num_pos_feats=128,
+ temperature=10000):
+ """Get the position embedding of proposal."""
+ num_pos_feats = self.embed_dims // 3 + 1
+ scale = 2 * math.pi
+ dim_t = torch.arange(
+ num_pos_feats, dtype=torch.float32, device=proposals.device)
+ dim_t = temperature ** (2 * (dim_t // 2) / num_pos_feats)
+ # N, L, 2
+ if self.init_q_sigmoid:
+ proposals = proposals.sigmoid() * scale
+ else:
+ proposals = proposals * scale
+
+ # N, L, 3, 86
+ pos = proposals[:, :, :, None] / dim_t
+ # N, L, 3, 43, 2
+ pos = torch.stack((pos[:, :, :, 0::2].sin(), pos[:, :, :, 1::2].cos()), dim=4).flatten(2)
+ return pos[:, :, :self.embed_dims]
+
+ @force_fp32(apply_to=('mlvl_feats', 'query_embed', 'mlvl_pos_embeds'))
+ def forward(self,
+ mlvl_feats,
+ mlvl_masks,
+ query_embed,
+ mlvl_pos_embeds,
+ reg_branches=None,
+ fc_coord=None,
+ cls_branches=None,
+ coord_init=None,
+ query_init=None,
+ **kwargs):
+ assert self.as_two_stage or query_embed is not None
+
+ feat_flatten = []
+ mask_flatten = []
+ lvl_pos_embed_flatten = []
+ spatial_shapes = []
+ for lvl, (feat, mask, pos_embed) in enumerate(
+ zip(mlvl_feats, mlvl_masks, mlvl_pos_embeds)):
+ bs, c, h, w = feat.shape
+ spatial_shape = (h, w)
+ spatial_shapes.append(spatial_shape)
+ feat = feat.flatten(2).transpose(1, 2)
+ mask = mask.flatten(1)
+ pos_embed = pos_embed.flatten(2).transpose(1, 2)
+ lvl_pos_embed = pos_embed + self.level_embeds[lvl].view(1, 1, -1)
+ lvl_pos_embed_flatten.append(lvl_pos_embed)
+ feat_flatten.append(feat)
+ mask_flatten.append(mask)
+ feat_flatten = torch.cat(feat_flatten, 1)
+ mask_flatten = torch.cat(mask_flatten, 1)
+ lvl_pos_embed_flatten = torch.cat(lvl_pos_embed_flatten, 1)
+ spatial_shapes = torch.as_tensor(
+ spatial_shapes, dtype=torch.long, device=feat_flatten.device)
+ level_start_index = torch.cat((spatial_shapes.new_zeros(
+ (1,)), spatial_shapes.prod(1).cumsum(0)[:-1]))
+ valid_ratios = torch.stack(
+ [self.get_valid_ratio(m) for m in mlvl_masks], 1)
+ # [bs, H*W, num_lvls, 2]
+ # print(spatial_shape)
+ reference_points = \
+ self.get_reference_points(spatial_shapes,
+ valid_ratios,
+ device=feat.device)
+ # print(reference_points.shape, valid_ratios.shape) # [bs, 4080, 4, 2]; [bs, 4, 2]
+ feat_flatten = feat_flatten.permute(1, 0, 2) # (H*W, bs, embed_dims)
+ lvl_pos_embed_flatten = lvl_pos_embed_flatten.permute(
+ 1, 0, 2) # (H*W, bs, embed_dims)
+
+ memory = self.encoder(
+ query=feat_flatten,
+ key=None,
+ value=None,
+ query_pos=lvl_pos_embed_flatten,
+ query_key_padding_mask=mask_flatten,
+ spatial_shapes=spatial_shapes,
+ reference_points=reference_points,
+ level_start_index=level_start_index,
+ valid_ratios=valid_ratios,
+ **kwargs)
+
+ memory = memory.permute(1, 0, 2)
+ bs, _, c = memory.shape
+
+ if self.proposal_feature == 'backbone_l':
+ x = mlvl_feats[0]
+ elif self.proposal_feature == 'backbone_s':
+ x = mlvl_feats[-1]
+ point_sample_feat = mlvl_feats[-1]
+ elif self.proposal_feature == 'encoder_memory_l':
+ x = memory.permute(0, 2, 1)[:, :, :int(level_start_index[1])].view_as(mlvl_feats[0])
+ point_sample_feat = memory.permute(0, 2, 1)[:, :, :int(level_start_index[1])].view_as(mlvl_feats[0])
+ elif self.proposal_feature == 'encoder_memory_s':
+ x = memory.permute(0, 2, 1)[:, :, int(level_start_index[-1]):].view_as(mlvl_feats[-1])
+ else:
+ raise NotImplementedError
+
+ BATCH_SIZE = x.shape[0]
+
+ if coord_init is not None:
+ pred_jts = coord_init
+ enc_outputs = None
+ else:
+ if self.use_soft_argmax:
+ out_coord = self.soft_argmax_coord(x) # bs, 17, 2
+ assert out_coord.shape[2] == 2
+ x = self.avg_pool(x).reshape(BATCH_SIZE, -1)
+ out_sigma = self.fc_sigma(x).reshape(BATCH_SIZE, self.num_joints, -1)
+ elif self.use_soft_argmax_def:
+ out_coord = self.soft_argmax_coord(x) # bs, 17, 2
+ assert out_coord.shape[2] == 2
+ x = self.avg_pool(x).reshape(BATCH_SIZE, -1)
+ out_sigma = self.fc_sigma(x).reshape(BATCH_SIZE, self.num_joints, -1)
+ else:
+ x = self.avg_pool(x).reshape(BATCH_SIZE, -1)
+ out_coord = self.fc_coord(x).reshape(BATCH_SIZE, self.num_joints, 3)
+ assert out_coord.shape[2] == 3
+ out_sigma = self.fc_sigma(x).reshape(BATCH_SIZE, self.num_joints, -1)
+
+ # (B, N, 3)
+ pred_jts = out_coord.reshape(BATCH_SIZE, self.num_joints, 3)
+ sigma = out_sigma.reshape(BATCH_SIZE, self.num_joints, -1).sigmoid()
+ scores = 1 - sigma
+
+ scores = torch.mean(scores, dim=2, keepdim=True)
+ enc_outputs = EasyDict(
+ pred_jts=pred_jts,
+ sigma=sigma,
+ maxvals=scores.float(),
+ )
+
+ reference_points = pred_jts.detach()
+ reference_points_cliped = reference_points.clip(0, 1)
+
+ init_reference_out = reference_points_cliped
+ if query_init is not None:
+ query = query_init
+ else:
+ pred_jts_pos_embed = self.get_proposal_pos_embed(reference_points.detach())
+ reference_points_pos_embed = self.get_proposal_pos_embed(reference_points_cliped.detach()) # query init here
+ if self.add_feat_2_query:
+ query_feat = point_sample(point_sample_feat, init_reference_out, align_corners=False).permute(0, 2, 1)
+ reference_points_pos_embed = reference_points_pos_embed + query_feat
+ query_pos_emb = torch.cat([pred_jts_pos_embed, reference_points_pos_embed], dim=2)
+ pos_trans_out = self.pos_trans_norm(self.pos_trans(query_pos_emb))
+
+ query = pos_trans_out
+
+ query_pos = self.pos_embed.weight.clone().repeat(bs, 1, 1).contiguous()
+
+ # decoder
+ query = query.permute(1, 0, 2)
+ memory = memory.permute(1, 0, 2)
+ query_pos = query_pos.permute(1, 0, 2)
+ inter_states, inter_references = self.decoder(
+ query=query,
+ key=None,
+ value=memory,
+ query_pos=query_pos,
+ key_padding_mask=mask_flatten,
+ reference_points=reference_points,
+ spatial_shapes=spatial_shapes,
+ level_start_index=level_start_index,
+ valid_ratios=valid_ratios,
+ reg_branches=reg_branches,
+ fc_coord=fc_coord,
+ **kwargs)
+ inter_references_out = inter_references
+ return memory.permute(1, 0, 2), spatial_shapes, level_start_index, inter_states, init_reference_out, \
+ inter_references_out, enc_outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..d6af823310ad59c2d1e52274f8af9a0fc0f14a72
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/__init__.py
@@ -0,0 +1,9 @@
+from .multi_scale_deform_attn import (MultiScaleDeformableAttention_share_value,
+ MultiScaleDeformableAttention_bottle_neck_v,
+ MultiScaleDeformableAttention_post_value,
+ MultiScaleDeformableAttention_post_v_stirct,
+ )
+
+__all__ = [
+ 'MultiScaleDeformableAttention',
+]
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/info.cpp b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/info.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..d252ba2edf71649c976923f9836da801fd71b48b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/info.cpp
@@ -0,0 +1,55 @@
+// modified from
+// https://github.com/facebookresearch/detectron2/blob/master/detectron2/layers/csrc/vision.cpp
+#include "pytorch_cpp_helper.hpp"
+
+#ifdef MMCV_WITH_CUDA
+#ifndef HIP_DIFF
+#include
+int get_cudart_version() { return CUDART_VERSION; }
+#endif
+#endif
+
+std::string get_compiling_cuda_version() {
+#ifdef MMCV_WITH_CUDA
+#ifndef HIP_DIFF
+ std::ostringstream oss;
+ // copied from
+ // https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/cuda/detail/CUDAHooks.cpp#L231
+ auto printCudaStyleVersion = [&](int v) {
+ oss << (v / 1000) << "." << (v / 10 % 100);
+ if (v % 10 != 0) {
+ oss << "." << (v % 10);
+ }
+ };
+ printCudaStyleVersion(get_cudart_version());
+ return oss.str();
+#else
+ return std::string("rocm not vailable");
+#endif
+#else
+ return std::string("not available");
+#endif
+}
+
+// similar to
+// https://github.com/pytorch/pytorch/blob/master/aten/src/ATen/Version.cpp
+std::string get_compiler_version() {
+ std::ostringstream ss;
+#if defined(__GNUC__)
+#ifndef __clang__
+ { ss << "GCC " << __GNUC__ << "." << __GNUC_MINOR__; }
+#endif
+#endif
+
+#if defined(__clang_major__)
+ {
+ ss << "clang " << __clang_major__ << "." << __clang_minor__ << "."
+ << __clang_patchlevel__;
+ }
+#endif
+
+#if defined(_MSC_VER)
+ { ss << "MSVC " << _MSC_FULL_VER; }
+#endif
+ return ss.str();
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn.cpp b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..1fda9aeba25b8fd87fd8b9e2d7e27d646271d7b3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn.cpp
@@ -0,0 +1,79 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from
+*https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include "pytorch_cpp_helper.hpp"
+
+#ifdef MMCV_WITH_CUDA
+Tensor ms_deform_attn_cuda_forward(const Tensor &value,
+ const Tensor &spatial_shapes,
+ const Tensor &level_start_index,
+ const Tensor &sampling_loc,
+ const Tensor &attn_weight,
+ const int im2col_step);
+
+void ms_deform_attn_cuda_backward(
+ const Tensor &value, const Tensor &spatial_shapes,
+ const Tensor &level_start_index, const Tensor &sampling_loc,
+ const Tensor &attn_weight, const Tensor &grad_output, Tensor &grad_value,
+ Tensor &grad_sampling_loc, Tensor &grad_attn_weight, const int im2col_step);
+
+#endif
+
+Tensor ms_deform_attn_forward(const Tensor &value, const Tensor &spatial_shapes,
+ const Tensor &level_start_index,
+ const Tensor &sampling_loc,
+ const Tensor &attn_weight,
+ const int im2col_step) {
+ if (value.type().is_cuda()) {
+#ifdef MMCV_WITH_CUDA
+ CHECK_CUDA_INPUT(value)
+ CHECK_CUDA_INPUT(spatial_shapes)
+ CHECK_CUDA_INPUT(level_start_index)
+ CHECK_CUDA_INPUT(sampling_loc)
+ CHECK_CUDA_INPUT(attn_weight)
+ return ms_deform_attn_cuda_forward(value, spatial_shapes, level_start_index,
+ sampling_loc, attn_weight, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ }
+ AT_ERROR("Not implemented on the CPU");
+}
+
+void ms_deform_attn_backward(const Tensor &value, const Tensor &spatial_shapes,
+ const Tensor &level_start_index,
+ const Tensor &sampling_loc,
+ const Tensor &attn_weight,
+ const Tensor &grad_output, Tensor &grad_value,
+ Tensor &grad_sampling_loc,
+ Tensor &grad_attn_weight, const int im2col_step) {
+ if (value.type().is_cuda()) {
+#ifdef MMCV_WITH_CUDA
+ CHECK_CUDA_INPUT(value)
+ CHECK_CUDA_INPUT(spatial_shapes)
+ CHECK_CUDA_INPUT(level_start_index)
+ CHECK_CUDA_INPUT(sampling_loc)
+ CHECK_CUDA_INPUT(attn_weight)
+ CHECK_CUDA_INPUT(grad_output)
+ CHECK_CUDA_INPUT(grad_value)
+ CHECK_CUDA_INPUT(grad_sampling_loc)
+ CHECK_CUDA_INPUT(grad_attn_weight)
+ ms_deform_attn_cuda_backward(value, spatial_shapes, level_start_index,
+ sampling_loc, attn_weight, grad_output,
+ grad_value, grad_sampling_loc,
+ grad_attn_weight, im2col_step);
+#else
+ AT_ERROR("Not compiled with GPU support");
+#endif
+ } else {
+ AT_ERROR("Not implemented on the CPU");
+ }
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda.cu b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda.cu
new file mode 100644
index 0000000000000000000000000000000000000000..4c2ad396cf68ae470431e2cba362506bc068cc7d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda.cu
@@ -0,0 +1,360 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from
+*https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+
+#include
+#include
+#include
+#include
+
+#include
+#include
+#include
+
+template
+void ms_deformable_im2col_cuda(cudaStream_t stream, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size,
+ const int num_heads, const int channels,
+ const int num_levels, const int num_query,
+ const int num_point, scalar_t *data_col) {
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ const int num_threads = CUDA_NUM_THREADS;
+ ms_deformable_im2col_gpu_kernel
+ <<>>(
+ num_kernels, data_value, data_spatial_shapes, data_level_start_index,
+ data_sampling_loc, data_attn_weight, batch_size, spatial_size,
+ num_heads, channels, num_levels, num_query, num_point, data_col);
+
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ printf("error in ms_deformable_im2col_cuda: %s\n", cudaGetErrorString(err));
+ }
+}
+
+template
+void ms_deformable_col2im_cuda(
+ cudaStream_t stream, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ const int num_threads =
+ (channels > CUDA_NUM_THREADS) ? CUDA_NUM_THREADS : channels;
+ const int num_kernels = batch_size * num_query * num_heads * channels;
+ const int num_actual_kernels = batch_size * num_query * num_heads * channels;
+ if (channels > 1024) {
+ if ((channels & 1023) == 0) {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks
+ <<>>(
+ num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels,
+ num_query, num_point, grad_value, grad_sampling_loc,
+ grad_attn_weight);
+ } else {
+ ms_deformable_col2im_gpu_kernel_gm
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ } else {
+ switch (channels) {
+ case 1:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 2:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 4:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 8:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 16:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 32:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 64:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 128:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 256:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 512:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ case 1024:
+ ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2
+ <<>>(num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc,
+ data_attn_weight, batch_size, spatial_size, num_heads,
+ channels, num_levels, num_query, num_point, grad_value,
+ grad_sampling_loc, grad_attn_weight);
+ break;
+ default:
+ if (channels < 64) {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v1
+ <<>>(
+ num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels,
+ num_query, num_point, grad_value, grad_sampling_loc,
+ grad_attn_weight);
+ } else {
+ ms_deformable_col2im_gpu_kernel_shm_reduce_v2
+ <<>>(
+ num_kernels, grad_col, data_value, data_spatial_shapes,
+ data_level_start_index, data_sampling_loc, data_attn_weight,
+ batch_size, spatial_size, num_heads, channels, num_levels,
+ num_query, num_point, grad_value, grad_sampling_loc,
+ grad_attn_weight);
+ }
+ }
+ }
+ cudaError_t err = cudaGetLastError();
+ if (err != cudaSuccess) {
+ printf("error in ms_deformable_col2im_cuda: %s\n", cudaGetErrorString(err));
+ }
+}
+
+at::Tensor ms_deform_attn_cuda_forward(const at::Tensor &value,
+ const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index,
+ const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight,
+ const int im2col_step) {
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(),
+ "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(),
+ "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(),
+ "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(),
+ "attn_weight tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(),
+ "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(),
+ "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(),
+ "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)",
+ batch, im2col_step_);
+
+ auto output =
+ at::zeros({batch, num_query, num_heads, channels}, value.options());
+
+ const int batch_n = im2col_step_;
+ auto output_n = output.view(
+ {batch / im2col_step_, batch_n, num_query, num_heads, channels});
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ for (int n = 0; n < batch / im2col_step_; ++n) {
+ auto columns = output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(
+ value.type(), "ms_deform_attn_forward_cuda", ([&] {
+ ms_deformable_im2col_cuda(
+ at::cuda::getCurrentCUDAStream(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(), level_start_index.data(),
+ sampling_loc.data() +
+ n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() +
+ n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query,
+ num_point, columns.data());
+ }));
+ }
+
+ output = output.view({batch, num_query, num_heads * channels});
+
+ return output;
+}
+
+void ms_deform_attn_cuda_backward(
+ const at::Tensor &value, const at::Tensor &spatial_shapes,
+ const at::Tensor &level_start_index, const at::Tensor &sampling_loc,
+ const at::Tensor &attn_weight, const at::Tensor &grad_output,
+ at::Tensor &grad_value, at::Tensor &grad_sampling_loc,
+ at::Tensor &grad_attn_weight, const int im2col_step) {
+ AT_ASSERTM(value.is_contiguous(), "value tensor has to be contiguous");
+ AT_ASSERTM(spatial_shapes.is_contiguous(),
+ "spatial_shapes tensor has to be contiguous");
+ AT_ASSERTM(level_start_index.is_contiguous(),
+ "level_start_index tensor has to be contiguous");
+ AT_ASSERTM(sampling_loc.is_contiguous(),
+ "sampling_loc tensor has to be contiguous");
+ AT_ASSERTM(attn_weight.is_contiguous(),
+ "attn_weight tensor has to be contiguous");
+ AT_ASSERTM(grad_output.is_contiguous(),
+ "grad_output tensor has to be contiguous");
+
+ AT_ASSERTM(value.type().is_cuda(), "value must be a CUDA tensor");
+ AT_ASSERTM(spatial_shapes.type().is_cuda(),
+ "spatial_shapes must be a CUDA tensor");
+ AT_ASSERTM(level_start_index.type().is_cuda(),
+ "level_start_index must be a CUDA tensor");
+ AT_ASSERTM(sampling_loc.type().is_cuda(),
+ "sampling_loc must be a CUDA tensor");
+ AT_ASSERTM(attn_weight.type().is_cuda(), "attn_weight must be a CUDA tensor");
+ AT_ASSERTM(grad_output.type().is_cuda(), "grad_output must be a CUDA tensor");
+
+ const int batch = value.size(0);
+ const int spatial_size = value.size(1);
+ const int num_heads = value.size(2);
+ const int channels = value.size(3);
+
+ const int num_levels = spatial_shapes.size(0);
+
+ const int num_query = sampling_loc.size(1);
+ const int num_point = sampling_loc.size(4);
+
+ const int im2col_step_ = std::min(batch, im2col_step);
+
+ AT_ASSERTM(batch % im2col_step_ == 0, "batch(%d) must divide im2col_step(%d)",
+ batch, im2col_step_);
+
+ const int batch_n = im2col_step_;
+ auto per_value_size = spatial_size * num_heads * channels;
+ auto per_sample_loc_size = num_query * num_heads * num_levels * num_point * 2;
+ auto per_attn_weight_size = num_query * num_heads * num_levels * num_point;
+ auto grad_output_n = grad_output.view(
+ {batch / im2col_step_, batch_n, num_query, num_heads, channels});
+
+ for (int n = 0; n < batch / im2col_step_; ++n) {
+ auto grad_output_g = grad_output_n.select(0, n);
+ AT_DISPATCH_FLOATING_TYPES(
+ value.type(), "ms_deform_attn_backward_cuda", ([&] {
+ ms_deformable_col2im_cuda(
+ at::cuda::getCurrentCUDAStream(), grad_output_g.data(),
+ value.data() + n * im2col_step_ * per_value_size,
+ spatial_shapes.data(), level_start_index.data(),
+ sampling_loc.data() +
+ n * im2col_step_ * per_sample_loc_size,
+ attn_weight.data() +
+ n * im2col_step_ * per_attn_weight_size,
+ batch_n, spatial_size, num_heads, channels, num_levels, num_query,
+ num_point,
+ grad_value.data() + n * im2col_step_ * per_value_size,
+ grad_sampling_loc.data() +
+ n * im2col_step_ * per_sample_loc_size,
+ grad_attn_weight.data() +
+ n * im2col_step_ * per_attn_weight_size);
+ }));
+ }
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda_kernel.cuh b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda_kernel.cuh
new file mode 100644
index 0000000000000000000000000000000000000000..cbdf3820117a5cab28e2d116f3404876efa6a0bd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/csrc/pytorch/ms_deform_attn_cuda_kernel.cuh
@@ -0,0 +1,807 @@
+/*!
+**************************************************************************************************
+* Deformable DETR
+* Copyright (c) 2020 SenseTime. All Rights Reserved.
+* Licensed under the Apache License, Version 2.0 [see LICENSE for details]
+**************************************************************************************************
+* Modified from
+*https://github.com/chengdazhi/Deformable-Convolution-V2-PyTorch/tree/pytorch_1.0.0
+**************************************************************************************************
+*/
+#ifndef DEFORM_ATTN_CUDA_KERNEL
+#define DEFORM_ATTN_CUDA_KERNEL
+
+#include "common_cuda_helper.hpp"
+#include "pytorch_cuda_helper.hpp"
+
+const int CUDA_NUM_THREADS = 1024;
+inline int GET_BLOCKS(const int N, const int num_threads) {
+ return (N + num_threads - 1) / num_threads;
+}
+
+template
+__device__ scalar_t ms_deform_attn_im2col_bilinear(
+ const scalar_t *&bottom_data, const int &height, const int &width,
+ const int &nheads, const int &channels, const scalar_t &h,
+ const scalar_t &w, const int &m, const int &c) {
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0) {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1) {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0) {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1) {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ }
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ return val;
+}
+
+template
+__device__ void ms_deform_attn_col2im_bilinear(
+ const scalar_t *&bottom_data, const int &height, const int &width,
+ const int &nheads, const int &channels, const scalar_t &h,
+ const scalar_t &w, const int &m, const int &c, const scalar_t &top_grad,
+ const scalar_t &attn_weight, scalar_t *&grad_value,
+ scalar_t *grad_sampling_loc, scalar_t *grad_attn_weight) {
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0) {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value + ptr1, w1 * top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1) {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value + ptr2, w2 * top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0) {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value + ptr3, w3 * top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1) {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value + ptr4, w4 * top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ *grad_attn_weight = top_grad * val;
+ *grad_sampling_loc = width * grad_w_weight * top_grad_value;
+ *(grad_sampling_loc + 1) = height * grad_h_weight * top_grad_value;
+}
+
+template
+__device__ void ms_deform_attn_col2im_bilinear_gm(
+ const scalar_t *&bottom_data, const int &height, const int &width,
+ const int &nheads, const int &channels, const scalar_t &h,
+ const scalar_t &w, const int &m, const int &c, const scalar_t &top_grad,
+ const scalar_t &attn_weight, scalar_t *&grad_value,
+ scalar_t *grad_sampling_loc, scalar_t *grad_attn_weight) {
+ const int h_low = floor(h);
+ const int w_low = floor(w);
+ const int h_high = h_low + 1;
+ const int w_high = w_low + 1;
+
+ const scalar_t lh = h - h_low;
+ const scalar_t lw = w - w_low;
+ const scalar_t hh = 1 - lh, hw = 1 - lw;
+
+ const int w_stride = nheads * channels;
+ const int h_stride = width * w_stride;
+ const int h_low_ptr_offset = h_low * h_stride;
+ const int h_high_ptr_offset = h_low_ptr_offset + h_stride;
+ const int w_low_ptr_offset = w_low * w_stride;
+ const int w_high_ptr_offset = w_low_ptr_offset + w_stride;
+ const int base_ptr = m * channels + c;
+
+ const scalar_t w1 = hh * hw, w2 = hh * lw, w3 = lh * hw, w4 = lh * lw;
+ const scalar_t top_grad_value = top_grad * attn_weight;
+ scalar_t grad_h_weight = 0, grad_w_weight = 0;
+
+ scalar_t v1 = 0;
+ if (h_low >= 0 && w_low >= 0) {
+ const int ptr1 = h_low_ptr_offset + w_low_ptr_offset + base_ptr;
+ v1 = bottom_data[ptr1];
+ grad_h_weight -= hw * v1;
+ grad_w_weight -= hh * v1;
+ atomicAdd(grad_value + ptr1, w1 * top_grad_value);
+ }
+ scalar_t v2 = 0;
+ if (h_low >= 0 && w_high <= width - 1) {
+ const int ptr2 = h_low_ptr_offset + w_high_ptr_offset + base_ptr;
+ v2 = bottom_data[ptr2];
+ grad_h_weight -= lw * v2;
+ grad_w_weight += hh * v2;
+ atomicAdd(grad_value + ptr2, w2 * top_grad_value);
+ }
+ scalar_t v3 = 0;
+ if (h_high <= height - 1 && w_low >= 0) {
+ const int ptr3 = h_high_ptr_offset + w_low_ptr_offset + base_ptr;
+ v3 = bottom_data[ptr3];
+ grad_h_weight += hw * v3;
+ grad_w_weight -= lh * v3;
+ atomicAdd(grad_value + ptr3, w3 * top_grad_value);
+ }
+ scalar_t v4 = 0;
+ if (h_high <= height - 1 && w_high <= width - 1) {
+ const int ptr4 = h_high_ptr_offset + w_high_ptr_offset + base_ptr;
+ v4 = bottom_data[ptr4];
+ grad_h_weight += lw * v4;
+ grad_w_weight += lh * v4;
+ atomicAdd(grad_value + ptr4, w4 * top_grad_value);
+ }
+
+ const scalar_t val = (w1 * v1 + w2 * v2 + w3 * v3 + w4 * v4);
+ atomicAdd(grad_attn_weight, top_grad * val);
+ atomicAdd(grad_sampling_loc, width * grad_w_weight * top_grad_value);
+ atomicAdd(grad_sampling_loc + 1, height * grad_h_weight * top_grad_value);
+}
+
+template
+__global__ void ms_deformable_im2col_gpu_kernel(
+ const int n, const scalar_t *data_value, const int64_t *data_spatial_shapes,
+ const int64_t *data_level_start_index, const scalar_t *data_sampling_loc,
+ const scalar_t *data_attn_weight, const int batch_size,
+ const int spatial_size, const int num_heads, const int channels,
+ const int num_levels, const int num_query, const int num_point,
+ scalar_t *data_col) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ scalar_t *data_col_ptr = data_col + index;
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+ scalar_t col = 0;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const scalar_t *data_value_ptr =
+ data_value +
+ (data_value_ptr_init_offset + level_start_id * qid_stride);
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ col += ms_deform_attn_im2col_bilinear(data_value_ptr, spatial_h,
+ spatial_w, num_heads, channels,
+ h_im, w_im, m_col, c_col) *
+ weight;
+ }
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ }
+ }
+ *data_col_ptr = col;
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v1(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc + (threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc + ((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight + threadIdx.x) = 0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc + (threadIdx.x << 1),
+ cache_grad_attn_weight + threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0) {
+ scalar_t _grad_w = cache_grad_sampling_loc[0],
+ _grad_h = cache_grad_sampling_loc[1],
+ _grad_a = cache_grad_attn_weight[0];
+ int sid = 2;
+ for (unsigned int tid = 1; tid < blockSize; ++tid) {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_blocksize_aware_reduce_v2(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ __shared__ scalar_t cache_grad_sampling_loc[blockSize * 2];
+ __shared__ scalar_t cache_grad_attn_weight[blockSize];
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc + (threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc + ((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight + threadIdx.x) = 0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc + (threadIdx.x << 1),
+ cache_grad_attn_weight + threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s = blockSize / 2; s > 0; s >>= 1) {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] +=
+ cache_grad_sampling_loc[xid2 + 1];
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0) {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v1(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ extern __shared__ int _s[];
+ scalar_t *cache_grad_sampling_loc = reinterpret_cast(_s);
+ scalar_t *cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc + (threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc + ((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight + threadIdx.x) = 0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc + (threadIdx.x << 1),
+ cache_grad_attn_weight + threadIdx.x);
+ }
+
+ __syncthreads();
+ if (tid == 0) {
+ scalar_t _grad_w = cache_grad_sampling_loc[0],
+ _grad_h = cache_grad_sampling_loc[1],
+ _grad_a = cache_grad_attn_weight[0];
+ int sid = 2;
+ for (unsigned int tid = 1; tid < blockDim.x; ++tid) {
+ _grad_w += cache_grad_sampling_loc[sid];
+ _grad_h += cache_grad_sampling_loc[sid + 1];
+ _grad_a += cache_grad_attn_weight[tid];
+ sid += 2;
+ }
+
+ *grad_sampling_loc = _grad_w;
+ *(grad_sampling_loc + 1) = _grad_h;
+ *grad_attn_weight = _grad_a;
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ extern __shared__ int _s[];
+ scalar_t *cache_grad_sampling_loc = reinterpret_cast(_s);
+ scalar_t *cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc + (threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc + ((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight + threadIdx.x) = 0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc + (threadIdx.x << 1),
+ cache_grad_attn_weight + threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s = blockDim.x / 2, spre = blockDim.x; s > 0;
+ s >>= 1, spre >>= 1) {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] +=
+ cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre) {
+ cache_grad_attn_weight[tid] +=
+ cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] +=
+ cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] +=
+ cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0) {
+ *grad_sampling_loc = cache_grad_sampling_loc[0];
+ *(grad_sampling_loc + 1) = cache_grad_sampling_loc[1];
+ *grad_attn_weight = cache_grad_attn_weight[0];
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_shm_reduce_v2_multi_blocks(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ extern __shared__ int _s[];
+ scalar_t *cache_grad_sampling_loc = reinterpret_cast(_s);
+ scalar_t *cache_grad_attn_weight = cache_grad_sampling_loc + 2 * blockDim.x;
+ unsigned int tid = threadIdx.x;
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ *(cache_grad_sampling_loc + (threadIdx.x << 1)) = 0;
+ *(cache_grad_sampling_loc + ((threadIdx.x << 1) + 1)) = 0;
+ *(cache_grad_attn_weight + threadIdx.x) = 0;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ cache_grad_sampling_loc + (threadIdx.x << 1),
+ cache_grad_attn_weight + threadIdx.x);
+ }
+
+ __syncthreads();
+
+ for (unsigned int s = blockDim.x / 2, spre = blockDim.x; s > 0;
+ s >>= 1, spre >>= 1) {
+ if (tid < s) {
+ const unsigned int xid1 = tid << 1;
+ const unsigned int xid2 = (tid + s) << 1;
+ cache_grad_attn_weight[tid] += cache_grad_attn_weight[tid + s];
+ cache_grad_sampling_loc[xid1] += cache_grad_sampling_loc[xid2];
+ cache_grad_sampling_loc[xid1 + 1] +=
+ cache_grad_sampling_loc[xid2 + 1];
+ if (tid + (s << 1) < spre) {
+ cache_grad_attn_weight[tid] +=
+ cache_grad_attn_weight[tid + (s << 1)];
+ cache_grad_sampling_loc[xid1] +=
+ cache_grad_sampling_loc[xid2 + (s << 1)];
+ cache_grad_sampling_loc[xid1 + 1] +=
+ cache_grad_sampling_loc[xid2 + 1 + (s << 1)];
+ }
+ }
+ __syncthreads();
+ }
+
+ if (tid == 0) {
+ atomicAdd(grad_sampling_loc, cache_grad_sampling_loc[0]);
+ atomicAdd(grad_sampling_loc + 1, cache_grad_sampling_loc[1]);
+ atomicAdd(grad_attn_weight, cache_grad_attn_weight[0]);
+ }
+ __syncthreads();
+
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+
+template
+__global__ void ms_deformable_col2im_gpu_kernel_gm(
+ const int n, const scalar_t *grad_col, const scalar_t *data_value,
+ const int64_t *data_spatial_shapes, const int64_t *data_level_start_index,
+ const scalar_t *data_sampling_loc, const scalar_t *data_attn_weight,
+ const int batch_size, const int spatial_size, const int num_heads,
+ const int channels, const int num_levels, const int num_query,
+ const int num_point, scalar_t *grad_value, scalar_t *grad_sampling_loc,
+ scalar_t *grad_attn_weight) {
+ CUDA_1D_KERNEL_LOOP(index, n) {
+ int _temp = index;
+ const int c_col = _temp % channels;
+ _temp /= channels;
+ const int sampling_index = _temp;
+ const int m_col = _temp % num_heads;
+ _temp /= num_heads;
+ const int q_col = _temp % num_query;
+ _temp /= num_query;
+ const int b_col = _temp;
+
+ const scalar_t top_grad = grad_col[index];
+
+ int data_weight_ptr = sampling_index * num_levels * num_point;
+ int data_loc_w_ptr = data_weight_ptr << 1;
+ const int grad_sampling_ptr = data_weight_ptr;
+ grad_sampling_loc += grad_sampling_ptr << 1;
+ grad_attn_weight += grad_sampling_ptr;
+ const int grad_weight_stride = 1;
+ const int grad_loc_stride = 2;
+ const int qid_stride = num_heads * channels;
+ const int data_value_ptr_init_offset = b_col * spatial_size * qid_stride;
+
+ for (int l_col = 0; l_col < num_levels; ++l_col) {
+ const int level_start_id = data_level_start_index[l_col];
+ const int spatial_h_ptr = l_col << 1;
+ const int spatial_h = data_spatial_shapes[spatial_h_ptr];
+ const int spatial_w = data_spatial_shapes[spatial_h_ptr + 1];
+ const int value_ptr_offset =
+ data_value_ptr_init_offset + level_start_id * qid_stride;
+ const scalar_t *data_value_ptr = data_value + value_ptr_offset;
+ scalar_t *grad_value_ptr = grad_value + value_ptr_offset;
+
+ for (int p_col = 0; p_col < num_point; ++p_col) {
+ const scalar_t loc_w = data_sampling_loc[data_loc_w_ptr];
+ const scalar_t loc_h = data_sampling_loc[data_loc_w_ptr + 1];
+ const scalar_t weight = data_attn_weight[data_weight_ptr];
+
+ const scalar_t h_im = loc_h * spatial_h - 0.5;
+ const scalar_t w_im = loc_w * spatial_w - 0.5;
+ if (h_im > -1 && w_im > -1 && h_im < spatial_h && w_im < spatial_w) {
+ ms_deform_attn_col2im_bilinear_gm(
+ data_value_ptr, spatial_h, spatial_w, num_heads, channels, h_im,
+ w_im, m_col, c_col, top_grad, weight, grad_value_ptr,
+ grad_sampling_loc, grad_attn_weight);
+ }
+ data_weight_ptr += 1;
+ data_loc_w_ptr += 2;
+ grad_attn_weight += grad_weight_stride;
+ grad_sampling_loc += grad_loc_stride;
+ }
+ }
+ }
+}
+#endif // DEFORM_ATTN_CUDA_KERNEL
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/multi_scale_deform_attn.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/multi_scale_deform_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..e58ca98ebd0cef0498607270b7650a4ad1f6ec27
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/ops/multi_scale_deform_attn.py
@@ -0,0 +1,1055 @@
+import math
+import warnings
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd.function import Function, once_differentiable
+
+from mmcv import deprecated_api_warning
+from mmcv.cnn import constant_init, xavier_init
+from mmcv.cnn.bricks.registry import ATTENTION
+from mmcv.runner import BaseModule
+from mmcv.utils import ext_loader
+from mmcv.ops.multi_scale_deform_attn import ext_module
+
+class MultiScaleDeformableAttnFunction(Function):
+
+ @staticmethod
+ def forward(ctx, value, value_spatial_shapes, value_level_start_index,
+ sampling_locations, attention_weights, im2col_step):
+ """GPU version of multi-scale deformable attention.
+ Args:
+ value (Tensor): The value has shape
+ (bs, num_keys, mum_heads, embed_dims//num_heads)
+ value_spatial_shapes (Tensor): Spatial shape of
+ each feature map, has shape (num_levels, 2),
+ last dimension 2 represent (h, w)
+ sampling_locations (Tensor): The location of sampling points,
+ has shape
+ (bs ,num_queries, num_heads, num_levels, num_points, 2),
+ the last dimension 2 represent (x, y).
+ attention_weights (Tensor): The weight of sampling points used
+ when calculate the attention, has shape
+ (bs ,num_queries, num_heads, num_levels, num_points),
+ im2col_step (Tensor): The step used in image to column.
+ Returns:
+ Tensor: has shape (bs, num_queries, embed_dims)
+ """
+
+ ctx.im2col_step = im2col_step
+ # print(im2col_step)
+ output = ext_module.ms_deform_attn_forward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ im2col_step=ctx.im2col_step)
+ ctx.save_for_backward(value, value_spatial_shapes,
+ value_level_start_index, sampling_locations,
+ attention_weights)
+ return output
+
+ @staticmethod
+ @once_differentiable
+ def backward(ctx, grad_output):
+ """GPU version of backward function.
+ Args:
+ grad_output (Tensor): Gradient
+ of output tensor of forward.
+ Returns:
+ Tuple[Tensor]: Gradient
+ of input tensors in forward.
+ """
+ value, value_spatial_shapes, value_level_start_index,\
+ sampling_locations, attention_weights = ctx.saved_tensors
+ grad_value = torch.zeros_like(value)
+ grad_sampling_loc = torch.zeros_like(sampling_locations)
+ grad_attn_weight = torch.zeros_like(attention_weights)
+
+ ext_module.ms_deform_attn_backward(
+ value,
+ value_spatial_shapes,
+ value_level_start_index,
+ sampling_locations,
+ attention_weights,
+ grad_output.contiguous(),
+ grad_value,
+ grad_sampling_loc,
+ grad_attn_weight,
+ im2col_step=ctx.im2col_step)
+
+ return grad_value, None, None, \
+ grad_sampling_loc, grad_attn_weight, None
+
+
+def multi_scale_deformable_attn_pytorch(value, value_spatial_shapes,
+ sampling_locations, attention_weights):
+ """CPU version of multi-scale deformable attention.
+ Args:
+ value (Tensor): The value has shape
+ (bs, num_keys, mum_heads, embed_dims//num_heads)
+ value_spatial_shapes (Tensor): Spatial shape of
+ each feature map, has shape (num_levels, 2),
+ last dimension 2 represent (h, w)
+ sampling_locations (Tensor): The location of sampling points,
+ has shape
+ (bs ,num_queries, num_heads, num_levels, num_points, 2),
+ the last dimension 2 represent (x, y).
+ attention_weights (Tensor): The weight of sampling points used
+ when calculate the attention, has shape
+ (bs ,num_queries, num_heads, num_levels, num_points),
+ Returns:
+ Tensor: has shape (bs, num_queries, embed_dims)
+ """
+
+ bs, _, num_heads, embed_dims = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ =\
+ sampling_locations.shape
+ value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes],
+ dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level, (H_, W_) in enumerate(value_spatial_shapes):
+ # bs, H_*W_, num_heads, embed_dims ->
+ # bs, H_*W_, num_heads*embed_dims ->
+ # bs, num_heads*embed_dims, H_*W_ ->
+ # bs*num_heads, embed_dims, H_, W_
+ value_l_ = value_list[level].flatten(2).transpose(1, 2).reshape(
+ bs * num_heads, embed_dims, H_, W_)
+ # bs, num_queries, num_heads, num_points, 2 ->
+ # bs, num_heads, num_queries, num_points, 2 ->
+ # bs*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :,
+ level].transpose(1, 2).flatten(0, 1)
+ # bs*num_heads, embed_dims, num_queries, num_points
+ sampling_value_l_ = F.grid_sample(
+ value_l_,
+ sampling_grid_l_,
+ mode='bilinear',
+ padding_mode='zeros',
+ align_corners=False)
+ sampling_value_list.append(sampling_value_l_)
+ # (bs, num_queries, num_heads, num_levels, num_points) ->
+ # (bs, num_heads, num_queries, num_levels, num_points) ->
+ # (bs, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ bs * num_heads, 1, num_queries, num_levels * num_points)
+ output = (torch.stack(sampling_value_list, dim=-2).flatten(-2) *
+ attention_weights).sum(-1).view(bs, num_heads * embed_dims,
+ num_queries)
+ return output.transpose(1, 2).contiguous()
+
+
+@ATTENTION.register_module()
+class MultiScaleDeformableAttention_share_value(BaseModule):
+ """An attention module used in Deformable-Detr. `Deformable DETR:
+ Deformable Transformers for End-to-End Object Detection.
+ `_.
+ Args:
+ embed_dims (int): The embedding dimension of Attention.
+ Default: 256.
+ num_heads (int): Parallel attention heads. Default: 64.
+ num_levels (int): The number of feature map used in
+ Attention. Default: 4.
+ num_points (int): The number of sampling points for
+ each query in each head. Default: 4.
+ im2col_step (int): The step used in image_to_column.
+ Default: 64.
+ dropout (float): A Dropout layer on `inp_identity`.
+ Default: 0.1.
+ batch_first (bool): Key, Query and Value are shape of
+ (batch, n, embed_dim)
+ or (n, batch, embed_dim). Default to False.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims=256,
+ num_heads=8,
+ num_levels=4,
+ num_points=4,
+ im2col_step=64,
+ dropout=0.1,
+ batch_first=False,
+ norm_cfg=None,
+ init_cfg=None):
+ super().__init__(init_cfg)
+ if embed_dims % num_heads != 0:
+ raise ValueError(f'embed_dims must be divisible by num_heads, '
+ f'but got {embed_dims} and {num_heads}')
+ dim_per_head = embed_dims // num_heads
+ self.norm_cfg = norm_cfg
+ self.dropout = nn.Dropout(dropout)
+ self.batch_first = batch_first
+ # print(im2col_step)
+
+ # you'd better set dim_per_head to a power of 2
+ # which is more efficient in the CUDA implementation
+ def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError(
+ 'invalid input for _is_power_of_2: {} (type: {})'.format(
+ n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+ if not _is_power_of_2(dim_per_head):
+ warnings.warn(
+ "You'd better set embed_dims in "
+ 'MultiScaleDeformAttention to make '
+ 'the dimension of each attention head a power of 2 '
+ 'which is more efficient in our CUDA implementation.')
+
+ # self.im2col_step = im2col_step
+ self.im2col_step = im2col_step*4
+ self.embed_dims = embed_dims
+ self.num_levels = num_levels
+ self.num_heads = num_heads
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(
+ embed_dims, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dims,
+ num_heads * num_levels * num_points)
+ # self.value_proj = nn.Linear(embed_dims, embed_dims)
+ self.output_proj = nn.Linear(embed_dims, embed_dims)
+ self.init_weights()
+
+ def init_weights(self):
+ """Default initialization for Parameters of Module."""
+ constant_init(self.sampling_offsets, 0.)
+ thetas = torch.arange(
+ self.num_heads,
+ dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (grid_init /
+ grid_init.abs().max(-1, keepdim=True)[0]).view(
+ self.num_heads, 1, 1,
+ 2).repeat(1, self.num_levels, self.num_points, 1)
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ self.sampling_offsets.bias.data = grid_init.view(-1)
+ constant_init(self.attention_weights, val=0., bias=0.)
+ # xavier_init(self.value_proj, distribution='uniform', bias=0.)
+ xavier_init(self.output_proj, distribution='uniform', bias=0.)
+ self._is_init = True
+
+ @deprecated_api_warning({'residual': 'identity'},
+ cls_name='MultiScaleDeformableAttention')
+ def forward(self,
+ query,
+ key=None,
+ value=None,
+ identity=None,
+ query_pos=None,
+ key_padding_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ **kwargs):
+ """Forward Function of MultiScaleDeformAttention.
+ Args:
+ query (Tensor): Query of Transformer with shape
+ (num_query, bs, embed_dims).
+ key (Tensor): The key tensor with shape
+ `(num_key, bs, embed_dims)`.
+ value (Tensor): The value tensor with shape
+ `(num_key, bs, embed_dims)`.
+ identity (Tensor): The tensor used for addition, with the
+ same shape as `query`. Default None. If None,
+ `query` will be used.
+ query_pos (Tensor): The positional encoding for `query`.
+ Default: None.
+ key_pos (Tensor): The positional encoding for `key`. Default
+ None.
+ reference_points (Tensor): The normalized reference
+ points with shape (bs, num_query, num_levels, 2),
+ all elements is range in [0, 1], top-left (0,0),
+ bottom-right (1, 1), including padding area.
+ or (N, Length_{query}, num_levels, 4), add
+ additional two dimensions is (w, h) to
+ form reference boxes.
+ key_padding_mask (Tensor): ByteTensor for `query`, with
+ shape [bs, num_key].
+ spatial_shapes (Tensor): Spatial shape of features in
+ different levels. With shape (num_levels, 2),
+ last dimension represents (h, w).
+ level_start_index (Tensor): The start index of each level.
+ A tensor has shape ``(num_levels, )`` and can be represented
+ as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
+ Returns:
+ Tensor: forwarded results with shape [num_query, bs, embed_dims].
+ """
+
+ if value is None:
+ value = query
+
+ if identity is None:
+ identity = query
+ if query_pos is not None:
+ query = query + query_pos
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ # value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], 0.0)
+ value = value.view(bs, num_value, self.num_heads, -1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2)
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points)
+ attention_weights = attention_weights.softmax(-1)
+
+ attention_weights = attention_weights.view(bs, num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points)
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack(
+ [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = reference_points[:, :, None, :, None, :] \
+ + sampling_offsets \
+ / offset_normalizer[None, None, None, :, None, :]
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = reference_points[:, :, None, :, None, :2] \
+ + sampling_offsets / self.num_points \
+ * reference_points[:, :, None, :, None, 2:] \
+ * 0.5
+ else:
+ raise ValueError(
+ f'Last dim of reference_points must be'
+ f' 2 or 4, but get {reference_points.shape[-1]} instead.')
+ if torch.cuda.is_available():
+ output = MultiScaleDeformableAttnFunction.apply(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+ else:
+ output = multi_scale_deformable_attn_pytorch(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ # (num_query, bs ,embed_dims)
+ output = output.permute(1, 0, 2)
+
+ return self.dropout(output) + identity
+
+class bottle_neck(nn.Module):
+ def __init__(self, embed_dims, hiddem_dims):
+ super().__init__()
+ self.fc1 = nn.Linear(embed_dims, hiddem_dims)
+ self.fc2 = nn.Linear(hiddem_dims, hiddem_dims)
+ self.fc3 = nn.Linear(hiddem_dims, embed_dims)
+ xavier_init(self.fc1, distribution='uniform', bias=0.)
+ xavier_init(self.fc2, distribution='uniform', bias=0.)
+ xavier_init(self.fc3, distribution='uniform', bias=0.)
+ def forward(self, x):
+ res = x
+ x = self.fc1(x)
+ x = self.fc2(x)
+ x = self.fc3(x)
+ x = x + res
+ return x
+
+
+
+@ATTENTION.register_module()
+class MultiScaleDeformableAttention_bottle_neck_v(BaseModule):
+ """An attention module used in Deformable-Detr. `Deformable DETR:
+ Deformable Transformers for End-to-End Object Detection.
+ `_.
+ Args:
+ embed_dims (int): The embedding dimension of Attention.
+ Default: 256.
+ num_heads (int): Parallel attention heads. Default: 64.
+ num_levels (int): The number of feature map used in
+ Attention. Default: 4.
+ num_points (int): The number of sampling points for
+ each query in each head. Default: 4.
+ im2col_step (int): The step used in image_to_column.
+ Default: 64.
+ dropout (float): A Dropout layer on `inp_identity`.
+ Default: 0.1.
+ batch_first (bool): Key, Query and Value are shape of
+ (batch, n, embed_dim)
+ or (n, batch, embed_dim). Default to False.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims=256,
+ num_heads=8,
+ num_levels=4,
+ num_points=4,
+ im2col_step=64,
+ dropout=0.1,
+ batch_first=False,
+ norm_cfg=None,
+ init_cfg=None):
+ super().__init__(init_cfg)
+ if embed_dims % num_heads != 0:
+ raise ValueError(f'embed_dims must be divisible by num_heads, '
+ f'but got {embed_dims} and {num_heads}')
+ dim_per_head = embed_dims // num_heads
+ self.norm_cfg = norm_cfg
+ self.dropout = nn.Dropout(dropout)
+ self.batch_first = batch_first
+
+ # you'd better set dim_per_head to a power of 2
+ # which is more efficient in the CUDA implementation
+ def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError(
+ 'invalid input for _is_power_of_2: {} (type: {})'.format(
+ n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+ if not _is_power_of_2(dim_per_head):
+ warnings.warn(
+ "You'd better set embed_dims in "
+ 'MultiScaleDeformAttention to make '
+ 'the dimension of each attention head a power of 2 '
+ 'which is more efficient in our CUDA implementation.')
+
+ self.im2col_step = im2col_step
+ self.embed_dims = embed_dims
+ self.num_levels = num_levels
+ self.num_heads = num_heads
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(
+ embed_dims, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dims,
+ num_heads * num_levels * num_points)
+ self.value_proj = bottle_neck(embed_dims, hiddem_dims = embed_dims//16)
+ self.output_proj = nn.Linear(embed_dims, embed_dims)
+ self.init_weights()
+
+ def init_weights(self):
+ """Default initialization for Parameters of Module."""
+ constant_init(self.sampling_offsets, 0.)
+ thetas = torch.arange(
+ self.num_heads,
+ dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (grid_init /
+ grid_init.abs().max(-1, keepdim=True)[0]).view(
+ self.num_heads, 1, 1,
+ 2).repeat(1, self.num_levels, self.num_points, 1)
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ self.sampling_offsets.bias.data = grid_init.view(-1)
+ constant_init(self.attention_weights, val=0., bias=0.)
+ # xavier_init(self.value_proj, distribution='uniform', bias=0.)
+ xavier_init(self.output_proj, distribution='uniform', bias=0.)
+ self._is_init = True
+
+ @deprecated_api_warning({'residual': 'identity'},
+ cls_name='MultiScaleDeformableAttention')
+ def forward(self,
+ query,
+ key=None,
+ value=None,
+ identity=None,
+ query_pos=None,
+ key_padding_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ **kwargs):
+ """Forward Function of MultiScaleDeformAttention.
+ Args:
+ query (Tensor): Query of Transformer with shape
+ (num_query, bs, embed_dims).
+ key (Tensor): The key tensor with shape
+ `(num_key, bs, embed_dims)`.
+ value (Tensor): The value tensor with shape
+ `(num_key, bs, embed_dims)`.
+ identity (Tensor): The tensor used for addition, with the
+ same shape as `query`. Default None. If None,
+ `query` will be used.
+ query_pos (Tensor): The positional encoding for `query`.
+ Default: None.
+ key_pos (Tensor): The positional encoding for `key`. Default
+ None.
+ reference_points (Tensor): The normalized reference
+ points with shape (bs, num_query, num_levels, 2),
+ all elements is range in [0, 1], top-left (0,0),
+ bottom-right (1, 1), including padding area.
+ or (N, Length_{query}, num_levels, 4), add
+ additional two dimensions is (w, h) to
+ form reference boxes.
+ key_padding_mask (Tensor): ByteTensor for `query`, with
+ shape [bs, num_key].
+ spatial_shapes (Tensor): Spatial shape of features in
+ different levels. With shape (num_levels, 2),
+ last dimension represents (h, w).
+ level_start_index (Tensor): The start index of each level.
+ A tensor has shape ``(num_levels, )`` and can be represented
+ as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
+ Returns:
+ Tensor: forwarded results with shape [num_query, bs, embed_dims].
+ """
+
+ if value is None:
+ value = query
+
+ if identity is None:
+ identity = query
+ if query_pos is not None:
+ query = query + query_pos
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], 0.0)
+ value = value.view(bs, num_value, self.num_heads, -1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2)
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points)
+ attention_weights = attention_weights.softmax(-1)
+
+ attention_weights = attention_weights.view(bs, num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points)
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack(
+ [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = reference_points[:, :, None, :, None, :] \
+ + sampling_offsets \
+ / offset_normalizer[None, None, None, :, None, :]
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = reference_points[:, :, None, :, None, :2] \
+ + sampling_offsets / self.num_points \
+ * reference_points[:, :, None, :, None, 2:] \
+ * 0.5
+ else:
+ raise ValueError(
+ f'Last dim of reference_points must be'
+ f' 2 or 4, but get {reference_points.shape[-1]} instead.')
+ if torch.cuda.is_available():
+ output = MultiScaleDeformableAttnFunction.apply(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+ else:
+ output = multi_scale_deformable_attn_pytorch(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ # (num_query, bs ,embed_dims)
+ output = output.permute(1, 0, 2)
+
+ return self.dropout(output) + identity
+
+@ATTENTION.register_module()
+class MultiScaleDeformableAttention_post_value(BaseModule):
+ """An attention module used in Deformable-Detr. `Deformable DETR:
+ Deformable Transformers for End-to-End Object Detection.
+ `_.
+ Args:
+ embed_dims (int): The embedding dimension of Attention.
+ Default: 256.
+ num_heads (int): Parallel attention heads. Default: 64.
+ num_levels (int): The number of feature map used in
+ Attention. Default: 4.
+ num_points (int): The number of sampling points for
+ each query in each head. Default: 4.
+ im2col_step (int): The step used in image_to_column.
+ Default: 64.
+ dropout (float): A Dropout layer on `inp_identity`.
+ Default: 0.1.
+ batch_first (bool): Key, Query and Value are shape of
+ (batch, n, embed_dim)
+ or (n, batch, embed_dim). Default to False.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims=256,
+ num_heads=8,
+ num_levels=4,
+ num_points=4,
+ im2col_step=64,
+ dropout=0.1,
+ batch_first=False,
+ norm_cfg=None,
+ init_cfg=None):
+ super().__init__(init_cfg)
+ if embed_dims % num_heads != 0:
+ raise ValueError(f'embed_dims must be divisible by num_heads, '
+ f'but got {embed_dims} and {num_heads}')
+ dim_per_head = embed_dims // num_heads
+ self.norm_cfg = norm_cfg
+ self.dropout = nn.Dropout(dropout)
+ self.batch_first = batch_first
+
+ # you'd better set dim_per_head to a power of 2
+ # which is more efficient in the CUDA implementation
+ def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError(
+ 'invalid input for _is_power_of_2: {} (type: {})'.format(
+ n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+ if not _is_power_of_2(dim_per_head):
+ warnings.warn(
+ "You'd better set embed_dims in "
+ 'MultiScaleDeformAttention to make '
+ 'the dimension of each attention head a power of 2 '
+ 'which is more efficient in our CUDA implementation.')
+
+ self.im2col_step = im2col_step
+ self.embed_dims = embed_dims
+ self.num_levels = num_levels
+ self.num_heads = num_heads
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(
+ embed_dims, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dims,
+ num_heads * num_levels * num_points)
+ # self.value_proj = nn.Linear(embed_dims, embed_dims)
+ self.output_proj = nn.Linear(embed_dims, embed_dims)
+ # self.value_proj = nn.Linear(embed_dims * 8, embed_dims//8,)
+ self.value_proj_weight = nn.Embedding(8*embed_dims, embed_dims//8)
+ self.value_proj_bias = nn.Embedding(8, embed_dims//8)
+ self.init_weights()
+
+ def init_weights(self):
+ """Default initialization for Parameters of Module."""
+ constant_init(self.sampling_offsets, 0.)
+ thetas = torch.arange(
+ self.num_heads,
+ dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (grid_init /
+ grid_init.abs().max(-1, keepdim=True)[0]).view(
+ self.num_heads, 1, 1,
+ 2).repeat(1, self.num_levels, self.num_points, 1)
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ self.sampling_offsets.bias.data = grid_init.view(-1)
+ constant_init(self.attention_weights, val=0., bias=0.)
+ # xavier_init(self.value_proj, distribution='uniform', bias=0.)
+ xavier_init(self.output_proj, distribution='uniform', bias=0.)
+ self._is_init = True
+
+ @deprecated_api_warning({'residual': 'identity'},
+ cls_name='MultiScaleDeformableAttention')
+ def forward(self,
+ query,
+ key=None,
+ value=None,
+ identity=None,
+ query_pos=None,
+ key_padding_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ **kwargs):
+ """Forward Function of MultiScaleDeformAttention.
+ Args:
+ query (Tensor): Query of Transformer with shape
+ (num_query, bs, embed_dims).
+ key (Tensor): The key tensor with shape
+ `(num_key, bs, embed_dims)`.
+ value (Tensor): The value tensor with shape
+ `(num_key, bs, embed_dims)`.
+ identity (Tensor): The tensor used for addition, with the
+ same shape as `query`. Default None. If None,
+ `query` will be used.
+ query_pos (Tensor): The positional encoding for `query`.
+ Default: None.
+ key_pos (Tensor): The positional encoding for `key`. Default
+ None.
+ reference_points (Tensor): The normalized reference
+ points with shape (bs, num_query, num_levels, 2),
+ all elements is range in [0, 1], top-left (0,0),
+ bottom-right (1, 1), including padding area.
+ or (N, Length_{query}, num_levels, 4), add
+ additional two dimensions is (w, h) to
+ form reference boxes.
+ key_padding_mask (Tensor): ByteTensor for `query`, with
+ shape [bs, num_key].
+ spatial_shapes (Tensor): Spatial shape of features in
+ different levels. With shape (num_levels, 2),
+ last dimension represents (h, w).
+ level_start_index (Tensor): The start index of each level.
+ A tensor has shape ``(num_levels, )`` and can be represented
+ as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
+ Returns:
+ Tensor: forwarded results with shape [num_query, bs, embed_dims].
+ """
+
+ if value is None:
+ value = query
+
+ if identity is None:
+ identity = query
+ if query_pos is not None:
+ query = query + query_pos
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ # value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], 0.0)
+ # value = value.view(bs, num_value, self.num_heads, -1)
+ value = value[:,:,None,:].repeat(1, 1, self.num_heads, 1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2)
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points)
+ attention_weights = attention_weights.softmax(-1)
+
+ attention_weights = attention_weights.view(bs, num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points)
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack(
+ [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = reference_points[:, :, None, :, None, :] \
+ + sampling_offsets \
+ / offset_normalizer[None, None, None, :, None, :]
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = reference_points[:, :, None, :, None, :2] \
+ + sampling_offsets / self.num_points \
+ * reference_points[:, :, None, :, None, 2:] \
+ * 0.5
+ else:
+ raise ValueError(
+ f'Last dim of reference_points must be'
+ f' 2 or 4, but get {reference_points.shape[-1]} instead.')
+ if torch.cuda.is_available():
+ output = MultiScaleDeformableAttnFunction.apply(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+ else:
+ output = multi_scale_deformable_attn_pytorch(
+ value, spatial_shapes, level_start_index, sampling_locations,
+ attention_weights, self.im2col_step)
+
+ bs, num_q, ch = output.shape
+ value_proj_weight = self.value_proj_weight.weight.clone()
+ value_proj_bias = self.value_proj_bias.weight.clone()
+ value_proj_weight = value_proj_weight.reshape(8,ch//8,-1)
+ output = output.reshape(bs,num_q,8,ch//8)
+ output = torch.einsum('bqhc,hco->bqho', output, value_proj_weight)
+ output = output + value_proj_bias[None,None,:,:]
+ output = output.flatten(-2)
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ # (num_query, bs ,embed_dims)
+ output = output.permute(1, 0, 2)
+
+ return self.dropout(output) + identity
+
+def multi_scale_deformable_post_v(value, value_spatial_shapes,
+ sampling_locations, attention_weights,
+ value_proj_weight, value_proj_bias):
+ """CPU version of multi-scale deformable attention.
+ Args:
+ value (Tensor): The value has shape
+ (bs, num_keys, mum_heads, embed_dims//num_heads)
+ value_spatial_shapes (Tensor): Spatial shape of
+ each feature map, has shape (num_levels, 2),
+ last dimension 2 represent (h, w)
+ sampling_locations (Tensor): The location of sampling points,
+ has shape
+ (bs ,num_queries, num_heads, num_levels, num_points, 2),
+ the last dimension 2 represent (x, y).
+ attention_weights (Tensor): The weight of sampling points used
+ when calculate the attention, has shape
+ (bs ,num_queries, num_heads, num_levels, num_points),
+ Returns:
+ Tensor: has shape (bs, num_queries, embed_dims)
+ """
+
+ bs, _, num_heads, embed_dims = value.shape
+ _, num_queries, num_heads, num_levels, num_points, _ =\
+ sampling_locations.shape
+ value_list = value.split([H_ * W_ for H_, W_ in value_spatial_shapes],
+ dim=1)
+ sampling_grids = 2 * sampling_locations - 1
+ sampling_value_list = []
+ for level, (H_, W_) in enumerate(value_spatial_shapes):
+ # bs, H_*W_, num_heads, embed_dims ->
+ # bs, H_*W_, num_heads*embed_dims ->
+ # bs, num_heads*embed_dims, H_*W_ ->
+ # bs*num_heads, embed_dims, H_, W_
+ value_l_ = value_list[level].flatten(2).transpose(1, 2).reshape(
+ bs * num_heads, embed_dims, H_, W_)
+ # bs, num_queries, num_heads, num_points, 2 ->
+ # bs, num_heads, num_queries, num_points, 2 ->
+ # bs*num_heads, num_queries, num_points, 2
+ sampling_grid_l_ = sampling_grids[:, :, :,
+ level].transpose(1, 2).flatten(0, 1)
+ # bs*num_heads, embed_dims, num_queries, num_points
+ sampling_value_l_ = F.grid_sample(
+ value_l_,
+ sampling_grid_l_,
+ mode='bilinear',
+ padding_mode='zeros',
+ align_corners=False)
+ sampling_value_list.append(sampling_value_l_)
+ # (bs, num_queries, num_heads, num_levels, num_points) ->
+ # (bs, num_heads, num_queries, num_levels, num_points) ->
+ # (bs, num_heads, 1, num_queries, num_levels*num_points)
+ attention_weights = attention_weights.transpose(1, 2).reshape(
+ bs * num_heads, 1, num_queries, num_levels * num_points)
+
+ value_proj_weight = value_proj_weight.weight.clone()
+ value_proj_weight = value_proj_weight.reshape(8,value_proj_weight.shape[0]//8,value_proj_weight.shape[1])
+ value_proj_bias = value_proj_bias.weight.clone()
+ sampling_value_list = torch.stack(sampling_value_list, dim=-2).flatten(-2)
+ sampling_value_list = sampling_value_list.reshape(bs,num_heads,value_proj_weight.shape[1],num_queries,num_levels*num_points)
+ sampling_value_list = torch.einsum('bhcqp,hco->bhoqp', sampling_value_list, value_proj_weight)
+ sampling_value_list = sampling_value_list + value_proj_bias[None,:,:,None,None]
+ sampling_value_list = sampling_value_list.reshape(bs*num_heads,value_proj_weight.shape[1]//num_heads,num_queries,num_levels*num_points)
+
+ output = (sampling_value_list *
+ attention_weights).sum(-1).view(bs, embed_dims,
+ num_queries)
+ return output.transpose(1, 2).contiguous()
+
+@ATTENTION.register_module()
+class MultiScaleDeformableAttention_post_v_stirct(BaseModule):
+ """An attention module used in Deformable-Detr. `Deformable DETR:
+ Deformable Transformers for End-to-End Object Detection.
+ `_.
+ Args:
+ embed_dims (int): The embedding dimension of Attention.
+ Default: 256.
+ num_heads (int): Parallel attention heads. Default: 64.
+ num_levels (int): The number of feature map used in
+ Attention. Default: 4.
+ num_points (int): The number of sampling points for
+ each query in each head. Default: 4.
+ im2col_step (int): The step used in image_to_column.
+ Default: 64.
+ dropout (float): A Dropout layer on `inp_identity`.
+ Default: 0.1.
+ batch_first (bool): Key, Query and Value are shape of
+ (batch, n, embed_dim)
+ or (n, batch, embed_dim). Default to False.
+ norm_cfg (dict): Config dict for normalization layer.
+ Default: None.
+ init_cfg (obj:`mmcv.ConfigDict`): The Config for initialization.
+ Default: None.
+ """
+
+ def __init__(self,
+ embed_dims=256,
+ num_heads=8,
+ num_levels=4,
+ num_points=4,
+ im2col_step=64,
+ dropout=0.1,
+ batch_first=False,
+ norm_cfg=None,
+ init_cfg=None):
+ super().__init__(init_cfg)
+ if embed_dims % num_heads != 0:
+ raise ValueError(f'embed_dims must be divisible by num_heads, '
+ f'but got {embed_dims} and {num_heads}')
+ dim_per_head = embed_dims // num_heads
+ self.norm_cfg = norm_cfg
+ self.dropout = nn.Dropout(dropout)
+ self.batch_first = batch_first
+
+ # you'd better set dim_per_head to a power of 2
+ # which is more efficient in the CUDA implementation
+ def _is_power_of_2(n):
+ if (not isinstance(n, int)) or (n < 0):
+ raise ValueError(
+ 'invalid input for _is_power_of_2: {} (type: {})'.format(
+ n, type(n)))
+ return (n & (n - 1) == 0) and n != 0
+
+ if not _is_power_of_2(dim_per_head):
+ warnings.warn(
+ "You'd better set embed_dims in "
+ 'MultiScaleDeformAttention to make '
+ 'the dimension of each attention head a power of 2 '
+ 'which is more efficient in our CUDA implementation.')
+
+ self.im2col_step = im2col_step
+ self.embed_dims = embed_dims
+ self.num_levels = num_levels
+ self.num_heads = num_heads
+ self.num_points = num_points
+ self.sampling_offsets = nn.Linear(
+ embed_dims, num_heads * num_levels * num_points * 2)
+ self.attention_weights = nn.Linear(embed_dims,
+ num_heads * num_levels * num_points)
+ # self.value_proj = nn.Linear(embed_dims, embed_dims)
+ self.output_proj = nn.Linear(embed_dims, embed_dims)
+ self.value_proj_weight = nn.Embedding(8*embed_dims, embed_dims//8)
+ self.value_proj_bias = nn.Embedding(8, embed_dims//8)
+ self.init_weights()
+
+ def init_weights(self):
+ """Default initialization for Parameters of Module."""
+ constant_init(self.sampling_offsets, 0.)
+ thetas = torch.arange(
+ self.num_heads,
+ dtype=torch.float32) * (2.0 * math.pi / self.num_heads)
+ grid_init = torch.stack([thetas.cos(), thetas.sin()], -1)
+ grid_init = (grid_init /
+ grid_init.abs().max(-1, keepdim=True)[0]).view(
+ self.num_heads, 1, 1,
+ 2).repeat(1, self.num_levels, self.num_points, 1)
+ for i in range(self.num_points):
+ grid_init[:, :, i, :] *= i + 1
+
+ self.sampling_offsets.bias.data = grid_init.view(-1)
+ constant_init(self.attention_weights, val=0., bias=0.)
+ # xavier_init(self.value_proj, distribution='uniform', bias=0.)
+ xavier_init(self.output_proj, distribution='uniform', bias=0.)
+ self._is_init = True
+
+ @deprecated_api_warning({'residual': 'identity'},
+ cls_name='MultiScaleDeformableAttention')
+ def forward(self,
+ query,
+ key=None,
+ value=None,
+ identity=None,
+ query_pos=None,
+ key_padding_mask=None,
+ reference_points=None,
+ spatial_shapes=None,
+ level_start_index=None,
+ **kwargs):
+ """Forward Function of MultiScaleDeformAttention.
+ Args:
+ query (Tensor): Query of Transformer with shape
+ (num_query, bs, embed_dims).
+ key (Tensor): The key tensor with shape
+ `(num_key, bs, embed_dims)`.
+ value (Tensor): The value tensor with shape
+ `(num_key, bs, embed_dims)`.
+ identity (Tensor): The tensor used for addition, with the
+ same shape as `query`. Default None. If None,
+ `query` will be used.
+ query_pos (Tensor): The positional encoding for `query`.
+ Default: None.
+ key_pos (Tensor): The positional encoding for `key`. Default
+ None.
+ reference_points (Tensor): The normalized reference
+ points with shape (bs, num_query, num_levels, 2),
+ all elements is range in [0, 1], top-left (0,0),
+ bottom-right (1, 1), including padding area.
+ or (N, Length_{query}, num_levels, 4), add
+ additional two dimensions is (w, h) to
+ form reference boxes.
+ key_padding_mask (Tensor): ByteTensor for `query`, with
+ shape [bs, num_key].
+ spatial_shapes (Tensor): Spatial shape of features in
+ different levels. With shape (num_levels, 2),
+ last dimension represents (h, w).
+ level_start_index (Tensor): The start index of each level.
+ A tensor has shape ``(num_levels, )`` and can be represented
+ as [0, h_0*w_0, h_0*w_0+h_1*w_1, ...].
+ Returns:
+ Tensor: forwarded results with shape [num_query, bs, embed_dims].
+ """
+
+ if value is None:
+ value = query
+
+ if identity is None:
+ identity = query
+ if query_pos is not None:
+ query = query + query_pos
+ if not self.batch_first:
+ # change to (bs, num_query ,embed_dims)
+ query = query.permute(1, 0, 2)
+ value = value.permute(1, 0, 2)
+
+ bs, num_query, _ = query.shape
+ bs, num_value, _ = value.shape
+ assert (spatial_shapes[:, 0] * spatial_shapes[:, 1]).sum() == num_value
+
+ # value = self.value_proj(value)
+ if key_padding_mask is not None:
+ value = value.masked_fill(key_padding_mask[..., None], 0.0)
+ value = value[:,:,None,:].expand(-1, -1, self.num_heads, -1)
+ sampling_offsets = self.sampling_offsets(query).view(
+ bs, num_query, self.num_heads, self.num_levels, self.num_points, 2)
+ attention_weights = self.attention_weights(query).view(
+ bs, num_query, self.num_heads, self.num_levels * self.num_points)
+ attention_weights = attention_weights.softmax(-1)
+
+ attention_weights = attention_weights.view(bs, num_query,
+ self.num_heads,
+ self.num_levels,
+ self.num_points)
+ if reference_points.shape[-1] == 2:
+ offset_normalizer = torch.stack(
+ [spatial_shapes[..., 1], spatial_shapes[..., 0]], -1)
+ sampling_locations = reference_points[:, :, None, :, None, :] \
+ + sampling_offsets \
+ / offset_normalizer[None, None, None, :, None, :]
+ elif reference_points.shape[-1] == 4:
+ sampling_locations = reference_points[:, :, None, :, None, :2] \
+ + sampling_offsets / self.num_points \
+ * reference_points[:, :, None, :, None, 2:] \
+ * 0.5
+ else:
+ raise ValueError(
+ f'Last dim of reference_points must be'
+ f' 2 or 4, but get {reference_points.shape[-1]} instead.')
+
+ output = multi_scale_deformable_post_v(
+ value, spatial_shapes, sampling_locations,
+ attention_weights, self.value_proj_weight, self.value_proj_bias)
+
+ output = self.output_proj(output)
+
+ if not self.batch_first:
+ # (num_query, bs ,embed_dims)
+ output = output.permute(1, 0, 2)
+
+ return self.dropout(output) + identity
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1293ca05aab2632e0d6df29734438bc38ed79c6c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/__init__.py
@@ -0,0 +1,9 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from .collect_env import collect_env
+from .logger import get_root_logger
+from .setup_env import setup_multi_processes
+from .timer import StopWatch
+
+__all__ = [
+ 'get_root_logger', 'collect_env', 'StopWatch', 'setup_multi_processes'
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/collect_env.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/collect_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..f75c5ea73383ccef367632cf497227498ac50078
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/collect_env.py
@@ -0,0 +1,16 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from mmcv.utils import collect_env as collect_basic_env
+from mmcv.utils import get_git_hash
+
+import mmpose
+
+
+def collect_env():
+ env_info = collect_basic_env()
+ env_info['MMPose'] = (mmpose.__version__ + '+' + get_git_hash(digits=7))
+ return env_info
+
+
+if __name__ == '__main__':
+ for name, val in collect_env().items():
+ print(f'{name}: {val}')
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/hooks.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/hooks.py
new file mode 100644
index 0000000000000000000000000000000000000000..b68940f2b7a8a618916ea5aab331e3ce45ba98e7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/hooks.py
@@ -0,0 +1,60 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import functools
+
+
+class OutputHook:
+
+ def __init__(self, module, outputs=None, as_tensor=False):
+ self.outputs = outputs
+ self.as_tensor = as_tensor
+ self.layer_outputs = {}
+ self.register(module)
+
+ def register(self, module):
+
+ def hook_wrapper(name):
+
+ def hook(model, input, output):
+ if self.as_tensor:
+ self.layer_outputs[name] = output
+ else:
+ if isinstance(output, list):
+ self.layer_outputs[name] = [
+ out.detach().cpu().numpy() for out in output
+ ]
+ else:
+ self.layer_outputs[name] = output.detach().cpu().numpy(
+ )
+
+ return hook
+
+ self.handles = []
+ if isinstance(self.outputs, (list, tuple)):
+ for name in self.outputs:
+ try:
+ layer = rgetattr(module, name)
+ h = layer.register_forward_hook(hook_wrapper(name))
+ except ModuleNotFoundError as module_not_found:
+ raise ModuleNotFoundError(
+ f'Module {name} not found') from module_not_found
+ self.handles.append(h)
+
+ def remove(self):
+ for h in self.handles:
+ h.remove()
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ self.remove()
+
+
+# using wonder's beautiful simplification:
+# https://stackoverflow.com/questions/31174295/getattr-and-setattr-on-nested-objects
+def rgetattr(obj, attr, *args):
+
+ def _getattr(obj, attr):
+ return getattr(obj, attr, *args)
+
+ return functools.reduce(_getattr, [obj] + attr.split('.'))
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/logger.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..294837fa6aec1e1896de8c8accf470f366f81296
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/logger.py
@@ -0,0 +1,25 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import logging
+
+from mmcv.utils import get_logger
+
+
+def get_root_logger(log_file=None, log_level=logging.INFO):
+ """Use `get_logger` method in mmcv to get the root logger.
+
+ The logger will be initialized if it has not been initialized. By default a
+ StreamHandler will be added. If `log_file` is specified, a FileHandler will
+ also be added. The name of the root logger is the top-level package name,
+ e.g., "mmpose".
+
+ Args:
+ log_file (str | None): The log filename. If specified, a FileHandler
+ will be added to the root logger.
+ log_level (int): The root logger level. Note that only the process of
+ rank 0 is affected, while other processes will set the level to
+ "Error" and be silent most of the time.
+
+ Returns:
+ logging.Logger: The root logger.
+ """
+ return get_logger(__name__.split('.')[0], log_file, log_level)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/setup_env.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/setup_env.py
new file mode 100644
index 0000000000000000000000000000000000000000..21def2f0809153a5f755af2431f7e702db625e5c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/setup_env.py
@@ -0,0 +1,47 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+import os
+import platform
+import warnings
+
+import cv2
+import torch.multiprocessing as mp
+
+
+def setup_multi_processes(cfg):
+ """Setup multi-processing environment variables."""
+ # set multi-process start method as `fork` to speed up the training
+ if platform.system() != 'Windows':
+ mp_start_method = cfg.get('mp_start_method', 'fork')
+ current_method = mp.get_start_method(allow_none=True)
+ if current_method is not None and current_method != mp_start_method:
+ warnings.warn(
+ f'Multi-processing start method `{mp_start_method}` is '
+ f'different from the previous setting `{current_method}`.'
+ f'It will be force set to `{mp_start_method}`. You can change '
+ f'this behavior by changing `mp_start_method` in your config.')
+ mp.set_start_method(mp_start_method, force=True)
+
+ # disable opencv multithreading to avoid system being overloaded
+ opencv_num_threads = cfg.get('opencv_num_threads', 0)
+ cv2.setNumThreads(opencv_num_threads)
+
+ # setup OMP threads
+ # This code is referred from https://github.com/pytorch/pytorch/blob/master/torch/distributed/run.py # noqa
+ if 'OMP_NUM_THREADS' not in os.environ and cfg.data.workers_per_gpu > 1:
+ omp_num_threads = 1
+ warnings.warn(
+ f'Setting OMP_NUM_THREADS environment variable for each process '
+ f'to be {omp_num_threads} in default, to avoid your system being '
+ f'overloaded, please further tune the variable for optimal '
+ f'performance in your application as needed.')
+ os.environ['OMP_NUM_THREADS'] = str(omp_num_threads)
+
+ # setup MKL threads
+ if 'MKL_NUM_THREADS' not in os.environ and cfg.data.workers_per_gpu > 1:
+ mkl_num_threads = 1
+ warnings.warn(
+ f'Setting MKL_NUM_THREADS environment variable for each process '
+ f'to be {mkl_num_threads} in default, to avoid your system being '
+ f'overloaded, please further tune the variable for optimal '
+ f'performance in your application as needed.')
+ os.environ['MKL_NUM_THREADS'] = str(mkl_num_threads)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/timer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/timer.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a3185c5e89ce73bd33591c22ce74fc73ef8e770
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/utils/timer.py
@@ -0,0 +1,117 @@
+# Copyright (c) OpenMMLab. All rights reserved.
+from collections import defaultdict
+from contextlib import contextmanager
+from functools import partial
+
+import numpy as np
+from mmcv import Timer
+
+
+class RunningAverage():
+ r"""A helper class to calculate running average in a sliding window.
+
+ Args:
+ window (int): The size of the sliding window.
+ """
+
+ def __init__(self, window: int = 1):
+ self.window = window
+ self._data = []
+
+ def update(self, value):
+ """Update a new data sample."""
+ self._data.append(value)
+ self._data = self._data[-self.window:]
+
+ def average(self):
+ """Get the average value of current window."""
+ return np.mean(self._data)
+
+
+class StopWatch:
+ r"""A helper class to measure FPS and detailed time consuming of each phase
+ in a video processing loop or similar scenarios.
+
+ Args:
+ window (int): The sliding window size to calculate the running average
+ of the time consuming.
+
+ Example:
+ >>> from mmpose.utils import StopWatch
+ >>> import time
+ >>> stop_watch = StopWatch(window=10)
+ >>> with stop_watch.timeit('total'):
+ >>> time.sleep(0.1)
+ >>> # 'timeit' support nested use
+ >>> with stop_watch.timeit('phase1'):
+ >>> time.sleep(0.1)
+ >>> with stop_watch.timeit('phase2'):
+ >>> time.sleep(0.2)
+ >>> time.sleep(0.2)
+ >>> report = stop_watch.report()
+ """
+
+ def __init__(self, window=1):
+ self.window = window
+ self._record = defaultdict(partial(RunningAverage, window=self.window))
+ self._timer_stack = []
+
+ @contextmanager
+ def timeit(self, timer_name='_FPS_'):
+ """Timing a code snippet with an assigned name.
+
+ Args:
+ timer_name (str): The unique name of the interested code snippet to
+ handle multiple timers and generate reports. Note that '_FPS_'
+ is a special key that the measurement will be in `fps` instead
+ of `millisecond`. Also see `report` and `report_strings`.
+ Default: '_FPS_'.
+ Note:
+ This function should always be used in a `with` statement, as shown
+ in the example.
+ """
+ self._timer_stack.append((timer_name, Timer()))
+ try:
+ yield
+ finally:
+ timer_name, timer = self._timer_stack.pop()
+ self._record[timer_name].update(timer.since_start())
+
+ def report(self, key=None):
+ """Report timing information.
+
+ Returns:
+ dict: The key is the timer name and the value is the \
+ corresponding average time consuming.
+ """
+ result = {
+ name: r.average() * 1000.
+ for name, r in self._record.items()
+ }
+
+ if '_FPS_' in result:
+ result['_FPS_'] = 1000. / result.pop('_FPS_')
+
+ if key is None:
+ return result
+ return result[key]
+
+ def report_strings(self):
+ """Report timing information in texture strings.
+
+ Returns:
+ list(str): Each element is the information string of a timed \
+ event, in format of '{timer_name}: {time_in_ms}'. \
+ Specially, if timer_name is '_FPS_', the result will \
+ be converted to fps.
+ """
+ result = self.report()
+ strings = []
+ if '_FPS_' in result:
+ strings.append(f'FPS: {result["_FPS_"]:>5.1f}')
+ strings += [f'{name}: {val:>3.0f}' for name, val in result.items()]
+ return strings
+
+ def reset(self):
+ self._record = defaultdict(list)
+ self._active_timer_stack = []
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/version.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/version.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c8908940628018788a5adc23afafbe7e352b3a2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/mmpose/version.py
@@ -0,0 +1,19 @@
+# Copyright (c) Open-MMLab. All rights reserved.
+
+__version__ = '0.28.0'
+short_version = __version__
+
+
+def parse_version_info(version_str):
+ version_info = []
+ for x in version_str.split('.'):
+ if x.isdigit():
+ version_info.append(int(x))
+ elif x.find('rc') != -1:
+ patch_version = x.split('rc')
+ version_info.append(int(patch_version[0]))
+ version_info.append(f'rc{patch_version[1]}')
+ return tuple(version_info)
+
+
+version_info = parse_version_info(__version__)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/model-index.yml b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/model-index.yml
new file mode 100644
index 0000000000000000000000000000000000000000..aa7691be16b169e2c08c6d9a482a32f23d17d80c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/model-index.yml
@@ -0,0 +1,147 @@
+Import:
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/animalpose/hrnet_animalpose.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/animalpose/resnet_animalpose.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/ap10k/hrnet_ap10k.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/ap10k/resnet_ap10k.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/atrw/hrnet_atrw.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/atrw/resnet_atrw.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/fly/resnet_fly.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/horse10/hrnet_horse10.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/horse10/resnet_horse10.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/locust/resnet_locust.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/macaque/hrnet_macaque.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/macaque/resnet_macaque.yml
+- configs/animal/2d_kpt_sview_rgb_img/topdown_heatmap/zebra/resnet_zebra.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/higherhrnet_aic.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/aic/hrnet_aic.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/higherhrnet_udp_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hourglass_ae_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/hrnet_udp_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/mobilenetv2_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/coco/resnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/crowdpose/higherhrnet_crowdpose.yml
+- configs/body/2d_kpt_sview_rgb_img/associative_embedding/mhp/hrnet_mhp.yml
+- configs/body/2d_kpt_sview_rgb_img/deeppose/coco/resnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/deeppose/coco/resnet_rle_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/deeppose/mpii/resnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/deeppose/mpii/resnet_rle_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/aic/hrnet_aic.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/aic/resnet_aic.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/alexnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/cpm_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hourglass_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrformer_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_augmentation_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_dark_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_fp16_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/hrnet_udp_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/litehrnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/mobilenetv2_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/mspn_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/pvt_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnest_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnet_dark_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnet_fp16_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnetv1d_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/resnext_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/rsn_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/scnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/seresnet_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/shufflenetv1_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/shufflenetv2_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/swin_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/vgg_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/coco/vipnas_coco.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/crowdpose/hrnet_crowdpose.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/crowdpose/resnet_crowdpose.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/h36m/hrnet_h36m.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/jhmdb/cpm_jhmdb.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/jhmdb/resnet_jhmdb.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mhp/resnet_mhp.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/cpm_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/hourglass_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/hrnet_dark_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/hrnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/litehrnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/mobilenetv2_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/resnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/resnetv1d_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/resnext_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/scnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/seresnet_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/shufflenetv1_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii/shufflenetv2_mpii.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/mpii_trb/resnet_mpii_trb.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/ochuman/hrnet_ochuman.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/ochuman/resnet_ochuman.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/posetrack18/hrnet_posetrack18.yml
+- configs/body/2d_kpt_sview_rgb_img/topdown_heatmap/posetrack18/resnet_posetrack18.yml
+- configs/body/2d_kpt_sview_rgb_vid/posewarper/posetrack18/hrnet_posetrack18_posewarper.yml
+- configs/body/3d_kpt_mview_rgb_img/voxelpose/campus/voxelpose_campus.yml
+- configs/body/3d_kpt_mview_rgb_img/voxelpose/panoptic/voxelpose_prn64x64x64_cpn80x80x20_panoptic_cam5.yml
+- configs/body/3d_kpt_mview_rgb_img/voxelpose/shelf/voxelpose_shelf.yml
+- configs/body/3d_kpt_sview_rgb_img/pose_lift/h36m/simplebaseline3d_h36m.yml
+- configs/body/3d_kpt_sview_rgb_img/pose_lift/mpi_inf_3dhp/simplebaseline3d_mpi-inf-3dhp.yml
+- configs/body/3d_kpt_sview_rgb_vid/video_pose_lift/h36m/videopose3d_h36m.yml
+- configs/body/3d_kpt_sview_rgb_vid/video_pose_lift/mpi_inf_3dhp/videopose3d_mpi-inf-3dhp.yml
+- configs/body/3d_mesh_sview_rgb_img/hmr/mixed/resnet_mixed.yml
+- configs/face/2d_kpt_sview_rgb_img/deeppose/wflw/resnet_softwingloss_wflw.yml
+- configs/face/2d_kpt_sview_rgb_img/deeppose/wflw/resnet_wflw.yml
+- configs/face/2d_kpt_sview_rgb_img/deeppose/wflw/resnet_wingloss_wflw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/300w/hrnetv2_300w.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/aflw/hrnetv2_aflw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/aflw/hrnetv2_dark_aflw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/hourglass_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/hrnetv2_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/hrnetv2_dark_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/mobilenetv2_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/resnet_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_face/scnet_coco_wholebody_face.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/cofw/hrnetv2_cofw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/wflw/hrnetv2_awing_wflw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/wflw/hrnetv2_dark_wflw.yml
+- configs/face/2d_kpt_sview_rgb_img/topdown_heatmap/wflw/hrnetv2_wflw.yml
+- configs/fashion/2d_kpt_sview_rgb_img/deeppose/deepfashion/resnet_deepfashion.yml
+- configs/fashion/2d_kpt_sview_rgb_img/topdown_heatmap/deepfashion/resnet_deepfashion.yml
+- configs/hand/2d_kpt_sview_rgb_img/deeppose/onehand10k/resnet_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/deeppose/panoptic2d/resnet_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/deeppose/rhd2d/resnet_rhd2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/hourglass_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/hrnetv2_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/hrnetv2_dark_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/litehrnet_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/mobilenetv2_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/resnet_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/coco_wholebody_hand/scnet_coco_wholebody_hand.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/freihand2d/resnet_freihand2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/interhand2d/resnet_interhand2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/hrnetv2_dark_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/hrnetv2_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/hrnetv2_udp_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/mobilenetv2_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/onehand10k/resnet_onehand10k.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/panoptic2d/hrnetv2_dark_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/panoptic2d/hrnetv2_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/panoptic2d/hrnetv2_udp_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/panoptic2d/mobilenetv2_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/panoptic2d/resnet_panoptic2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/rhd2d/hrnetv2_dark_rhd2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/rhd2d/hrnetv2_rhd2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/rhd2d/hrnetv2_udp_rhd2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/rhd2d/mobilenetv2_rhd2d.yml
+- configs/hand/2d_kpt_sview_rgb_img/topdown_heatmap/rhd2d/resnet_rhd2d.yml
+- configs/hand/3d_kpt_sview_rgb_img/internet/interhand3d/internet_interhand3d.yml
+- configs/hand/gesture_sview_rgbd_vid/mtut/nvgesture/i3d_nvgesture.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/higherhrnet_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/associative_embedding/coco-wholebody/hrnet_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/hrnet_dark_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/resnet_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/tcformer_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/vipnas_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/coco-wholebody/vipnas_dark_coco-wholebody.yml
+- configs/wholebody/2d_kpt_sview_rgb_img/topdown_heatmap/halpe/hrnet_dark_halpe.yml
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/pytest.ini b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/pytest.ini
new file mode 100644
index 0000000000000000000000000000000000000000..9796e871e70c7c67345b1d6bcf708c0c82377a98
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/pytest.ini
@@ -0,0 +1,7 @@
+[pytest]
+addopts = --xdoctest --xdoctest-style=auto
+norecursedirs = .git ignore build __pycache__ data docker docs .eggs
+
+filterwarnings= default
+ ignore:.*No cfgstr given in Cacher constructor or call.*:Warning
+ ignore:.*Define the __nice__ method for.*:Warning
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b5b5d97a6ea7837890ff0247bac8c5f24f6eabab
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements.txt
@@ -0,0 +1,4 @@
+-r requirements/build.txt
+-r requirements/runtime.txt
+-r requirements/tests.txt
+-r requirements/optional.txt
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/build.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/build.txt
new file mode 100644
index 0000000000000000000000000000000000000000..a9566943cef029e5c8dab0b52ba564a7f9c7ad30
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/build.txt
@@ -0,0 +1,3 @@
+# These must be installed before building mmpose
+numpy
+torch>=1.3
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/docs.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/docs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..20170845c44eefcb139ee2baa1a3d375b71c34ec
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/docs.txt
@@ -0,0 +1,6 @@
+docutils==0.16.0
+myst-parser
+-e git+https://github.com/gaotongxiao/pytorch_sphinx_theme.git#egg=pytorch_sphinx_theme
+sphinx==4.0.2
+sphinx_copybutton
+sphinx_markdown_tables
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/mminstall.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/mminstall.txt
new file mode 100644
index 0000000000000000000000000000000000000000..89199e36061dcd5361d029606fa25cb791af110a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/mminstall.txt
@@ -0,0 +1,3 @@
+mmcv-full>=1.3.8
+mmdet>=2.14.0
+mmtrack>=0.6.0
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/optional.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/optional.txt
new file mode 100644
index 0000000000000000000000000000000000000000..bfb1e75f86aba2fd074b0b1723e9b07a2037e9c3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/optional.txt
@@ -0,0 +1,8 @@
+albumentations>=0.3.2 --no-binary qudida,albumentations
+onnx
+onnxruntime
+poseval@git+https://github.com/svenkreiss/poseval.git
+pyrender
+requests
+smplx>=0.1.28
+trimesh
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/readthedocs.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/readthedocs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..b8b69d3ca2f051dcb6d6a96a25e7cb9054483c76
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/readthedocs.txt
@@ -0,0 +1,9 @@
+mmcv-full
+munkres
+poseval@git+https://github.com/svenkreiss/poseval.git
+regex
+scipy
+titlecase
+torch
+torchvision
+xtcocotools>=1.8
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/runtime.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/runtime.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c1d1b5a2336ecd0fbe555718f77cbc3125cddf1e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/runtime.txt
@@ -0,0 +1,14 @@
+chumpy
+dataclasses; python_version == '3.7'
+json_tricks
+matplotlib
+munkres
+numpy
+opencv-python
+pillow
+scipy
+torchvision
+xtcocotools>=1.12
+# easydict
+# einops
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/tests.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/tests.txt
new file mode 100644
index 0000000000000000000000000000000000000000..aa23e69da611f7dec62cf84541b7b508f4437a26
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/requirements/tests.txt
@@ -0,0 +1,9 @@
+coverage
+flake8
+interrogate
+isort==4.3.21
+pytest
+pytest-runner
+smplx>=0.1.28
+xdoctest>=0.10.0
+yapf
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.cfg b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..c4d8643bc91a06cc48f0d88b23288e892121249c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.cfg
@@ -0,0 +1,24 @@
+[bdist_wheel]
+universal=1
+
+[aliases]
+test=pytest
+
+[tool:pytest]
+addopts=tests/
+
+[yapf]
+based_on_style = pep8
+blank_line_before_nested_class_or_def = true
+split_before_expression_after_opening_paren = true
+split_penalty_import_names=0
+SPLIT_PENALTY_AFTER_OPENING_BRACKET=800
+
+[isort]
+line_length = 79
+multi_line_output = 0
+extra_standard_library = pkg_resources,setuptools
+known_first_party = mmpose
+known_third_party = PIL,cv2,h5py,json_tricks,matplotlib,mmcv,munkres,numpy,pytest,pytorch_sphinx_theme,requests,scipy,seaborn,spacepy,titlecase,torch,torchvision,webcam_apis,xmltodict,xtcocotools
+no_lines_before = STDLIB,LOCALFOLDER
+default_section = THIRDPARTY
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..f63ee82dc65093a1bd9dbdbef7369682b936f42d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/transformer_utils/setup.py
@@ -0,0 +1,194 @@
+import os
+import os.path as osp
+import platform
+import shutil
+import sys
+import warnings
+from setuptools import find_packages, setup
+
+
+def readme():
+ with open('README.md', encoding='utf-8') as f:
+ content = f.read()
+ return content
+
+
+version_file = 'mmpose/version.py'
+
+
+def get_version():
+ with open(version_file, 'r') as f:
+ exec(compile(f.read(), version_file, 'exec'))
+ import sys
+
+ # return short version for sdist
+ if 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
+ return locals()['short_version']
+ else:
+ return locals()['__version__']
+
+
+def parse_requirements(fname='requirements.txt', with_version=True):
+ """Parse the package dependencies listed in a requirements file but strips
+ specific versioning information.
+
+ Args:
+ fname (str): path to requirements file
+ with_version (bool, default=False): if True include version specs
+
+ Returns:
+ List[str]: list of requirements items
+
+ CommandLine:
+ python -c "import setup; print(setup.parse_requirements())"
+ """
+ import re
+ import sys
+ from os.path import exists
+ require_fpath = fname
+
+ def parse_line(line):
+ """Parse information from a line in a requirements text file."""
+ if line.startswith('-r '):
+ # Allow specifying requirements in other files
+ target = line.split(' ')[1]
+ for info in parse_require_file(target):
+ yield info
+ else:
+ info = {'line': line}
+ if line.startswith('-e '):
+ info['package'] = line.split('#egg=')[1]
+ elif '@git+' in line:
+ info['package'] = line
+ else:
+ # Remove versioning from the package
+ pat = '(' + '|'.join(['>=', '==', '>']) + ')'
+ parts = re.split(pat, line, maxsplit=1)
+ parts = [p.strip() for p in parts]
+
+ info['package'] = parts[0]
+ if len(parts) > 1:
+ op, rest = parts[1:]
+ if ';' in rest:
+ # Handle platform specific dependencies
+ # http://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-platform-specific-dependencies
+ version, platform_deps = map(str.strip,
+ rest.split(';'))
+ info['platform_deps'] = platform_deps
+ else:
+ version = rest # NOQA
+ info['version'] = (op, version)
+ yield info
+
+ def parse_require_file(fpath):
+ with open(fpath, 'r') as f:
+ for line in f.readlines():
+ line = line.strip()
+ if line and not line.startswith('#'):
+ for info in parse_line(line):
+ yield info
+
+ def gen_packages_items():
+ if exists(require_fpath):
+ for info in parse_require_file(require_fpath):
+ parts = [info['package']]
+ if with_version and 'version' in info:
+ parts.extend(info['version'])
+ if not sys.version.startswith('3.4'):
+ # apparently package_deps are broken in 3.4
+ platform_deps = info.get('platform_deps')
+ if platform_deps is not None:
+ parts.append(';' + platform_deps)
+ item = ''.join(parts)
+ yield item
+
+ packages = list(gen_packages_items())
+ return packages
+
+
+def add_mim_extension():
+ """Add extra files that are required to support MIM into the package.
+
+ These files will be added by creating a symlink to the originals if the
+ package is installed in `editable` mode (e.g. pip install -e .), or by
+ copying from the originals otherwise.
+ """
+
+ # parse installment mode
+ if 'develop' in sys.argv:
+ # installed by `pip install -e .`
+ if platform.system() == 'Windows':
+ mode = 'copy'
+ else:
+ mode = 'symlink'
+ elif 'sdist' in sys.argv or 'bdist_wheel' in sys.argv:
+ # installed by `pip install .`
+ # or create source distribution by `python setup.py sdist`
+ mode = 'copy'
+ else:
+ return
+
+ filenames = ['tools', 'configs', 'demo', 'model-index.yml']
+ repo_path = osp.dirname(__file__)
+ mim_path = osp.join(repo_path, 'mmpose', '.mim')
+ os.makedirs(mim_path, exist_ok=True)
+
+ for filename in filenames:
+ if osp.exists(filename):
+ src_path = osp.join(repo_path, filename)
+ tar_path = osp.join(mim_path, filename)
+
+ if osp.isfile(tar_path) or osp.islink(tar_path):
+ os.remove(tar_path)
+ elif osp.isdir(tar_path):
+ shutil.rmtree(tar_path)
+
+ if mode == 'symlink':
+ src_relpath = osp.relpath(src_path, osp.dirname(tar_path))
+ os.symlink(src_relpath, tar_path)
+ elif mode == 'copy':
+ if osp.isfile(src_path):
+ shutil.copyfile(src_path, tar_path)
+ elif osp.isdir(src_path):
+ shutil.copytree(src_path, tar_path)
+ else:
+ warnings.warn(f'Cannot copy file {src_path}.')
+ else:
+ raise ValueError(f'Invalid mode {mode}')
+
+
+if __name__ == '__main__':
+ add_mim_extension()
+ setup(
+ name='mmpose',
+ version=get_version(),
+ description='OpenMMLab Pose Estimation Toolbox and Benchmark.',
+ author='MMPose Contributors',
+ author_email='openmmlab@gmail.com',
+ keywords='computer vision, pose estimation',
+ # long_description=readme(),
+ long_description_content_type='text/markdown',
+ packages=find_packages(exclude=('configs', 'tools', 'demo')),
+ include_package_data=True,
+ package_data={'mmpose.ops': ['*/*.so']},
+ classifiers=[
+ 'Development Status :: 4 - Beta',
+ 'License :: OSI Approved :: Apache Software License',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
+ 'Programming Language :: Python :: 3.7',
+ 'Programming Language :: Python :: 3.8',
+ 'Programming Language :: Python :: 3.9',
+ ],
+ url='https://github.com/open-mmlab/mmpose',
+ license='Apache License 2.0',
+ install_requires=parse_requirements('requirements/runtime.txt'),
+ extras_require={
+ 'tests': parse_requirements('requirements/tests.txt'),
+ 'build': parse_requirements('requirements/build.txt'),
+ 'runtime': parse_requirements('requirements/runtime.txt'),
+ 'mim': parse_requirements('requirements/mminstall.txt'),
+ },
+ zip_safe=False)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/dir.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/dir.py
new file mode 100644
index 0000000000000000000000000000000000000000..6fbbfe7a57e49f7b581df245c21405f4090608bb
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/dir.py
@@ -0,0 +1,12 @@
+import os
+import sys
+
+def make_folder(folder_name):
+ os.makedirs(folder_name, exist_ok=True)
+ # if not os.path.exists(folder_name):
+ # os.makedirs(folder_name)
+
+def add_pypath(path):
+ if path not in sys.path:
+ sys.path.insert(0, path)
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/geometry.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/geometry.py
new file mode 100644
index 0000000000000000000000000000000000000000..28439e4e13ffdf324a5ff1a37738ee49e361d9dc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/geometry.py
@@ -0,0 +1,378 @@
+import numpy as np
+import torch
+from torch.nn import functional as F
+
+
+def batch_rodrigues(theta):
+ """Convert axis-angle representation to rotation matrix.
+
+ Args:
+ theta: size = [B, 3]
+ Returns:
+ Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
+ """
+ l1norm = torch.norm(theta + 1e-8, p=2, dim=1)
+ angle = torch.unsqueeze(l1norm, -1)
+ normalized = torch.div(theta, angle)
+ angle = angle * 0.5
+ v_cos = torch.cos(angle)
+ v_sin = torch.sin(angle)
+ quat = torch.cat([v_cos, v_sin * normalized], dim=1)
+ return quat_to_rotmat(quat)
+
+
+def quat_to_rotmat(quat):
+ """Convert quaternion coefficients to rotation matrix.
+
+ Args:
+ quat: size = [B, 4] 4 <===>(w, x, y, z)
+ Returns:
+ Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]
+ """
+ norm_quat = quat
+ norm_quat = norm_quat / norm_quat.norm(p=2, dim=1, keepdim=True)
+ w = norm_quat[:, 0]
+ x = norm_quat[:, 1]
+ y = norm_quat[:, 2]
+ z = norm_quat[:, 3]
+ B = quat.size(0)
+
+ w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)
+ wx, wy, wz = w * x, w * y, w * z
+ xy, xz, yz = x * y, x * z, y * z
+
+ rotMat = torch.stack([
+ w2 + x2 - y2 - z2, 2 * xy - 2 * wz, 2 * wy + 2 * xz, 2 * wz + 2 * xy,
+ w2 - x2 + y2 - z2, 2 * yz - 2 * wx, 2 * xz - 2 * wy, 2 * wx + 2 * yz,
+ w2 - x2 - y2 + z2
+ ],
+ dim=1).view(B, 3, 3)
+ return rotMat
+
+
+def rot6d_to_rotmat(x):
+ """Convert 6D rotation representation to 3x3 rotation matrix.
+
+ Based on Zhou et al., "On the Continuity of Rotation
+ Representations in Neural Networks", CVPR 2019
+ Input:
+ (B,6) Batch of 6-D rotation representations
+ Output:
+ (B,3,3) Batch of corresponding rotation matrices
+ """
+ if isinstance(x, torch.Tensor):
+ x = x.reshape(-1, 3, 2)
+ elif isinstance(x, np.ndarray):
+ x = x.view(-1, 3, 2)
+ a1 = x[:, :, 0]
+ a2 = x[:, :, 1]
+ b1 = F.normalize(a1)
+ b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)
+ b3 = torch.cross(b1, b2)
+ return torch.stack((b1, b2, b3), dim=-1)
+
+
+def rotation_matrix_to_angle_axis(rotation_matrix):
+ """
+ This function is borrowed from https://github.com/kornia/kornia
+ Convert 3x4 rotation matrix to Rodrigues vector
+ Args:
+ rotation_matrix (Tensor): rotation matrix.
+ Returns:
+ Tensor: Rodrigues vector transformation.
+ Shape:
+ - Input: :math:`(N, 3, 4)`
+ - Output: :math:`(N, 3)`
+ Example:
+ >>> input = torch.rand(2, 3, 4) # Nx3x4
+ >>> output = tgm.rotation_matrix_to_angle_axis(input) # Nx3
+ """
+ if rotation_matrix.shape[1:] == (3, 3):
+ rot_mat = rotation_matrix.reshape(-1, 3, 3)
+ hom = torch.tensor([0, 0, 1],
+ dtype=torch.float32,
+ device=rotation_matrix.device)
+ hom = hom.reshape(1, 3, 1).expand(rot_mat.shape[0], -1, -1)
+ rotation_matrix = torch.cat([rot_mat, hom], dim=-1)
+
+ quaternion = rotation_matrix_to_quaternion(rotation_matrix)
+ aa = quaternion_to_angle_axis(quaternion)
+ aa[torch.isnan(aa)] = 0.0
+ return aa
+
+
+def quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:
+ """
+ This function is borrowed from https://github.com/kornia/kornia
+ Convert quaternion vector to angle axis of rotation.
+ Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h
+ Args:
+ quaternion (torch.Tensor): tensor with quaternions.
+ Return:
+ torch.Tensor: tensor with angle axis of rotation.
+ Shape:
+ - Input: :math:`(*, 4)` where `*` means, any number of dimensions
+ - Output: :math:`(*, 3)`
+ Example:
+ >>> quaternion = torch.rand(2, 4) # Nx4
+ >>> angle_axis = tgm.quaternion_to_angle_axis(quaternion) # Nx3
+ """
+ if not torch.is_tensor(quaternion):
+ raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
+ type(quaternion)))
+
+ if not quaternion.shape[-1] == 4:
+ raise ValueError(
+ 'Input must be a tensor of shape Nx4 or 4. Got {}'.format(
+ quaternion.shape))
+ # unpack input and compute conversion
+ q1: torch.Tensor = quaternion[..., 1]
+ q2: torch.Tensor = quaternion[..., 2]
+ q3: torch.Tensor = quaternion[..., 3]
+ sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3
+
+ sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)
+ cos_theta: torch.Tensor = quaternion[..., 0]
+ two_theta: torch.Tensor = 2.0 * torch.where(
+ cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta),
+ torch.atan2(sin_theta, cos_theta))
+
+ k_pos: torch.Tensor = two_theta / sin_theta
+ k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)
+ k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
+
+ angle_axis: torch.Tensor = torch.zeros_like(quaternion)[..., :3]
+ angle_axis[..., 0] += q1 * k
+ angle_axis[..., 1] += q2 * k
+ angle_axis[..., 2] += q3 * k
+ return angle_axis
+
+
+def rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):
+ """
+ This function is borrowed from https://github.com/kornia/kornia
+ Convert 3x4 rotation matrix to 4d quaternion vector
+ This algorithm is based on algorithm described in
+ https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201
+ Args:
+ rotation_matrix (Tensor): the rotation matrix to convert.
+ Return:
+ Tensor: the rotation in quaternion
+ Shape:
+ - Input: :math:`(N, 3, 4)`
+ - Output: :math:`(N, 4)`
+ Example:
+ >>> input = torch.rand(4, 3, 4) # Nx3x4
+ >>> output = tgm.rotation_matrix_to_quaternion(input) # Nx4
+ """
+ if not torch.is_tensor(rotation_matrix):
+ raise TypeError('Input type is not a torch.Tensor. Got {}'.format(
+ type(rotation_matrix)))
+
+ if len(rotation_matrix.shape) > 3:
+ raise ValueError(
+ 'Input size must be a three dimensional tensor. Got {}'.format(
+ rotation_matrix.shape))
+ if not rotation_matrix.shape[-2:] == (3, 4):
+ raise ValueError(
+ 'Input size must be a N x 3 x 4 tensor. Got {}'.format(
+ rotation_matrix.shape))
+
+ rmat_t = torch.transpose(rotation_matrix, 1, 2)
+
+ mask_d2 = rmat_t[:, 2, 2] < eps
+
+ mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]
+ mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]
+
+ t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
+ q0 = torch.stack([
+ rmat_t[:, 1, 2] - rmat_t[:, 2, 1], t0,
+ rmat_t[:, 0, 1] + rmat_t[:, 1, 0], rmat_t[:, 2, 0] + rmat_t[:, 0, 2]
+ ], -1)
+ t0_rep = t0.repeat(4, 1).t()
+
+ t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]
+ q1 = torch.stack([
+ rmat_t[:, 2, 0] - rmat_t[:, 0, 2], rmat_t[:, 0, 1] + rmat_t[:, 1, 0],
+ t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]
+ ], -1)
+ t1_rep = t1.repeat(4, 1).t()
+
+ t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
+ q2 = torch.stack([
+ rmat_t[:, 0, 1] - rmat_t[:, 1, 0], rmat_t[:, 2, 0] + rmat_t[:, 0, 2],
+ rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2
+ ], -1)
+ t2_rep = t2.repeat(4, 1).t()
+
+ t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]
+ q3 = torch.stack([
+ t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],
+ rmat_t[:, 2, 0] - rmat_t[:, 0, 2], rmat_t[:, 0, 1] - rmat_t[:, 1, 0]
+ ], -1)
+ t3_rep = t3.repeat(4, 1).t()
+
+ mask_c0 = mask_d2 * mask_d0_d1
+ mask_c1 = mask_d2 * ~mask_d0_d1
+ mask_c2 = ~mask_d2 * mask_d0_nd1
+ mask_c3 = ~mask_d2 * ~mask_d0_nd1
+ mask_c0 = mask_c0.view(-1, 1).type_as(q0)
+ mask_c1 = mask_c1.view(-1, 1).type_as(q1)
+ mask_c2 = mask_c2.view(-1, 1).type_as(q2)
+ mask_c3 = mask_c3.view(-1, 1).type_as(q3)
+
+ q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3
+ q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa
+ t2_rep * mask_c2 + t3_rep * mask_c3) # noqa
+ q *= 0.5
+ return q
+
+
+def perspective_projection(points, rotation, translation, focal_length,
+ camera_center):
+ """This function computes the perspective projection of a set of points.
+
+ Input:
+ points (bs, N, 3): 3D points
+ rotation (bs, 3, 3): Camera rotation
+ translation (bs, 3): Camera translation
+ focal_length (bs,) or scalar: Focal length
+ camera_center (bs, 2): Camera center
+ """
+ batch_size = points.shape[0]
+ K = torch.zeros([batch_size, 3, 3], device=points.device)
+ K[:, 0, 0] = focal_length
+ K[:, 1, 1] = focal_length
+ K[:, 2, 2] = 1.
+ K[:, :-1, -1] = camera_center
+
+ # Transform points
+ points = torch.einsum('bij,bkj->bki', rotation, points)
+ points = points + translation.unsqueeze(1)
+
+ # Apply perspective distortion
+ projected_points = points / points[:, :, -1].unsqueeze(-1)
+
+ # Apply camera intrinsics
+ projected_points = torch.einsum('bij,bkj->bki', K, projected_points)
+
+ return projected_points[:, :, :-1]
+
+
+def estimate_translation_np(S,
+ joints_2d,
+ joints_conf,
+ focal_length=5000,
+ img_size=224):
+ """Find camera translation that brings 3D joints S closest to 2D the
+ corresponding joints_2d.
+
+ Input:
+ S: (25, 3) 3D joint locations
+ joints: (25, 3) 2D joint locations and confidence
+ Returns:
+ (3,) camera translation vector
+ """
+
+ num_joints = S.shape[0]
+ # focal length
+ f = np.array([focal_length, focal_length])
+ # optical center
+ center = np.array([img_size / 2., img_size / 2.])
+
+ # transformations
+ Z = np.reshape(np.tile(S[:, 2], (2, 1)).T, -1)
+ XY = np.reshape(S[:, 0:2], -1)
+ OO = np.tile(center, num_joints)
+ F = np.tile(f, num_joints)
+ weight2 = np.reshape(np.tile(np.sqrt(joints_conf), (2, 1)).T, -1)
+
+ # least squares
+ Q = np.array([
+ F * np.tile(np.array([1, 0]), num_joints),
+ F * np.tile(np.array([0, 1]), num_joints),
+ OO - np.reshape(joints_2d, -1)
+ ]).T
+ c = (np.reshape(joints_2d, -1) - OO) * Z - F * XY
+
+ # weighted least squares
+ W = np.diagflat(weight2)
+ Q = np.dot(W, Q)
+ c = np.dot(W, c)
+
+ # square matrix
+ A = np.dot(Q.T, Q)
+ b = np.dot(Q.T, c)
+
+ # solution
+ trans = np.linalg.solve(A, b)
+
+ return trans
+
+
+def estimate_translation(S, joints_2d, focal_length=5000., img_size=224.):
+ """Find camera translation that brings 3D joints S closest to 2D the
+ corresponding joints_2d.
+
+ Input:
+ S: (B, 49, 3) 3D joint locations
+ joints: (B, 49, 3) 2D joint locations and confidence
+ Returns:
+ (B, 3) camera translation vectors
+ """
+
+ device = S.device
+ # Use only joints 25:49 (GT joints)
+ S = S[:, 25:, :].cpu().numpy()
+ joints_2d = joints_2d[:, 25:, :].cpu().numpy()
+ joints_conf = joints_2d[:, :, -1]
+ joints_2d = joints_2d[:, :, :-1]
+ trans = np.zeros((S.shape[0], 3), dtype=np.float32)
+ # Find the translation for each example in the batch
+ for i in range(S.shape[0]):
+ S_i = S[i]
+ joints_i = joints_2d[i]
+ conf_i = joints_conf[i]
+ trans[i] = estimate_translation_np(
+ S_i,
+ joints_i,
+ conf_i,
+ focal_length=focal_length,
+ img_size=img_size)
+ return torch.from_numpy(trans).to(device)
+
+
+def project_points(points_3d, camera, focal_length, img_res):
+ """Perform orthographic projection of 3D points using the camera
+ parameters, return projected 2D points in image plane.
+
+ Notes:
+ batch size: B
+ point number: N
+ Args:
+ points_3d (Tensor([B, N, 3])): 3D points.
+ camera (Tensor([B, 3])): camera parameters with the
+ 3 channel as (scale, translation_x, translation_y)
+ Returns:
+ points_2d (Tensor([B, N, 2])): projected 2D points
+ in image space.
+ """
+ batch_size = points_3d.shape[0]
+ device = points_3d.device
+ cam_t = torch.stack([
+ camera[:, 1], camera[:, 2], 2 * focal_length /
+ (img_res * camera[:, 0] + 1e-9)
+ ],
+ dim=-1)
+ camera_center = camera.new_zeros([batch_size, 2])
+ rot_t = torch.eye(
+ 3, device=device,
+ dtype=points_3d.dtype).unsqueeze(0).expand(batch_size, -1, -1)
+ keypoints_2d = perspective_projection(
+ points_3d,
+ rotation=rot_t,
+ translation=cam_t,
+ focal_length=focal_length,
+ camera_center=camera_center)
+ return keypoints_2d
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/human_models.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/human_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..49f86d09666957b23d7ec2920c0b7eda65a144ba
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/human_models.py
@@ -0,0 +1,241 @@
+import numpy as np
+import torch
+import os.path as osp
+from config import cfg
+from utils.smplx import smplx
+import pickle
+from utils.transforms import transform_joint_to_other_db
+
+class SMPLX(object):
+ def __init__(self):
+ self.layer_arg = {'create_global_orient': False, 'create_body_pose': False, 'create_left_hand_pose': False, 'create_right_hand_pose': False, 'create_jaw_pose': False, 'create_leye_pose': False, 'create_reye_pose': False, 'create_betas': False, 'create_expression': False, 'create_transl': False}
+ self.layer = {'neutral': smplx.create(cfg.human_model_path, 'smplx', gender='NEUTRAL', use_pca=False, use_face_contour=True, **self.layer_arg),
+ 'male': smplx.create(cfg.human_model_path, 'smplx', gender='MALE', use_pca=False, use_face_contour=True, **self.layer_arg),
+ 'female': smplx.create(cfg.human_model_path, 'smplx', gender='FEMALE', use_pca=False, use_face_contour=True, **self.layer_arg)
+ }
+ self.vertex_num = 10475
+ self.face = self.layer['neutral'].faces
+ self.shape_param_dim = 10
+ self.expr_code_dim = 10
+ with open(osp.join(cfg.human_model_path, 'smplx', 'SMPLX_to_J14.pkl'), 'rb') as f:
+ self.j14_regressor = pickle.load(f, encoding='latin1')
+ with open(osp.join(cfg.human_model_path, 'smplx', 'MANO_SMPLX_vertex_ids.pkl'), 'rb') as f:
+ self.hand_vertex_idx = pickle.load(f, encoding='latin1')
+ self.face_vertex_idx = np.load(osp.join(cfg.human_model_path, 'smplx', 'SMPL-X__FLAME_vertex_ids.npy'))
+ self.J_regressor = self.layer['neutral'].J_regressor.numpy()
+ self.J_regressor_idx = {'pelvis': 0, 'lwrist': 20, 'rwrist': 21, 'neck': 12}
+ self.orig_hand_regressor = self.make_hand_regressor()
+ #self.orig_hand_regressor = {'left': self.layer.J_regressor.numpy()[[20,37,38,39,25,26,27,28,29,30,34,35,36,31,32,33],:], 'right': self.layer.J_regressor.numpy()[[21,52,53,54,40,41,42,43,44,45,49,50,51,46,47,48],:]}
+
+ # original SMPLX joint set
+ self.orig_joint_num = 53 # 22 (body joints) + 30 (hand joints) + 1 (face jaw joint)
+ self.orig_joints_name = \
+ ('Pelvis', 'L_Hip', 'R_Hip', 'Spine_1', 'L_Knee', 'R_Knee', 'Spine_2', 'L_Ankle', 'R_Ankle', 'Spine_3', 'L_Foot', 'R_Foot', 'Neck', 'L_Collar', 'R_Collar', 'Head', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', # body joints
+ 'L_Index_1', 'L_Index_2', 'L_Index_3', 'L_Middle_1', 'L_Middle_2', 'L_Middle_3', 'L_Pinky_1', 'L_Pinky_2', 'L_Pinky_3', 'L_Ring_1', 'L_Ring_2', 'L_Ring_3', 'L_Thumb_1', 'L_Thumb_2', 'L_Thumb_3', # left hand joints
+ 'R_Index_1', 'R_Index_2', 'R_Index_3', 'R_Middle_1', 'R_Middle_2', 'R_Middle_3', 'R_Pinky_1', 'R_Pinky_2', 'R_Pinky_3', 'R_Ring_1', 'R_Ring_2', 'R_Ring_3', 'R_Thumb_1', 'R_Thumb_2', 'R_Thumb_3', # right hand joints
+ 'Jaw' # face jaw joint
+ )
+ self.orig_flip_pairs = \
+ ( (1,2), (4,5), (7,8), (10,11), (13,14), (16,17), (18,19), (20,21), # body joints
+ (22,37), (23,38), (24,39), (25,40), (26,41), (27,42), (28,43), (29,44), (30,45), (31,46), (32,47), (33,48), (34,49), (35,50), (36,51) # hand joints
+ )
+ self.orig_root_joint_idx = self.orig_joints_name.index('Pelvis')
+ self.orig_joint_part = \
+ {'body': range(self.orig_joints_name.index('Pelvis'), self.orig_joints_name.index('R_Wrist')+1),
+ 'lhand': range(self.orig_joints_name.index('L_Index_1'), self.orig_joints_name.index('L_Thumb_3')+1),
+ 'rhand': range(self.orig_joints_name.index('R_Index_1'), self.orig_joints_name.index('R_Thumb_3')+1),
+ 'face': range(self.orig_joints_name.index('Jaw'), self.orig_joints_name.index('Jaw')+1)}
+
+ # changed SMPLX joint set for the supervision
+ self.joint_num = 137 # 25 (body joints) + 40 (hand joints) + 72 (face keypoints)
+ self.joints_name = \
+ ('Pelvis', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle', 'Neck', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Big_toe', 'L_Small_toe', 'L_Heel', 'R_Big_toe', 'R_Small_toe', 'R_Heel', 'L_Ear', 'R_Ear', 'L_Eye', 'R_Eye', 'Nose',# body joints
+ 'L_Thumb_1', 'L_Thumb_2', 'L_Thumb_3', 'L_Thumb_4', 'L_Index_1', 'L_Index_2', 'L_Index_3', 'L_Index_4', 'L_Middle_1', 'L_Middle_2', 'L_Middle_3', 'L_Middle_4', 'L_Ring_1', 'L_Ring_2', 'L_Ring_3', 'L_Ring_4', 'L_Pinky_1', 'L_Pinky_2', 'L_Pinky_3', 'L_Pinky_4', # left hand joints
+ 'R_Thumb_1', 'R_Thumb_2', 'R_Thumb_3', 'R_Thumb_4', 'R_Index_1', 'R_Index_2', 'R_Index_3', 'R_Index_4', 'R_Middle_1', 'R_Middle_2', 'R_Middle_3', 'R_Middle_4', 'R_Ring_1', 'R_Ring_2', 'R_Ring_3', 'R_Ring_4', 'R_Pinky_1', 'R_Pinky_2', 'R_Pinky_3', 'R_Pinky_4', # right hand joints
+ *['Face_' + str(i) for i in range(1,73)] # face keypoints (too many keypoints... omit real names. have same name of keypoints defined in FLAME class)
+ )
+ self.root_joint_idx = self.joints_name.index('Pelvis')
+ self.lwrist_idx = self.joints_name.index('L_Wrist')
+ self.rwrist_idx = self.joints_name.index('R_Wrist')
+ self.neck_idx = self.joints_name.index('Neck')
+ self.flip_pairs = \
+ ( (1,2), (3,4), (5,6), (8,9), (10,11), (12,13), (14,17), (15,18), (16,19), (20,21), (22,23), # body joints
+ (25,45), (26,46), (27,47), (28,48), (29,49), (30,50), (31,51), (32,52), (33,53), (34,54), (35,55), (36,56), (37,57), (38,58), (39,59), (40,60), (41,61), (42,62), (43,63), (44,64), # hand joints
+ (67,68), # face eyeballs
+ (69,78), (70,77), (71,76), (72,75), (73,74), # face eyebrow
+ (83,87), (84,86), # face below nose
+ (88,97), (89,96), (90,95), (91,94), (92,99), (93,98), # face eyes
+ (100,106), (101,105), (102,104), (107,111), (108,110), # face mouth
+ (112,116), (113,115), (117,119), # face lip
+ (120,136), (121,135), (122,134), (123,133), (124,132), (125,131), (126,130), (127,129) # face contours
+ )
+ self.joint_idx = \
+ (0,1,2,4,5,7,8,12,16,17,18,19,20,21,60,61,62,63,64,65,59,58,57,56,55, # body joints
+ 37,38,39,66,25,26,27,67,28,29,30,68,34,35,36,69,31,32,33,70, # left hand joints
+ 52,53,54,71,40,41,42,72,43,44,45,73,49,50,51,74,46,47,48,75, # right hand joints
+ 22,15, # jaw, head
+ 57,56, # eyeballs
+ 76,77,78,79,80,81,82,83,84,85, # eyebrow
+ 86,87,88,89, # nose
+ 90,91,92,93,94, # below nose
+ 95,96,97,98,99,100,101,102,103,104,105,106, # eyes
+ 107, # right mouth
+ 108,109,110,111,112, # upper mouth
+ 113, # left mouth
+ 114,115,116,117,118, # lower mouth
+ 119, # right lip
+ 120,121,122, # upper lip
+ 123, # left lip
+ 124,125,126, # lower lip
+ 127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 # face contour
+ )
+ self.joint_part = \
+ {'body': range(self.joints_name.index('Pelvis'), self.joints_name.index('Nose')+1),
+ 'lhand': range(self.joints_name.index('L_Thumb_1'), self.joints_name.index('L_Pinky_4')+1),
+ 'rhand': range(self.joints_name.index('R_Thumb_1'), self.joints_name.index('R_Pinky_4')+1),
+ 'hand': range(self.joints_name.index('L_Thumb_1'), self.joints_name.index('R_Pinky_4')+1),
+ 'face': range(self.joints_name.index('Face_1'), self.joints_name.index('Face_72')+1)}
+
+ # changed SMPLX joint set for PositionNet prediction
+ self.pos_joint_num = 65 # 25 (body joints) + 40 (hand joints)
+ self.pos_joints_name = \
+ ('Pelvis', 'L_Hip', 'R_Hip', 'L_Knee', 'R_Knee', 'L_Ankle', 'R_Ankle', 'Neck', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Big_toe', 'L_Small_toe', 'L_Heel', 'R_Big_toe', 'R_Small_toe', 'R_Heel', 'L_Ear', 'R_Ear', 'L_Eye', 'R_Eye', 'Nose', # body joints
+ 'L_Thumb_1', 'L_Thumb_2', 'L_Thumb_3', 'L_Thumb_4', 'L_Index_1', 'L_Index_2', 'L_Index_3', 'L_Index_4', 'L_Middle_1', 'L_Middle_2', 'L_Middle_3', 'L_Middle_4', 'L_Ring_1', 'L_Ring_2', 'L_Ring_3', 'L_Ring_4', 'L_Pinky_1', 'L_Pinky_2', 'L_Pinky_3', 'L_Pinky_4', # left hand joints
+ 'R_Thumb_1', 'R_Thumb_2', 'R_Thumb_3', 'R_Thumb_4', 'R_Index_1', 'R_Index_2', 'R_Index_3', 'R_Index_4', 'R_Middle_1', 'R_Middle_2', 'R_Middle_3', 'R_Middle_4', 'R_Ring_1', 'R_Ring_2', 'R_Ring_3', 'R_Ring_4', 'R_Pinky_1', 'R_Pinky_2', 'R_Pinky_3', 'R_Pinky_4', # right hand joints
+ )
+ self.pos_joint_part = \
+ {'body': range(self.pos_joints_name.index('Pelvis'), self.pos_joints_name.index('Nose')+1),
+ 'lhand': range(self.pos_joints_name.index('L_Thumb_1'), self.pos_joints_name.index('L_Pinky_4')+1),
+ 'rhand': range(self.pos_joints_name.index('R_Thumb_1'), self.pos_joints_name.index('R_Pinky_4')+1),
+ 'hand': range(self.pos_joints_name.index('L_Thumb_1'), self.pos_joints_name.index('R_Pinky_4')+1)}
+ self.pos_joint_part['L_MCP'] = [self.pos_joints_name.index('L_Index_1') - len(self.pos_joint_part['body']),
+ self.pos_joints_name.index('L_Middle_1') - len(self.pos_joint_part['body']),
+ self.pos_joints_name.index('L_Ring_1') - len(self.pos_joint_part['body']),
+ self.pos_joints_name.index('L_Pinky_1') - len(self.pos_joint_part['body'])]
+ self.pos_joint_part['R_MCP'] = [self.pos_joints_name.index('R_Index_1') - len(self.pos_joint_part['body']) - len(self.pos_joint_part['lhand']),
+ self.pos_joints_name.index('R_Middle_1') - len(self.pos_joint_part['body']) - len(self.pos_joint_part['lhand']),
+ self.pos_joints_name.index('R_Ring_1') - len(self.pos_joint_part['body']) - len(self.pos_joint_part['lhand']),
+ self.pos_joints_name.index('R_Pinky_1') - len(self.pos_joint_part['body']) - len(self.pos_joint_part['lhand'])]
+
+ def make_hand_regressor(self):
+ regressor = self.layer['neutral'].J_regressor.numpy()
+ lhand_regressor = np.concatenate((regressor[[20,37,38,39],:],
+ np.eye(self.vertex_num)[5361,None],
+ regressor[[25,26,27],:],
+ np.eye(self.vertex_num)[4933,None],
+ regressor[[28,29,30],:],
+ np.eye(self.vertex_num)[5058,None],
+ regressor[[34,35,36],:],
+ np.eye(self.vertex_num)[5169,None],
+ regressor[[31,32,33],:],
+ np.eye(self.vertex_num)[5286,None]))
+ rhand_regressor = np.concatenate((regressor[[21,52,53,54],:],
+ np.eye(self.vertex_num)[8079,None],
+ regressor[[40,41,42],:],
+ np.eye(self.vertex_num)[7669,None],
+ regressor[[43,44,45],:],
+ np.eye(self.vertex_num)[7794,None],
+ regressor[[49,50,51],:],
+ np.eye(self.vertex_num)[7905,None],
+ regressor[[46,47,48],:],
+ np.eye(self.vertex_num)[8022,None]))
+ hand_regressor = {'left': lhand_regressor, 'right': rhand_regressor}
+ return hand_regressor
+
+
+ def reduce_joint_set(self, joint):
+ new_joint = []
+ for name in self.pos_joints_name:
+ idx = self.joints_name.index(name)
+ new_joint.append(joint[:,idx,:])
+ new_joint = torch.stack(new_joint,1)
+ return new_joint
+
+class SMPL(object):
+ def __init__(self):
+ self.layer_arg = {'create_body_pose': False, 'create_betas': False, 'create_global_orient': False, 'create_transl': False}
+ self.layer = {'neutral': smplx.create(cfg.human_model_path, 'smpl', gender='NEUTRAL', **self.layer_arg), 'male': smplx.create(cfg.human_model_path, 'smpl', gender='MALE', **self.layer_arg), 'female': smplx.create(cfg.human_model_path, 'smpl', gender='FEMALE', **self.layer_arg)}
+ self.vertex_num = 6890
+ self.face = self.layer['neutral'].faces
+ self.shape_param_dim = 10
+ self.vposer_code_dim = 32
+
+ # original SMPL joint set
+ self.orig_joint_num = 24
+ self.orig_joints_name = ('Pelvis', 'L_Hip', 'R_Hip', 'Spine_1', 'L_Knee', 'R_Knee', 'Spine_2', 'L_Ankle', 'R_Ankle', 'Spine_3', 'L_Foot', 'R_Foot', 'Neck', 'L_Collar', 'R_Collar', 'Head', 'L_Shoulder', 'R_Shoulder', 'L_Elbow', 'R_Elbow', 'L_Wrist', 'R_Wrist', 'L_Hand', 'R_Hand')
+ self.orig_flip_pairs = ( (1,2), (4,5), (7,8), (10,11), (13,14), (16,17), (18,19), (20,21), (22,23) )
+ self.orig_root_joint_idx = self.orig_joints_name.index('Pelvis')
+ self.orig_joint_regressor = self.layer['neutral'].J_regressor.numpy().astype(np.float32)
+
+ self.joint_num = self.orig_joint_num
+ self.joints_name = self.orig_joints_name
+ self.flip_pairs = self.orig_flip_pairs
+ self.root_joint_idx = self.orig_root_joint_idx
+ self.joint_regressor = self.orig_joint_regressor
+
+class MANO(object):
+ def __init__(self):
+ self.layer_arg = {'create_global_orient': False, 'create_hand_pose': False, 'create_betas': False, 'create_transl': False}
+ self.layer = {'right': smplx.create(cfg.human_model_path, 'mano', is_rhand=True, use_pca=False, flat_hand_mean=False, **self.layer_arg),
+ 'left': smplx.create(cfg.human_model_path, 'mano', is_rhand=False, use_pca=False, flat_hand_mean=False, **self.layer_arg)}
+ self.vertex_num = 778
+ self.face = {'right': self.layer['right'].faces, 'left': self.layer['left'].faces}
+ self.shape_param_dim = 10
+
+ if torch.sum(torch.abs(self.layer['left'].shapedirs[:,0,:] - self.layer['right'].shapedirs[:,0,:])) < 1:
+ print('Fix shapedirs bug of MANO')
+ self.layer['left'].shapedirs[:,0,:] *= -1
+
+ # original MANO joint set
+ self.orig_joint_num = 16
+ self.orig_joints_name = ('Wrist', 'Index_1', 'Index_2', 'Index_3', 'Middle_1', 'Middle_2', 'Middle_3', 'Pinky_1', 'Pinky_2', 'Pinky_3', 'Ring_1', 'Ring_2', 'Ring_3', 'Thumb_1', 'Thumb_2', 'Thumb_3')
+ self.orig_root_joint_idx = self.orig_joints_name.index('Wrist')
+ self.orig_flip_pairs = ()
+ self.orig_joint_regressor = self.layer['right'].J_regressor.numpy() # same for the right and left hands
+
+ # changed MANO joint set
+ self.joint_num = 21 # manually added fingertips
+ self.joints_name = ('Wrist', 'Thumb_1', 'Thumb_2', 'Thumb_3', 'Thumb_4', 'Index_1', 'Index_2', 'Index_3', 'Index_4', 'Middle_1', 'Middle_2', 'Middle_3', 'Middle_4', 'Ring_1', 'Ring_2', 'Ring_3', 'Ring_4', 'Pinky_1', 'Pinky_2', 'Pinky_3', 'Pinky_4')
+ self.skeleton = ( (0,1), (0,5), (0,9), (0,13), (0,17), (1,2), (2,3), (3,4), (5,6), (6,7), (7,8), (9,10), (10,11), (11,12), (13,14), (14,15), (15,16), (17,18), (18,19), (19,20) )
+ self.root_joint_idx = self.joints_name.index('Wrist')
+ self.flip_pairs = ()
+ # add fingertips to joint_regressor
+ self.joint_regressor = transform_joint_to_other_db(self.orig_joint_regressor, self.orig_joints_name, self.joints_name)
+ self.joint_regressor[self.joints_name.index('Thumb_4')] = np.array([1 if i == 745 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
+ self.joint_regressor[self.joints_name.index('Index_4')] = np.array([1 if i == 317 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
+ self.joint_regressor[self.joints_name.index('Middle_4')] = np.array([1 if i == 445 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
+ self.joint_regressor[self.joints_name.index('Ring_4')] = np.array([1 if i == 556 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
+ self.joint_regressor[self.joints_name.index('Pinky_4')] = np.array([1 if i == 673 else 0 for i in range(self.joint_regressor.shape[1])], dtype=np.float32).reshape(1,-1)
+
+class FLAME(object):
+ def __init__(self):
+ self.layer_arg = {'create_betas': False, 'create_expression': False, 'create_global_orient': False, 'create_neck_pose': False, 'create_jaw_pose': False, 'create_leye_pose': False, 'create_reye_pose': False, 'create_transl': False}
+ self.layer = smplx.create(cfg.human_model_path, 'flame', use_face_contour=True, **self.layer_arg)
+ self.vertex_num = 5023
+ self.face = self.layer.faces
+ self.shape_param_dim = 10
+ self.expr_code_dim = 10
+
+ # FLAME joint set
+ self.orig_joint_num = 73
+ self.orig_flip_pairs = ( (3,4), # eyeballs
+ (5,14), (6,13), (7,12), (8,11), (9,10), # eyebrow
+ (19,23), (20,22), # below nose
+ (24,33), (25,32), (26,31), (27,30), (28,35), (29,34), # eyes
+ (36,42), (37,41), (38,40), (43,47), (44,46), # mouth
+ (48,52), (49,51), (53,55), # lip
+ (56,72), (57,71), (58,70), (59,69), (60,68), (61,67), (62,66), (63,65) # face controus
+ )
+ self.orig_joints_name = [str(i) for i in range(self.orig_joint_num)]
+ self.orig_root_joint_idx = 0
+
+ # changed FLAME joint set
+ self.joint_num = self.orig_joint_num
+ self.flip_pairs = self.orig_flip_pairs
+ self.joints_name = self.orig_joints_name
+ self.root_joint_idx = self.orig_root_joint_idx
+
+smpl_x = SMPLX()
+smpl = SMPL()
+mano = MANO()
+flame = FLAME()
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/preprocessing.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/preprocessing.py
new file mode 100644
index 0000000000000000000000000000000000000000..5a068e9abae6f7a7e4632939a42be01a51b478e3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/preprocessing.py
@@ -0,0 +1,621 @@
+import numpy as np
+import cv2
+import random
+from config import cfg
+import math
+from utils.human_models import smpl_x, smpl
+from utils.transforms import cam2pixel, transform_joint_to_other_db
+from plyfile import PlyData, PlyElement
+import torch
+
+def compute_iou(bbox1, bbox2, center=False):
+ """Compute the iou of two boxes.
+ Parameters
+ ----------
+ bbox1, bbox2: list.
+ The bounding box coordinates: [xmin, ymin, xmax, ymax] or [xcenter, ycenter, w, h].
+ center: str, default is 'False'.
+ The format of coordinate.
+ center=False: [xmin, ymin, xmax, ymax]
+ center=True: [xcenter, ycenter, w, h]
+ Returns
+ -------
+ iou: float.
+ The iou of bbox1 and bbox2.
+ """
+ if center == False:
+ xmin1, ymin1, xmax1, ymax1 = bbox1
+ xmin2, ymin2, xmax2, ymax2 = bbox2
+ else:
+ xmin1, ymin1 = int(bbox1[0] - bbox1[2] / 2.0), int(bbox1[1] - bbox1[3] / 2.0)
+ xmax1, ymax1 = int(bbox1[0] + bbox1[2] / 2.0), int(bbox1[1] + bbox1[3] / 2.0)
+ xmin2, ymin2 = int(bbox2[0] - bbox2[2] / 2.0), int(bbox2[1] - bbox2[3] / 2.0)
+ xmax2, ymax2 = int(bbox2[0] + bbox2[2] / 2.0), int(bbox2[1] + bbox2[3] / 2.0)
+
+ xx1 = np.max([xmin1, xmin2])
+ yy1 = np.max([ymin1, ymin2])
+ xx2 = np.min([xmax1, xmax2])
+ yy2 = np.min([ymax1, ymax2])
+
+ area1 = (xmax1 - xmin1 + 1) * (ymax1 - ymin1 + 1)
+ area2 = (xmax2 - xmin2 + 1) * (ymax2 - ymin2 + 1)
+
+ inter_area = (np.max([0, xx2 - xx1])) * (np.max([0, yy2 - yy1]))
+
+ iou = inter_area / (area1 + area2 - inter_area + 1e-6)
+ return iou
+
+def load_img(path, order='RGB'):
+ img = cv2.imread(path, cv2.IMREAD_COLOR | cv2.IMREAD_IGNORE_ORIENTATION)
+ if not isinstance(img, np.ndarray):
+ raise IOError("Fail to read %s" % path)
+
+ if order=='RGB':
+ img = img[:,:,::-1].copy()
+
+ img = img.astype(np.float32)
+ return img
+
+def resize_bbox(bbox, scale=1.2):
+ if isinstance(bbox, list):
+ x1, y1, x2, y2 = bbox[0], bbox[1], bbox[2], bbox[3]
+ else:
+ x1, y1, x2, y2 = bbox
+ x_center = (x1+x2)/2.0
+ y_center = (y1+y2)/2.0
+ x_size, y_size = x2-x1, y2-y1
+ x1_resize = x_center-x_size/2.0*scale
+ x2_resize = x_center+x_size/2.0*scale
+ y1_resize = y_center - y_size / 2.0 * scale
+ y2_resize = y_center + y_size / 2.0 * scale
+ bbox[0], bbox[1], bbox[2], bbox[3] = x1_resize, y1_resize, x2_resize, y2_resize
+ return bbox
+
+def get_bbox(joint_img, joint_valid, extend_ratio=1.2):
+
+ x_img, y_img = joint_img[:,0], joint_img[:,1]
+ x_img = x_img[joint_valid==1]; y_img = y_img[joint_valid==1];
+ xmin = min(x_img); ymin = min(y_img); xmax = max(x_img); ymax = max(y_img);
+
+ x_center = (xmin+xmax)/2.; width = xmax-xmin;
+ xmin = x_center - 0.5 * width * extend_ratio
+ xmax = x_center + 0.5 * width * extend_ratio
+
+ y_center = (ymin+ymax)/2.; height = ymax-ymin;
+ ymin = y_center - 0.5 * height * extend_ratio
+ ymax = y_center + 0.5 * height * extend_ratio
+
+ bbox = np.array([xmin, ymin, xmax - xmin, ymax - ymin]).astype(np.float32)
+ return bbox
+
+def sanitize_bbox(bbox, img_width, img_height):
+ x, y, w, h = bbox
+ x1 = np.max((0, x))
+ y1 = np.max((0, y))
+ x2 = np.min((img_width - 1, x1 + np.max((0, w - 1))))
+ y2 = np.min((img_height - 1, y1 + np.max((0, h - 1))))
+ if w*h > 0 and x2 > x1 and y2 > y1:
+ bbox = np.array([x1, y1, x2-x1, y2-y1])
+ else:
+ bbox = None
+
+ return bbox
+
+def process_bbox(bbox, img_width, img_height):
+ bbox = sanitize_bbox(bbox, img_width, img_height)
+ if bbox is None:
+ return bbox
+
+ # aspect ratio preserving bbox
+ w = bbox[2]
+ h = bbox[3]
+ c_x = bbox[0] + w/2.
+ c_y = bbox[1] + h/2.
+ aspect_ratio = cfg.input_img_shape[1]/cfg.input_img_shape[0]
+ if w > aspect_ratio * h:
+ h = w / aspect_ratio
+ elif w < aspect_ratio * h:
+ w = h * aspect_ratio
+ bbox[2] = w*1.25
+ bbox[3] = h*1.25
+ bbox[0] = c_x - bbox[2]/2.
+ bbox[1] = c_y - bbox[3]/2.
+
+ bbox = bbox.astype(np.float32)
+ return bbox
+
+def get_aug_config():
+ scale_factor = 0.25
+ rot_factor = 30
+ color_factor = 0.2
+
+ scale = np.clip(np.random.randn(), -1.0, 1.0) * scale_factor + 1.0
+ rot = np.clip(np.random.randn(), -2.0,
+ 2.0) * rot_factor if random.random() <= 0.6 else 0
+ c_up = 1.0 + color_factor
+ c_low = 1.0 - color_factor
+ color_scale = np.array([random.uniform(c_low, c_up), random.uniform(c_low, c_up), random.uniform(c_low, c_up)])
+ do_flip = random.random() <= 0.5
+
+ return scale, rot, color_scale, do_flip
+
+def augmentation(img, bbox, data_split):
+ if data_split == 'train' and cfg.do_augment:
+ scale, rot, color_scale, do_flip = get_aug_config()
+ else:
+ scale, rot, color_scale, do_flip = 1.0, 0.0, np.array([1,1,1]), False
+
+ img, trans, inv_trans = generate_patch_image(img, bbox, scale, rot, do_flip, cfg.input_img_shape)
+ img = np.clip(img * color_scale[None,None,:], 0, 255)
+ return img, trans, inv_trans, rot, do_flip
+
+def generate_patch_image(cvimg, bbox, scale, rot, do_flip, out_shape):
+ img = cvimg.copy()
+ img_height, img_width, img_channels = img.shape
+
+ bb_c_x = float(bbox[0] + 0.5*bbox[2])
+ bb_c_y = float(bbox[1] + 0.5*bbox[3])
+ bb_width = float(bbox[2])
+ bb_height = float(bbox[3])
+
+ if do_flip:
+ img = img[:, ::-1, :]
+ bb_c_x = img_width - bb_c_x - 1
+
+ trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot)
+ img_patch = cv2.warpAffine(img, trans, (int(out_shape[1]), int(out_shape[0])), flags=cv2.INTER_LINEAR)
+ img_patch = img_patch.astype(np.float32)
+ inv_trans = gen_trans_from_patch_cv(bb_c_x, bb_c_y, bb_width, bb_height, out_shape[1], out_shape[0], scale, rot, inv=True)
+
+ return img_patch, trans, inv_trans
+
+def rotate_2d(pt_2d, rot_rad):
+ x = pt_2d[0]
+ y = pt_2d[1]
+ sn, cs = np.sin(rot_rad), np.cos(rot_rad)
+ xx = x * cs - y * sn
+ yy = x * sn + y * cs
+ return np.array([xx, yy], dtype=np.float32)
+
+def gen_trans_from_patch_cv(c_x, c_y, src_width, src_height, dst_width, dst_height, scale, rot, inv=False):
+ # augment size with scale
+ src_w = src_width * scale
+ src_h = src_height * scale
+ src_center = np.array([c_x, c_y], dtype=np.float32)
+
+ # augment rotation
+ rot_rad = np.pi * rot / 180
+ src_downdir = rotate_2d(np.array([0, src_h * 0.5], dtype=np.float32), rot_rad)
+ src_rightdir = rotate_2d(np.array([src_w * 0.5, 0], dtype=np.float32), rot_rad)
+
+ dst_w = dst_width
+ dst_h = dst_height
+ dst_center = np.array([dst_w * 0.5, dst_h * 0.5], dtype=np.float32)
+ dst_downdir = np.array([0, dst_h * 0.5], dtype=np.float32)
+ dst_rightdir = np.array([dst_w * 0.5, 0], dtype=np.float32)
+
+ src = np.zeros((3, 2), dtype=np.float32)
+ src[0, :] = src_center
+ src[1, :] = src_center + src_downdir
+ src[2, :] = src_center + src_rightdir
+
+ dst = np.zeros((3, 2), dtype=np.float32)
+ dst[0, :] = dst_center
+ dst[1, :] = dst_center + dst_downdir
+ dst[2, :] = dst_center + dst_rightdir
+
+ if inv:
+ trans = cv2.getAffineTransform(np.float32(dst), np.float32(src))
+ else:
+ trans = cv2.getAffineTransform(np.float32(src), np.float32(dst))
+
+ trans = trans.astype(np.float32)
+ return trans
+
+def process_db_coord(joint_img, joint_cam, joint_valid, do_flip, img_shape, flip_pairs, img2bb_trans, rot, src_joints_name,
+ target_joints_name, joint_valid_3d=None, joint_img_global=None, joint_cam_global=None):
+ joint_img, joint_cam, joint_valid = joint_img.copy(), joint_cam.copy(), joint_valid.copy()
+ if joint_valid_3d is not None:
+ joint_valid_3d = joint_valid_3d.copy()
+ joint_img_global = joint_img_global.copy()
+ joint_cam_global = joint_cam_global.copy()
+
+ # flip augmentation
+ if do_flip:
+ joint_cam[:,0] = -joint_cam[:,0]
+ joint_img[:,0] = img_shape[1] - 1 - joint_img[:,0]
+ for pair in flip_pairs:
+ joint_img[pair[0],:], joint_img[pair[1],:] = joint_img[pair[1],:].copy(), joint_img[pair[0],:].copy()
+ joint_cam[pair[0],:], joint_cam[pair[1],:] = joint_cam[pair[1],:].copy(), joint_cam[pair[0],:].copy()
+ joint_valid[pair[0],:], joint_valid[pair[1],:] = joint_valid[pair[1],:].copy(), joint_valid[pair[0],:].copy()
+ if joint_valid_3d is not None:
+ joint_valid_3d[pair[0],:], joint_valid_3d[pair[1],:] = joint_valid_3d[pair[1],:].copy(), joint_valid_3d[pair[0],:].copy()
+
+ # 3D data rotation augmentation
+ rot_aug_mat = np.array([[np.cos(np.deg2rad(-rot)), -np.sin(np.deg2rad(-rot)), 0],
+ [np.sin(np.deg2rad(-rot)), np.cos(np.deg2rad(-rot)), 0],
+ [0, 0, 1]], dtype=np.float32)
+ joint_cam = np.dot(rot_aug_mat, joint_cam.transpose(1,0)).transpose(1,0)
+
+ # affine transformation
+ joint_img_xy1 = np.concatenate((joint_img[:,:2], np.ones_like(joint_img[:,:1])),1)
+ joint_img[:,:2] = np.dot(img2bb_trans, joint_img_xy1.transpose(1,0)).transpose(1,0)
+ joint_img[:,0] = joint_img[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2]
+ joint_img[:,1] = joint_img[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1]
+ joint_img[:,2] = (joint_img[:,2] / (cfg.body_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0]
+
+ # check truncation
+ joint_trunc = joint_valid * ((joint_img[:,0] >= 0) * (joint_img[:,0] < cfg.output_hm_shape[2]) * \
+ (joint_img[:,1] >= 0) * (joint_img[:,1] < cfg.output_hm_shape[1]) * \
+ (joint_img[:,2] >= 0) * (joint_img[:,2] < cfg.output_hm_shape[0])).reshape(-1,1).astype(np.float32)
+
+ # transform joints to target db joints
+ joint_img = transform_joint_to_other_db(joint_img, src_joints_name, target_joints_name)
+ joint_cam = transform_joint_to_other_db(joint_cam, src_joints_name, target_joints_name)
+ joint_valid = transform_joint_to_other_db(joint_valid, src_joints_name, target_joints_name)
+ joint_trunc = transform_joint_to_other_db(joint_trunc, src_joints_name, target_joints_name)
+ if joint_valid_3d is not None:
+ joint_valid_3d = transform_joint_to_other_db(joint_valid_3d, src_joints_name, target_joints_name)
+ joint_img_global = transform_joint_to_other_db(joint_img_global, src_joints_name, target_joints_name)
+ joint_cam_global = transform_joint_to_other_db(joint_cam_global, src_joints_name, target_joints_name)
+ return joint_img, joint_cam, joint_valid, joint_trunc, joint_valid_3d, joint_img_global, joint_cam_global
+ return joint_img, joint_cam, joint_valid, joint_trunc
+
+def process_human_model_output(human_model_param, cam_param, do_flip, img_shape, img2bb_trans, rot, human_model_type, flame_betas=None, flame_expression=None):
+
+ if human_model_type == 'smplx':
+ human_model = smpl_x
+ rotation_valid = np.ones((smpl_x.orig_joint_num), dtype=np.float32)
+ coord_valid = np.ones((smpl_x.joint_num), dtype=np.float32)
+
+ root_pose, body_pose, shape, trans = human_model_param['root_pose'], human_model_param['body_pose'], \
+ human_model_param['shape'], human_model_param['trans']
+ if 'lhand_pose' in human_model_param and human_model_param['lhand_valid']:
+ lhand_pose = human_model_param['lhand_pose']
+ else:
+ lhand_pose = np.zeros((3 * len(smpl_x.orig_joint_part['lhand'])), dtype=np.float32)
+ rotation_valid[smpl_x.orig_joint_part['lhand']] = 0
+ coord_valid[smpl_x.joint_part['lhand']] = 0
+ if 'rhand_pose' in human_model_param and human_model_param['rhand_valid']:
+ rhand_pose = human_model_param['rhand_pose']
+ else:
+ rhand_pose = np.zeros((3 * len(smpl_x.orig_joint_part['rhand'])), dtype=np.float32)
+ rotation_valid[smpl_x.orig_joint_part['rhand']] = 0
+ coord_valid[smpl_x.joint_part['rhand']] = 0
+ if 'jaw_pose' in human_model_param and 'expr' in human_model_param and human_model_param['face_valid']:
+ jaw_pose = human_model_param['jaw_pose']
+ expr = human_model_param['expr']
+ expr_valid = True
+ else:
+ jaw_pose = np.zeros((3), dtype=np.float32)
+ expr = np.zeros((smpl_x.expr_code_dim), dtype=np.float32)
+ rotation_valid[smpl_x.orig_joint_part['face']] = 0
+ coord_valid[smpl_x.joint_part['face']] = 0
+ expr_valid = False
+ if 'gender' in human_model_param:
+ gender = human_model_param['gender']
+ else:
+ gender = 'neutral'
+ root_pose = torch.FloatTensor(root_pose).view(1, 3) # (1,3)
+ body_pose = torch.FloatTensor(body_pose).view(-1, 3) # (21,3)
+ lhand_pose = torch.FloatTensor(lhand_pose).view(-1, 3) # (15,3)
+ rhand_pose = torch.FloatTensor(rhand_pose).view(-1, 3) # (15,3)
+ jaw_pose = torch.FloatTensor(jaw_pose).view(-1, 3) # (1,3)
+ shape = torch.FloatTensor(shape).view(1, -1) # SMPLX shape parameter
+ expr = torch.FloatTensor(expr).view(1, -1) # SMPLX expression parameter
+ trans = torch.FloatTensor(trans).view(1, -1) # translation vector
+
+ # apply camera extrinsic (rotation)
+ # merge root pose and camera rotation
+ if 'R' in cam_param:
+ R = np.array(cam_param['R'], dtype=np.float32).reshape(3, 3)
+ root_pose = root_pose.numpy()
+ root_pose, _ = cv2.Rodrigues(root_pose)
+ root_pose, _ = cv2.Rodrigues(np.dot(R, root_pose))
+ root_pose = torch.from_numpy(root_pose).view(1, 3)
+
+ # get mesh and joint coordinates
+ zero_pose = torch.zeros((1, 3)).float() # eye poses
+ with torch.no_grad():
+ if cfg.use_flame:
+ flame_betas = human_model_param['new_shape']
+ flame_expression = human_model_param['new_expr']
+ flame_betas = torch.FloatTensor(flame_betas).view(1, -1) # SMPLX shape parameter
+ flame_expression = torch.FloatTensor(flame_expression).view(1, -1) # SMPLX expression parameter
+ output = smpl_x.layer[gender](betas=shape, body_pose=body_pose.view(1, -1), global_orient=root_pose,
+ transl=trans, left_hand_pose=lhand_pose.view(1, -1),
+ right_hand_pose=rhand_pose.view(1, -1), jaw_pose=jaw_pose.view(1, -1),
+ leye_pose=zero_pose, reye_pose=zero_pose, expression=expr,
+ flame_betas=flame_betas, flame_expression=flame_expression)
+ else:
+ output = smpl_x.layer[gender](betas=shape, body_pose=body_pose.view(1, -1), global_orient=root_pose,
+ transl=trans, left_hand_pose=lhand_pose.view(1, -1),
+ right_hand_pose=rhand_pose.view(1, -1), jaw_pose=jaw_pose.view(1, -1),
+ leye_pose=zero_pose, reye_pose=zero_pose, expression=expr)
+ mesh_cam = output.vertices[0].numpy()
+ joint_cam = output.joints[0].numpy()[smpl_x.joint_idx, :]
+
+ # apply camera exrinsic (translation)
+ # compenstate rotation (translation from origin to root joint was not cancled)
+ if 'R' in cam_param and 't' in cam_param:
+ R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3, 3), np.array(cam_param['t'],
+ dtype=np.float32).reshape(1, 3)
+ root_cam = joint_cam[smpl_x.root_joint_idx, None, :]
+ joint_cam = joint_cam - root_cam + np.dot(R, root_cam.transpose(1, 0)).transpose(1, 0) + t
+ mesh_cam = mesh_cam - root_cam + np.dot(R, root_cam.transpose(1, 0)).transpose(1, 0) + t
+
+ # concat root, body, two hands, and jaw pose
+ pose = torch.cat((root_pose, body_pose, lhand_pose, rhand_pose, jaw_pose))
+
+ # joint coordinates
+ joint_img = cam2pixel(joint_cam, cam_param['focal'], cam_param['princpt'])
+ joint_cam = joint_cam - joint_cam[smpl_x.root_joint_idx, None, :] # root-relative
+ joint_cam[smpl_x.joint_part['lhand'], :] = joint_cam[smpl_x.joint_part['lhand'], :] - joint_cam[
+ smpl_x.lwrist_idx, None,
+ :] # left hand root-relative
+ joint_cam[smpl_x.joint_part['rhand'], :] = joint_cam[smpl_x.joint_part['rhand'], :] - joint_cam[
+ smpl_x.rwrist_idx, None,
+ :] # right hand root-relative
+ joint_cam[smpl_x.joint_part['face'], :] = joint_cam[smpl_x.joint_part['face'], :] - joint_cam[smpl_x.neck_idx,
+ None,
+ :] # face root-relative
+ joint_img[smpl_x.joint_part['body'], 2] = (joint_cam[smpl_x.joint_part['body'], 2].copy() / (
+ cfg.body_3d_size / 2) + 1) / 2. * cfg.output_hm_shape[0] # body depth discretize
+ joint_img[smpl_x.joint_part['lhand'], 2] = (joint_cam[smpl_x.joint_part['lhand'], 2].copy() / (
+ cfg.hand_3d_size / 2) + 1) / 2. * cfg.output_hm_shape[0] # left hand depth discretize
+ joint_img[smpl_x.joint_part['rhand'], 2] = (joint_cam[smpl_x.joint_part['rhand'], 2].copy() / (
+ cfg.hand_3d_size / 2) + 1) / 2. * cfg.output_hm_shape[0] # right hand depth discretize
+ joint_img[smpl_x.joint_part['face'], 2] = (joint_cam[smpl_x.joint_part['face'], 2].copy() / (
+ cfg.face_3d_size / 2) + 1) / 2. * cfg.output_hm_shape[0] # face depth discretize
+
+ # human_model = smpl_x
+ # rotation_valid = np.ones((smpl_x.orig_joint_num), dtype=np.float32)
+ # coord_valid = np.ones((smpl_x.joint_num), dtype=np.float32)
+ #
+ # root_pose, body_pose, shape, trans = human_model_param['root_pose'], human_model_param['body_pose'], human_model_param['shape'], human_model_param['trans']
+ # if 'lhand_pose' in human_model_param and human_model_param['lhand_valid']:
+ # lhand_pose = human_model_param['lhand_pose']
+ # else:
+ # lhand_pose = np.zeros((3*len(smpl_x.orig_joint_part['lhand'])), dtype=np.float32)
+ # rotation_valid[smpl_x.orig_joint_part['lhand']] = 0
+ # coord_valid[smpl_x.joint_part['lhand']] = 0
+ # if 'rhand_pose' in human_model_param and human_model_param['rhand_valid']:
+ # rhand_pose = human_model_param['rhand_pose']
+ # else:
+ # rhand_pose = np.zeros((3*len(smpl_x.orig_joint_part['rhand'])), dtype=np.float32)
+ # rotation_valid[smpl_x.orig_joint_part['rhand']] = 0
+ # coord_valid[smpl_x.joint_part['rhand']] = 0
+ # if 'jaw_pose' in human_model_param and 'expr' in human_model_param and human_model_param['face_valid']:
+ # jaw_pose = human_model_param['jaw_pose']
+ # expr = human_model_param['expr']
+ # expr_valid = True
+ # else:
+ # jaw_pose = np.zeros((3), dtype=np.float32)
+ # expr = np.zeros((smpl_x.expr_code_dim), dtype=np.float32)
+ # rotation_valid[smpl_x.orig_joint_part['face']] = 0
+ # coord_valid[smpl_x.joint_part['face']] = 0
+ # expr_valid = False
+ # if 'gender' in human_model_param:
+ # gender = human_model_param['gender']
+ # else:
+ # gender = 'neutral'
+ # root_pose = torch.FloatTensor(root_pose).view(1,3) # (1,3)
+ # body_pose = torch.FloatTensor(body_pose).view(-1,3) # (21,3)
+ # lhand_pose = torch.FloatTensor(lhand_pose).view(-1,3) # (15,3)
+ # rhand_pose = torch.FloatTensor(rhand_pose).view(-1,3) # (15,3)
+ # jaw_pose = torch.FloatTensor(jaw_pose).view(-1,3) # (1,3)
+ # shape = torch.FloatTensor(shape).view(1,-1) # SMPLX shape parameter
+ # expr = torch.FloatTensor(expr).view(1,-1) # SMPLX expression parameter
+ # trans = torch.FloatTensor(trans).view(1,-1) # translation vector
+ #
+ # # apply camera extrinsic (rotation)
+ # # merge root pose and camera rotation
+ # if 'R' in cam_param:
+ # R = np.array(cam_param['R'], dtype=np.float32).reshape(3,3)
+ # root_pose = root_pose.numpy()
+ # root_pose, _ = cv2.Rodrigues(root_pose)
+ # root_pose, _ = cv2.Rodrigues(np.dot(R,root_pose))
+ # root_pose = torch.from_numpy(root_pose).view(1,3)
+ #
+ # # get mesh and joint coordinates
+ # zero_pose = torch.zeros((1,3)).float() # eye poses
+ # with torch.no_grad():
+ # output = smpl_x.layer[gender](betas=shape, body_pose=body_pose.view(1,-1), global_orient=root_pose, transl=trans, left_hand_pose=lhand_pose.view(1,-1), right_hand_pose=rhand_pose.view(1,-1), jaw_pose=jaw_pose.view(1,-1), leye_pose=zero_pose, reye_pose=zero_pose, expression=expr)
+ # mesh_cam = output.vertices[0].numpy()
+ # joint_cam = output.joints[0].numpy()[smpl_x.joint_idx,:]
+ #
+ # root_cam = joint_cam[smpl_x.root_joint_idx, None, :]
+ #
+ # # apply camera exrinsic (translation)
+ # # compenstate rotation (translation from origin to root joint was not cancled)
+ # if 'R' in cam_param and 't' in cam_param:
+ # R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3,3), np.array(cam_param['t'], dtype=np.float32).reshape(1,3)
+ # joint_cam = joint_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+ # mesh_cam = mesh_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+ #
+ # # concat root, body, two hands, and jaw pose
+ # pose = torch.cat((root_pose, body_pose, lhand_pose, rhand_pose, jaw_pose))
+ #
+ # # joint coordinates
+ # joint_img = cam2pixel(joint_cam, cam_param['focal'], cam_param['princpt'])
+ # joint_cam = joint_cam - root_cam # root-relative
+ # joint_cam[smpl_x.joint_part['lhand'],:] = joint_cam[smpl_x.joint_part['lhand'],:] - joint_cam[smpl_x.lwrist_idx,None,:] # left hand root-relative
+ # joint_cam[smpl_x.joint_part['rhand'],:] = joint_cam[smpl_x.joint_part['rhand'],:] - joint_cam[smpl_x.rwrist_idx,None,:] # right hand root-relative
+ # joint_cam[smpl_x.joint_part['face'],:] = joint_cam[smpl_x.joint_part['face'],:] - joint_cam[smpl_x.neck_idx,None,:] # face root-relative
+ # joint_img[smpl_x.joint_part['body'],2] = (joint_cam[smpl_x.joint_part['body'],2].copy() / (cfg.body_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # body depth discretize
+ # joint_img[smpl_x.joint_part['lhand'],2] = (joint_cam[smpl_x.joint_part['lhand'],2].copy() / (cfg.hand_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # left hand depth discretize
+ # joint_img[smpl_x.joint_part['rhand'],2] = (joint_cam[smpl_x.joint_part['rhand'],2].copy() / (cfg.hand_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # right hand depth discretize
+ # joint_img[smpl_x.joint_part['face'],2] = (joint_cam[smpl_x.joint_part['face'],2].copy() / (cfg.face_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # face depth discretize
+
+ elif human_model_type == 'smpl':
+ human_model = smpl
+ pose, shape, trans = human_model_param['pose'], human_model_param['shape'], human_model_param['trans']
+ if 'gender' in human_model_param:
+ gender = human_model_param['gender']
+ else:
+ gender = 'neutral'
+ pose = torch.FloatTensor(pose).view(-1,3)
+ shape = torch.FloatTensor(shape).view(1,-1);
+ trans = torch.FloatTensor(trans).view(1,-1) # translation vector
+
+ # apply camera extrinsic (rotation)
+ # merge root pose and camera rotation
+ if 'R' in cam_param:
+ R = np.array(cam_param['R'], dtype=np.float32).reshape(3,3)
+ root_pose = pose[smpl.orig_root_joint_idx,:].numpy()
+ root_pose, _ = cv2.Rodrigues(root_pose)
+ root_pose, _ = cv2.Rodrigues(np.dot(R,root_pose))
+ pose[smpl.orig_root_joint_idx] = torch.from_numpy(root_pose).view(3)
+
+ # get mesh and joint coordinates
+ root_pose = pose[smpl.orig_root_joint_idx].view(1,3)
+ body_pose = torch.cat((pose[:smpl.orig_root_joint_idx,:], pose[smpl.orig_root_joint_idx+1:,:])).view(1,-1)
+ with torch.no_grad():
+ output = smpl.layer[gender](betas=shape, body_pose=body_pose, global_orient=root_pose, transl=trans)
+ mesh_cam = output.vertices[0].numpy()
+ joint_cam = np.dot(smpl.joint_regressor, mesh_cam)
+
+ # apply camera exrinsic (translation)
+ # compenstate rotation (translation from origin to root joint was not cancled)
+ if 'R' in cam_param and 't' in cam_param:
+ R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3,3), np.array(cam_param['t'], dtype=np.float32).reshape(1,3)
+ root_cam = joint_cam[smpl.root_joint_idx,None,:]
+ joint_cam = joint_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+ mesh_cam = mesh_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+
+ # joint coordinates
+ joint_img = cam2pixel(joint_cam, cam_param['focal'], cam_param['princpt'])
+ joint_cam = joint_cam - joint_cam[smpl.root_joint_idx,None,:] # body root-relative
+ joint_img[:,2] = (joint_cam[:,2].copy() / (cfg.body_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # body depth discretize
+
+ elif human_model_type == 'mano':
+ human_model = mano
+ pose, shape, trans = human_model_param['pose'], human_model_param['shape'], human_model_param['trans']
+ hand_type = human_model_param['hand_type']
+ pose = torch.FloatTensor(pose).view(-1,3)
+ shape = torch.FloatTensor(shape).view(1,-1);
+ trans = torch.FloatTensor(trans).view(1,-1) # translation vector
+
+ # apply camera extrinsic (rotation)
+ # merge root pose and camera rotation
+ if 'R' in cam_param:
+ R = np.array(cam_param['R'], dtype=np.float32).reshape(3,3)
+ root_pose = pose[mano.orig_root_joint_idx,:].numpy()
+ root_pose, _ = cv2.Rodrigues(root_pose)
+ root_pose, _ = cv2.Rodrigues(np.dot(R,root_pose))
+ pose[mano.orig_root_joint_idx] = torch.from_numpy(root_pose).view(3)
+
+ # get mesh and joint coordinates
+ root_pose = pose[mano.orig_root_joint_idx].view(1,3)
+ hand_pose = torch.cat((pose[:mano.orig_root_joint_idx,:], pose[mano.orig_root_joint_idx+1:,:])).view(1,-1)
+ with torch.no_grad():
+ output = mano.layer[hand_type](betas=shape, hand_pose=hand_pose, global_orient=root_pose, transl=trans)
+ mesh_cam = output.vertices[0].numpy()
+ joint_cam = np.dot(mano.joint_regressor, mesh_cam)
+
+ # apply camera exrinsic (translation)
+ # compenstate rotation (translation from origin to root joint was not cancled)
+ if 'R' in cam_param and 't' in cam_param:
+ R, t = np.array(cam_param['R'], dtype=np.float32).reshape(3,3), np.array(cam_param['t'], dtype=np.float32).reshape(1,3)
+ root_cam = joint_cam[mano.root_joint_idx,None,:]
+ joint_cam = joint_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+ mesh_cam = mesh_cam - root_cam + np.dot(R, root_cam.transpose(1,0)).transpose(1,0) + t
+
+ # joint coordinates
+ joint_img = cam2pixel(joint_cam, cam_param['focal'], cam_param['princpt'])
+ joint_cam = joint_cam - joint_cam[mano.root_joint_idx,None,:] # hand root-relative
+ joint_img[:,2] = (joint_cam[:,2].copy() / (cfg.hand_3d_size / 2) + 1)/2. * cfg.output_hm_shape[0] # hand depth discretize
+
+
+ mesh_cam_orig = mesh_cam.copy() # back-up the original one
+
+ ## so far, data augmentations are not applied yet
+ ## now, apply data augmentations
+
+ # image projection
+ if do_flip:
+ joint_cam[:,0] = -joint_cam[:,0]
+ joint_img[:,0] = img_shape[1] - 1 - joint_img[:,0]
+ for pair in human_model.flip_pairs:
+ joint_cam[pair[0], :], joint_cam[pair[1], :] = joint_cam[pair[1], :].copy(), joint_cam[pair[0], :].copy()
+ joint_img[pair[0], :], joint_img[pair[1], :] = joint_img[pair[1], :].copy(), joint_img[pair[0], :].copy()
+ if human_model_type == 'smplx':
+ coord_valid[pair[0]], coord_valid[pair[1]] = coord_valid[pair[1]].copy(), coord_valid[pair[0]].copy()
+
+ # x,y affine transform, root-relative depth
+ joint_img_xy1 = np.concatenate((joint_img[:,:2], np.ones_like(joint_img[:,0:1])),1)
+ joint_img[:,:2] = np.dot(img2bb_trans, joint_img_xy1.transpose(1,0)).transpose(1,0)[:,:2]
+ joint_img[:,0] = joint_img[:,0] / cfg.input_img_shape[1] * cfg.output_hm_shape[2]
+ joint_img[:,1] = joint_img[:,1] / cfg.input_img_shape[0] * cfg.output_hm_shape[1]
+
+ # check truncation
+ joint_trunc = ((joint_img[:,0] >= 0) * (joint_img[:,0] < cfg.output_hm_shape[2]) * \
+ (joint_img[:,1] >= 0) * (joint_img[:,1] < cfg.output_hm_shape[1]) * \
+ (joint_img[:,2] >= 0) * (joint_img[:,2] < cfg.output_hm_shape[0])).reshape(-1,1).astype(np.float32)
+
+ # 3D data rotation augmentation
+ rot_aug_mat = np.array([[np.cos(np.deg2rad(-rot)), -np.sin(np.deg2rad(-rot)), 0],
+ [np.sin(np.deg2rad(-rot)), np.cos(np.deg2rad(-rot)), 0],
+ [0, 0, 1]], dtype=np.float32)
+ # coordinate
+ joint_cam = np.dot(rot_aug_mat, joint_cam.transpose(1,0)).transpose(1,0)
+ # parameters
+ # flip pose parameter (axis-angle)
+ if do_flip:
+ for pair in human_model.orig_flip_pairs:
+ pose[pair[0], :], pose[pair[1], :] = pose[pair[1], :].clone(), pose[pair[0], :].clone()
+ if human_model_type == 'smplx':
+ rotation_valid[pair[0]], rotation_valid[pair[1]] = rotation_valid[pair[1]].copy(), rotation_valid[pair[0]].copy()
+ pose[:,1:3] *= -1 # multiply -1 to y and z axis of axis-angle
+
+ # rotate root pose
+ pose = pose.numpy()
+ root_pose = pose[human_model.orig_root_joint_idx,:]
+ root_pose, _ = cv2.Rodrigues(root_pose)
+ root_pose, _ = cv2.Rodrigues(np.dot(rot_aug_mat,root_pose))
+ pose[human_model.orig_root_joint_idx] = root_pose.reshape(3)
+
+ # change to mean shape if beta is too far from it
+ shape[(shape.abs() > 3).any(dim=1)] = 0.
+ shape = shape.numpy().reshape(-1)
+
+ # return results
+ if human_model_type == 'smplx':
+ pose = pose.reshape(-1)
+ expr = expr.numpy().reshape(-1)
+ return joint_img, joint_cam, joint_trunc, pose, shape, expr, rotation_valid, coord_valid, expr_valid, mesh_cam_orig
+ elif human_model_type == 'smpl':
+ pose = pose.reshape(-1)
+ return joint_img, joint_cam, joint_trunc, pose, shape, mesh_cam_orig
+ elif human_model_type == 'mano':
+ pose = pose.reshape(-1)
+ return joint_img, joint_cam, joint_trunc, pose, shape, mesh_cam_orig
+
+def get_fitting_error_3D(db_joint, db_joint_from_fit, joint_valid):
+ # mask coordinate
+ db_joint = db_joint[np.tile(joint_valid,(1,3)) == 1].reshape(-1,3)
+ db_joint_from_fit = db_joint_from_fit[np.tile(joint_valid,(1,3)) == 1].reshape(-1,3)
+
+ db_joint_from_fit = db_joint_from_fit - np.mean(db_joint_from_fit,0)[None,:] + np.mean(db_joint,0)[None,:] # translation alignment
+ error = np.sqrt(np.sum((db_joint - db_joint_from_fit)**2,1)).mean()
+ return error
+
+def load_obj(file_name):
+ v = []
+ obj_file = open(file_name)
+ for line in obj_file:
+ words = line.split(' ')
+ if words[0] == 'v':
+ x,y,z = float(words[1]), float(words[2]), float(words[3])
+ v.append(np.array([x,y,z]))
+ return np.stack(v)
+
+def load_ply(file_name):
+ plydata = PlyData.read(file_name)
+ x = plydata['vertex']['x']
+ y = plydata['vertex']['y']
+ z = plydata['vertex']['z']
+ v = np.stack((x,y,z),1)
+ return v
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..3034a97b164d6e006655493e950314ec58e200cd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/LICENSE
@@ -0,0 +1,58 @@
+License
+
+Software Copyright License for non-commercial scientific research purposes
+Please read carefully the following terms and conditions and any accompanying documentation before you download and/or use the SMPL-X/SMPLify-X model, data and software, (the "Model & Software"), including 3D meshes, blend weights, blend shapes, textures, software, scripts, and animations. By downloading and/or using the Model & Software (including downloading, cloning, installing, and any other use of this github repository), you acknowledge that you have read these terms and conditions, understand them, and agree to be bound by them. If you do not agree with these terms and conditions, you must not download and/or use the Model & Software. Any infringement of the terms of this agreement will automatically terminate your rights under this License
+
+Ownership / Licensees
+The Software and the associated materials has been developed at the
+
+Max Planck Institute for Intelligent Systems (hereinafter "MPI").
+
+Any copyright or patent right is owned by and proprietary material of the
+
+Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (hereinafter “MPG”; MPI and MPG hereinafter collectively “Max-Planck”)
+
+hereinafter the “Licensor”.
+
+License Grant
+Licensor grants you (Licensee) personally a single-user, non-exclusive, non-transferable, free of charge right:
+
+To install the Model & Software on computers owned, leased or otherwise controlled by you and/or your organization;
+To use the Model & Software for the sole purpose of performing non-commercial scientific research, non-commercial education, or non-commercial artistic projects;
+Any other use, in particular any use for commercial purposes, is prohibited. This includes, without limitation, incorporation in a commercial product, use in a commercial service, or production of other artifacts for commercial purposes. The Model & Software may not be reproduced, modified and/or made available in any form to any third party without Max-Planck’s prior written permission.
+
+The Model & Software may not be used for pornographic purposes or to generate pornographic material whether commercial or not. This license also prohibits the use of the Model & Software to train methods/algorithms/neural networks/etc. for commercial use of any kind. By downloading the Model & Software, you agree not to reverse engineer it.
+
+No Distribution
+The Model & Software and the license herein granted shall not be copied, shared, distributed, re-sold, offered for re-sale, transferred or sub-licensed in whole or in part except that you may make one copy for archive purposes only.
+
+Disclaimer of Representations and Warranties
+You expressly acknowledge and agree that the Model & Software results from basic research, is provided “AS IS”, may contain errors, and that any use of the Model & Software is at your sole risk. LICENSOR MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE MODEL & SOFTWARE, NEITHER EXPRESS NOR IMPLIED, AND THE ABSENCE OF ANY LEGAL OR ACTUAL DEFECTS, WHETHER DISCOVERABLE OR NOT. Specifically, and not to limit the foregoing, licensor makes no representations or warranties (i) regarding the merchantability or fitness for a particular purpose of the Model & Software, (ii) that the use of the Model & Software will not infringe any patents, copyrights or other intellectual property rights of a third party, and (iii) that the use of the Model & Software will not cause any damage of any kind to you or a third party.
+
+Limitation of Liability
+Because this Model & Software License Agreement qualifies as a donation, according to Section 521 of the German Civil Code (Bürgerliches Gesetzbuch – BGB) Licensor as a donor is liable for intent and gross negligence only. If the Licensor fraudulently conceals a legal or material defect, they are obliged to compensate the Licensee for the resulting damage.
+Licensor shall be liable for loss of data only up to the amount of typical recovery costs which would have arisen had proper and regular data backup measures been taken. For the avoidance of doubt Licensor shall be liable in accordance with the German Product Liability Act in the event of product liability. The foregoing applies also to Licensor’s legal representatives or assistants in performance. Any further liability shall be excluded.
+Patent claims generated through the usage of the Model & Software cannot be directed towards the copyright holders.
+The Model & Software is provided in the state of development the licensor defines. If modified or extended by Licensee, the Licensor makes no claims about the fitness of the Model & Software and is not responsible for any problems such modifications cause.
+
+No Maintenance Services
+You understand and agree that Licensor is under no obligation to provide either maintenance services, update services, notices of latent defects, or corrections of defects with regard to the Model & Software. Licensor nevertheless reserves the right to update, modify, or discontinue the Model & Software at any time.
+
+Defects of the Model & Software must be notified in writing to the Licensor with a comprehensible description of the error symptoms. The notification of the defect should enable the reproduction of the error. The Licensee is encouraged to communicate any use, results, modification or publication.
+
+Publications using the Model & Software
+You acknowledge that the Model & Software is a valuable scientific resource and agree to appropriately reference the following paper in any publication making use of the Model & Software.
+
+Citation:
+
+
+@inproceedings{SMPL-X:2019,
+ title = {Expressive Body Capture: 3D Hands, Face, and Body from a Single Image},
+ author = {Pavlakos, Georgios and Choutas, Vasileios and Ghorbani, Nima and Bolkart, Timo and Osman, Ahmed A. A. and Tzionas, Dimitrios and Black, Michael J.},
+ booktitle = {Proceedings IEEE Conf. on Computer Vision and Pattern Recognition (CVPR)},
+ year = {2019}
+}
+Commercial licensing opportunities
+For commercial uses of the Software, please send email to ps-license@tue.mpg.de
+
+This Agreement shall be governed by the laws of the Federal Republic of Germany except for the UN Sales Convention.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..fb2df07aae5c116d23056b53160505316d72ea5f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/README.md
@@ -0,0 +1,186 @@
+## SMPL-X: A new joint 3D model of the human body, face and hands together
+
+[[Paper Page](https://smpl-x.is.tue.mpg.de)] [[Paper](https://ps.is.tuebingen.mpg.de/uploads_file/attachment/attachment/497/SMPL-X.pdf)]
+[[Supp. Mat.](https://ps.is.tuebingen.mpg.de/uploads_file/attachment/attachment/498/SMPL-X-supp.pdf)]
+
+
+
+## Table of Contents
+ * [License](#license)
+ * [Description](#description)
+ * [Installation](#installation)
+ * [Downloading the model](#downloading-the-model)
+ * [Loading SMPL-X, SMPL+H and SMPL](#loading-smpl-x-smplh-and-smpl)
+ * [SMPL and SMPL+H setup](#smpl-and-smplh-setup)
+ * [Model loading](https://github.com/vchoutas/smplx#model-loading)
+ * [MANO and FLAME correspondences](#mano-and-flame-correspondences)
+ * [Example](#example)
+ * [Citation](#citation)
+ * [Acknowledgments](#acknowledgments)
+ * [Contact](#contact)
+
+## License
+
+Software Copyright License for **non-commercial scientific research purposes**.
+Please read carefully the [terms and conditions](https://github.com/vchoutas/smplx/blob/master/LICENSE) and any accompanying documentation before you download and/or use the SMPL-X/SMPLify-X model, data and software, (the "Model & Software"), including 3D meshes, blend weights, blend shapes, textures, software, scripts, and animations. By downloading and/or using the Model & Software (including downloading, cloning, installing, and any other use of this github repository), you acknowledge that you have read these terms and conditions, understand them, and agree to be bound by them. If you do not agree with these terms and conditions, you must not download and/or use the Model & Software. Any infringement of the terms of this agreement will automatically terminate your rights under this [License](./LICENSE).
+
+## Disclaimer
+
+The original images used for the figures 1 and 2 of the paper can be found in this link.
+The images in the paper are used under license from gettyimages.com.
+We have acquired the right to use them in the publication, but redistribution is not allowed.
+Please follow the instructions on the given link to acquire right of usage.
+Our results are obtained on the 483 × 724 pixels resolution of the original images.
+
+## Description
+
+*SMPL-X* (SMPL eXpressive) is a unified body model with shape parameters trained jointly for the
+face, hands and body. *SMPL-X* uses standard vertex based linear blend skinning with learned corrective blend
+shapes, has N = 10, 475 vertices and K = 54 joints,
+which include joints for the neck, jaw, eyeballs and fingers.
+SMPL-X is defined by a function M(θ, β, ψ), where θ is the pose parameters, β the shape parameters and
+ψ the facial expression parameters.
+
+
+## Installation
+
+To install the model please follow the next steps in the specified order:
+1. To install from PyPi simply run:
+ ```Shell
+ pip install smplx[all]
+ ```
+2. Clone this repository and install it using the *setup.py* script:
+```Shell
+git clone https://github.com/vchoutas/smplx
+python setup.py install
+```
+
+## Downloading the model
+
+To download the *SMPL-X* model go to [this project website](https://smpl-x.is.tue.mpg.de) and register to get access to the downloads section.
+
+To download the *SMPL+H* model go to [this project website](http://mano.is.tue.mpg.de) and register to get access to the downloads section.
+
+To download the *SMPL* model go to [this](http://smpl.is.tue.mpg.de) (male and female models) and [this](http://smplify.is.tue.mpg.de) (gender neutral model) project website and register to get access to the downloads section.
+
+## Loading SMPL-X, SMPL+H and SMPL
+
+### SMPL and SMPL+H setup
+
+The loader gives the option to use any of the SMPL-X, SMPL+H, SMPL, and MANO models. Depending on the model you want to use, please follow the respective download instructions. To switch between MANO, SMPL, SMPL+H and SMPL-X just change the *model_path* or *model_type* parameters. For more details please check the docs of the model classes.
+Before using SMPL and SMPL+H you should follow the instructions in [tools/README.md](./tools/README.md) to remove the
+Chumpy objects from both model pkls, as well as merge the MANO parameters with SMPL+H.
+
+### Model loading
+
+You can either use the [create](https://github.com/vchoutas/smplx/blob/c63c02b478c5c6f696491ed9167e3af6b08d89b1/smplx/body_models.py#L54)
+function from [body_models](./smplx/body_models.py) or directly call the constructor for the
+[SMPL](https://github.com/vchoutas/smplx/blob/c63c02b478c5c6f696491ed9167e3af6b08d89b1/smplx/body_models.py#L106),
+[SMPL+H](https://github.com/vchoutas/smplx/blob/c63c02b478c5c6f696491ed9167e3af6b08d89b1/smplx/body_models.py#L395) and
+[SMPL-X](https://github.com/vchoutas/smplx/blob/c63c02b478c5c6f696491ed9167e3af6b08d89b1/smplx/body_models.py#L628) model. The path to the model can either be the path to the file with the parameters or a directory with the following structure:
+```bash
+models
+├── smpl
+│ ├── SMPL_FEMALE.pkl
+│ └── SMPL_MALE.pkl
+│ └── SMPL_NEUTRAL.pkl
+├── smplh
+│ ├── SMPLH_FEMALE.pkl
+│ └── SMPLH_MALE.pkl
+├── mano
+| ├── MANO_RIGHT.pkl
+| └── MANO_LEFT.pkl
+└── smplx
+ ├── SMPLX_FEMALE.npz
+ ├── SMPLX_FEMALE.pkl
+ ├── SMPLX_MALE.npz
+ ├── SMPLX_MALE.pkl
+ ├── SMPLX_NEUTRAL.npz
+ └── SMPLX_NEUTRAL.pkl
+```
+
+
+## MANO and FLAME correspondences
+
+The vertex correspondences between SMPL-X and MANO, FLAME can be downloaded
+from [the project website](https://smpl-x.is.tue.mpg.de). If you have extracted
+the correspondence data in the folder *correspondences*, then use the following
+scripts to visualize them:
+
+1. To view MANO correspondences run the following command:
+
+```
+python examples/vis_mano_vertices.py --model-folder $SMPLX_FOLDER --corr-fname correspondences/MANO_SMPLX_vertex_ids.pkl
+```
+
+2. To view FLAME correspondences run the following command:
+
+```
+python examples/vis_flame_vertices.py --model-folder $SMPLX_FOLDER --corr-fname correspondences/SMPL-X__FLAME_vertex_ids.npy
+```
+
+## Example
+
+After installing the *smplx* package and downloading the model parameters you should be able to run the *demo.py*
+script to visualize the results. For this step you have to install the [pyrender](https://pyrender.readthedocs.io/en/latest/index.html) and [trimesh](https://trimsh.org/) packages.
+
+`python examples/demo.py --model-folder $SMPLX_FOLDER --plot-joints=True --gender="neutral"`
+
+
+
+## Citation
+
+Depending on which model is loaded for your project, i.e. SMPL-X or SMPL+H or SMPL, please cite the most relevant work below, listed in the same order:
+
+```
+@inproceedings{SMPL-X:2019,
+ title = {Expressive Body Capture: 3D Hands, Face, and Body from a Single Image},
+ author = {Pavlakos, Georgios and Choutas, Vasileios and Ghorbani, Nima and Bolkart, Timo and Osman, Ahmed A. A. and Tzionas, Dimitrios and Black, Michael J.},
+ booktitle = {Proceedings IEEE Conf. on Computer Vision and Pattern Recognition (CVPR)},
+ year = {2019}
+}
+```
+
+```
+@article{MANO:SIGGRAPHASIA:2017,
+ title = {Embodied Hands: Modeling and Capturing Hands and Bodies Together},
+ author = {Romero, Javier and Tzionas, Dimitrios and Black, Michael J.},
+ journal = {ACM Transactions on Graphics, (Proc. SIGGRAPH Asia)},
+ volume = {36},
+ number = {6},
+ series = {245:1--245:17},
+ month = nov,
+ year = {2017},
+ month_numeric = {11}
+ }
+```
+
+```
+@article{SMPL:2015,
+ author = {Loper, Matthew and Mahmood, Naureen and Romero, Javier and Pons-Moll, Gerard and Black, Michael J.},
+ title = {{SMPL}: A Skinned Multi-Person Linear Model},
+ journal = {ACM Transactions on Graphics, (Proc. SIGGRAPH Asia)},
+ month = oct,
+ number = {6},
+ pages = {248:1--248:16},
+ publisher = {ACM},
+ volume = {34},
+ year = {2015}
+}
+```
+
+This repository was originally developed for SMPL-X / SMPLify-X (CVPR 2019), you might be interested in having a look: [https://smpl-x.is.tue.mpg.de](https://smpl-x.is.tue.mpg.de).
+
+## Acknowledgments
+
+### Facial Contour
+
+Special thanks to [Soubhik Sanyal](https://github.com/soubhiksanyal) for sharing the Tensorflow code used for the facial
+landmarks.
+
+## Contact
+The code of this repository was implemented by [Vassilis Choutas](vassilis.choutas@tuebingen.mpg.de).
+
+For questions, please contact [smplx@tue.mpg.de](smplx@tue.mpg.de).
+
+For commercial licensing (and all related questions for business applications), please contact [ps-licensing@tue.mpg.de](ps-licensing@tue.mpg.de).
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a6fd5024f4ac05d9f5db336b769d84836b51c18
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo.py
@@ -0,0 +1,180 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import os.path as osp
+import argparse
+
+import numpy as np
+import torch
+
+import smplx
+
+
+def main(model_folder,
+ model_type='smplx',
+ ext='npz',
+ gender='neutral',
+ plot_joints=False,
+ num_betas=10,
+ sample_shape=True,
+ sample_expression=True,
+ num_expression_coeffs=10,
+ plotting_module='pyrender',
+ use_face_contour=False):
+
+ model = smplx.create(model_folder, model_type=model_type,
+ gender=gender, use_face_contour=use_face_contour,
+ num_betas=num_betas,
+ num_expression_coeffs=num_expression_coeffs,
+ ext=ext)
+ print(model)
+
+ betas, expression = None, None
+ if sample_shape:
+ betas = torch.randn([1, model.num_betas], dtype=torch.float32)
+ if sample_expression:
+ expression = torch.randn(
+ [1, model.num_expression_coeffs], dtype=torch.float32)
+
+ output = model(betas=betas, expression=expression,
+ return_verts=True)
+ vertices = output.vertices.detach().cpu().numpy().squeeze()
+ joints = output.joints.detach().cpu().numpy().squeeze()
+
+ print('Vertices shape =', vertices.shape)
+ print('Joints shape =', joints.shape)
+
+ if plotting_module == 'pyrender':
+ import pyrender
+ import trimesh
+ vertex_colors = np.ones([vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8]
+ tri_mesh = trimesh.Trimesh(vertices, model.faces,
+ vertex_colors=vertex_colors)
+
+ mesh = pyrender.Mesh.from_trimesh(tri_mesh)
+
+ scene = pyrender.Scene()
+ scene.add(mesh)
+
+ if plot_joints:
+ sm = trimesh.creation.uv_sphere(radius=0.005)
+ sm.visual.vertex_colors = [0.9, 0.1, 0.1, 1.0]
+ tfs = np.tile(np.eye(4), (len(joints), 1, 1))
+ tfs[:, :3, 3] = joints
+ joints_pcl = pyrender.Mesh.from_trimesh(sm, poses=tfs)
+ scene.add(joints_pcl)
+
+ pyrender.Viewer(scene, use_raymond_lighting=True)
+ elif plotting_module == 'matplotlib':
+ from matplotlib import pyplot as plt
+ from mpl_toolkits.mplot3d import Axes3D
+ from mpl_toolkits.mplot3d.art3d import Poly3DCollection
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection='3d')
+
+ mesh = Poly3DCollection(vertices[model.faces], alpha=0.1)
+ face_color = (1.0, 1.0, 0.9)
+ edge_color = (0, 0, 0)
+ mesh.set_edgecolor(edge_color)
+ mesh.set_facecolor(face_color)
+ ax.add_collection3d(mesh)
+ ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2], color='r')
+
+ if plot_joints:
+ ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2], alpha=0.1)
+ plt.show()
+ elif plotting_module == 'open3d':
+ import open3d as o3d
+
+ mesh = o3d.geometry.TriangleMesh()
+ mesh.vertices = o3d.utility.Vector3dVector(
+ vertices)
+ mesh.triangles = o3d.utility.Vector3iVector(model.faces)
+ mesh.compute_vertex_normals()
+ mesh.paint_uniform_color([0.3, 0.3, 0.3])
+
+ geometry = [mesh]
+ if plot_joints:
+ joints_pcl = o3d.geometry.PointCloud()
+ joints_pcl.points = o3d.utility.Vector3dVector(joints)
+ joints_pcl.paint_uniform_color([0.7, 0.3, 0.3])
+ geometry.append(joints_pcl)
+
+ o3d.visualization.draw_geometries(geometry)
+ else:
+ raise ValueError('Unknown plotting_module: {}'.format(plotting_module))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='SMPL-X Demo')
+
+ parser.add_argument('--model-folder', required=True, type=str,
+ help='The path to the model folder')
+ parser.add_argument('--model-type', default='smplx', type=str,
+ choices=['smpl', 'smplh', 'smplx', 'mano', 'flame'],
+ help='The type of model to load')
+ parser.add_argument('--gender', type=str, default='neutral',
+ help='The gender of the model')
+ parser.add_argument('--num-betas', default=10, type=int,
+ dest='num_betas',
+ help='Number of shape coefficients.')
+ parser.add_argument('--num-expression-coeffs', default=10, type=int,
+ dest='num_expression_coeffs',
+ help='Number of expression coefficients.')
+ parser.add_argument('--plotting-module', type=str, default='pyrender',
+ dest='plotting_module',
+ choices=['pyrender', 'matplotlib', 'open3d'],
+ help='The module to use for plotting the result')
+ parser.add_argument('--ext', type=str, default='npz',
+ help='Which extension to use for loading')
+ parser.add_argument('--plot-joints', default=False,
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='The path to the model folder')
+ parser.add_argument('--sample-shape', default=True,
+ dest='sample_shape',
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Sample a random shape')
+ parser.add_argument('--sample-expression', default=True,
+ dest='sample_expression',
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Sample a random expression')
+ parser.add_argument('--use-face-contour', default=False,
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Compute the contour of the face')
+
+ args = parser.parse_args()
+
+ model_folder = osp.expanduser(osp.expandvars(args.model_folder))
+ model_type = args.model_type
+ plot_joints = args.plot_joints
+ use_face_contour = args.use_face_contour
+ gender = args.gender
+ ext = args.ext
+ plotting_module = args.plotting_module
+ num_betas = args.num_betas
+ num_expression_coeffs = args.num_expression_coeffs
+ sample_shape = args.sample_shape
+ sample_expression = args.sample_expression
+
+ main(model_folder, model_type, ext=ext,
+ gender=gender, plot_joints=plot_joints,
+ num_betas=num_betas,
+ num_expression_coeffs=num_expression_coeffs,
+ sample_shape=sample_shape,
+ sample_expression=sample_expression,
+ plotting_module=plotting_module,
+ use_face_contour=use_face_contour)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo_layers.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d4e18226c02a6c06c5158dc66276598ba96163a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/demo_layers.py
@@ -0,0 +1,181 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import os.path as osp
+import argparse
+
+import numpy as np
+import torch
+
+import smplx
+
+
+def main(model_folder,
+ model_type='smplx',
+ ext='npz',
+ gender='neutral',
+ plot_joints=False,
+ num_betas=10,
+ sample_shape=True,
+ sample_expression=True,
+ num_expression_coeffs=10,
+ plotting_module='pyrender',
+ use_face_contour=False):
+
+ model = smplx.build_layer(
+ model_folder, model_type=model_type,
+ gender=gender, use_face_contour=use_face_contour,
+ num_betas=num_betas,
+ num_expression_coeffs=num_expression_coeffs,
+ ext=ext)
+ print(model)
+
+ betas, expression = None, None
+ if sample_shape:
+ betas = torch.randn([1, model.num_betas], dtype=torch.float32)
+ if sample_expression:
+ expression = torch.randn(
+ [1, model.num_expression_coeffs], dtype=torch.float32)
+
+ output = model(betas=betas, expression=expression,
+ return_verts=True)
+ vertices = output.vertices.detach().cpu().numpy().squeeze()
+ joints = output.joints.detach().cpu().numpy().squeeze()
+
+ print('Vertices shape =', vertices.shape)
+ print('Joints shape =', joints.shape)
+
+ if plotting_module == 'pyrender':
+ import pyrender
+ import trimesh
+ vertex_colors = np.ones([vertices.shape[0], 4]) * [0.3, 0.3, 0.3, 0.8]
+ tri_mesh = trimesh.Trimesh(vertices, model.faces,
+ vertex_colors=vertex_colors)
+
+ mesh = pyrender.Mesh.from_trimesh(tri_mesh)
+
+ scene = pyrender.Scene()
+ scene.add(mesh)
+
+ if plot_joints:
+ sm = trimesh.creation.uv_sphere(radius=0.005)
+ sm.visual.vertex_colors = [0.9, 0.1, 0.1, 1.0]
+ tfs = np.tile(np.eye(4), (len(joints), 1, 1))
+ tfs[:, :3, 3] = joints
+ joints_pcl = pyrender.Mesh.from_trimesh(sm, poses=tfs)
+ scene.add(joints_pcl)
+
+ pyrender.Viewer(scene, use_raymond_lighting=True)
+ elif plotting_module == 'matplotlib':
+ from matplotlib import pyplot as plt
+ from mpl_toolkits.mplot3d import Axes3D
+ from mpl_toolkits.mplot3d.art3d import Poly3DCollection
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection='3d')
+
+ mesh = Poly3DCollection(vertices[model.faces], alpha=0.1)
+ face_color = (1.0, 1.0, 0.9)
+ edge_color = (0, 0, 0)
+ mesh.set_edgecolor(edge_color)
+ mesh.set_facecolor(face_color)
+ ax.add_collection3d(mesh)
+ ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2], color='r')
+
+ if plot_joints:
+ ax.scatter(joints[:, 0], joints[:, 1], joints[:, 2], alpha=0.1)
+ plt.show()
+ elif plotting_module == 'open3d':
+ import open3d as o3d
+
+ mesh = o3d.geometry.TriangleMesh()
+ mesh.vertices = o3d.utility.Vector3dVector(
+ vertices)
+ mesh.triangles = o3d.utility.Vector3iVector(model.faces)
+ mesh.compute_vertex_normals()
+ mesh.paint_uniform_color([0.3, 0.3, 0.3])
+
+ geometry = [mesh]
+ if plot_joints:
+ joints_pcl = o3d.geometry.PointCloud()
+ joints_pcl.points = o3d.utility.Vector3dVector(joints)
+ joints_pcl.paint_uniform_color([0.7, 0.3, 0.3])
+ geometry.append(joints_pcl)
+
+ o3d.visualization.draw_geometries(geometry)
+ else:
+ raise ValueError('Unknown plotting_module: {}'.format(plotting_module))
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='SMPL-X Demo')
+
+ parser.add_argument('--model-folder', required=True, type=str,
+ help='The path to the model folder')
+ parser.add_argument('--model-type', default='smplx', type=str,
+ choices=['smpl', 'smplh', 'smplx', 'mano', 'flame'],
+ help='The type of model to load')
+ parser.add_argument('--gender', type=str, default='neutral',
+ help='The gender of the model')
+ parser.add_argument('--num-betas', default=10, type=int,
+ dest='num_betas',
+ help='Number of shape coefficients.')
+ parser.add_argument('--num-expression-coeffs', default=10, type=int,
+ dest='num_expression_coeffs',
+ help='Number of expression coefficients.')
+ parser.add_argument('--plotting-module', type=str, default='pyrender',
+ dest='plotting_module',
+ choices=['pyrender', 'matplotlib', 'open3d'],
+ help='The module to use for plotting the result')
+ parser.add_argument('--ext', type=str, default='npz',
+ help='Which extension to use for loading')
+ parser.add_argument('--plot-joints', default=False,
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='The path to the model folder')
+ parser.add_argument('--sample-shape', default=True,
+ dest='sample_shape',
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Sample a random shape')
+ parser.add_argument('--sample-expression', default=True,
+ dest='sample_expression',
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Sample a random expression')
+ parser.add_argument('--use-face-contour', default=False,
+ type=lambda arg: arg.lower() in ['true', '1'],
+ help='Compute the contour of the face')
+
+ args = parser.parse_args()
+
+ model_folder = osp.expanduser(osp.expandvars(args.model_folder))
+ model_type = args.model_type
+ plot_joints = args.plot_joints
+ use_face_contour = args.use_face_contour
+ gender = args.gender
+ ext = args.ext
+ plotting_module = args.plotting_module
+ num_betas = args.num_betas
+ num_expression_coeffs = args.num_expression_coeffs
+ sample_shape = args.sample_shape
+ sample_expression = args.sample_expression
+
+ main(model_folder, model_type, ext=ext,
+ gender=gender, plot_joints=plot_joints,
+ num_betas=num_betas,
+ num_expression_coeffs=num_expression_coeffs,
+ sample_shape=sample_shape,
+ sample_expression=sample_expression,
+ plotting_module=plotting_module,
+ use_face_contour=use_face_contour)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_flame_vertices.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_flame_vertices.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8d6b9b33610876a9d555f87492b326b172692a7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_flame_vertices.py
@@ -0,0 +1,92 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import os.path as osp
+import argparse
+import pickle
+
+import numpy as np
+import torch
+import open3d as o3d
+
+import smplx
+
+
+def main(model_folder, corr_fname, ext='npz',
+ head_color=(0.3, 0.3, 0.6),
+ gender='neutral'):
+
+ head_idxs = np.load(corr_fname)
+
+ model = smplx.create(model_folder, model_type='smplx',
+ gender=gender,
+ ext=ext)
+ betas = torch.zeros([1, 10], dtype=torch.float32)
+ expression = torch.zeros([1, 10], dtype=torch.float32)
+
+ output = model(betas=betas, expression=expression,
+ return_verts=True)
+ vertices = output.vertices.detach().cpu().numpy().squeeze()
+ joints = output.joints.detach().cpu().numpy().squeeze()
+
+ print('Vertices shape =', vertices.shape)
+ print('Joints shape =', joints.shape)
+
+ mesh = o3d.geometry.TriangleMesh()
+ mesh.vertices = o3d.utility.Vector3dVector(vertices)
+ mesh.triangles = o3d.utility.Vector3iVector(model.faces)
+ mesh.compute_vertex_normals()
+
+ colors = np.ones_like(vertices) * [0.3, 0.3, 0.3]
+ colors[head_idxs] = head_color
+
+ mesh.vertex_colors = o3d.utility.Vector3dVector(colors)
+
+ o3d.visualization.draw_geometries([mesh])
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='SMPL-X Demo')
+
+ parser.add_argument('--model-folder', required=True, type=str,
+ help='The path to the model folder')
+ parser.add_argument('--corr-fname', required=True, type=str,
+ dest='corr_fname',
+ help='Filename with the head correspondences')
+ parser.add_argument('--gender', type=str, default='neutral',
+ help='The gender of the model')
+ parser.add_argument('--ext', type=str, default='npz',
+ help='Which extension to use for loading')
+ parser.add_argument('--head', default='right',
+ choices=['right', 'left'],
+ type=str, help='Which head to plot')
+ parser.add_argument('--head-color', type=float, nargs=3, dest='head_color',
+ default=(0.3, 0.3, 0.6),
+ help='Color for the head vertices')
+
+ args = parser.parse_args()
+
+ model_folder = osp.expanduser(osp.expandvars(args.model_folder))
+ corr_fname = args.corr_fname
+ gender = args.gender
+ ext = args.ext
+ head = args.head
+ head_color = args.head_color
+
+ main(model_folder, corr_fname, ext=ext,
+ head_color=head_color,
+ gender=gender
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_mano_vertices.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_mano_vertices.py
new file mode 100644
index 0000000000000000000000000000000000000000..1741542a1808071cc35fa1fcdef01a869885ec7e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/examples/vis_mano_vertices.py
@@ -0,0 +1,99 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import os.path as osp
+import argparse
+import pickle
+
+import numpy as np
+import torch
+import open3d as o3d
+
+import smplx
+
+
+def main(model_folder, corr_fname, ext='npz',
+ hand_color=(0.3, 0.3, 0.6),
+ gender='neutral', hand='right'):
+
+ with open(corr_fname, 'rb') as f:
+ idxs_data = pickle.load(f)
+ if hand == 'both':
+ hand_idxs = np.concatenate(
+ [idxs_data['left_hand'], idxs_data['right_hand']]
+ )
+ else:
+ hand_idxs = idxs_data[f'{hand}_hand']
+
+ model = smplx.create(model_folder, model_type='smplx',
+ gender=gender,
+ ext=ext)
+ betas = torch.zeros([1, 10], dtype=torch.float32)
+ expression = torch.zeros([1, 10], dtype=torch.float32)
+
+ output = model(betas=betas, expression=expression,
+ return_verts=True)
+ vertices = output.vertices.detach().cpu().numpy().squeeze()
+ joints = output.joints.detach().cpu().numpy().squeeze()
+
+ print('Vertices shape =', vertices.shape)
+ print('Joints shape =', joints.shape)
+
+ mesh = o3d.geometry.TriangleMesh()
+ mesh.vertices = o3d.utility.Vector3dVector(vertices)
+ mesh.triangles = o3d.utility.Vector3iVector(model.faces)
+ mesh.compute_vertex_normals()
+
+ colors = np.ones_like(vertices) * [0.3, 0.3, 0.3]
+ colors[hand_idxs] = hand_color
+
+ mesh.vertex_colors = o3d.utility.Vector3dVector(colors)
+
+ o3d.visualization.draw_geometries([mesh])
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='SMPL-X Demo')
+
+ parser.add_argument('--model-folder', required=True, type=str,
+ help='The path to the model folder')
+ parser.add_argument('--corr-fname', required=True, type=str,
+ dest='corr_fname',
+ help='Filename with the hand correspondences')
+ parser.add_argument('--gender', type=str, default='neutral',
+ help='The gender of the model')
+ parser.add_argument('--ext', type=str, default='npz',
+ help='Which extension to use for loading')
+ parser.add_argument('--hand', default='right',
+ choices=['right', 'left', 'both'],
+ type=str, help='Which hand to plot')
+ parser.add_argument('--hand-color', type=float, nargs=3, dest='hand_color',
+ default=(0.3, 0.3, 0.6),
+ help='Color for the hand vertices')
+
+ args = parser.parse_args()
+
+ model_folder = osp.expanduser(osp.expandvars(args.model_folder))
+ corr_fname = args.corr_fname
+ gender = args.gender
+ ext = args.ext
+ hand = args.hand
+ hand_color = args.hand_color
+
+ main(model_folder, corr_fname, ext=ext,
+ hand_color=hand_color,
+ gender=gender, hand=hand
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/setup.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..0496b2a2ae47157e60c6f1a1b6766404df9c7e16
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/setup.py
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems and the Max Planck Institute for Biological
+# Cybernetics. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import io
+import os
+
+from setuptools import setup
+
+# Package meta-data.
+NAME = 'smplx'
+DESCRIPTION = 'PyTorch module for loading the SMPLX body model'
+URL = 'http://smpl-x.is.tuebingen.mpg.de'
+EMAIL = 'vassilis.choutas@tuebingen.mpg.de'
+AUTHOR = 'Vassilis Choutas'
+REQUIRES_PYTHON = '>=3.6.0'
+VERSION = '0.1.21'
+
+here = os.path.abspath(os.path.dirname(__file__))
+
+try:
+ FileNotFoundError
+except NameError:
+ FileNotFoundError = IOError
+
+# Import the README and use it as the long-description.
+# Note: this will only work if 'README.md' is present in your MANIFEST.in file!
+try:
+ with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f:
+ long_description = '\n' + f.read()
+except FileNotFoundError:
+ long_description = DESCRIPTION
+
+# Load the package's __version__.py module as a dictionary.
+about = {}
+if not VERSION:
+ with open(os.path.join(here, NAME, '__version__.py')) as f:
+ exec(f.read(), about)
+else:
+ about['__version__'] = VERSION
+
+pyrender_reqs = ['pyrender>=0.1.23', 'trimesh>=2.37.6', 'shapely']
+matplotlib_reqs = ['matplotlib']
+open3d_reqs = ['open3d-python']
+
+setup(name=NAME,
+ version=about['__version__'],
+ description=DESCRIPTION,
+ long_description=long_description,
+ long_description_content_type='text/markdown',
+ author=AUTHOR,
+ author_email=EMAIL,
+ python_requires=REQUIRES_PYTHON,
+ url=URL,
+ install_requires=[
+ 'numpy>=1.16.2',
+ 'torch>=1.0.1.post2',
+ 'torchgeometry>=0.1.2'
+ ],
+ extras_require={
+ 'pyrender': pyrender_reqs,
+ 'open3d': open3d_reqs,
+ 'matplotlib': matplotlib_reqs,
+ 'all': pyrender_reqs + matplotlib_reqs + open3d_reqs
+ },
+ packages=['smplx', 'tools'])
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..886949df670691d1ef5995737cafa285224826c4
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/__init__.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from .body_models import (
+ create,
+ SMPL,
+ SMPLH,
+ SMPLX,
+ MANO,
+ FLAME,
+ build_layer,
+ SMPLLayer,
+ SMPLHLayer,
+ SMPLXLayer,
+ MANOLayer,
+ FLAMELayer,
+)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/body_models.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/body_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..b25d88a6b2eea33f26fd03d423c065f8230f76d7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/body_models.py
@@ -0,0 +1,2328 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from typing import Optional, Dict, Union
+import os
+import os.path as osp
+
+import pickle
+
+import numpy as np
+
+import torch
+import torch.nn as nn
+
+from .lbs import (
+ lbs, vertices2landmarks, find_dynamic_lmk_idx_and_bcoords)
+
+from .vertex_ids import vertex_ids as VERTEX_IDS
+from .utils import (
+ Struct, to_np, to_tensor, Tensor, Array,
+ SMPLOutput,
+ SMPLHOutput,
+ SMPLXOutput,
+ MANOOutput,
+ FLAMEOutput,
+ find_joint_kin_chain)
+from .vertex_joint_selector import VertexJointSelector
+from config import cfg
+
+class SMPL(nn.Module):
+
+ NUM_JOINTS = 23
+ NUM_BODY_JOINTS = 23
+ SHAPE_SPACE_DIM = 300
+
+ def __init__(
+ self, model_path: str,
+ data_struct: Optional[Struct] = None,
+ create_betas: bool = True,
+ betas: Optional[Tensor] = None,
+ num_betas: int = 10,
+ create_global_orient: bool = True,
+ global_orient: Optional[Tensor] = None,
+ create_body_pose: bool = True,
+ body_pose: Optional[Tensor] = None,
+ create_transl: bool = True,
+ transl: Optional[Tensor] = None,
+ dtype=torch.float32,
+ batch_size: int = 1,
+ joint_mapper=None,
+ gender: str = 'neutral',
+ vertex_ids: Dict[str, int] = None,
+ v_template: Optional[Union[Tensor, Array]] = None,
+ **kwargs
+ ) -> None:
+ ''' SMPL model constructor
+
+ Parameters
+ ----------
+ model_path: str
+ The path to the folder or to the file where the model
+ parameters are stored
+ data_struct: Strct
+ A struct object. If given, then the parameters of the model are
+ read from the object. Otherwise, the model tries to read the
+ parameters from the given `model_path`. (default = None)
+ create_global_orient: bool, optional
+ Flag for creating a member variable for the global orientation
+ of the body. (default = True)
+ global_orient: torch.tensor, optional, Bx3
+ The default value for the global orientation variable.
+ (default = None)
+ create_body_pose: bool, optional
+ Flag for creating a member variable for the pose of the body.
+ (default = True)
+ body_pose: torch.tensor, optional, Bx(Body Joints * 3)
+ The default value for the body pose variable.
+ (default = None)
+ num_betas: int, optional
+ Number of shape components to use
+ (default = 10).
+ create_betas: bool, optional
+ Flag for creating a member variable for the shape space
+ (default = True).
+ betas: torch.tensor, optional, Bx10
+ The default value for the shape member variable.
+ (default = None)
+ create_transl: bool, optional
+ Flag for creating a member variable for the translation
+ of the body. (default = True)
+ transl: torch.tensor, optional, Bx3
+ The default value for the transl variable.
+ (default = None)
+ dtype: torch.dtype, optional
+ The data type for the created variables
+ batch_size: int, optional
+ The batch size used for creating the member variables
+ joint_mapper: object, optional
+ An object that re-maps the joints. Useful if one wants to
+ re-order the SMPL joints to some other convention (e.g. MSCOCO)
+ (default = None)
+ gender: str, optional
+ Which gender to load
+ vertex_ids: dict, optional
+ A dictionary containing the indices of the extra vertices that
+ will be selected
+ '''
+
+ self.gender = gender
+
+ if data_struct is None:
+ if osp.isdir(model_path):
+ model_fn = 'SMPL_{}.{ext}'.format(gender.upper(), ext='pkl')
+ smpl_path = os.path.join(model_path, model_fn)
+ else:
+ smpl_path = model_path
+ assert osp.exists(smpl_path), 'Path {} does not exist!'.format(
+ smpl_path)
+
+ with open(smpl_path, 'rb') as smpl_file:
+ data_struct = Struct(**pickle.load(smpl_file,
+ encoding='latin1'))
+
+ super(SMPL, self).__init__()
+ self.batch_size = batch_size
+ shapedirs = data_struct.shapedirs
+ if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM):
+ print(f'WARNING: You are using a {self.name()} model, with only'
+ ' 10 shape coefficients.')
+ num_betas = min(num_betas, 10)
+ else:
+ num_betas = min(num_betas, self.SHAPE_SPACE_DIM)
+
+ self._num_betas = num_betas
+ shapedirs = shapedirs[:, :, :num_betas]
+ # The shape components
+ self.register_buffer(
+ 'shapedirs',
+ to_tensor(to_np(shapedirs), dtype=dtype))
+
+ if vertex_ids is None:
+ # SMPL and SMPL-H share the same topology, so any extra joints can
+ # be drawn from the same place
+ vertex_ids = VERTEX_IDS['smplh']
+
+ self.dtype = dtype
+
+ self.joint_mapper = joint_mapper
+
+ self.vertex_joint_selector = VertexJointSelector(
+ vertex_ids=vertex_ids, **kwargs)
+
+ self.faces = data_struct.f
+ self.register_buffer('faces_tensor',
+ to_tensor(to_np(self.faces, dtype=np.int64),
+ dtype=torch.long))
+
+ if create_betas:
+ if betas is None:
+ default_betas = torch.zeros(
+ [batch_size, self.num_betas], dtype=dtype)
+ else:
+ if torch.is_tensor(betas):
+ default_betas = betas.clone().detach()
+ else:
+ default_betas = torch.tensor(betas, dtype=dtype)
+
+ self.register_parameter(
+ 'betas', nn.Parameter(default_betas, requires_grad=True))
+
+ # The tensor that contains the global rotation of the model
+ # It is separated from the pose of the joints in case we wish to
+ # optimize only over one of them
+ if create_global_orient:
+ if global_orient is None:
+ default_global_orient = torch.zeros(
+ [batch_size, 3], dtype=dtype)
+ else:
+ if torch.is_tensor(global_orient):
+ default_global_orient = global_orient.clone().detach()
+ else:
+ default_global_orient = torch.tensor(
+ global_orient, dtype=dtype)
+
+ global_orient = nn.Parameter(default_global_orient,
+ requires_grad=True)
+ self.register_parameter('global_orient', global_orient)
+
+ if create_body_pose:
+ if body_pose is None:
+ default_body_pose = torch.zeros(
+ [batch_size, self.NUM_BODY_JOINTS * 3], dtype=dtype)
+ else:
+ if torch.is_tensor(body_pose):
+ default_body_pose = body_pose.clone().detach()
+ else:
+ default_body_pose = torch.tensor(body_pose,
+ dtype=dtype)
+ self.register_parameter(
+ 'body_pose',
+ nn.Parameter(default_body_pose, requires_grad=True))
+
+ if create_transl:
+ if transl is None:
+ default_transl = torch.zeros([batch_size, 3],
+ dtype=dtype,
+ requires_grad=True)
+ else:
+ default_transl = torch.tensor(transl, dtype=dtype)
+ self.register_parameter(
+ 'transl', nn.Parameter(default_transl, requires_grad=True))
+
+ if v_template is None:
+ v_template = data_struct.v_template
+ if not torch.is_tensor(v_template):
+ v_template = to_tensor(to_np(v_template), dtype=dtype)
+ # The vertices of the template model
+ self.register_buffer('v_template', v_template)
+
+ j_regressor = to_tensor(to_np(
+ data_struct.J_regressor), dtype=dtype)
+ self.register_buffer('J_regressor', j_regressor)
+
+ # Pose blend shape basis: 6890 x 3 x 207, reshaped to 6890*3 x 207
+ num_pose_basis = data_struct.posedirs.shape[-1]
+ # 207 x 20670
+ posedirs = np.reshape(data_struct.posedirs, [-1, num_pose_basis]).T
+ self.register_buffer('posedirs',
+ to_tensor(to_np(posedirs), dtype=dtype))
+
+ # indices of parents for each joints
+ parents = to_tensor(to_np(data_struct.kintree_table[0])).long()
+ parents[0] = -1
+ self.register_buffer('parents', parents)
+
+ self.register_buffer(
+ 'lbs_weights', to_tensor(to_np(data_struct.weights), dtype=dtype))
+
+ @property
+ def num_betas(self):
+ return self._num_betas
+
+ @property
+ def num_expression_coeffs(self):
+ return 0
+
+ def create_mean_pose(self, data_struct) -> Tensor:
+ pass
+
+ def name(self) -> str:
+ return 'SMPL'
+
+ @torch.no_grad()
+ def reset_params(self, **params_dict) -> None:
+ for param_name, param in self.named_parameters():
+ if param_name in params_dict:
+ param[:] = torch.tensor(params_dict[param_name])
+ else:
+ param.fill_(0)
+
+ def get_num_verts(self) -> int:
+ return self.v_template.shape[0]
+
+ def get_num_faces(self) -> int:
+ return self.faces.shape[0]
+
+ def extra_repr(self) -> str:
+ msg = [
+ f'Gender: {self.gender.upper()}',
+ f'Number of joints: {self.J_regressor.shape[0]}',
+ f'Betas: {self.num_betas}',
+ ]
+ return '\n'.join(msg)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts=True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> SMPLOutput:
+ ''' Forward pass for the SMPL model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ body_pose: torch.tensor, optional, shape Bx(J*3)
+ If given, ignore the member variable `body_pose` and use it
+ instead. For example, it can used if someone predicts the
+ pose of the body joints are predicted from some external model.
+ It should be a tensor that contains joint rotations in
+ axis-angle format. (default=None)
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full axis-angle pose vector (default=False)
+
+ Returns
+ -------
+ '''
+ # If no shape and pose parameters are passed along, then use the
+ # ones from the module
+ global_orient = (global_orient if global_orient is not None else
+ self.global_orient)
+ body_pose = body_pose if body_pose is not None else self.body_pose
+ betas = betas if betas is not None else self.betas
+
+ apply_trans = transl is not None or hasattr(self, 'transl')
+ if transl is None and hasattr(self, 'transl'):
+ transl = self.transl
+
+ full_pose = torch.cat([global_orient, body_pose], dim=1)
+
+ batch_size = max(betas.shape[0], global_orient.shape[0],
+ body_pose.shape[0])
+
+ if betas.shape[0] != batch_size:
+ num_repeats = int(batch_size / betas.shape[0])
+ betas = betas.expand(num_repeats, -1)
+
+ vertices, joints = lbs(betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=pose2rot)
+
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Map the joints to the current dataset
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if apply_trans:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLOutput(vertices=vertices if return_verts else None,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ joints=joints,
+ betas=betas,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class SMPLLayer(SMPL):
+ def __init__(
+ self,
+ *args,
+ **kwargs
+ ) -> None:
+ # Just create a SMPL module without any member variables
+ super(SMPLLayer, self).__init__(
+ create_body_pose=False,
+ create_betas=False,
+ create_global_orient=False,
+ create_transl=False,
+ *args,
+ **kwargs,
+ )
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts=True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> SMPLOutput:
+ ''' Forward pass for the SMPL model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ body_pose: torch.tensor, optional, shape Bx(J*3)
+ If given, ignore the member variable `body_pose` and use it
+ instead. For example, it can used if someone predicts the
+ pose of the body joints are predicted from some external model.
+ It should be a tensor that contains joint rotations in
+ axis-angle format. (default=None)
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full axis-angle pose vector (default=False)
+
+ Returns
+ -------
+ '''
+ device, dtype = self.shapedirs.device, self.shapedirs.dtype
+ if global_orient is None:
+ batch_size = 1
+ global_orient = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 1, 1).contiguous()
+ else:
+ batch_size = global_orient.shape[0]
+ if body_pose is None:
+ body_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(
+ batch_size, self.NUM_BODY_JOINTS, 1).contiguous()
+ if betas is None:
+ betas = torch.zeros([batch_size, self.num_betas],
+ dtype=dtype, device=device)
+ if transl is None:
+ transl = torch.zeros([batch_size, 3], dtype=dtype, device=device)
+ full_pose = torch.cat(
+ [global_orient.reshape(-1, 1, 3),
+ body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3)],
+ dim=1)
+
+ vertices, joints = lbs(betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights,
+ pose2rot=True)
+
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Map the joints to the current dataset
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if transl is not None:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLOutput(vertices=vertices if return_verts else None,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ joints=joints,
+ betas=betas,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class SMPLH(SMPL):
+
+ # The hand joints are replaced by MANO
+ NUM_BODY_JOINTS = SMPL.NUM_JOINTS - 2
+ NUM_HAND_JOINTS = 15
+ NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS
+
+ def __init__(
+ self, model_path,
+ data_struct: Optional[Struct] = None,
+ create_left_hand_pose: bool = True,
+ left_hand_pose: Optional[Tensor] = None,
+ create_right_hand_pose: bool = True,
+ right_hand_pose: Optional[Tensor] = None,
+ use_pca: bool = True,
+ num_pca_comps: int = 6,
+ flat_hand_mean: bool = False,
+ batch_size: int = 1,
+ gender: str = 'neutral',
+ dtype=torch.float32,
+ vertex_ids=None,
+ use_compressed: bool = True,
+ ext: str = 'pkl',
+ **kwargs
+ ) -> None:
+ ''' SMPLH model constructor
+
+ Parameters
+ ----------
+ model_path: str
+ The path to the folder or to the file where the model
+ parameters are stored
+ data_struct: Strct
+ A struct object. If given, then the parameters of the model are
+ read from the object. Otherwise, the model tries to read the
+ parameters from the given `model_path`. (default = None)
+ create_left_hand_pose: bool, optional
+ Flag for creating a member variable for the pose of the left
+ hand. (default = True)
+ left_hand_pose: torch.tensor, optional, BxP
+ The default value for the left hand pose member variable.
+ (default = None)
+ create_right_hand_pose: bool, optional
+ Flag for creating a member variable for the pose of the right
+ hand. (default = True)
+ right_hand_pose: torch.tensor, optional, BxP
+ The default value for the right hand pose member variable.
+ (default = None)
+ num_pca_comps: int, optional
+ The number of PCA components to use for each hand.
+ (default = 6)
+ flat_hand_mean: bool, optional
+ If False, then the pose of the hand is initialized to False.
+ batch_size: int, optional
+ The batch size used for creating the member variables
+ gender: str, optional
+ Which gender to load
+ dtype: torch.dtype, optional
+ The data type for the created variables
+ vertex_ids: dict, optional
+ A dictionary containing the indices of the extra vertices that
+ will be selected
+ '''
+
+ self.num_pca_comps = num_pca_comps
+ # If no data structure is passed, then load the data from the given
+ # model folder
+ if data_struct is None:
+ # Load the model
+ if osp.isdir(model_path):
+ model_fn = 'SMPLH_{}.{ext}'.format(gender.upper(), ext=ext)
+ smplh_path = os.path.join(model_path, model_fn)
+ else:
+ smplh_path = model_path
+ assert osp.exists(smplh_path), 'Path {} does not exist!'.format(
+ smplh_path)
+
+ if ext == 'pkl':
+ with open(smplh_path, 'rb') as smplh_file:
+ model_data = pickle.load(smplh_file, encoding='latin1')
+ elif ext == 'npz':
+ model_data = np.load(smplh_path, allow_pickle=True)
+ else:
+ raise ValueError('Unknown extension: {}'.format(ext))
+ data_struct = Struct(**model_data)
+
+ if vertex_ids is None:
+ vertex_ids = VERTEX_IDS['smplh']
+
+ super(SMPLH, self).__init__(
+ model_path=model_path,
+ data_struct=data_struct,
+ batch_size=batch_size, vertex_ids=vertex_ids, gender=gender,
+ use_compressed=use_compressed, dtype=dtype, ext=ext, **kwargs)
+
+ self.use_pca = use_pca
+ self.num_pca_comps = num_pca_comps
+ self.flat_hand_mean = flat_hand_mean
+
+ left_hand_components = data_struct.hands_componentsl[:num_pca_comps]
+ right_hand_components = data_struct.hands_componentsr[:num_pca_comps]
+
+ self.np_left_hand_components = left_hand_components
+ self.np_right_hand_components = right_hand_components
+ if self.use_pca:
+ self.register_buffer(
+ 'left_hand_components',
+ torch.tensor(left_hand_components, dtype=dtype))
+ self.register_buffer(
+ 'right_hand_components',
+ torch.tensor(right_hand_components, dtype=dtype))
+
+ if self.flat_hand_mean:
+ left_hand_mean = np.zeros_like(data_struct.hands_meanl)
+ else:
+ left_hand_mean = data_struct.hands_meanl
+
+ if self.flat_hand_mean:
+ right_hand_mean = np.zeros_like(data_struct.hands_meanr)
+ else:
+ right_hand_mean = data_struct.hands_meanr
+
+ self.register_buffer('left_hand_mean',
+ to_tensor(left_hand_mean, dtype=self.dtype))
+ self.register_buffer('right_hand_mean',
+ to_tensor(right_hand_mean, dtype=self.dtype))
+
+ # Create the buffers for the pose of the left hand
+ hand_pose_dim = num_pca_comps if use_pca else 3 * self.NUM_HAND_JOINTS
+ if create_left_hand_pose:
+ if left_hand_pose is None:
+ default_lhand_pose = torch.zeros([batch_size, hand_pose_dim],
+ dtype=dtype)
+ else:
+ default_lhand_pose = torch.tensor(left_hand_pose, dtype=dtype)
+
+ left_hand_pose_param = nn.Parameter(default_lhand_pose,
+ requires_grad=True)
+ self.register_parameter('left_hand_pose',
+ left_hand_pose_param)
+
+ if create_right_hand_pose:
+ if right_hand_pose is None:
+ default_rhand_pose = torch.zeros([batch_size, hand_pose_dim],
+ dtype=dtype)
+ else:
+ default_rhand_pose = torch.tensor(right_hand_pose, dtype=dtype)
+
+ right_hand_pose_param = nn.Parameter(default_rhand_pose,
+ requires_grad=True)
+ self.register_parameter('right_hand_pose',
+ right_hand_pose_param)
+
+ # Create the buffer for the mean pose.
+ pose_mean_tensor = self.create_mean_pose(
+ data_struct, flat_hand_mean=flat_hand_mean)
+ if not torch.is_tensor(pose_mean_tensor):
+ pose_mean_tensor = torch.tensor(pose_mean_tensor, dtype=dtype)
+ self.register_buffer('pose_mean', pose_mean_tensor)
+
+ def create_mean_pose(self, data_struct, flat_hand_mean=False):
+ # Create the array for the mean pose. If flat_hand is false, then use
+ # the mean that is given by the data, rather than the flat open hand
+ global_orient_mean = torch.zeros([3], dtype=self.dtype)
+ body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],
+ dtype=self.dtype)
+
+ pose_mean = torch.cat([global_orient_mean, body_pose_mean,
+ self.left_hand_mean,
+ self.right_hand_mean], dim=0)
+ return pose_mean
+
+ def name(self) -> str:
+ return 'SMPL+H'
+
+ def extra_repr(self):
+ msg = super(SMPLH, self).extra_repr()
+ msg = [msg]
+ if self.use_pca:
+ msg.append(f'Number of PCA components: {self.num_pca_comps}')
+ msg.append(f'Flat hand mean: {self.flat_hand_mean}')
+ return '\n'.join(msg)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ left_hand_pose: Optional[Tensor] = None,
+ right_hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> SMPLHOutput:
+ '''
+ '''
+ # If no shape and pose parameters are passed along, then use the
+ # ones from the module
+ global_orient = (global_orient if global_orient is not None else
+ self.global_orient)
+ body_pose = body_pose if body_pose is not None else self.body_pose
+ betas = betas if betas is not None else self.betas
+ left_hand_pose = (left_hand_pose if left_hand_pose is not None else
+ self.left_hand_pose)
+ right_hand_pose = (right_hand_pose if right_hand_pose is not None else
+ self.right_hand_pose)
+
+ apply_trans = transl is not None or hasattr(self, 'transl')
+ if transl is None:
+ if hasattr(self, 'transl'):
+ transl = self.transl
+
+ if self.use_pca:
+ left_hand_pose = torch.einsum(
+ 'bi,ij->bj', [left_hand_pose, self.left_hand_components])
+ right_hand_pose = torch.einsum(
+ 'bi,ij->bj', [right_hand_pose, self.right_hand_components])
+
+ full_pose = torch.cat([global_orient, body_pose,
+ left_hand_pose,
+ right_hand_pose], dim=1)
+ full_pose += self.pose_mean
+
+ vertices, joints = lbs(self.betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=pose2rot)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if apply_trans:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLHOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ left_hand_pose=left_hand_pose,
+ right_hand_pose=right_hand_pose,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class SMPLHLayer(SMPLH):
+
+ def __init__(
+ self, *args, **kwargs
+ ) -> None:
+ ''' SMPL+H as a layer model constructor
+ '''
+ super(SMPLHLayer, self).__init__(
+ create_global_orient=False,
+ create_body_pose=False,
+ create_left_hand_pose=False,
+ create_right_hand_pose=False,
+ create_betas=False,
+ create_transl=False,
+ *args,
+ **kwargs)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ left_hand_pose: Optional[Tensor] = None,
+ right_hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> SMPLHOutput:
+ '''
+ '''
+ device, dtype = self.shapedirs.device, self.shapedirs.dtype
+ if global_orient is None:
+ batch_size = 1
+ global_orient = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ else:
+ batch_size = global_orient.shape[0]
+ if body_pose is None:
+ body_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 21, -1).contiguous()
+ if left_hand_pose is None:
+ left_hand_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 15, -1).contiguous()
+ if right_hand_pose is None:
+ right_hand_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 15, -1).contiguous()
+ if betas is None:
+ betas = torch.zeros([batch_size, self.num_betas],
+ dtype=dtype, device=device)
+ if transl is None:
+ transl = torch.zeros([batch_size, 3], dtype=dtype, device=device)
+
+ # Concatenate all pose vectors
+ full_pose = torch.cat(
+ [global_orient.reshape(-1, 1, 3),
+ body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3),
+ left_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3),
+ right_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3)],
+ dim=1)
+
+ vertices, joints = lbs(betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=True)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if transl is not None:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLHOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ left_hand_pose=left_hand_pose,
+ right_hand_pose=right_hand_pose,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class SMPLX(SMPLH):
+ '''
+ SMPL-X (SMPL eXpressive) is a unified body model, with shape parameters
+ trained jointly for the face, hands and body.
+ SMPL-X uses standard vertex based linear blend skinning with learned
+ corrective blend shapes, has N=10475 vertices and K=54 joints,
+ which includes joints for the neck, jaw, eyeballs and fingers.
+ '''
+
+ NUM_BODY_JOINTS = SMPLH.NUM_BODY_JOINTS
+ NUM_HAND_JOINTS = 15
+ NUM_FACE_JOINTS = 3
+ NUM_JOINTS = NUM_BODY_JOINTS + 2 * NUM_HAND_JOINTS + NUM_FACE_JOINTS
+ EXPRESSION_SPACE_DIM = 100
+ NECK_IDX = 12
+
+ def __init__(
+ self, model_path: str,
+ num_expression_coeffs: int = 10,
+ create_expression: bool = True,
+ expression: Optional[Tensor] = None,
+ create_jaw_pose: bool = True,
+ jaw_pose: Optional[Tensor] = None,
+ create_leye_pose: bool = True,
+ leye_pose: Optional[Tensor] = None,
+ create_reye_pose=True,
+ reye_pose: Optional[Tensor] = None,
+ use_face_contour: bool = False,
+ batch_size: int = 1,
+ gender: str = 'neutral',
+ dtype=torch.float32,
+ ext: str = 'npz',
+ **kwargs
+ ) -> None:
+ ''' SMPLX model constructor
+
+ Parameters
+ ----------
+ model_path: str
+ The path to the folder or to the file where the model
+ parameters are stored
+ num_expression_coeffs: int, optional
+ Number of expression components to use
+ (default = 10).
+ create_expression: bool, optional
+ Flag for creating a member variable for the expression space
+ (default = True).
+ expression: torch.tensor, optional, Bx10
+ The default value for the expression member variable.
+ (default = None)
+ create_jaw_pose: bool, optional
+ Flag for creating a member variable for the jaw pose.
+ (default = False)
+ jaw_pose: torch.tensor, optional, Bx3
+ The default value for the jaw pose variable.
+ (default = None)
+ create_leye_pose: bool, optional
+ Flag for creating a member variable for the left eye pose.
+ (default = False)
+ leye_pose: torch.tensor, optional, Bx10
+ The default value for the left eye pose variable.
+ (default = None)
+ create_reye_pose: bool, optional
+ Flag for creating a member variable for the right eye pose.
+ (default = False)
+ reye_pose: torch.tensor, optional, Bx10
+ The default value for the right eye pose variable.
+ (default = None)
+ use_face_contour: bool, optional
+ Whether to compute the keypoints that form the facial contour
+ batch_size: int, optional
+ The batch size used for creating the member variables
+ gender: str, optional
+ Which gender to load
+ dtype: torch.dtype
+ The data type for the created variables
+ '''
+
+ # Load the model
+ if osp.isdir(model_path):
+ model_fn = 'SMPLX_{}.{ext}'.format(gender.upper(), ext=ext)
+ smplx_path = os.path.join(model_path, model_fn)
+ else:
+ smplx_path = model_path
+ assert osp.exists(smplx_path), 'Path {} does not exist!'.format(smplx_path)
+ if ext == 'pkl':
+ with open(smplx_path, 'rb') as smplx_file:
+ model_data = pickle.load(smplx_file, encoding='latin1')
+ elif ext == 'npz':
+ model_data = np.load(smplx_path, allow_pickle=True)
+ else:
+ raise ValueError('Unknown extension: {}'.format(ext))
+
+ data_struct = Struct(**model_data)
+
+ super(SMPLX, self).__init__(
+ model_path=model_path,
+ data_struct=data_struct,
+ dtype=dtype,
+ batch_size=batch_size,
+ vertex_ids=VERTEX_IDS['smplx'],
+ gender=gender, ext=ext,
+ **kwargs)
+
+ lmk_faces_idx = data_struct.lmk_faces_idx
+ self.register_buffer('lmk_faces_idx',
+ torch.tensor(lmk_faces_idx, dtype=torch.long))
+ lmk_bary_coords = data_struct.lmk_bary_coords
+ self.register_buffer('lmk_bary_coords',
+ torch.tensor(lmk_bary_coords, dtype=dtype))
+
+ self.use_face_contour = use_face_contour
+ if self.use_face_contour:
+ dynamic_lmk_faces_idx = data_struct.dynamic_lmk_faces_idx
+ dynamic_lmk_faces_idx = torch.tensor(
+ dynamic_lmk_faces_idx,
+ dtype=torch.long)
+ self.register_buffer('dynamic_lmk_faces_idx',
+ dynamic_lmk_faces_idx)
+
+ dynamic_lmk_bary_coords = data_struct.dynamic_lmk_bary_coords
+ dynamic_lmk_bary_coords = torch.tensor(
+ dynamic_lmk_bary_coords, dtype=dtype)
+ self.register_buffer('dynamic_lmk_bary_coords',
+ dynamic_lmk_bary_coords)
+
+ neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents)
+ self.register_buffer(
+ 'neck_kin_chain',
+ torch.tensor(neck_kin_chain, dtype=torch.long))
+
+ if create_jaw_pose:
+ if jaw_pose is None:
+ default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype)
+ jaw_pose_param = nn.Parameter(default_jaw_pose,
+ requires_grad=True)
+ self.register_parameter('jaw_pose', jaw_pose_param)
+
+ if create_leye_pose:
+ if leye_pose is None:
+ default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_leye_pose = torch.tensor(leye_pose, dtype=dtype)
+ leye_pose_param = nn.Parameter(default_leye_pose,
+ requires_grad=True)
+ self.register_parameter('leye_pose', leye_pose_param)
+
+ if create_reye_pose:
+ if reye_pose is None:
+ default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_reye_pose = torch.tensor(reye_pose, dtype=dtype)
+ reye_pose_param = nn.Parameter(default_reye_pose,
+ requires_grad=True)
+ self.register_parameter('reye_pose', reye_pose_param)
+
+ shapedirs = data_struct.shapedirs
+ if len(shapedirs.shape) < 3:
+ shapedirs = shapedirs[:, :, None]
+ if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM +
+ self.EXPRESSION_SPACE_DIM):
+ print(f'WARNING: You are using a {self.name()} model, with only'
+ ' 10 shape and 10 expression coefficients.')
+ expr_start_idx = 10
+ expr_end_idx = 20
+ num_expression_coeffs = min(num_expression_coeffs, 10)
+ else:
+ expr_start_idx = self.SHAPE_SPACE_DIM
+ expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs
+ num_expression_coeffs = min(
+ num_expression_coeffs, self.EXPRESSION_SPACE_DIM)
+
+ self._num_expression_coeffs = num_expression_coeffs
+
+ expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx]
+ self.register_buffer(
+ 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype))
+
+ if create_expression:
+ if expression is None:
+ default_expression = torch.zeros(
+ [batch_size, self.num_expression_coeffs], dtype=dtype)
+ else:
+ default_expression = torch.tensor(expression, dtype=dtype)
+ expression_param = nn.Parameter(default_expression,
+ requires_grad=True)
+ self.register_parameter('expression', expression_param)
+
+ def name(self) -> str:
+ return 'SMPL-X'
+
+ @property
+ def num_expression_coeffs(self):
+ return self._num_expression_coeffs
+
+ def create_mean_pose(self, data_struct, flat_hand_mean=False):
+ # Create the array for the mean pose. If flat_hand is false, then use
+ # the mean that is given by the data, rather than the flat open hand
+ global_orient_mean = torch.zeros([3], dtype=self.dtype)
+ body_pose_mean = torch.zeros([self.NUM_BODY_JOINTS * 3],
+ dtype=self.dtype)
+ jaw_pose_mean = torch.zeros([3], dtype=self.dtype)
+ leye_pose_mean = torch.zeros([3], dtype=self.dtype)
+ reye_pose_mean = torch.zeros([3], dtype=self.dtype)
+
+ pose_mean = np.concatenate([global_orient_mean, body_pose_mean,
+ jaw_pose_mean,
+ leye_pose_mean, reye_pose_mean,
+ self.left_hand_mean, self.right_hand_mean],
+ axis=0)
+
+ return pose_mean
+
+ def extra_repr(self):
+ msg = super(SMPLX, self).extra_repr()
+ msg = [
+ msg,
+ f'Number of Expression Coefficients: {self.num_expression_coeffs}'
+ ]
+ return '\n'.join(msg)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ left_hand_pose: Optional[Tensor] = None,
+ right_hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ expression: Optional[Tensor] = None,
+ jaw_pose: Optional[Tensor] = None,
+ leye_pose: Optional[Tensor] = None,
+ reye_pose: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> SMPLXOutput:
+ '''
+ Forward pass for the SMPLX model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ expression: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `expression` and use it
+ instead. For example, it can used if expression parameters
+ `expression` are predicted from some external model.
+ body_pose: torch.tensor, optional, shape Bx(J*3)
+ If given, ignore the member variable `body_pose` and use it
+ instead. For example, it can used if someone predicts the
+ pose of the body joints are predicted from some external model.
+ It should be a tensor that contains joint rotations in
+ axis-angle format. (default=None)
+ left_hand_pose: torch.tensor, optional, shape BxP
+ If given, ignore the member variable `left_hand_pose` and
+ use this instead. It should either contain PCA coefficients or
+ joint rotations in axis-angle format.
+ right_hand_pose: torch.tensor, optional, shape BxP
+ If given, ignore the member variable `right_hand_pose` and
+ use this instead. It should either contain PCA coefficients or
+ joint rotations in axis-angle format.
+ jaw_pose: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full axis-angle pose vector (default=False)
+
+ Returns
+ -------
+ output: ModelOutput
+ A named tuple of type `ModelOutput`
+ '''
+
+ # If no shape and pose parameters are passed along, then use the
+ # ones from the module
+ global_orient = (global_orient if global_orient is not None else
+ self.global_orient)
+ body_pose = body_pose if body_pose is not None else self.body_pose
+ betas = betas if betas is not None else self.betas
+
+ left_hand_pose = (left_hand_pose if left_hand_pose is not None else
+ self.left_hand_pose)
+ right_hand_pose = (right_hand_pose if right_hand_pose is not None else
+ self.right_hand_pose)
+ jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose
+ leye_pose = leye_pose if leye_pose is not None else self.leye_pose
+ reye_pose = reye_pose if reye_pose is not None else self.reye_pose
+ expression = expression if expression is not None else self.expression
+
+ apply_trans = transl is not None or hasattr(self, 'transl')
+ if transl is None:
+ if hasattr(self, 'transl'):
+ transl = self.transl
+
+ if self.use_pca:
+ left_hand_pose = torch.einsum(
+ 'bi,ij->bj', [left_hand_pose, self.left_hand_components])
+ right_hand_pose = torch.einsum(
+ 'bi,ij->bj', [right_hand_pose, self.right_hand_components])
+
+ full_pose = torch.cat([global_orient, body_pose,
+ jaw_pose, leye_pose, reye_pose,
+ left_hand_pose,
+ right_hand_pose], dim=1)
+
+ # Add the mean pose of the model. Does not affect the body, only the
+ # hands when flat_hand_mean == False
+ full_pose += self.pose_mean
+
+ batch_size = max(betas.shape[0], global_orient.shape[0],
+ body_pose.shape[0])
+ # Concatenate the shape and expression coefficients
+ scale = int(batch_size / betas.shape[0])
+ if scale > 1:
+ betas = betas.expand(scale, -1)
+ shape_components = torch.cat([betas, expression], dim=-1)
+
+ shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)
+
+ vertices, joints = lbs(shape_components, full_pose, self.v_template,
+ shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=pose2rot,
+ )
+
+ lmk_faces_idx = self.lmk_faces_idx.unsqueeze(
+ dim=0).expand(batch_size, -1).contiguous()
+ lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(
+ self.batch_size, 1, 1)
+ if self.use_face_contour:
+ lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(
+ vertices, full_pose, self.dynamic_lmk_faces_idx,
+ self.dynamic_lmk_bary_coords,
+ self.neck_kin_chain,
+ pose2rot=True,
+ )
+ dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords
+
+ lmk_faces_idx = torch.cat([lmk_faces_idx,
+ dyn_lmk_faces_idx], 1)
+ lmk_bary_coords = torch.cat(
+ [lmk_bary_coords.expand(batch_size, -1, -1),
+ dyn_lmk_bary_coords], 1)
+
+ landmarks = vertices2landmarks(vertices, self.faces_tensor,
+ lmk_faces_idx,
+ lmk_bary_coords)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Add the landmarks to the joints
+ joints = torch.cat([joints, landmarks], dim=1)
+ # Map the joints to the current dataset
+
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints=joints, vertices=vertices)
+
+ if apply_trans:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLXOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ expression=expression,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ left_hand_pose=left_hand_pose,
+ right_hand_pose=right_hand_pose,
+ jaw_pose=jaw_pose,
+ full_pose=full_pose if return_full_pose else None)
+ return output
+
+
+class SMPLXLayer(SMPLX):
+ def __init__(
+ self,
+ *args,
+ **kwargs
+ ) -> None:
+ # Just create a SMPLX module without any member variables
+ super(SMPLXLayer, self).__init__(
+ create_global_orient=False,
+ create_body_pose=False,
+ create_left_hand_pose=False,
+ create_right_hand_pose=False,
+ create_jaw_pose=False,
+ create_leye_pose=False,
+ create_reye_pose=False,
+ create_betas=False,
+ create_expression=False,
+ create_transl=False,
+ *args, **kwargs,
+ )
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ body_pose: Optional[Tensor] = None,
+ left_hand_pose: Optional[Tensor] = None,
+ right_hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ expression: Optional[Tensor] = None,
+ jaw_pose: Optional[Tensor] = None,
+ leye_pose: Optional[Tensor] = None,
+ reye_pose: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ **kwargs
+ ) -> SMPLXOutput:
+ '''
+ Forward pass for the SMPLX model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ expression: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `expression` and use it
+ instead. For example, it can used if expression parameters
+ `expression` are predicted from some external model.
+ body_pose: torch.tensor, optional, shape Bx(J*3)
+ If given, ignore the member variable `body_pose` and use it
+ instead. For example, it can used if someone predicts the
+ pose of the body joints are predicted from some external model.
+ It should be a tensor that contains joint rotations in
+ axis-angle format. (default=None)
+ left_hand_pose: torch.tensor, optional, shape BxP
+ If given, ignore the member variable `left_hand_pose` and
+ use this instead. It should either contain PCA coefficients or
+ joint rotations in axis-angle format.
+ right_hand_pose: torch.tensor, optional, shape BxP
+ If given, ignore the member variable `right_hand_pose` and
+ use this instead. It should either contain PCA coefficients or
+ joint rotations in axis-angle format.
+ jaw_pose: torch.tensor, optional, shape Bx3x3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full pose vector (default=False)
+ Returns
+ -------
+ output: ModelOutput
+ A data class that contains the posed vertices and joints
+ '''
+ device, dtype = self.shapedirs.device, self.shapedirs.dtype
+
+ if global_orient is None:
+ batch_size = 1
+ global_orient = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ else:
+ batch_size = global_orient.shape[0]
+ if body_pose is None:
+ body_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(
+ batch_size, self.NUM_BODY_JOINTS, -1).contiguous()
+ if left_hand_pose is None:
+ left_hand_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 15, -1).contiguous()
+ if right_hand_pose is None:
+ right_hand_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 15, -1).contiguous()
+ if jaw_pose is None:
+ jaw_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if leye_pose is None:
+ leye_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if reye_pose is None:
+ reye_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if expression is None:
+ expression = torch.zeros([batch_size, self.num_expression_coeffs],
+ dtype=dtype, device=device)
+ if betas is None:
+ betas = torch.zeros([batch_size, self.num_betas],
+ dtype=dtype, device=device)
+ if transl is None:
+ transl = torch.zeros([batch_size, 3], dtype=dtype, device=device)
+
+ # Concatenate all pose vectors
+ full_pose = torch.cat(
+ [global_orient.reshape(-1, 1, 3),
+ body_pose.reshape(-1, self.NUM_BODY_JOINTS, 3),
+ jaw_pose.reshape(-1, 1, 3),
+ leye_pose.reshape(-1, 1, 3),
+ reye_pose.reshape(-1, 1, 3),
+ left_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3),
+ right_hand_pose.reshape(-1, self.NUM_HAND_JOINTS, 3)],
+ dim=1)
+ shape_components = torch.cat([betas, expression], dim=-1)
+
+ shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)
+
+ vertices, joints = lbs(shape_components, full_pose, self.v_template,
+ shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=True)
+
+ lmk_faces_idx = self.lmk_faces_idx.unsqueeze(
+ dim=0).expand(batch_size, -1).contiguous()
+ lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(
+ self.batch_size, 1, 1)
+ if self.use_face_contour:
+ lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(
+ vertices, full_pose,
+ self.dynamic_lmk_faces_idx,
+ self.dynamic_lmk_bary_coords,
+ self.neck_kin_chain,
+ pose2rot=False,
+ )
+ dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords
+
+ lmk_faces_idx = torch.cat([lmk_faces_idx, dyn_lmk_faces_idx], 1)
+ lmk_bary_coords = torch.cat(
+ [lmk_bary_coords.expand(batch_size, -1, -1),
+ dyn_lmk_bary_coords], 1)
+
+ landmarks = vertices2landmarks(vertices, self.faces_tensor,
+ lmk_faces_idx,
+ lmk_bary_coords)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Add the landmarks to the joints
+ joints = torch.cat([joints, landmarks], dim=1)
+ # Map the joints to the current dataset
+
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints=joints, vertices=vertices)
+
+ if transl is not None:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = SMPLXOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ expression=expression,
+ global_orient=global_orient,
+ body_pose=body_pose,
+ left_hand_pose=left_hand_pose,
+ right_hand_pose=right_hand_pose,
+ jaw_pose=jaw_pose,
+ transl=transl,
+ full_pose=full_pose if return_full_pose else None)
+ return output
+
+
+class MANO(SMPL):
+ # The hand joints are replaced by MANO
+ NUM_BODY_JOINTS = 1
+ NUM_HAND_JOINTS = 15
+ NUM_JOINTS = NUM_BODY_JOINTS + NUM_HAND_JOINTS
+
+ def __init__(
+ self,
+ model_path: str,
+ is_rhand: bool = True,
+ data_struct: Optional[Struct] = None,
+ create_hand_pose: bool = True,
+ hand_pose: Optional[Tensor] = None,
+ use_pca: bool = True,
+ num_pca_comps: int = 6,
+ flat_hand_mean: bool = False,
+ batch_size: int = 1,
+ dtype=torch.float32,
+ vertex_ids=None,
+ use_compressed: bool = True,
+ ext: str = 'pkl',
+ **kwargs
+ ) -> None:
+ ''' MANO model constructor
+
+ Parameters
+ ----------
+ model_path: str
+ The path to the folder or to the file where the model
+ parameters are stored
+ data_struct: Strct
+ A struct object. If given, then the parameters of the model are
+ read from the object. Otherwise, the model tries to read the
+ parameters from the given `model_path`. (default = None)
+ create_hand_pose: bool, optional
+ Flag for creating a member variable for the pose of the right
+ hand. (default = True)
+ hand_pose: torch.tensor, optional, BxP
+ The default value for the right hand pose member variable.
+ (default = None)
+ num_pca_comps: int, optional
+ The number of PCA components to use for each hand.
+ (default = 6)
+ flat_hand_mean: bool, optional
+ If False, then the pose of the hand is initialized to False.
+ batch_size: int, optional
+ The batch size used for creating the member variables
+ dtype: torch.dtype, optional
+ The data type for the created variables
+ vertex_ids: dict, optional
+ A dictionary containing the indices of the extra vertices that
+ will be selected
+ '''
+
+ self.num_pca_comps = num_pca_comps
+ self.is_rhand = is_rhand
+ # If no data structure is passed, then load the data from the given
+ # model folder
+ if data_struct is None:
+ # Load the model
+ if osp.isdir(model_path):
+ model_fn = 'MANO_{}.{ext}'.format(
+ 'RIGHT' if is_rhand else 'LEFT', ext=ext)
+ mano_path = os.path.join(model_path, model_fn)
+ else:
+ mano_path = model_path
+ self.is_rhand = True if 'RIGHT' in os.path.basename(
+ model_path) else False
+ assert osp.exists(mano_path), 'Path {} does not exist!'.format(
+ mano_path)
+
+ if ext == 'pkl':
+ with open(mano_path, 'rb') as mano_file:
+ model_data = pickle.load(mano_file, encoding='latin1')
+ elif ext == 'npz':
+ model_data = np.load(mano_path, allow_pickle=True)
+ else:
+ raise ValueError('Unknown extension: {}'.format(ext))
+ data_struct = Struct(**model_data)
+
+ if vertex_ids is None:
+ vertex_ids = VERTEX_IDS['smplh']
+
+ super(MANO, self).__init__(
+ model_path=model_path, data_struct=data_struct,
+ batch_size=batch_size, vertex_ids=vertex_ids,
+ use_compressed=use_compressed, dtype=dtype, ext=ext, **kwargs)
+
+ # add only MANO tips to the extra joints
+ self.vertex_joint_selector.extra_joints_idxs = to_tensor(
+ list(VERTEX_IDS['mano'].values()), dtype=torch.long)
+
+ self.use_pca = use_pca
+ self.num_pca_comps = num_pca_comps
+ if self.num_pca_comps == 45:
+ self.use_pca = False
+ self.flat_hand_mean = flat_hand_mean
+
+ hand_components = data_struct.hands_components[:num_pca_comps]
+
+ self.np_hand_components = hand_components
+
+ if self.use_pca:
+ self.register_buffer(
+ 'hand_components',
+ torch.tensor(hand_components, dtype=dtype))
+
+ if self.flat_hand_mean:
+ hand_mean = np.zeros_like(data_struct.hands_mean)
+ else:
+ hand_mean = data_struct.hands_mean
+
+ self.register_buffer('hand_mean',
+ to_tensor(hand_mean, dtype=self.dtype))
+
+ # Create the buffers for the pose of the left hand
+ hand_pose_dim = num_pca_comps if use_pca else 3 * self.NUM_HAND_JOINTS
+ if create_hand_pose:
+ if hand_pose is None:
+ default_hand_pose = torch.zeros([batch_size, hand_pose_dim],
+ dtype=dtype)
+ else:
+ default_hand_pose = torch.tensor(hand_pose, dtype=dtype)
+
+ hand_pose_param = nn.Parameter(default_hand_pose,
+ requires_grad=True)
+ self.register_parameter('hand_pose',
+ hand_pose_param)
+
+ # Create the buffer for the mean pose.
+ pose_mean = self.create_mean_pose(
+ data_struct, flat_hand_mean=flat_hand_mean)
+ pose_mean_tensor = pose_mean.clone().to(dtype)
+ # pose_mean_tensor = torch.tensor(pose_mean, dtype=dtype)
+ self.register_buffer('pose_mean', pose_mean_tensor)
+
+ def name(self) -> str:
+ return 'MANO'
+
+ def create_mean_pose(self, data_struct, flat_hand_mean=False):
+ # Create the array for the mean pose. If flat_hand is false, then use
+ # the mean that is given by the data, rather than the flat open hand
+ global_orient_mean = torch.zeros([3], dtype=self.dtype)
+ pose_mean = torch.cat([global_orient_mean, self.hand_mean], dim=0)
+ return pose_mean
+
+ def extra_repr(self):
+ msg = [super(MANO, self).extra_repr()]
+ if self.use_pca:
+ msg.append(f'Number of PCA components: {self.num_pca_comps}')
+ msg.append(f'Flat hand mean: {self.flat_hand_mean}')
+ return '\n'.join(msg)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ **kwargs
+ ) -> MANOOutput:
+ ''' Forward pass for the MANO model
+ '''
+ # If no shape and pose parameters are passed along, then use the
+ # ones from the module
+ global_orient = (global_orient if global_orient is not None else
+ self.global_orient)
+ betas = betas if betas is not None else self.betas
+ hand_pose = (hand_pose if hand_pose is not None else
+ self.hand_pose)
+
+ apply_trans = transl is not None or hasattr(self, 'transl')
+ if transl is None:
+ if hasattr(self, 'transl'):
+ transl = self.transl
+
+ if self.use_pca:
+ hand_pose = torch.einsum(
+ 'bi,ij->bj', [hand_pose, self.hand_components])
+
+ full_pose = torch.cat([global_orient, hand_pose], dim=1)
+ full_pose += self.pose_mean
+
+ vertices, joints = lbs(betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=True,
+ )
+
+ # # Add pre-selected extra joints that might be needed
+ # joints = self.vertex_joint_selector(vertices, joints)
+
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if apply_trans:
+ joints = joints + transl.unsqueeze(dim=1)
+ vertices = vertices + transl.unsqueeze(dim=1)
+
+ output = MANOOutput(vertices=vertices if return_verts else None,
+ joints=joints if return_verts else None,
+ betas=betas,
+ global_orient=global_orient,
+ hand_pose=hand_pose,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class MANOLayer(MANO):
+ def __init__(self, *args, **kwargs) -> None:
+ ''' MANO as a layer model constructor
+ '''
+ super(MANOLayer, self).__init__(
+ create_global_orient=False,
+ create_hand_pose=False,
+ create_betas=False,
+ create_transl=False,
+ *args, **kwargs)
+
+ def name(self) -> str:
+ return 'MANO'
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ hand_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ **kwargs
+ ) -> MANOOutput:
+ ''' Forward pass for the MANO model
+ '''
+ device, dtype = self.shapedirs.device, self.shapedirs.dtype
+ if global_orient is None:
+ batch_size = 1
+ global_orient = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ else:
+ batch_size = global_orient.shape[0]
+ if hand_pose is None:
+ hand_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 15, -1).contiguous()
+ if betas is None:
+ betas = torch.zeros(
+ [batch_size, self.num_betas], dtype=dtype, device=device)
+ if transl is None:
+ transl = torch.zeros([batch_size, 3], dtype=dtype, device=device)
+
+ full_pose = torch.cat([global_orient, hand_pose], dim=1)
+ vertices, joints = lbs(betas, full_pose, self.v_template,
+ self.shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=True)
+
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints)
+
+ if transl is not None:
+ joints = joints + transl.unsqueeze(dim=1)
+ vertices = vertices + transl.unsqueeze(dim=1)
+
+ output = MANOOutput(
+ vertices=vertices if return_verts else None,
+ joints=joints if return_verts else None,
+ betas=betas,
+ global_orient=global_orient,
+ hand_pose=hand_pose,
+ full_pose=full_pose if return_full_pose else None)
+
+ return output
+
+
+class FLAME(SMPL):
+ NUM_JOINTS = 5
+ SHAPE_SPACE_DIM = 300
+ EXPRESSION_SPACE_DIM = 100
+ NECK_IDX = 0
+
+ def __init__(
+ self,
+ model_path: str,
+ data_struct=None,
+ num_expression_coeffs=10,
+ create_expression: bool = True,
+ expression: Optional[Tensor] = None,
+ create_neck_pose: bool = True,
+ neck_pose: Optional[Tensor] = None,
+ create_jaw_pose: bool = True,
+ jaw_pose: Optional[Tensor] = None,
+ create_leye_pose: bool = True,
+ leye_pose: Optional[Tensor] = None,
+ create_reye_pose=True,
+ reye_pose: Optional[Tensor] = None,
+ use_face_contour=False,
+ batch_size: int = 1,
+ gender: str = 'neutral',
+ dtype: torch.dtype = torch.float32,
+ ext='pkl',
+ **kwargs
+ ) -> None:
+ ''' FLAME model constructor
+
+ Parameters
+ ----------
+ model_path: str
+ The path to the folder or to the file where the model
+ parameters are stored
+ num_expression_coeffs: int, optional
+ Number of expression components to use
+ (default = 10).
+ create_expression: bool, optional
+ Flag for creating a member variable for the expression space
+ (default = True).
+ expression: torch.tensor, optional, Bx10
+ The default value for the expression member variable.
+ (default = None)
+ create_neck_pose: bool, optional
+ Flag for creating a member variable for the neck pose.
+ (default = False)
+ neck_pose: torch.tensor, optional, Bx3
+ The default value for the neck pose variable.
+ (default = None)
+ create_jaw_pose: bool, optional
+ Flag for creating a member variable for the jaw pose.
+ (default = False)
+ jaw_pose: torch.tensor, optional, Bx3
+ The default value for the jaw pose variable.
+ (default = None)
+ create_leye_pose: bool, optional
+ Flag for creating a member variable for the left eye pose.
+ (default = False)
+ leye_pose: torch.tensor, optional, Bx10
+ The default value for the left eye pose variable.
+ (default = None)
+ create_reye_pose: bool, optional
+ Flag for creating a member variable for the right eye pose.
+ (default = False)
+ reye_pose: torch.tensor, optional, Bx10
+ The default value for the right eye pose variable.
+ (default = None)
+ use_face_contour: bool, optional
+ Whether to compute the keypoints that form the facial contour
+ batch_size: int, optional
+ The batch size used for creating the member variables
+ gender: str, optional
+ Which gender to load
+ dtype: torch.dtype
+ The data type for the created variables
+ '''
+ model_fn = f'FLAME_{gender.upper()}.{ext}'
+ flame_path = os.path.join(model_path, model_fn)
+ assert osp.exists(flame_path), 'Path {} does not exist!'.format(
+ flame_path)
+ if ext == 'npz':
+ file_data = np.load(flame_path, allow_pickle=True)
+ elif ext == 'pkl':
+ with open(flame_path, 'rb') as smpl_file:
+ file_data = pickle.load(smpl_file, encoding='latin1')
+ else:
+ raise ValueError('Unknown extension: {}'.format(ext))
+ data_struct = Struct(**file_data)
+
+ super(FLAME, self).__init__(
+ model_path=model_path,
+ data_struct=data_struct,
+ dtype=dtype,
+ batch_size=batch_size,
+ gender=gender,
+ ext=ext,
+ **kwargs)
+
+ self.use_face_contour = use_face_contour
+
+ self.vertex_joint_selector.extra_joints_idxs = to_tensor(
+ [], dtype=torch.long)
+
+ if create_neck_pose:
+ if neck_pose is None:
+ default_neck_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_neck_pose = torch.tensor(neck_pose, dtype=dtype)
+ neck_pose_param = nn.Parameter(
+ default_neck_pose, requires_grad=True)
+ self.register_parameter('neck_pose', neck_pose_param)
+
+ if create_jaw_pose:
+ if jaw_pose is None:
+ default_jaw_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_jaw_pose = torch.tensor(jaw_pose, dtype=dtype)
+ jaw_pose_param = nn.Parameter(default_jaw_pose,
+ requires_grad=True)
+ self.register_parameter('jaw_pose', jaw_pose_param)
+
+ if create_leye_pose:
+ if leye_pose is None:
+ default_leye_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_leye_pose = torch.tensor(leye_pose, dtype=dtype)
+ leye_pose_param = nn.Parameter(default_leye_pose,
+ requires_grad=True)
+ self.register_parameter('leye_pose', leye_pose_param)
+
+ if create_reye_pose:
+ if reye_pose is None:
+ default_reye_pose = torch.zeros([batch_size, 3], dtype=dtype)
+ else:
+ default_reye_pose = torch.tensor(reye_pose, dtype=dtype)
+ reye_pose_param = nn.Parameter(default_reye_pose,
+ requires_grad=True)
+ self.register_parameter('reye_pose', reye_pose_param)
+
+ shapedirs = data_struct.shapedirs
+ if len(shapedirs.shape) < 3:
+ shapedirs = shapedirs[:, :, None]
+ if (shapedirs.shape[-1] < self.SHAPE_SPACE_DIM +
+ self.EXPRESSION_SPACE_DIM):
+ print(f'WARNING: You are using a {self.name()} model, with only'
+ ' 10 shape and 10 expression coefficients.')
+ expr_start_idx = 10
+ expr_end_idx = 20
+ num_expression_coeffs = min(num_expression_coeffs, 10)
+ else:
+ expr_start_idx = self.SHAPE_SPACE_DIM
+ expr_end_idx = self.SHAPE_SPACE_DIM + num_expression_coeffs
+ num_expression_coeffs = min(
+ num_expression_coeffs, self.EXPRESSION_SPACE_DIM)
+
+ self._num_expression_coeffs = num_expression_coeffs
+
+ expr_dirs = shapedirs[:, :, expr_start_idx:expr_end_idx]
+ self.register_buffer(
+ 'expr_dirs', to_tensor(to_np(expr_dirs), dtype=dtype))
+
+ if create_expression:
+ if expression is None:
+ default_expression = torch.zeros(
+ [batch_size, self.num_expression_coeffs], dtype=dtype)
+ else:
+ default_expression = torch.tensor(expression, dtype=dtype)
+ expression_param = nn.Parameter(default_expression,
+ requires_grad=True)
+ self.register_parameter('expression', expression_param)
+
+ # The pickle file that contains the barycentric coordinates for
+ # regressing the landmarks
+ landmark_bcoord_filename = osp.join(
+ model_path, 'flame_static_embedding.pkl')
+
+ with open(landmark_bcoord_filename, 'rb') as fp:
+ landmarks_data = pickle.load(fp, encoding='latin1')
+
+ lmk_faces_idx = landmarks_data['lmk_face_idx'].astype(np.int64)
+ self.register_buffer('lmk_faces_idx',
+ torch.tensor(lmk_faces_idx, dtype=torch.long))
+ lmk_bary_coords = landmarks_data['lmk_b_coords']
+ self.register_buffer('lmk_bary_coords',
+ torch.tensor(lmk_bary_coords, dtype=dtype))
+ if self.use_face_contour:
+ face_contour_path = os.path.join(
+ model_path, 'flame_dynamic_embedding.npy')
+ contour_embeddings = np.load(face_contour_path,
+ allow_pickle=True,
+ encoding='latin1')[()]
+
+ dynamic_lmk_faces_idx = np.array(
+ contour_embeddings['lmk_face_idx'], dtype=np.int64)
+ dynamic_lmk_faces_idx = torch.tensor(
+ dynamic_lmk_faces_idx,
+ dtype=torch.long)
+ self.register_buffer('dynamic_lmk_faces_idx',
+ dynamic_lmk_faces_idx)
+
+ dynamic_lmk_b_coords = torch.tensor(
+ contour_embeddings['lmk_b_coords'], dtype=dtype)
+ self.register_buffer(
+ 'dynamic_lmk_bary_coords', dynamic_lmk_b_coords)
+
+ neck_kin_chain = find_joint_kin_chain(self.NECK_IDX, self.parents)
+ self.register_buffer(
+ 'neck_kin_chain',
+ torch.tensor(neck_kin_chain, dtype=torch.long))
+
+ @property
+ def num_expression_coeffs(self):
+ return self._num_expression_coeffs
+
+ def name(self) -> str:
+ return 'FLAME'
+
+ def extra_repr(self):
+ msg = [
+ super(FLAME, self).extra_repr(),
+ f'Number of Expression Coefficients: {self.num_expression_coeffs}',
+ f'Use face contour: {self.use_face_contour}',
+ ]
+ return '\n'.join(msg)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ neck_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ expression: Optional[Tensor] = None,
+ jaw_pose: Optional[Tensor] = None,
+ leye_pose: Optional[Tensor] = None,
+ reye_pose: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> FLAMEOutput:
+ '''
+ Forward pass for the SMPLX model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ expression: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `expression` and use it
+ instead. For example, it can used if expression parameters
+ `expression` are predicted from some external model.
+ jaw_pose: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ jaw_pose: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full axis-angle pose vector (default=False)
+
+ Returns
+ -------
+ output: ModelOutput
+ A named tuple of type `ModelOutput`
+ '''
+
+ # If no shape and pose parameters are passed along, then use the
+ # ones from the module
+ global_orient = (global_orient if global_orient is not None else
+ self.global_orient)
+ jaw_pose = jaw_pose if jaw_pose is not None else self.jaw_pose
+ neck_pose = neck_pose if neck_pose is not None else self.neck_pose
+
+ leye_pose = leye_pose if leye_pose is not None else self.leye_pose
+ reye_pose = reye_pose if reye_pose is not None else self.reye_pose
+
+ betas = betas if betas is not None else self.betas
+ expression = expression if expression is not None else self.expression
+
+ apply_trans = transl is not None or hasattr(self, 'transl')
+ if transl is None:
+ if hasattr(self, 'transl'):
+ transl = self.transl
+
+ full_pose = torch.cat(
+ [global_orient, neck_pose, jaw_pose, leye_pose, reye_pose], dim=1)
+
+ batch_size = max(betas.shape[0], global_orient.shape[0],
+ jaw_pose.shape[0])
+ # Concatenate the shape and expression coefficients
+ scale = int(batch_size / betas.shape[0])
+ if scale > 1:
+ betas = betas.expand(scale, -1)
+ shape_components = torch.cat([betas, expression], dim=-1)
+ shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)
+
+ vertices, joints = lbs(shape_components, full_pose, self.v_template,
+ shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=pose2rot,
+ )
+
+ lmk_faces_idx = self.lmk_faces_idx.unsqueeze(
+ dim=0).expand(batch_size, -1).contiguous()
+ lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(
+ self.batch_size, 1, 1)
+ if self.use_face_contour:
+ lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(
+ vertices, full_pose, self.dynamic_lmk_faces_idx,
+ self.dynamic_lmk_bary_coords,
+ self.neck_kin_chain,
+ pose2rot=True,
+ )
+ dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords
+ lmk_faces_idx = torch.cat([lmk_faces_idx,
+ dyn_lmk_faces_idx], 1)
+ lmk_bary_coords = torch.cat(
+ [lmk_bary_coords.expand(batch_size, -1, -1),
+ dyn_lmk_bary_coords], 1)
+
+ landmarks = vertices2landmarks(vertices, self.faces_tensor,
+ lmk_faces_idx,
+ lmk_bary_coords)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Add the landmarks to the joints
+ joints = torch.cat([joints, landmarks], dim=1)
+
+ # Map the joints to the current dataset
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints=joints, vertices=vertices)
+
+ if apply_trans:
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = FLAMEOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ expression=expression,
+ global_orient=global_orient,
+ neck_pose=neck_pose,
+ jaw_pose=jaw_pose,
+ full_pose=full_pose if return_full_pose else None)
+ return output
+
+
+class FLAMELayer(FLAME):
+ def __init__(self, *args, **kwargs) -> None:
+ ''' FLAME as a layer model constructor '''
+ super(FLAMELayer, self).__init__(
+ create_betas=False,
+ create_expression=False,
+ create_global_orient=False,
+ create_neck_pose=False,
+ create_jaw_pose=False,
+ create_leye_pose=False,
+ create_reye_pose=False,
+ *args,
+ **kwargs)
+
+ def forward(
+ self,
+ betas: Optional[Tensor] = None,
+ global_orient: Optional[Tensor] = None,
+ neck_pose: Optional[Tensor] = None,
+ transl: Optional[Tensor] = None,
+ expression: Optional[Tensor] = None,
+ jaw_pose: Optional[Tensor] = None,
+ leye_pose: Optional[Tensor] = None,
+ reye_pose: Optional[Tensor] = None,
+ return_verts: bool = True,
+ return_full_pose: bool = False,
+ pose2rot: bool = True,
+ **kwargs
+ ) -> FLAMEOutput:
+ '''
+ Forward pass for the SMPLX model
+
+ Parameters
+ ----------
+ global_orient: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable and use it as the global
+ rotation of the body. Useful if someone wishes to predicts this
+ with an external model. (default=None)
+ betas: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `betas` and use it
+ instead. For example, it can used if shape parameters
+ `betas` are predicted from some external model.
+ (default=None)
+ expression: torch.tensor, optional, shape Bx10
+ If given, ignore the member variable `expression` and use it
+ instead. For example, it can used if expression parameters
+ `expression` are predicted from some external model.
+ jaw_pose: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ jaw_pose: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `jaw_pose` and
+ use this instead. It should either joint rotations in
+ axis-angle format.
+ transl: torch.tensor, optional, shape Bx3
+ If given, ignore the member variable `transl` and use it
+ instead. For example, it can used if the translation
+ `transl` is predicted from some external model.
+ (default=None)
+ return_verts: bool, optional
+ Return the vertices. (default=True)
+ return_full_pose: bool, optional
+ Returns the full axis-angle pose vector (default=False)
+
+ Returns
+ -------
+ output: ModelOutput
+ A named tuple of type `ModelOutput`
+ '''
+ device, dtype = self.shapedirs.device, self.shapedirs.dtype
+ if global_orient is None:
+ batch_size = 1
+ global_orient = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ else:
+ batch_size = global_orient.shape[0]
+ if neck_pose is None:
+ neck_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, 1, -1).contiguous()
+ if jaw_pose is None:
+ jaw_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if leye_pose is None:
+ leye_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if reye_pose is None:
+ reye_pose = torch.zeros(3, device=device, dtype=dtype).view(
+ 1, 1, 3).expand(batch_size, -1, -1).contiguous()
+ if betas is None:
+ betas = torch.zeros([batch_size, self.num_betas],
+ dtype=dtype, device=device)
+ if expression is None:
+ expression = torch.zeros([batch_size, self.num_expression_coeffs],
+ dtype=dtype, device=device)
+ if transl is None:
+ transl = torch.zeros([batch_size, 3], dtype=dtype, device=device)
+
+ full_pose = torch.cat(
+ [global_orient, neck_pose, jaw_pose, leye_pose, reye_pose], dim=1)
+
+ shape_components = torch.cat([betas, expression], dim=-1)
+ shapedirs = torch.cat([self.shapedirs, self.expr_dirs], dim=-1)
+
+ vertices, joints = lbs(shape_components, full_pose, self.v_template,
+ shapedirs, self.posedirs,
+ self.J_regressor, self.parents,
+ self.lbs_weights, pose2rot=True,
+ )
+
+ lmk_faces_idx = self.lmk_faces_idx.unsqueeze(
+ dim=0).expand(batch_size, -1).contiguous()
+ lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).repeat(
+ self.batch_size, 1, 1)
+ if self.use_face_contour:
+ lmk_idx_and_bcoords = find_dynamic_lmk_idx_and_bcoords(
+ vertices, full_pose, self.dynamic_lmk_faces_idx,
+ self.dynamic_lmk_bary_coords,
+ self.neck_kin_chain,
+ pose2rot=False,
+ )
+ dyn_lmk_faces_idx, dyn_lmk_bary_coords = lmk_idx_and_bcoords
+ lmk_faces_idx = torch.cat([lmk_faces_idx,
+ dyn_lmk_faces_idx], 1)
+ lmk_bary_coords = torch.cat(
+ [lmk_bary_coords.expand(batch_size, -1, -1),
+ dyn_lmk_bary_coords], 1)
+
+ landmarks = vertices2landmarks(vertices, self.faces_tensor,
+ lmk_faces_idx,
+ lmk_bary_coords)
+
+ # Add any extra joints that might be needed
+ joints = self.vertex_joint_selector(vertices, joints)
+ # Add the landmarks to the joints
+ joints = torch.cat([joints, landmarks], dim=1)
+
+ # Map the joints to the current dataset
+ if self.joint_mapper is not None:
+ joints = self.joint_mapper(joints=joints, vertices=vertices)
+
+ joints += transl.unsqueeze(dim=1)
+ vertices += transl.unsqueeze(dim=1)
+
+ output = FLAMEOutput(vertices=vertices if return_verts else None,
+ joints=joints,
+ betas=betas,
+ expression=expression,
+ global_orient=global_orient,
+ neck_pose=neck_pose,
+ jaw_pose=jaw_pose,
+ full_pose=full_pose if return_full_pose else None)
+ return output
+
+
+def build_layer(
+ model_path: str,
+ model_type: str = 'smpl',
+ **kwargs
+) -> Union[SMPLLayer, SMPLHLayer, SMPLXLayer, MANOLayer, FLAMELayer]:
+ ''' Method for creating a model from a path and a model type
+
+ Parameters
+ ----------
+ model_path: str
+ Either the path to the model you wish to load or a folder,
+ where each subfolder contains the differents types, i.e.:
+ model_path:
+ |
+ |-- smpl
+ |-- SMPL_FEMALE
+ |-- SMPL_NEUTRAL
+ |-- SMPL_MALE
+ |-- smplh
+ |-- SMPLH_FEMALE
+ |-- SMPLH_MALE
+ |-- smplx
+ |-- SMPLX_FEMALE
+ |-- SMPLX_NEUTRAL
+ |-- SMPLX_MALE
+ |-- mano
+ |-- MANO RIGHT
+ |-- MANO LEFT
+ |-- flame
+ |-- FLAME_FEMALE
+ |-- FLAME_MALE
+ |-- FLAME_NEUTRAL
+
+ model_type: str, optional
+ When model_path is a folder, then this parameter specifies the
+ type of model to be loaded
+ **kwargs: dict
+ Keyword arguments
+
+ Returns
+ -------
+ body_model: nn.Module
+ The PyTorch module that implements the corresponding body model
+ Raises
+ ------
+ ValueError: In case the model type is not one of SMPL, SMPLH,
+ SMPLX, MANO or FLAME
+ '''
+ if osp.isdir(model_path):
+ model_path = os.path.join(model_path, model_type)
+ else:
+ model_type = osp.basename(model_path).split('_')[0].lower()
+ if model_type.lower() == 'smpl':
+ return SMPLLayer(model_path, **kwargs)
+ elif model_type.lower() == 'smplh':
+ return SMPLHLayer(model_path, **kwargs)
+ elif model_type.lower() == 'smplx':
+ return SMPLXLayer(model_path, **kwargs)
+ elif 'mano' in model_type.lower():
+ return MANOLayer(model_path, **kwargs)
+ elif 'flame' in model_type.lower():
+ return FLAMELayer(model_path, **kwargs)
+ else:
+ raise ValueError(f'Unknown model type {model_type}, exiting!')
+
+
+def create(
+ model_path: str,
+ model_type: str = 'smpl',
+ **kwargs
+) -> Union[SMPL, SMPLH, SMPLX, MANO, FLAME]:
+ ''' Method for creating a model from a path and a model type
+
+ Parameters
+ ----------
+ model_path: str
+ Either the path to the model you wish to load or a folder,
+ where each subfolder contains the differents types, i.e.:
+ model_path:
+ |
+ |-- smpl
+ |-- SMPL_FEMALE
+ |-- SMPL_NEUTRAL
+ |-- SMPL_MALE
+ |-- smplh
+ |-- SMPLH_FEMALE
+ |-- SMPLH_MALE
+ |-- smplx
+ |-- SMPLX_FEMALE
+ |-- SMPLX_NEUTRAL
+ |-- SMPLX_MALE
+ |-- mano
+ |-- MANO RIGHT
+ |-- MANO LEFT
+
+ model_type: str, optional
+ When model_path is a folder, then this parameter specifies the
+ type of model to be loaded
+ **kwargs: dict
+ Keyword arguments
+
+ Returns
+ -------
+ body_model: nn.Module
+ The PyTorch module that implements the corresponding body model
+ Raises
+ ------
+ ValueError: In case the model type is not one of SMPL, SMPLH,
+ SMPLX, MANO or FLAME
+ '''
+
+ # If it's a folder, assume
+ if osp.isdir(model_path):
+ model_path = os.path.join(model_path, model_type)
+ else:
+ model_type = osp.basename(model_path).split('_')[0].lower()
+ if model_type.lower() == 'smpl':
+ return SMPL(model_path, **kwargs)
+ elif model_type.lower() == 'smplh':
+ return SMPLH(model_path, **kwargs)
+ elif model_type.lower() == 'smplx':
+ return SMPLX(model_path, **kwargs)
+ elif 'mano' in model_type.lower():
+ return MANO(model_path, **kwargs)
+ elif 'flame' in model_type.lower():
+ return FLAME(model_path, **kwargs)
+ else:
+ raise ValueError(f'Unknown model type {model_type}, exiting!')
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/joint_names.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/joint_names.py
new file mode 100644
index 0000000000000000000000000000000000000000..0a3a10f8cef8b50075dc9f680459fc5d596a0013
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/joint_names.py
@@ -0,0 +1,163 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+JOINT_NAMES = [
+ 'pelvis',
+ 'left_hip',
+ 'right_hip',
+ 'spine1',
+ 'left_knee',
+ 'right_knee',
+ 'spine2',
+ 'left_ankle',
+ 'right_ankle',
+ 'spine3',
+ 'left_foot',
+ 'right_foot',
+ 'neck',
+ 'left_collar',
+ 'right_collar',
+ 'head',
+ 'left_shoulder',
+ 'right_shoulder',
+ 'left_elbow',
+ 'right_elbow',
+ 'left_wrist',
+ 'right_wrist',
+ 'jaw',
+ 'left_eye_smplhf',
+ 'right_eye_smplhf',
+ 'left_index1',
+ 'left_index2',
+ 'left_index3',
+ 'left_middle1',
+ 'left_middle2',
+ 'left_middle3',
+ 'left_pinky1',
+ 'left_pinky2',
+ 'left_pinky3',
+ 'left_ring1',
+ 'left_ring2',
+ 'left_ring3',
+ 'left_thumb1',
+ 'left_thumb2',
+ 'left_thumb3',
+ 'right_index1',
+ 'right_index2',
+ 'right_index3',
+ 'right_middle1',
+ 'right_middle2',
+ 'right_middle3',
+ 'right_pinky1',
+ 'right_pinky2',
+ 'right_pinky3',
+ 'right_ring1',
+ 'right_ring2',
+ 'right_ring3',
+ 'right_thumb1',
+ 'right_thumb2',
+ 'right_thumb3',
+ 'nose',
+ 'right_eye',
+ 'left_eye',
+ 'right_ear',
+ 'left_ear',
+ 'left_big_toe',
+ 'left_small_toe',
+ 'left_heel',
+ 'right_big_toe',
+ 'right_small_toe',
+ 'right_heel',
+ 'left_thumb',
+ 'left_index',
+ 'left_middle',
+ 'left_ring',
+ 'left_pinky',
+ 'right_thumb',
+ 'right_index',
+ 'right_middle',
+ 'right_ring',
+ 'right_pinky',
+ 'right_eye_brow1',
+ 'right_eye_brow2',
+ 'right_eye_brow3',
+ 'right_eye_brow4',
+ 'right_eye_brow5',
+ 'left_eye_brow5',
+ 'left_eye_brow4',
+ 'left_eye_brow3',
+ 'left_eye_brow2',
+ 'left_eye_brow1',
+ 'nose1',
+ 'nose2',
+ 'nose3',
+ 'nose4',
+ 'right_nose_2',
+ 'right_nose_1',
+ 'nose_middle',
+ 'left_nose_1',
+ 'left_nose_2',
+ 'right_eye1',
+ 'right_eye2',
+ 'right_eye3',
+ 'right_eye4',
+ 'right_eye5',
+ 'right_eye6',
+ 'left_eye4',
+ 'left_eye3',
+ 'left_eye2',
+ 'left_eye1',
+ 'left_eye6',
+ 'left_eye5',
+ 'right_mouth_1',
+ 'right_mouth_2',
+ 'right_mouth_3',
+ 'mouth_top',
+ 'left_mouth_3',
+ 'left_mouth_2',
+ 'left_mouth_1',
+ 'left_mouth_5', # 59 in OpenPose output
+ 'left_mouth_4', # 58 in OpenPose output
+ 'mouth_bottom',
+ 'right_mouth_4',
+ 'right_mouth_5',
+ 'right_lip_1',
+ 'right_lip_2',
+ 'lip_top',
+ 'left_lip_2',
+ 'left_lip_1',
+ 'left_lip_3',
+ 'lip_bottom',
+ 'right_lip_3',
+ # Face contour
+ 'right_contour_1',
+ 'right_contour_2',
+ 'right_contour_3',
+ 'right_contour_4',
+ 'right_contour_5',
+ 'right_contour_6',
+ 'right_contour_7',
+ 'right_contour_8',
+ 'contour_middle',
+ 'left_contour_8',
+ 'left_contour_7',
+ 'left_contour_6',
+ 'left_contour_5',
+ 'left_contour_4',
+ 'left_contour_3',
+ 'left_contour_2',
+ 'left_contour_1',
+]
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/lbs.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/lbs.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2b2853eb8f899f14613c4f2236a3154cfbb79d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/lbs.py
@@ -0,0 +1,508 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from __future__ import absolute_import
+from __future__ import print_function
+from __future__ import division
+
+from typing import Tuple, List
+import numpy as np
+
+import torch
+import torch.nn.functional as F
+
+from .utils import rot_mat_to_euler, Tensor
+
+
+def find_dynamic_lmk_idx_and_bcoords(
+ vertices: Tensor,
+ pose: Tensor,
+ dynamic_lmk_faces_idx: Tensor,
+ dynamic_lmk_b_coords: Tensor,
+ neck_kin_chain: List[int],
+ pose2rot: bool = True,
+) -> Tuple[Tensor, Tensor]:
+ ''' Compute the faces, barycentric coordinates for the dynamic landmarks
+
+
+ To do so, we first compute the rotation of the neck around the y-axis
+ and then use a pre-computed look-up table to find the faces and the
+ barycentric coordinates that will be used.
+
+ Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de)
+ for providing the original TensorFlow implementation and for the LUT.
+
+ Parameters
+ ----------
+ vertices: torch.tensor BxVx3, dtype = torch.float32
+ The tensor of input vertices
+ pose: torch.tensor Bx(Jx3), dtype = torch.float32
+ The current pose of the body model
+ dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long
+ The look-up table from neck rotation to faces
+ dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32
+ The look-up table from neck rotation to barycentric coordinates
+ neck_kin_chain: list
+ A python list that contains the indices of the joints that form the
+ kinematic chain of the neck.
+ dtype: torch.dtype, optional
+
+ Returns
+ -------
+ dyn_lmk_faces_idx: torch.tensor, dtype = torch.long
+ A tensor of size BxL that contains the indices of the faces that
+ will be used to compute the current dynamic landmarks.
+ dyn_lmk_b_coords: torch.tensor, dtype = torch.float32
+ A tensor of size BxL that contains the indices of the faces that
+ will be used to compute the current dynamic landmarks.
+ '''
+
+ dtype = vertices.dtype
+ batch_size = vertices.shape[0]
+
+ if pose2rot:
+ aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,
+ neck_kin_chain)
+ rot_mats = batch_rodrigues(
+ aa_pose.view(-1, 3)).view(batch_size, -1, 3, 3)
+ else:
+ rot_mats = torch.index_select(
+ pose.view(batch_size, -1, 3, 3), 1, neck_kin_chain)
+
+ rel_rot_mat = torch.eye(
+ 3, device=vertices.device, dtype=dtype).unsqueeze_(dim=0).repeat(
+ batch_size, 1, 1)
+ for idx in range(len(neck_kin_chain)):
+ rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)
+
+ y_rot_angle = torch.round(
+ torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,
+ max=39)).to(dtype=torch.long)
+ neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)
+ mask = y_rot_angle.lt(-39).to(dtype=torch.long)
+ neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)
+ y_rot_angle = (neg_mask * neg_vals +
+ (1 - neg_mask) * y_rot_angle)
+
+ dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,
+ 0, y_rot_angle)
+ dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,
+ 0, y_rot_angle)
+
+ return dyn_lmk_faces_idx, dyn_lmk_b_coords
+
+
+def vertices2landmarks(
+ vertices: Tensor,
+ faces: Tensor,
+ lmk_faces_idx: Tensor,
+ lmk_bary_coords: Tensor
+) -> Tensor:
+ ''' Calculates landmarks by barycentric interpolation
+
+ Parameters
+ ----------
+ vertices: torch.tensor BxVx3, dtype = torch.float32
+ The tensor of input vertices
+ faces: torch.tensor Fx3, dtype = torch.long
+ The faces of the mesh
+ lmk_faces_idx: torch.tensor L, dtype = torch.long
+ The tensor with the indices of the faces used to calculate the
+ landmarks.
+ lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32
+ The tensor of barycentric coordinates that are used to interpolate
+ the landmarks
+
+ Returns
+ -------
+ landmarks: torch.tensor BxLx3, dtype = torch.float32
+ The coordinates of the landmarks for each mesh in the batch
+ '''
+ # Extract the indices of the vertices for each face
+ # BxLx3
+ batch_size, num_verts = vertices.shape[:2]
+ device = vertices.device
+
+ lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(
+ batch_size, -1, 3)
+
+ lmk_faces += torch.arange(
+ batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts
+
+ lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(
+ batch_size, -1, 3, 3)
+
+ landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])
+ return landmarks
+
+
+def lbs(
+ betas: Tensor,
+ pose: Tensor,
+ v_template: Tensor,
+ shapedirs: Tensor,
+ posedirs: Tensor,
+ J_regressor: Tensor,
+ parents: Tensor,
+ lbs_weights: Tensor,
+ pose2rot: bool = True,
+) -> Tuple[Tensor, Tensor]:
+ ''' Performs Linear Blend Skinning with the given shape and pose parameters
+
+ Parameters
+ ----------
+ betas : torch.tensor BxNB
+ The tensor of shape parameters
+ pose : torch.tensor Bx(J + 1) * 3
+ The pose parameters in axis-angle format
+ v_template torch.tensor BxVx3
+ The template mesh that will be deformed
+ shapedirs : torch.tensor 1xNB
+ The tensor of PCA shape displacements
+ posedirs : torch.tensor Px(V * 3)
+ The pose PCA coefficients
+ J_regressor : torch.tensor JxV
+ The regressor array that is used to calculate the joints from
+ the position of the vertices
+ parents: torch.tensor J
+ The array that describes the kinematic tree for the model
+ lbs_weights: torch.tensor N x V x (J + 1)
+ The linear blend skinning weights that represent how much the
+ rotation matrix of each part affects each vertex
+ pose2rot: bool, optional
+ Flag on whether to convert the input pose tensor to rotation
+ matrices. The default value is True. If False, then the pose tensor
+ should already contain rotation matrices and have a size of
+ Bx(J + 1)x9
+ dtype: torch.dtype, optional
+
+ Returns
+ -------
+ verts: torch.tensor BxVx3
+ The vertices of the mesh after applying the shape and pose
+ displacements.
+ joints: torch.tensor BxJx3
+ The joints of the model
+ '''
+
+ batch_size = max(betas.shape[0], pose.shape[0])
+ device, dtype = betas.device, betas.dtype
+
+ # Add shape contribution
+ v_shaped = v_template + blend_shapes(betas, shapedirs)
+
+ # Get the joints
+ # NxJx3 array
+ J = vertices2joints(J_regressor, v_shaped)
+
+ # 3. Add pose blend shapes
+ # N x J x 3 x 3
+ ident = torch.eye(3, dtype=dtype, device=device)
+ if pose2rot:
+ rot_mats = batch_rodrigues(pose.view(-1, 3)).view(
+ [batch_size, -1, 3, 3])
+
+ pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])
+ # (N x P) x (P, V * 3) -> N x V x 3
+ pose_offsets = torch.matmul(
+ pose_feature, posedirs).view(batch_size, -1, 3)
+ else:
+ pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident
+ rot_mats = pose.view(batch_size, -1, 3, 3)
+
+ pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),
+ posedirs).view(batch_size, -1, 3)
+
+ v_posed = pose_offsets + v_shaped
+
+ # 4. Get the global joint location
+ J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)
+
+ # 5. Do skinning:
+ # W is N x V x (J + 1)
+ W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])
+ # (N x V x (J + 1)) x (N x (J + 1) x 16)
+ num_joints = J_regressor.shape[0]
+ T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \
+ .view(batch_size, -1, 4, 4)
+
+ homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],
+ dtype=dtype, device=device)
+ v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)
+ v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))
+ verts = v_homo[:, :, :3, 0]
+
+ return verts, J_transformed
+
+
+def lbs_v2(
+ betas: Tensor,
+ pose: Tensor,
+ v_template: Tensor,
+ shapedirs: Tensor,
+ posedirs: Tensor,
+ J_regressor: Tensor,
+ parents: Tensor,
+ lbs_weights: Tensor,
+ flame_betas: Tensor,
+ flame_shapedirs: Tensor,
+ head_idxs: np.array,
+ pose2rot: bool = True,
+) -> Tuple[Tensor, Tensor]:
+ ''' Performs Linear Blend Skinning with the given shape and pose parameters
+
+ Parameters
+ ----------
+ betas : torch.tensor BxNB
+ The tensor of shape parameters
+ pose : torch.tensor Bx(J + 1) * 3
+ The pose parameters in axis-angle format
+ v_template torch.tensor BxVx3
+ The template mesh that will be deformed
+ shapedirs : torch.tensor 1xNB
+ The tensor of PCA shape displacements
+ posedirs : torch.tensor Px(V * 3)
+ The pose PCA coefficients
+ J_regressor : torch.tensor JxV
+ The regressor array that is used to calculate the joints from
+ the position of the vertices
+ parents: torch.tensor J
+ The array that describes the kinematic tree for the model
+ lbs_weights: torch.tensor N x V x (J + 1)
+ The linear blend skinning weights that represent how much the
+ rotation matrix of each part affects each vertex
+ pose2rot: bool, optional
+ Flag on whether to convert the input pose tensor to rotation
+ matrices. The default value is True. If False, then the pose tensor
+ should already contain rotation matrices and have a size of
+ Bx(J + 1)x9
+ dtype: torch.dtype, optional
+
+ Returns
+ -------
+ verts: torch.tensor BxVx3
+ The vertices of the mesh after applying the shape and pose
+ displacements.
+ joints: torch.tensor BxJx3
+ The joints of the model
+ '''
+
+ batch_size = max(betas.shape[0], pose.shape[0])
+ device, dtype = betas.device, betas.dtype
+
+ # Add shape contribution
+ v_shaped = v_template + blend_shapes(betas, shapedirs)
+
+ # Add shape contribution of FLAME
+ flame_v_shape = v_template[head_idxs] + blend_shapes(flame_betas, flame_shapedirs)
+ v_shaped[:, head_idxs] = flame_v_shape
+
+ # Get the joints
+ # NxJx3 array
+ J = vertices2joints(J_regressor, v_shaped)
+
+ # 3. Add pose blend shapes
+ # N x J x 3 x 3
+ ident = torch.eye(3, dtype=dtype, device=device)
+ if pose2rot:
+ rot_mats = batch_rodrigues(pose.view(-1, 3)).view(
+ [batch_size, -1, 3, 3])
+
+ pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])
+ # (N x P) x (P, V * 3) -> N x V x 3
+ pose_offsets = torch.matmul(
+ pose_feature, posedirs).view(batch_size, -1, 3)
+ else:
+ pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident
+ rot_mats = pose.view(batch_size, -1, 3, 3)
+
+ pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),
+ posedirs).view(batch_size, -1, 3)
+
+ v_posed = pose_offsets + v_shaped
+
+ # 4. Get the global joint location
+ J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)
+
+ # 5. Do skinning:
+ # W is N x V x (J + 1)
+ W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])
+ # (N x V x (J + 1)) x (N x (J + 1) x 16)
+ num_joints = J_regressor.shape[0]
+ T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \
+ .view(batch_size, -1, 4, 4)
+
+ homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], dtype=dtype, device=device)
+ v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)
+ v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))
+ verts = v_homo[:, :, :3, 0]
+
+ return verts, J_transformed
+
+def vertices2joints(J_regressor: Tensor, vertices: Tensor) -> Tensor:
+ ''' Calculates the 3D joint locations from the vertices
+
+ Parameters
+ ----------
+ J_regressor : torch.tensor JxV
+ The regressor array that is used to calculate the joints from the
+ position of the vertices
+ vertices : torch.tensor BxVx3
+ The tensor of mesh vertices
+
+ Returns
+ -------
+ torch.tensor BxJx3
+ The location of the joints
+ '''
+
+ return torch.einsum('bik,ji->bjk', [vertices, J_regressor])
+
+
+def blend_shapes(betas: Tensor, shape_disps: Tensor) -> Tensor:
+ ''' Calculates the per vertex displacement due to the blend shapes
+
+
+ Parameters
+ ----------
+ betas : torch.tensor Bx(num_betas)
+ Blend shape coefficients
+ shape_disps: torch.tensor Vx3x(num_betas)
+ Blend shapes
+
+ Returns
+ -------
+ torch.tensor BxVx3
+ The per-vertex displacement due to shape deformation
+ '''
+
+ # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]
+ # i.e. Multiply each shape displacement by its corresponding beta and
+ # then sum them.
+ blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])
+ return blend_shape
+
+
+def batch_rodrigues(
+ rot_vecs: Tensor,
+ epsilon: float = 1e-8,
+) -> Tensor:
+ ''' Calculates the rotation matrices for a batch of rotation vectors
+ Parameters
+ ----------
+ rot_vecs: torch.tensor Nx3
+ array of N axis-angle vectors
+ Returns
+ -------
+ R: torch.tensor Nx3x3
+ The rotation matrices for the given axis-angle parameters
+ '''
+
+ batch_size = rot_vecs.shape[0]
+ device, dtype = rot_vecs.device, rot_vecs.dtype
+
+ angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)
+ rot_dir = rot_vecs / angle
+
+ cos = torch.unsqueeze(torch.cos(angle), dim=1)
+ sin = torch.unsqueeze(torch.sin(angle), dim=1)
+
+ # Bx1 arrays
+ rx, ry, rz = torch.split(rot_dir, 1, dim=1)
+ K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)
+
+ zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)
+ K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \
+ .view((batch_size, 3, 3))
+
+ ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)
+ rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)
+ return rot_mat
+
+
+def transform_mat(R: Tensor, t: Tensor) -> Tensor:
+ ''' Creates a batch of transformation matrices
+ Args:
+ - R: Bx3x3 array of a batch of rotation matrices
+ - t: Bx3x1 array of a batch of translation vectors
+ Returns:
+ - T: Bx4x4 Transformation matrix
+ '''
+ # No padding left or right, only add an extra row
+ return torch.cat([F.pad(R, [0, 0, 0, 1]),
+ F.pad(t, [0, 0, 0, 1], value=1)], dim=2)
+
+
+def batch_rigid_transform(
+ rot_mats: Tensor,
+ joints: Tensor,
+ parents: Tensor,
+ dtype=torch.float32
+) -> Tensor:
+ """
+ Applies a batch of rigid transformations to the joints
+
+ Parameters
+ ----------
+ rot_mats : torch.tensor BxNx3x3
+ Tensor of rotation matrices
+ joints : torch.tensor BxNx3
+ Locations of joints
+ parents : torch.tensor BxN
+ The kinematic tree of each object
+ dtype : torch.dtype, optional:
+ The data type of the created tensors, the default is torch.float32
+
+ Returns
+ -------
+ posed_joints : torch.tensor BxNx3
+ The locations of the joints after applying the pose rotations
+ rel_transforms : torch.tensor BxNx4x4
+ The relative (with respect to the root joint) rigid transformations
+ for all the joints
+ """
+
+ joints = torch.unsqueeze(joints, dim=-1)
+
+ rel_joints = joints.clone()
+ rel_joints[:, 1:] -= joints[:, parents[1:]]
+
+ transforms_mat = transform_mat(
+ rot_mats.reshape(-1, 3, 3),
+ rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)
+
+ transform_chain = [transforms_mat[:, 0]]
+ for i in range(1, parents.shape[0]):
+ # Subtract the joint location at the rest pose
+ # No need for rotation, since it's identity when at rest
+ curr_res = torch.matmul(transform_chain[parents[i]],
+ transforms_mat[:, i])
+ transform_chain.append(curr_res)
+
+ transforms = torch.stack(transform_chain, dim=1)
+
+ # The last column of the transformations contains the posed joints
+ posed_joints = transforms[:, :, :3, 3]
+
+ # The last column of the transformations contains the posed joints
+ posed_joints = transforms[:, :, :3, 3]
+
+ joints_homogen = F.pad(joints, [0, 0, 0, 1])
+
+ rel_transforms = transforms - F.pad(
+ torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])
+
+ return posed_joints, rel_transforms
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/utils.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..55dd1ed6d94582c744d0b99bc4150b1040cf58a0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/utils.py
@@ -0,0 +1,125 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from typing import NewType, Union, Optional
+from dataclasses import dataclass, asdict, fields
+import numpy as np
+import torch
+
+Tensor = NewType('Tensor', torch.Tensor)
+Array = NewType('Array', np.ndarray)
+
+
+@dataclass
+class ModelOutput:
+ vertices: Optional[Tensor] = None
+ joints: Optional[Tensor] = None
+ full_pose: Optional[Tensor] = None
+ global_orient: Optional[Tensor] = None
+ transl: Optional[Tensor] = None
+
+ def __getitem__(self, key):
+ return getattr(self, key)
+
+ def get(self, key, default=None):
+ return getattr(self, key, default)
+
+ def __iter__(self):
+ return self.keys()
+
+ def keys(self):
+ keys = [t.name for t in fields(self)]
+ return iter(keys)
+
+ def values(self):
+ values = [getattr(self, t.name) for t in fields(self)]
+ return iter(values)
+
+ def items(self):
+ data = [(t.name, getattr(self, t.name)) for t in fields(self)]
+ return iter(data)
+
+
+@dataclass
+class SMPLOutput(ModelOutput):
+ betas: Optional[Tensor] = None
+ body_pose: Optional[Tensor] = None
+
+
+@dataclass
+class SMPLHOutput(SMPLOutput):
+ left_hand_pose: Optional[Tensor] = None
+ right_hand_pose: Optional[Tensor] = None
+ transl: Optional[Tensor] = None
+
+
+@dataclass
+class SMPLXOutput(SMPLHOutput):
+ expression: Optional[Tensor] = None
+ jaw_pose: Optional[Tensor] = None
+
+
+@dataclass
+class MANOOutput(ModelOutput):
+ betas: Optional[Tensor] = None
+ hand_pose: Optional[Tensor] = None
+
+
+@dataclass
+class FLAMEOutput(ModelOutput):
+ betas: Optional[Tensor] = None
+ expression: Optional[Tensor] = None
+ jaw_pose: Optional[Tensor] = None
+ neck_pose: Optional[Tensor] = None
+
+
+def find_joint_kin_chain(joint_id, kinematic_tree):
+ kin_chain = []
+ curr_idx = joint_id
+ while curr_idx != -1:
+ kin_chain.append(curr_idx)
+ curr_idx = kinematic_tree[curr_idx]
+ return kin_chain
+
+
+def to_tensor(
+ array: Union[Array, Tensor], dtype=torch.float32
+) -> Tensor:
+ if torch.is_tensor(array):
+ return array
+ else:
+ return torch.tensor(array, dtype=dtype)
+
+
+class Struct(object):
+ def __init__(self, **kwargs):
+ for key, val in kwargs.items():
+ setattr(self, key, val)
+
+
+def to_np(array, dtype=np.float32):
+ if 'scipy.sparse' in str(type(array)):
+ array = array.todense()
+ return np.array(array, dtype=dtype)
+
+
+def rot_mat_to_euler(rot_mats):
+ # Calculates rotation matrix to euler angles
+ # Careful for extreme cases of eular angles like [0.0, pi, 0.0]
+
+ sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] +
+ rot_mats[:, 1, 0] * rot_mats[:, 1, 0])
+ return torch.atan2(-rot_mats[:, 2, 0], sy)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_ids.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_ids.py
new file mode 100644
index 0000000000000000000000000000000000000000..0e7a4c36700f002da54a9e181eabbd47af2a95bc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_ids.py
@@ -0,0 +1,77 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import division
+
+# Joint name to vertex mapping. SMPL/SMPL-H/SMPL-X vertices that correspond to
+# MSCOCO and OpenPose joints
+vertex_ids = {
+ 'smplh': {
+ 'nose': 332,
+ 'reye': 6260,
+ 'leye': 2800,
+ 'rear': 4071,
+ 'lear': 583,
+ 'rthumb': 6191,
+ 'rindex': 5782,
+ 'rmiddle': 5905,
+ 'rring': 6016,
+ 'rpinky': 6133,
+ 'lthumb': 2746,
+ 'lindex': 2319,
+ 'lmiddle': 2445,
+ 'lring': 2556,
+ 'lpinky': 2673,
+ 'LBigToe': 3216,
+ 'LSmallToe': 3226,
+ 'LHeel': 3387,
+ 'RBigToe': 6617,
+ 'RSmallToe': 6624,
+ 'RHeel': 6787
+ },
+ 'smplx': {
+ 'nose': 9120,
+ 'reye': 9929,
+ 'leye': 9448,
+ 'rear': 616,
+ 'lear': 6,
+ 'rthumb': 8079,
+ 'rindex': 7669,
+ 'rmiddle': 7794,
+ 'rring': 7905,
+ 'rpinky': 8022,
+ 'lthumb': 5361,
+ 'lindex': 4933,
+ 'lmiddle': 5058,
+ 'lring': 5169,
+ 'lpinky': 5286,
+ 'LBigToe': 5770,
+ 'LSmallToe': 5780,
+ 'LHeel': 8846,
+ 'RBigToe': 8463,
+ 'RSmallToe': 8474,
+ 'RHeel': 8635
+ },
+ 'mano': {
+ 'thumb': 744,
+ 'index': 320,
+ 'middle': 443,
+ 'ring': 554,
+ 'pinky': 671,
+ }
+}
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_joint_selector.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_joint_selector.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b8298bd5e087731f86c1c699703b5219e046c5c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/smplx/vertex_joint_selector.py
@@ -0,0 +1,77 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from __future__ import absolute_import
+from __future__ import print_function
+from __future__ import division
+
+import numpy as np
+
+import torch
+import torch.nn as nn
+
+from .utils import to_tensor
+
+
+class VertexJointSelector(nn.Module):
+
+ def __init__(self, vertex_ids=None,
+ use_hands=True,
+ use_feet_keypoints=True, **kwargs):
+ super(VertexJointSelector, self).__init__()
+
+ extra_joints_idxs = []
+
+ face_keyp_idxs = np.array([
+ vertex_ids['nose'],
+ vertex_ids['reye'],
+ vertex_ids['leye'],
+ vertex_ids['rear'],
+ vertex_ids['lear']], dtype=np.int64)
+
+ extra_joints_idxs = np.concatenate([extra_joints_idxs,
+ face_keyp_idxs])
+
+ if use_feet_keypoints:
+ feet_keyp_idxs = np.array([vertex_ids['LBigToe'],
+ vertex_ids['LSmallToe'],
+ vertex_ids['LHeel'],
+ vertex_ids['RBigToe'],
+ vertex_ids['RSmallToe'],
+ vertex_ids['RHeel']], dtype=np.int32)
+
+ extra_joints_idxs = np.concatenate(
+ [extra_joints_idxs, feet_keyp_idxs])
+
+ if use_hands:
+ self.tip_names = ['thumb', 'index', 'middle', 'ring', 'pinky']
+
+ tips_idxs = []
+ for hand_id in ['l', 'r']:
+ for tip_name in self.tip_names:
+ tips_idxs.append(vertex_ids[hand_id + tip_name])
+
+ extra_joints_idxs = np.concatenate(
+ [extra_joints_idxs, tips_idxs])
+
+ self.register_buffer('extra_joints_idxs',
+ to_tensor(extra_joints_idxs, dtype=torch.long))
+
+ def forward(self, vertices, joints):
+ extra_joints = torch.index_select(vertices, 1, self.extra_joints_idxs)
+ joints = torch.cat([joints, extra_joints], dim=1)
+
+ return joints
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..1e69d971bc22f8d65f2e751c24c6125d363a3e76
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/README.md
@@ -0,0 +1,20 @@
+## Removing Chumpy objects
+
+In a Python 2 virtual environment with [Chumpy](https://github.com/mattloper/chumpy) installed run the following to remove any Chumpy objects from the model data:
+
+```bash
+python tools/clean_ch.py --input-models path-to-models/*.pkl --output-folder output-folder
+```
+
+## Merging SMPL-H and MANO parameters
+
+In order to use the given PyTorch SMPL-H module we first need to merge the SMPL-H and MANO parameters in a single file. After agreeing to the license and downloading the models, run the following command:
+
+```bash
+python tools/merge_smplh_mano.py --smplh-fn SMPLH_FOLDER/SMPLH_GENDER.pkl \
+ --mano-left-fn MANO_FOLDER/MANO_LEFT.pkl \
+ --mano-right-fn MANO_FOLDER/MANO_RIGHT.pkl \
+ --output-folder OUTPUT_FOLDER
+```
+
+where SMPLH_FOLDER is the folder with the SMPL-H files and MANO_FOLDER the one for the MANO files.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..098b529b7f169758710ab788be94fe5d83e51256
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/__init__.py
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems and the Max Planck Institute for Biological
+# Cybernetics. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+import clean_ch
+import merge_smplh_mano
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/clean_ch.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/clean_ch.py
new file mode 100644
index 0000000000000000000000000000000000000000..56874b374c5d25aeb4ace0aefb3570bd7b891c22
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/clean_ch.py
@@ -0,0 +1,68 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems and the Max Planck Institute for Biological
+# Cybernetics. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from __future__ import print_function
+from __future__ import absolute_import
+from __future__ import division
+
+import argparse
+import os
+import os.path as osp
+
+import pickle
+
+from tqdm import tqdm
+import numpy as np
+
+
+def clean_fn(fn, output_folder='output'):
+ with open(fn, 'rb') as body_file:
+ body_data = pickle.load(body_file)
+
+ output_dict = {}
+ for key, data in body_data.iteritems():
+ if 'chumpy' in str(type(data)):
+ output_dict[key] = np.array(data)
+ else:
+ output_dict[key] = data
+
+ out_fn = osp.split(fn)[1]
+
+ out_path = osp.join(output_folder, out_fn)
+ with open(out_path, 'wb') as out_file:
+ pickle.dump(output_dict, out_file)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--input-models', dest='input_models', nargs='+',
+ required=True, type=str,
+ help='The path to the model that will be processed')
+ parser.add_argument('--output-folder', dest='output_folder',
+ required=True, type=str,
+ help='The path to the output folder')
+
+ args = parser.parse_args()
+
+ input_models = args.input_models
+ output_folder = args.output_folder
+ if not osp.exists(output_folder):
+ print('Creating directory: {}'.format(output_folder))
+ os.makedirs(output_folder)
+
+ for input_model in input_models:
+ clean_fn(input_model, output_folder=output_folder)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/merge_smplh_mano.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/merge_smplh_mano.py
new file mode 100644
index 0000000000000000000000000000000000000000..eab9d1ea60c224cf3785bd90dc542569ad81cd78
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/smplx/tools/merge_smplh_mano.py
@@ -0,0 +1,89 @@
+# -*- coding: utf-8 -*-
+
+# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
+# holder of all proprietary rights on this computer program.
+# You can only use this computer program if you have closed
+# a license agreement with MPG or you get the right to use the computer
+# program from someone who is authorized to grant you that right.
+# Any use of the computer program without a valid license is prohibited and
+# liable to prosecution.
+#
+# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
+# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
+# for Intelligent Systems and the Max Planck Institute for Biological
+# Cybernetics. All rights reserved.
+#
+# Contact: ps-license@tuebingen.mpg.de
+
+from __future__ import print_function
+
+import os
+import os.path as osp
+import pickle
+
+import argparse
+
+import numpy as np
+
+
+def merge_models(smplh_fn, mano_left_fn, mano_right_fn,
+ output_folder='output'):
+
+ with open(smplh_fn, 'rb') as body_file:
+ body_data = pickle.load(body_file)
+
+ with open(mano_left_fn, 'rb') as lhand_file:
+ lhand_data = pickle.load(lhand_file)
+
+ with open(mano_right_fn, 'rb') as rhand_file:
+ rhand_data = pickle.load(rhand_file)
+
+ out_fn = osp.split(smplh_fn)[1]
+
+ output_data = body_data.copy()
+ output_data['hands_componentsl'] = lhand_data['hands_components']
+ output_data['hands_componentsr'] = rhand_data['hands_components']
+
+ output_data['hands_coeffsl'] = lhand_data['hands_coeffs']
+ output_data['hands_coeffsr'] = rhand_data['hands_coeffs']
+
+ output_data['hands_meanl'] = lhand_data['hands_mean']
+ output_data['hands_meanr'] = rhand_data['hands_mean']
+
+ for key, data in output_data.iteritems():
+ if 'chumpy' in str(type(data)):
+ output_data[key] = np.array(data)
+ else:
+ output_data[key] = data
+
+ out_path = osp.join(output_folder, out_fn)
+ print(out_path)
+ print('Saving to {}'.format(out_path))
+ with open(out_path, 'wb') as output_file:
+ pickle.dump(output_data, output_file)
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--smplh-fn', dest='smplh_fn', required=True,
+ type=str, help='The path to the SMPLH model')
+ parser.add_argument('--mano-left-fn', dest='mano_left_fn', required=True,
+ type=str, help='The path to the left hand MANO model')
+ parser.add_argument('--mano-right-fn', dest='mano_right_fn', required=True,
+ type=str, help='The path to the right hand MANO model')
+ parser.add_argument('--output-folder', dest='output_folder',
+ required=True, type=str,
+ help='The path to the output folder')
+
+ args = parser.parse_args()
+
+ smplh_fn = args.smplh_fn
+ mano_left_fn = args.mano_left_fn
+ mano_right_fn = args.mano_right_fn
+ output_folder = args.output_folder
+
+ if not osp.exists(output_folder):
+ print('Creating directory: {}'.format(output_folder))
+ os.makedirs(output_folder)
+
+ merge_models(smplh_fn, mano_left_fn, mano_right_fn, output_folder)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/transforms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f2c05a257f60ed1e7b66fc4209562a59094222c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/transforms.py
@@ -0,0 +1,160 @@
+import torch
+import numpy as np
+import scipy
+from config import cfg
+from torch.nn import functional as F
+from utils.geometry import rotation_matrix_to_angle_axis
+
+def cam2pixel(cam_coord, f, c):
+ x = cam_coord[:,0] / cam_coord[:,2] * f[0] + c[0]
+ y = cam_coord[:,1] / cam_coord[:,2] * f[1] + c[1]
+ z = cam_coord[:,2]
+ return np.stack((x,y,z),1)
+
+def pixel2cam(pixel_coord, f, c):
+ x = (pixel_coord[:,0] - c[0]) / f[0] * pixel_coord[:,2]
+ y = (pixel_coord[:,1] - c[1]) / f[1] * pixel_coord[:,2]
+ z = pixel_coord[:,2]
+ return np.stack((x,y,z),1)
+
+def world2cam(world_coord, R, t):
+ cam_coord = np.dot(R, world_coord.transpose(1,0)).transpose(1,0) + t.reshape(1,3)
+ return cam_coord
+
+def cam2world(cam_coord, R, t):
+ world_coord = np.dot(np.linalg.inv(R), (cam_coord - t.reshape(1,3)).transpose(1,0)).transpose(1,0)
+ return world_coord
+
+def rigid_transform_3D(A, B):
+ n, dim = A.shape
+ centroid_A = np.mean(A, axis = 0)
+ centroid_B = np.mean(B, axis = 0)
+ H = np.dot(np.transpose(A - centroid_A), B - centroid_B) / n
+ U, s, V = np.linalg.svd(H)
+ R = np.dot(np.transpose(V), np.transpose(U))
+ if np.linalg.det(R) < 0:
+ s[-1] = -s[-1]
+ V[2] = -V[2]
+ R = np.dot(np.transpose(V), np.transpose(U))
+
+ varP = np.var(A, axis=0).sum()
+ c = 1/varP * np.sum(s)
+
+ t = -np.dot(c*R, np.transpose(centroid_A)) + np.transpose(centroid_B)
+ return c, R, t
+
+def rigid_align(A, B):
+ c, R, t = rigid_transform_3D(A, B)
+ A2 = np.transpose(np.dot(c*R, np.transpose(A))) + t
+ return A2
+
+def transform_joint_to_other_db(src_joint, src_name, dst_name):
+ src_joint_num = len(src_name)
+ dst_joint_num = len(dst_name)
+
+ new_joint = np.zeros(((dst_joint_num,) + src_joint.shape[1:]), dtype=np.float32)
+ for src_idx in range(len(src_name)):
+ name = src_name[src_idx]
+ if name in dst_name:
+ dst_idx = dst_name.index(name)
+ new_joint[dst_idx] = src_joint[src_idx]
+
+ return new_joint
+
+def rot6d_to_axis_angle(x):
+ batch_size = x.shape[0]
+
+ x = x.view(-1,3,2)
+ a1 = x[:, :, 0]
+ a2 = x[:, :, 1]
+ b1 = F.normalize(a1)
+ b2 = F.normalize(a2 - torch.einsum('bi,bi->b', b1, a2).unsqueeze(-1) * b1)
+ b3 = torch.cross(b1, b2)
+ rot_mat = torch.stack((b1, b2, b3), dim=-1) # 3x3 rotation matrix
+
+ rot_mat = torch.cat([rot_mat,torch.zeros((batch_size,3,1)).cuda().float()],2) # 3x4 rotation matrix
+ axis_angle = rotation_matrix_to_angle_axis(rot_mat).reshape(-1,3) # axis-angle
+ axis_angle[torch.isnan(axis_angle)] = 0.0
+ return axis_angle
+
+def sample_joint_features(img_feat, joint_xy):
+ height, width = img_feat.shape[2:]
+ x = joint_xy[:,:,0] / (width-1) * 2 - 1
+ y = joint_xy[:,:,1] / (height-1) * 2 - 1
+ grid = torch.stack((x,y),2)[:,:,None,:]
+ img_feat = F.grid_sample(img_feat, grid, align_corners=True)[:,:,:,0] # batch_size, channel_dim, joint_num
+ img_feat = img_feat.permute(0,2,1).contiguous() # batch_size, joint_num, channel_dim
+ return img_feat
+
+
+def soft_argmax_2d(heatmap2d):
+ batch_size = heatmap2d.shape[0]
+ height, width = heatmap2d.shape[2:]
+ heatmap2d = heatmap2d.reshape((batch_size, -1, height*width))
+ heatmap2d = F.softmax(heatmap2d, 2)
+ heatmap2d = heatmap2d.reshape((batch_size, -1, height, width))
+
+ accu_x = heatmap2d.sum(dim=(2))
+ accu_y = heatmap2d.sum(dim=(3))
+
+ accu_x = accu_x * torch.arange(width).float().cuda()[None,None,:]
+ accu_y = accu_y * torch.arange(height).float().cuda()[None,None,:]
+
+ accu_x = accu_x.sum(dim=2, keepdim=True)
+ accu_y = accu_y.sum(dim=2, keepdim=True)
+
+ coord_out = torch.cat((accu_x, accu_y), dim=2)
+ return coord_out
+
+def soft_argmax_3d(heatmap3d):
+ batch_size = heatmap3d.shape[0]
+ depth, height, width = heatmap3d.shape[2:]
+ heatmap3d = heatmap3d.reshape((batch_size, -1, depth*height*width))
+ heatmap3d = F.softmax(heatmap3d, 2)
+ heatmap3d = heatmap3d.reshape((batch_size, -1, depth, height, width))
+
+ accu_x = heatmap3d.sum(dim=(2,3))
+ accu_y = heatmap3d.sum(dim=(2,4))
+ accu_z = heatmap3d.sum(dim=(3,4))
+
+ accu_x = accu_x * torch.arange(width).float().cuda()[None,None,:]
+ accu_y = accu_y * torch.arange(height).float().cuda()[None,None,:]
+ accu_z = accu_z * torch.arange(depth).float().cuda()[None,None,:]
+
+ accu_x = accu_x.sum(dim=2, keepdim=True)
+ accu_y = accu_y.sum(dim=2, keepdim=True)
+ accu_z = accu_z.sum(dim=2, keepdim=True)
+
+ coord_out = torch.cat((accu_x, accu_y, accu_z), dim=2)
+ return coord_out
+
+def restore_bbox(bbox_center, bbox_size, aspect_ratio, extension_ratio):
+ bbox = bbox_center.view(-1,1,2) + torch.cat((-bbox_size.view(-1,1,2)/2., bbox_size.view(-1,1,2)/2.),1) # xyxy in (cfg.output_hm_shape[2], cfg.output_hm_shape[1]) space
+ bbox[:,:,0] = bbox[:,:,0] / cfg.output_hm_shape[2] * cfg.input_body_shape[1]
+ bbox[:,:,1] = bbox[:,:,1] / cfg.output_hm_shape[1] * cfg.input_body_shape[0]
+ bbox = bbox.view(-1,4)
+
+ # xyxy -> xywh
+ bbox[:,2] = bbox[:,2] - bbox[:,0]
+ bbox[:,3] = bbox[:,3] - bbox[:,1]
+
+ # aspect ratio preserving bbox
+ w = bbox[:,2]
+ h = bbox[:,3]
+ c_x = bbox[:,0] + w/2.
+ c_y = bbox[:,1] + h/2.
+
+ mask1 = w > (aspect_ratio * h)
+ mask2 = w < (aspect_ratio * h)
+ h[mask1] = w[mask1] / aspect_ratio
+ w[mask2] = h[mask2] * aspect_ratio
+
+ bbox[:,2] = w*extension_ratio
+ bbox[:,3] = h*extension_ratio
+ bbox[:,0] = c_x - bbox[:,2]/2.
+ bbox[:,1] = c_y - bbox[:,3]/2.
+
+ # xywh -> xyxy
+ bbox[:,2] = bbox[:,2] + bbox[:,0]
+ bbox[:,3] = bbox[:,3] + bbox[:,1]
+ return bbox
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/vis.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/vis.py
new file mode 100644
index 0000000000000000000000000000000000000000..054f47800dc0f38636b6ecd4a6e9680bab20958e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded-sam-osx/utils/vis.py
@@ -0,0 +1,175 @@
+import os
+import cv2
+import numpy as np
+from mpl_toolkits.mplot3d import Axes3D
+import matplotlib.pyplot as plt
+import matplotlib as mpl
+import os
+
+os.environ["PYOPENGL_PLATFORM"] = "egl"
+import pyrender
+import trimesh
+from config import cfg
+
+
+def vis_keypoints_with_skeleton(img, kps, kps_lines, kp_thresh=0.4, alpha=1):
+ # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
+ cmap = plt.get_cmap('rainbow')
+ colors = [cmap(i) for i in np.linspace(0, 1, len(kps_lines) + 2)]
+ colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
+
+ # Perform the drawing on a copy of the image, to allow for blending.
+ kp_mask = np.copy(img)
+
+ # Draw the keypoints.
+ for l in range(len(kps_lines)):
+ i1 = kps_lines[l][0]
+ i2 = kps_lines[l][1]
+ p1 = kps[0, i1].astype(np.int32), kps[1, i1].astype(np.int32)
+ p2 = kps[0, i2].astype(np.int32), kps[1, i2].astype(np.int32)
+ if kps[2, i1] > kp_thresh and kps[2, i2] > kp_thresh:
+ cv2.line(
+ kp_mask, p1, p2,
+ color=colors[l], thickness=2, lineType=cv2.LINE_AA)
+ if kps[2, i1] > kp_thresh:
+ cv2.circle(
+ kp_mask, p1,
+ radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)
+ if kps[2, i2] > kp_thresh:
+ cv2.circle(
+ kp_mask, p2,
+ radius=3, color=colors[l], thickness=-1, lineType=cv2.LINE_AA)
+
+ # Blend the keypoints.
+ return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)
+
+
+def vis_keypoints(img, kps, alpha=1):
+ # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
+ cmap = plt.get_cmap('rainbow')
+ colors = [cmap(i) for i in np.linspace(0, 1, len(kps) + 2)]
+ colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
+
+ # Perform the drawing on a copy of the image, to allow for blending.
+ kp_mask = np.copy(img)
+
+ # Draw the keypoints.
+ for i in range(len(kps)):
+ p = kps[i][0].astype(np.int32), kps[i][1].astype(np.int32)
+ cv2.circle(kp_mask, p, radius=3, color=colors[i], thickness=-1, lineType=cv2.LINE_AA)
+
+ # Blend the keypoints.
+ return cv2.addWeighted(img, 1.0 - alpha, kp_mask, alpha, 0)
+
+
+def vis_mesh(img, mesh_vertex, alpha=0.5):
+ # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
+ cmap = plt.get_cmap('rainbow')
+ colors = [cmap(i) for i in np.linspace(0, 1, len(mesh_vertex))]
+ colors = [(c[2] * 255, c[1] * 255, c[0] * 255) for c in colors]
+
+ # Perform the drawing on a copy of the image, to allow for blending.
+ mask = np.copy(img)
+
+ # Draw the mesh
+ for i in range(len(mesh_vertex)):
+ p = mesh_vertex[i][0].astype(np.int32), mesh_vertex[i][1].astype(np.int32)
+ cv2.circle(mask, p, radius=3, color=colors[i], thickness=-1, lineType=cv2.LINE_AA)
+
+ # Blend the keypoints.
+ return cv2.addWeighted(img, 1.0 - alpha, mask, alpha, 0)
+
+
+def vis_3d_skeleton(kpt_3d, kpt_3d_vis, kps_lines, filename=None):
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection='3d')
+
+ # Convert from plt 0-1 RGBA colors to 0-255 BGR colors for opencv.
+ cmap = plt.get_cmap('rainbow')
+ colors = [cmap(i) for i in np.linspace(0, 1, len(kps_lines) + 2)]
+ colors = [np.array((c[2], c[1], c[0])) for c in colors]
+
+ for l in range(len(kps_lines)):
+ i1 = kps_lines[l][0]
+ i2 = kps_lines[l][1]
+ x = np.array([kpt_3d[i1, 0], kpt_3d[i2, 0]])
+ y = np.array([kpt_3d[i1, 1], kpt_3d[i2, 1]])
+ z = np.array([kpt_3d[i1, 2], kpt_3d[i2, 2]])
+
+ if kpt_3d_vis[i1, 0] > 0 and kpt_3d_vis[i2, 0] > 0:
+ ax.plot(x, z, -y, c=colors[l], linewidth=2)
+ if kpt_3d_vis[i1, 0] > 0:
+ ax.scatter(kpt_3d[i1, 0], kpt_3d[i1, 2], -kpt_3d[i1, 1], c=colors[l], marker='o')
+ if kpt_3d_vis[i2, 0] > 0:
+ ax.scatter(kpt_3d[i2, 0], kpt_3d[i2, 2], -kpt_3d[i2, 1], c=colors[l], marker='o')
+
+ x_r = np.array([0, cfg.input_shape[1]], dtype=np.float32)
+ y_r = np.array([0, cfg.input_shape[0]], dtype=np.float32)
+ z_r = np.array([0, 1], dtype=np.float32)
+
+ if filename is None:
+ ax.set_title('3D vis')
+ else:
+ ax.set_title(filename)
+
+ ax.set_xlabel('X Label')
+ ax.set_ylabel('Z Label')
+ ax.set_zlabel('Y Label')
+ ax.legend()
+
+ plt.show()
+ cv2.waitKey(0)
+
+
+def save_obj(v, f, file_name='output.obj'):
+ obj_file = open(file_name, 'w')
+ for i in range(len(v)):
+ obj_file.write('v ' + str(v[i][0]) + ' ' + str(v[i][1]) + ' ' + str(v[i][2]) + '\n')
+ for i in range(len(f)):
+ obj_file.write('f ' + str(f[i][0] + 1) + '/' + str(f[i][0] + 1) + ' ' + str(f[i][1] + 1) + '/' + str(
+ f[i][1] + 1) + ' ' + str(f[i][2] + 1) + '/' + str(f[i][2] + 1) + '\n')
+ obj_file.close()
+
+
+def render_mesh(img, mesh, face, cam_param, mesh_save_path=None):
+ # mesh
+ mesh = trimesh.Trimesh(mesh, face)
+ rot = trimesh.transformations.rotation_matrix(
+ np.radians(180), [1, 0, 0])
+ mesh.apply_transform(rot)
+ material = pyrender.MetallicRoughnessMaterial(metallicFactor=0.0, alphaMode='OPAQUE',
+ baseColorFactor=(1.0, 1.0, 0.9, 1.0))
+ mesh = pyrender.Mesh.from_trimesh(mesh, material=material, smooth=True)
+
+ scene = pyrender.Scene(ambient_light=(0.3, 0.3, 0.3))
+ scene.add(mesh, 'mesh')
+
+ focal, princpt = cam_param['focal'], cam_param['princpt']
+ camera = pyrender.IntrinsicsCamera(fx=focal[0], fy=focal[1], cx=princpt[0], cy=princpt[1])
+ scene.add(camera)
+
+ # renderer
+ renderer = pyrender.OffscreenRenderer(viewport_width=img.shape[1], viewport_height=img.shape[0], point_size=1.0)
+
+ # light
+ light = pyrender.DirectionalLight(color=[1.0, 1.0, 1.0], intensity=0.8)
+ light_pose = np.eye(4)
+ light_pose[:3, 3] = np.array([0, -1, 1])
+ scene.add(light, pose=light_pose)
+ light_pose[:3, 3] = np.array([0, 1, 1])
+ scene.add(light, pose=light_pose)
+ light_pose[:3, 3] = np.array([1, 1, 2])
+ scene.add(light, pose=light_pose)
+
+ # render
+ flags = (pyrender.RenderFlags.RGBA |
+ pyrender.RenderFlags.SKIP_CULL_FACES)
+ rgb, depth = renderer.render(scene, flags=flags)
+ renderer.delete()
+ rgb = rgb[:, :, :3].astype(np.float32)
+ valid_mask = (depth > 0)[:, :, None]
+
+ # save to image
+ img = rgb * valid_mask + img * (1 - valid_mask)
+ img_black_bg = rgb * valid_mask
+ return img, img_black_bg
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded_sam_demo.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded_sam_demo.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a8d3db002726914e7b9cebb954b344933277299
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/grounded_sam_demo.py
@@ -0,0 +1,226 @@
+import argparse
+import os
+import copy
+
+import numpy as np
+import json
+import torch
+from PIL import Image, ImageDraw, ImageFont
+
+# Grounding DINO
+import GroundingDINO.groundingdino.datasets.transforms as T
+from GroundingDINO.groundingdino.models import build_model
+from GroundingDINO.groundingdino.util import box_ops
+from GroundingDINO.groundingdino.util.slconfig import SLConfig
+from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
+
+# segment anything
+from segment_anything import build_sam, SamPredictor
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+def load_image(image_path):
+ # load image
+ image_pil = Image.open(image_path).convert("RGB") # load image
+
+ transform = T.Compose(
+ [
+ T.RandomResize([800], max_size=1333),
+ T.ToTensor(),
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
+ ]
+ )
+ image, _ = transform(image_pil, None) # 3, h, w
+ return image_pil, image
+
+
+def load_model(model_config_path, model_checkpoint_path, device):
+ args = SLConfig.fromfile(model_config_path)
+ args.device = device
+ model = build_model(args)
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
+ load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
+ print(load_res)
+ _ = model.eval()
+ return model
+
+
+def get_grounding_output(model, image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
+ caption = caption.lower()
+ caption = caption.strip()
+ if not caption.endswith("."):
+ caption = caption + "."
+ model = model.to(device)
+ image = image.to(device)
+ with torch.no_grad():
+ outputs = model(image[None], captions=[caption])
+ logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
+ boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
+ logits.shape[0]
+
+ # filter output
+ logits_filt = logits.clone()
+ boxes_filt = boxes.clone()
+ filt_mask = logits_filt.max(dim=1)[0] > box_threshold
+ logits_filt = logits_filt[filt_mask] # num_filt, 256
+ boxes_filt = boxes_filt[filt_mask] # num_filt, 4
+ logits_filt.shape[0]
+
+ # get phrase
+ tokenlizer = model.tokenizer
+ tokenized = tokenlizer(caption)
+ # build pred
+ pred_phrases = []
+ for logit, box in zip(logits_filt, boxes_filt):
+ pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
+ if with_logits:
+ pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
+ else:
+ pred_phrases.append(pred_phrase)
+
+ return boxes_filt, pred_phrases
+
+def show_mask(mask, ax, random_color=False):
+ if random_color:
+ color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
+ else:
+ color = np.array([30/255, 144/255, 255/255, 0.6])
+ h, w = mask.shape[-2:]
+ mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
+ ax.imshow(mask_image)
+
+
+def show_box(box, ax, label):
+ x0, y0 = box[0], box[1]
+ w, h = box[2] - box[0], box[3] - box[1]
+ ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
+ ax.text(x0, y0, label)
+
+
+def save_mask_data(output_dir, filename, mask_list, box_list, label_list):
+ value = 0 # 0 for background
+
+ mask_img = torch.zeros(mask_list.shape[-2:])
+ for idx, mask in enumerate(mask_list):
+ mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
+ plt.figure(figsize=(10, 10))
+ plt.imshow(mask_img.numpy())
+ plt.axis('off')
+ plt.savefig(os.path.join(output_dir, filename + '.mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)
+
+ mask = mask_img.numpy().astype(np.uint8)
+ fname = os.path.join(output_dir, filename + '.mask.png')
+ Image.fromarray(mask).save(fname)
+
+ json_data = [{
+ 'value': value,
+ 'label': 'background'
+ }]
+ for label, box in zip(label_list, box_list):
+ value += 1
+ name, logit = label.split('(')
+ logit = logit[:-1] # the last is ')'
+ json_data.append({
+ 'value': value,
+ 'label': name,
+ 'logit': float(logit),
+ 'box': box.numpy().tolist(),
+ })
+ with open(os.path.join(output_dir, filename + '.mask.json'), 'w') as f:
+ json.dump(json_data, f)
+
+
+if __name__ == "__main__":
+
+ parser = argparse.ArgumentParser("Grounded-Segment-Anything Demo", add_help=True)
+ parser.add_argument("--config", type=str, required=True, help="path to config file")
+ parser.add_argument(
+ "--grounded_checkpoint", type=str, required=True, help="path to checkpoint file"
+ )
+ parser.add_argument(
+ "--sam_checkpoint", type=str, required=True, help="path to checkpoint file"
+ )
+ parser.add_argument("--input_image", type=str, required=True, help="path to image file")
+ parser.add_argument("--text_prompt", type=str, required=True, help="text prompt")
+ parser.add_argument(
+ "--output_dir", "-o", type=str, default="outputs", help="output directory"
+ )
+
+ parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold")
+ parser.add_argument("--text_threshold", type=float, default=0.25, help="text threshold")
+
+ parser.add_argument("--device", type=str, default="cpu", help="running on cpu only!, default=False")
+ args = parser.parse_args()
+
+ # cfg
+ config_file = args.config # change the path of the model config file
+ grounded_checkpoint = args.grounded_checkpoint # change the path of the model
+ sam_checkpoint = args.sam_checkpoint
+ image_path = args.input_image
+ text_prompt = args.text_prompt
+ # output_dir = args.output_dir
+
+ # Split the file path into a directory path and a filename
+ dir_path, filename = os.path.split(image_path)
+ # Add the new folder to the directory path
+ output_dir = os.path.join(dir_path, 'grounded_sam')
+ box_threshold = args.box_threshold
+ text_threshold = args.text_threshold
+ device = args.device
+
+ # make dir
+ os.makedirs(output_dir, exist_ok=True)
+ # load image
+ image_pil, image = load_image(image_path)
+ # load model
+ model = load_model(config_file, grounded_checkpoint, device=device)
+
+ # visualize raw image
+ # image_pil.save(os.path.join(output_dir, "raw_image.jpg"))
+
+ # run grounding dino model
+ boxes_filt, pred_phrases = get_grounding_output(
+ model, image, text_prompt, box_threshold, text_threshold, device=device
+ )
+
+ # initialize SAM
+ predictor = SamPredictor(build_sam(checkpoint=sam_checkpoint).to(device))
+ image = cv2.imread(image_path)
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+ predictor.set_image(image)
+
+ size = image_pil.size
+ H, W = size[1], size[0]
+ for i in range(boxes_filt.size(0)):
+ boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
+ boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
+ boxes_filt[i][2:] += boxes_filt[i][:2]
+
+ boxes_filt = boxes_filt.cpu()
+ transformed_boxes = predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(device)
+
+ masks, _, _ = predictor.predict_torch(
+ point_coords = None,
+ point_labels = None,
+ boxes = transformed_boxes.to(device),
+ multimask_output = False,
+ )
+
+ # draw output image
+ # plt.figure(figsize=(10, 10))
+ # plt.imshow(image)
+ # for mask in masks:
+ # show_mask(mask.cpu().numpy(), plt.gca(), random_color=True)
+ # for box, label in zip(boxes_filt, pred_phrases):
+ # show_box(box.numpy(), plt.gca(), label)
+
+ # plt.axis('off')
+ # plt.savefig(
+ # os.path.join(output_dir, filename + "grounded_sam_output.jpg"),
+ # bbox_inches="tight", dpi=300, pad_inches=0.0
+ # )
+
+ save_mask_data(output_dir, filename, masks, boxes_filt, pred_phrases)
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/kevin.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/kevin.py
new file mode 100644
index 0000000000000000000000000000000000000000..6d142f3631a0a1c712d8670fa64c3a5611e6b6b9
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/kevin.py
@@ -0,0 +1,5 @@
+import sys
+import os
+pythonpath = os.path.abspath(
+ os.path.dirname(__file__))
+print(pythonpath)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/requirements.txt b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..308bcc660251a0e3edde9b27c09661f3a8d9cbde
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/requirements.txt
@@ -0,0 +1,21 @@
+addict
+diffusers
+gradio
+huggingface_hub
+matplotlib
+numpy
+onnxruntime
+opencv-python
+Pillow
+pycocotools
+PyYAML
+requests
+setuptools
+supervision
+termcolor
+timm
+torch
+torchvision
+transformers
+yapf
+tqdm
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run.py
new file mode 100644
index 0000000000000000000000000000000000000000..b08d6fa01f11ff0e16da4c82935a72beafe60ba7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run.py
@@ -0,0 +1,241 @@
+import argparse
+import os, sys
+# Add the current directory to sys.path
+pythonpath = os.path.abspath(os.path.dirname(__file__))
+sys.path.append(pythonpath)
+print(pythonpath)
+import copy
+import numpy as np
+import json
+import torch
+from PIL import Image, ImageDraw, ImageFont
+
+# Grounding DINO
+import GroundingDINO.groundingdino.datasets.transforms as T
+from GroundingDINO.groundingdino.models import build_model
+from GroundingDINO.groundingdino.util import box_ops
+from GroundingDINO.groundingdino.util.slconfig import SLConfig
+from GroundingDINO.groundingdino.util.utils import clean_state_dict, get_phrases_from_posmap
+
+# segment anything
+from segment_anything import build_sam, SamPredictor
+import cv2
+import numpy as np
+import matplotlib.pyplot as plt
+from tqdm import tqdm
+
+def load_image(image_path):
+ # load image
+ image_pil = Image.open(image_path).convert("RGB") # load image
+
+ transform = T.Compose(
+ [
+ T.RandomResize([800], max_size=1333),
+ T.ToTensor(),
+ T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
+ ]
+ )
+ image, _ = transform(image_pil, None) # 3, h, w
+ return image_pil, image
+
+
+def load_model(model_config_path, model_checkpoint_path, device):
+ args = SLConfig.fromfile(model_config_path)
+ args.device = device
+ model = build_model(args)
+ checkpoint = torch.load(model_checkpoint_path, map_location="cpu")
+ load_res = model.load_state_dict(clean_state_dict(checkpoint["model"]), strict=False)
+ print(load_res)
+ _ = model.eval()
+ return model
+
+
+def get_grounding_output(model, image, caption, box_threshold, text_threshold, with_logits=True, device="cpu"):
+ caption = caption.lower()
+ caption = caption.strip()
+ if not caption.endswith("."):
+ caption = caption + "."
+ model = model.to(device)
+ image = image.to(device)
+ with torch.no_grad():
+ outputs = model(image[None], captions=[caption])
+ logits = outputs["pred_logits"].cpu().sigmoid()[0] # (nq, 256)
+ boxes = outputs["pred_boxes"].cpu()[0] # (nq, 4)
+ logits.shape[0]
+
+ # filter output
+ logits_filt = logits.clone()
+ boxes_filt = boxes.clone()
+ filt_mask = logits_filt.max(dim=1)[0] > box_threshold
+ logits_filt = logits_filt[filt_mask] # num_filt, 256
+ boxes_filt = boxes_filt[filt_mask] # num_filt, 4
+ logits_filt.shape[0]
+
+ # get phrase
+ tokenlizer = model.tokenizer
+ tokenized = tokenlizer(caption)
+ # build pred
+ pred_phrases = []
+ for logit, box in zip(logits_filt, boxes_filt):
+ pred_phrase = get_phrases_from_posmap(logit > text_threshold, tokenized, tokenlizer)
+ if with_logits:
+ pred_phrases.append(pred_phrase + f"({str(logit.max().item())[:4]})")
+ else:
+ pred_phrases.append(pred_phrase)
+
+ return boxes_filt, pred_phrases
+
+# def show_mask(mask, ax, random_color=False):
+# if random_color:
+# color = np.concatenate([np.random.random(3), np.array([0.6])], axis=0)
+# else:
+# color = np.array([30/255, 144/255, 255/255, 0.6])
+# h, w = mask.shape[-2:]
+# mask_image = mask.reshape(h, w, 1) * color.reshape(1, 1, -1)
+# ax.imshow(mask_image)
+
+
+def show_box(box, ax, label):
+ x0, y0 = box[0], box[1]
+ w, h = box[2] - box[0], box[3] - box[1]
+ ax.add_patch(plt.Rectangle((x0, y0), w, h, edgecolor='green', facecolor=(0,0,0,0), lw=2))
+ ax.text(x0, y0, label)
+
+
+def save_mask_data(json_out_folder_name, image_out_folder_name, numpy_out_folder_name, filename, mask_list, box_list, label_list):
+ value = 0 # 0 for background
+
+ mask_img = torch.zeros(mask_list.shape[-2:])
+ for idx, mask in enumerate(mask_list):
+ mask_img[mask.cpu().numpy()[0] == True] = value + idx + 1
+
+ # np.save(os.path.join(numpy_out_folder_name, filename + '.mask.npy'), mask_img.numpy()) # too slow for I/O
+
+ plt.figure(figsize=(10, 10))
+ plt.imshow(mask_img.numpy())
+ plt.axis('off')
+ plt.savefig(os.path.join(image_out_folder_name, filename + '.mask.jpg'), bbox_inches="tight", dpi=300, pad_inches=0.0)
+
+ mask = mask_img.numpy().astype(np.uint8)
+ fname = os.path.join(image_out_folder_name, filename + '.mask.png')
+ Image.fromarray(mask).save(fname)
+
+ json_data = [{
+ 'value': value,
+ 'label': 'background'
+ }]
+ for label, box in zip(label_list, box_list):
+ value += 1
+ name, logit = label.split('(')
+ logit = logit[:-1] # the last is ')'
+ json_data.append({
+ 'value': value,
+ 'label': name,
+ 'logit': float(logit),
+ 'box': box.numpy().tolist(),
+ })
+ with open(os.path.join(json_out_folder_name, filename + '.mask.json'), 'w') as f:
+ json.dump(json_data, f)
+
+
+def get_filelist(todo_list, i):
+ folder_path = todo_list[i]
+ # Get a list of all files in the folder
+ files = os.listdir(folder_path)
+ # Filter the list to only include image files
+ image_files = ['{}/{}'.format(folder_path,file) for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ return folder_path, image_files
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser("Grounded-Segment-Anything Demo", add_help=True)
+ parser.add_argument("--config", type=str, default="./annotator/grounded-sam/GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py", help="path to config file")
+ parser.add_argument(
+ "--grounded_checkpoint", type=str, default="/blob/keli/debug_output/vid_syn/grounded_sam/groundingdino_swint_ogc.pth", help="path to checkpoint file"
+ )
+ parser.add_argument(
+ "--sam_checkpoint", type=str, default="/blob/keli/debug_output/vid_syn/grounded_sam/sam_vit_h_4b8939.pth", help="path to checkpoint file"
+ )
+ parser.add_argument(
+ "--partition", type=int, required=True
+ )
+ parser.add_argument("--box_threshold", type=float, default=0.3, help="box threshold")
+ parser.add_argument("--text_threshold", type=float, default=0.25, help="text threshold")
+ parser.add_argument("--device", type=str, default="cuda", help="running on cpu only!, default=False")
+ parser.add_argument("--text_prompt", type=str, default="person")
+ parser.add_argument("--todo_folder_list", type=str, default="tiktok_scale_smalllist.txt")
+ args = parser.parse_args()
+
+ # cfg
+ config_file = args.config # change the path of the model config file
+ grounded_checkpoint = args.grounded_checkpoint # change the path of the model
+ sam_checkpoint = args.sam_checkpoint
+ text_prompt = args.text_prompt
+ box_threshold = args.box_threshold
+ text_threshold = args.text_threshold
+ device = args.device
+
+ # load model
+ model = load_model(config_file, grounded_checkpoint, device=device)
+
+ todo_list = []
+ with open(args.todo_folder_list, 'r') as file:
+ for line in file:
+ todo_list.append(line.strip())
+
+
+ for index in range(args.partition, (args.partition+10)):
+ print('processing video ID: {:05d}'.format(index))
+ try:
+ folder_path, img_list = get_filelist(todo_list, index)
+
+ json_out_folder_name = '{}/groundsam_json'.format(folder_path)
+ os.makedirs(json_out_folder_name, exist_ok=True)
+ image_out_folder_name = '{}/groundsam_vis'.format(folder_path)
+ os.makedirs(image_out_folder_name, exist_ok=True)
+ numpy_out_folder_name = '{}/groundsam_npy'.format(folder_path)
+ os.makedirs(numpy_out_folder_name, exist_ok=True)
+
+ for item in tqdm(img_list):
+ image_path = item
+ # Split the file path into a directory path and a filename
+ dir_path, filename = os.path.split(image_path)
+ npy_out_name = os.path.join(numpy_out_folder_name, filename + '.mask.npy')
+
+ if not os.path.isfile(npy_out_name):
+ # load image
+ image_pil, image = load_image(image_path)
+
+ # run grounding dino model
+ boxes_filt, pred_phrases = get_grounding_output(
+ model, image, text_prompt, box_threshold, text_threshold, device=device
+ )
+
+ # initialize SAM
+ predictor = SamPredictor(build_sam(checkpoint=sam_checkpoint).to(device))
+ image = cv2.imread(image_path)
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+ predictor.set_image(image)
+
+ size = image_pil.size
+ H, W = size[1], size[0]
+ for i in range(boxes_filt.size(0)):
+ boxes_filt[i] = boxes_filt[i] * torch.Tensor([W, H, W, H])
+ boxes_filt[i][:2] -= boxes_filt[i][2:] / 2
+ boxes_filt[i][2:] += boxes_filt[i][:2]
+
+ boxes_filt = boxes_filt.cpu()
+ transformed_boxes = predictor.transform.apply_boxes_torch(boxes_filt, image.shape[:2]).to(device)
+
+ masks, _, _ = predictor.predict_torch(
+ point_coords = None,
+ point_labels = None,
+ boxes = transformed_boxes.to(device),
+ multimask_output = False,
+ )
+ save_mask_data(json_out_folder_name, image_out_folder_name, numpy_out_folder_name, filename, masks, boxes_filt, pred_phrases)
+ except Exception as e:
+ print(e)
+ pass
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run_local_test.sh b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run_local_test.sh
new file mode 100644
index 0000000000000000000000000000000000000000..dede9f096eb80834e9fae1e8d5e699661d80824d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/run_local_test.sh
@@ -0,0 +1,10 @@
+export CUDA_VISIBLE_DEVICES=0
+python grounded_sam_demo.py \
+ --config GroundingDINO/groundingdino/config/GroundingDINO_SwinT_OGC.py \
+ --grounded_checkpoint groundingdino_swint_ogc.pth \
+ --sam_checkpoint sam_vit_h_4b8939.pth \
+ --input_image test_image.jpg \
+ --box_threshold 0.3 \
+ --text_threshold 0.25 \
+ --text_prompt "face" \
+ --device "cpu"
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/.flake8 b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/.flake8
new file mode 100644
index 0000000000000000000000000000000000000000..6b0759587aa5756e66a13ef034c6bcdd76a885f5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/.flake8
@@ -0,0 +1,7 @@
+[flake8]
+ignore = W503, E203, E221, C901, C408, E741, C407, B017, F811, C101, EXE001, EXE002
+max-line-length = 100
+max-complexity = 18
+select = B,C,E,F,W,T4,B9
+per-file-ignores =
+ **/__init__.py:F401,F403,E402
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CODE_OF_CONDUCT.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CODE_OF_CONDUCT.md
new file mode 100644
index 0000000000000000000000000000000000000000..08b500a221857ec3f451338e80b4a9ab1173a1af
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CODE_OF_CONDUCT.md
@@ -0,0 +1,80 @@
+# Code of Conduct
+
+## Our Pledge
+
+In the interest of fostering an open and welcoming environment, we as
+contributors and maintainers pledge to make participation in our project and
+our community a harassment-free experience for everyone, regardless of age, body
+size, disability, ethnicity, sex characteristics, gender identity and expression,
+level of experience, education, socio-economic status, nationality, personal
+appearance, race, religion, or sexual identity and orientation.
+
+## Our Standards
+
+Examples of behavior that contributes to creating a positive environment
+include:
+
+* Using welcoming and inclusive language
+* Being respectful of differing viewpoints and experiences
+* Gracefully accepting constructive criticism
+* Focusing on what is best for the community
+* Showing empathy towards other community members
+
+Examples of unacceptable behavior by participants include:
+
+* The use of sexualized language or imagery and unwelcome sexual attention or
+ advances
+* Trolling, insulting/derogatory comments, and personal or political attacks
+* Public or private harassment
+* Publishing others' private information, such as a physical or electronic
+ address, without explicit permission
+* Other conduct which could reasonably be considered inappropriate in a
+ professional setting
+
+## Our Responsibilities
+
+Project maintainers are responsible for clarifying the standards of acceptable
+behavior and are expected to take appropriate and fair corrective action in
+response to any instances of unacceptable behavior.
+
+Project maintainers have the right and responsibility to remove, edit, or
+reject comments, commits, code, wiki edits, issues, and other contributions
+that are not aligned to this Code of Conduct, or to ban temporarily or
+permanently any contributor for other behaviors that they deem inappropriate,
+threatening, offensive, or harmful.
+
+## Scope
+
+This Code of Conduct applies within all project spaces, and it also applies when
+an individual is representing the project or its community in public spaces.
+Examples of representing a project or community include using an official
+project e-mail address, posting via an official social media account, or acting
+as an appointed representative at an online or offline event. Representation of
+a project may be further defined and clarified by project maintainers.
+
+This Code of Conduct also applies outside the project spaces when there is a
+reasonable belief that an individual's behavior may have a negative impact on
+the project or its community.
+
+## Enforcement
+
+Instances of abusive, harassing, or otherwise unacceptable behavior may be
+reported by contacting the project team at . All
+complaints will be reviewed and investigated and will result in a response that
+is deemed necessary and appropriate to the circumstances. The project team is
+obligated to maintain confidentiality with regard to the reporter of an incident.
+Further details of specific enforcement policies may be posted separately.
+
+Project maintainers who do not follow or enforce the Code of Conduct in good
+faith may face temporary or permanent repercussions as determined by other
+members of the project's leadership.
+
+## Attribution
+
+This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
+available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
+
+[homepage]: https://www.contributor-covenant.org
+
+For answers to common questions about this code of conduct, see
+https://www.contributor-covenant.org/faq
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CONTRIBUTING.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CONTRIBUTING.md
new file mode 100644
index 0000000000000000000000000000000000000000..263991c9496cf29ed4b99e03a9fb9a38e6bfaf86
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/CONTRIBUTING.md
@@ -0,0 +1,31 @@
+# Contributing to segment-anything
+We want to make contributing to this project as easy and transparent as
+possible.
+
+## Pull Requests
+We actively welcome your pull requests.
+
+1. Fork the repo and create your branch from `main`.
+2. If you've added code that should be tested, add tests.
+3. If you've changed APIs, update the documentation.
+4. Ensure the test suite passes.
+5. Make sure your code lints, using the `linter.sh` script in the project's root directory. Linting requires `black==23.*`, `isort==5.12.0`, `flake8`, and `mypy`.
+6. If you haven't already, complete the Contributor License Agreement ("CLA").
+
+## Contributor License Agreement ("CLA")
+In order to accept your pull request, we need you to submit a CLA. You only need
+to do this once to work on any of Facebook's open source projects.
+
+Complete your CLA here:
+
+## Issues
+We use GitHub issues to track public bugs. Please ensure your description is
+clear and has sufficient instructions to be able to reproduce the issue.
+
+Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
+disclosure of security bugs. In those cases, please go through the process
+outlined on that page and do not file a public issue.
+
+## License
+By contributing to segment-anything, you agree that your contributions will be licensed
+under the LICENSE file in the root directory of this source tree.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/LICENSE b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/README.md b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..6256d2b7f5a387988338d538df4e699eb17ba702
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/README.md
@@ -0,0 +1,107 @@
+# Segment Anything
+
+**[Meta AI Research, FAIR](https://ai.facebook.com/research/)**
+
+[Alexander Kirillov](https://alexander-kirillov.github.io/), [Eric Mintun](https://ericmintun.github.io/), [Nikhila Ravi](https://nikhilaravi.com/), [Hanzi Mao](https://hanzimao.me/), Chloe Rolland, Laura Gustafson, [Tete Xiao](https://tetexiao.com), [Spencer Whitehead](https://www.spencerwhitehead.com/), Alex Berg, Wan-Yen Lo, [Piotr Dollar](https://pdollar.github.io/), [Ross Girshick](https://www.rossgirshick.info/)
+
+[[`Paper`](https://ai.facebook.com/research/publications/segment-anything/)] [[`Project`](https://segment-anything.com/)] [[`Demo`](https://segment-anything.com/demo)] [[`Dataset`](https://segment-anything.com/dataset/index.html)] [[`Blog`](https://ai.facebook.com/blog/segment-anything-foundation-model-image-segmentation/)]
+
+
+
+The **Segment Anything Model (SAM)** produces high quality object masks from input prompts such as points or boxes, and it can be used to generate masks for all objects in an image. It has been trained on a [dataset](https://segment-anything.com/dataset/index.html) of 11 million images and 1.1 billion masks, and has strong zero-shot performance on a variety of segmentation tasks.
+
+
+
+
+
+
+## Installation
+
+The code requires `python>=3.8`, as well as `pytorch>=1.7` and `torchvision>=0.8`. Please follow the instructions [here](https://pytorch.org/get-started/locally/) to install both PyTorch and TorchVision dependencies. Installing both PyTorch and TorchVision with CUDA support is strongly recommended.
+
+Install Segment Anything:
+
+```
+pip install git+https://github.com/facebookresearch/segment-anything.git
+```
+
+or clone the repository locally and install with
+
+```
+git clone git@github.com:facebookresearch/segment-anything.git
+cd segment-anything; pip install -e .
+```
+
+The following optional dependencies are necessary for mask post-processing, saving masks in COCO format, the example notebooks, and exporting the model in ONNX format. `jupyter` is also required to run the example notebooks.
+```
+pip install opencv-python pycocotools matplotlib onnxruntime onnx
+```
+
+
+## Getting Started
+
+First download a [model checkpoint](#model-checkpoints). Then the model can be used in just a few lines to get masks from a given prompt:
+
+```
+from segment_anything import build_sam, SamPredictor
+predictor = SamPredictor(build_sam(checkpoint=""))
+predictor.set_image()
+masks, _, _ = predictor.predict()
+```
+
+or generate masks for an entire image:
+
+```
+from segment_anything import build_sam, SamAutomaticMaskGenerator
+mask_generator = SamAutomaticMaskGenerator(build_sam(checkpoint=""))
+masks = mask_generator_generate()
+```
+
+Additionally, masks can be generated for images from the command line:
+
+```
+python scripts/amg.py --checkpoint --input --output
+```
+
+See the examples notebooks on [using SAM with prompts](/notebooks/predictor_example.ipynb) and [automatically generating masks](/notebooks/automatic_mask_generator_example.ipynb) for more details.
+
+
+
+
+
+
+## ONNX Export
+
+SAM's lightweight mask decoder can be exported to ONNX format so that it can be run in any environment that supports ONNX runtime, such as in-browser as showcased in the [demo](https://segment-anything.com/demo). Export the model with
+
+```
+python scripts/export_onnx_model.py --checkpoint --output
+```
+
+See the [example notebook](https://github.com/facebookresearch/segment-anything/blob/main/notebooks/onnx_model_example.ipynb) for details on how to combine image preprocessing via SAM's backbone with mask prediction using the ONNX model. It is recommended to use the latest stable version of PyTorch for ONNX export.
+
+## Model Checkpoints
+
+Three model versions of the model are available with different backbone sizes. These models can be instantiated by running
+```
+from segment_anything import sam_model_registry
+sam = sam_model_registry[""](checkpoint="")
+```
+Click the links below to download the checkpoint for the corresponding model name. The default model in bold can also be instantiated with `build_sam`, as in the examples in [Getting Started](#getting-started).
+
+* **`default` or `vit_h`: [ViT-H SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth)**
+* `vit_l`: [ViT-L SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_l_0b3195.pth)
+* `vit_b`: [ViT-B SAM model.](https://dl.fbaipublicfiles.com/segment_anything/sam_vit_b_01ec64.pth)
+
+## License
+The model is licensed under the [Apache 2.0 license](LICENSE).
+
+## Contributing
+
+See [contributing](CONTRIBUTING.md) and the [code of conduct](CODE_OF_CONDUCT.md).
+
+## Contributors
+
+The Segment Anything project was made possible with the help of many contributors (alphabetical):
+
+Aaron Adcock, Vaibhav Aggarwal, Morteza Behrooz, Cheng-Yang Fu, Ashley Gabriel, Ahuva Goldstand, Allen Goodman, Sumanth Gurram, Jiabo Hu, Somya Jain, Devansh Kukreja, Robert Kuo, Joshua Lane, Yanghao Li, Lilian Luong, Jitendra Malik, Mallika Malhotra, William Ngan, Omkar Parkhi, Nikhil Raina, Dirk Rowe, Neil Sejoor, Vanessa Stark, Bala Varadarajan, Bram Wasti, Zachary Winstrom
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/linter.sh b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/linter.sh
new file mode 100644
index 0000000000000000000000000000000000000000..df2e17436d30e89ff1728109301599f425f1ad6b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/linter.sh
@@ -0,0 +1,32 @@
+#!/bin/bash -e
+# Copyright (c) Facebook, Inc. and its affiliates.
+
+{
+ black --version | grep -E "23\." > /dev/null
+} || {
+ echo "Linter requires 'black==23.*' !"
+ exit 1
+}
+
+ISORT_VERSION=$(isort --version-number)
+if [[ "$ISORT_VERSION" != 5.12* ]]; then
+ echo "Linter requires isort==5.12.0 !"
+ exit 1
+fi
+
+echo "Running isort ..."
+isort . --atomic
+
+echo "Running black ..."
+black -l 100 .
+
+echo "Running flake8 ..."
+if [ -x "$(command -v flake8)" ]; then
+ flake8 .
+else
+ python3 -m flake8 .
+fi
+
+echo "Running mypy..."
+
+mypy --exclude 'setup.py|notebooks' .
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/amg.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/amg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cae6ff720e5cb718045ff3f1082340968516d6a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/amg.py
@@ -0,0 +1,238 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import cv2 # type: ignore
+
+from segment_anything import SamAutomaticMaskGenerator, sam_model_registry
+
+import argparse
+import json
+import os
+from typing import Any, Dict, List
+
+parser = argparse.ArgumentParser(
+ description=(
+ "Runs automatic mask generation on an input image or directory of images, "
+ "and outputs masks as either PNGs or COCO-style RLEs. Requires open-cv, "
+ "as well as pycocotools if saving in RLE format."
+ )
+)
+
+parser.add_argument(
+ "--input",
+ type=str,
+ required=True,
+ help="Path to either a single input image or folder of images.",
+)
+
+parser.add_argument(
+ "--output",
+ type=str,
+ required=True,
+ help=(
+ "Path to the directory where masks will be output. Output will be either a folder "
+ "of PNGs per image or a single json with COCO-style masks."
+ ),
+)
+
+parser.add_argument(
+ "--model-type",
+ type=str,
+ default="default",
+ help="The type of model to load, in ['default', 'vit_l', 'vit_b']",
+)
+
+parser.add_argument(
+ "--checkpoint",
+ type=str,
+ required=True,
+ help="The path to the SAM checkpoint to use for mask generation.",
+)
+
+parser.add_argument("--device", type=str, default="cuda", help="The device to run generation on.")
+
+parser.add_argument(
+ "--convert-to-rle",
+ action="store_true",
+ help=(
+ "Save masks as COCO RLEs in a single json instead of as a folder of PNGs. "
+ "Requires pycocotools."
+ ),
+)
+
+amg_settings = parser.add_argument_group("AMG Settings")
+
+amg_settings.add_argument(
+ "--points-per-side",
+ type=int,
+ default=None,
+ help="Generate masks by sampling a grid over the image with this many points to a side.",
+)
+
+amg_settings.add_argument(
+ "--points-per-batch",
+ type=int,
+ default=None,
+ help="How many input points to process simultaneously in one batch.",
+)
+
+amg_settings.add_argument(
+ "--pred-iou-thresh",
+ type=float,
+ default=None,
+ help="Exclude masks with a predicted score from the model that is lower than this threshold.",
+)
+
+amg_settings.add_argument(
+ "--stability-score-thresh",
+ type=float,
+ default=None,
+ help="Exclude masks with a stability score lower than this threshold.",
+)
+
+amg_settings.add_argument(
+ "--stability-score-offset",
+ type=float,
+ default=None,
+ help="Larger values perturb the mask more when measuring stability score.",
+)
+
+amg_settings.add_argument(
+ "--box-nms-thresh",
+ type=float,
+ default=None,
+ help="The overlap threshold for excluding a duplicate mask.",
+)
+
+amg_settings.add_argument(
+ "--crop-n-layers",
+ type=int,
+ default=None,
+ help=(
+ "If >0, mask generation is run on smaller crops of the image to generate more masks. "
+ "The value sets how many different scales to crop at."
+ ),
+)
+
+amg_settings.add_argument(
+ "--crop-nms-thresh",
+ type=float,
+ default=None,
+ help="The overlap threshold for excluding duplicate masks across different crops.",
+)
+
+amg_settings.add_argument(
+ "--crop-overlap-ratio",
+ type=int,
+ default=None,
+ help="Larger numbers mean image crops will overlap more.",
+)
+
+amg_settings.add_argument(
+ "--crop-n-points-downscale-factor",
+ type=int,
+ default=None,
+ help="The number of points-per-side in each layer of crop is reduced by this factor.",
+)
+
+amg_settings.add_argument(
+ "--min-mask-region-area",
+ type=int,
+ default=None,
+ help=(
+ "Disconnected mask regions or holes with area smaller than this value "
+ "in pixels are removed by postprocessing."
+ ),
+)
+
+
+def write_masks_to_folder(masks: List[Dict[str, Any]], path: str) -> None:
+ header = "id,area,bbox_x0,bbox_y0,bbox_w,bbox_h,point_input_x,point_input_y,predicted_iou,stability_score,crop_box_x0,crop_box_y0,crop_box_w,crop_box_h" # noqa
+ metadata = [header]
+ for i, mask_data in enumerate(masks):
+ mask = mask_data["segmentation"]
+ filename = f"{i}.png"
+ cv2.imwrite(os.path.join(path, filename), mask * 255)
+ mask_metadata = [
+ str(i),
+ str(mask_data["area"]),
+ *[str(x) for x in mask_data["bbox"]],
+ *[str(x) for x in mask_data["point_coords"][0]],
+ str(mask_data["predicted_iou"]),
+ str(mask_data["stability_score"]),
+ *[str(x) for x in mask_data["crop_box"]],
+ ]
+ row = ",".join(mask_metadata)
+ metadata.append(row)
+ metadata_path = os.path.join(path, "metadata.csv")
+ with open(metadata_path, "w") as f:
+ f.write("\n".join(metadata))
+
+ return
+
+
+def get_amg_kwargs(args):
+ amg_kwargs = {
+ "points_per_side": args.points_per_side,
+ "points_per_batch": args.points_per_batch,
+ "pred_iou_thresh": args.pred_iou_thresh,
+ "stability_score_thresh": args.stability_score_thresh,
+ "stability_score_offset": args.stability_score_offset,
+ "box_nms_thresh": args.box_nms_thresh,
+ "crop_n_layers": args.crop_n_layers,
+ "crop_nms_thresh": args.crop_nms_thresh,
+ "crop_overlap_ratio": args.crop_overlap_ratio,
+ "crop_n_points_downscale_factor": args.crop_n_points_downscale_factor,
+ "min_mask_region_area": args.min_mask_region_area,
+ }
+ amg_kwargs = {k: v for k, v in amg_kwargs.items() if v is not None}
+ return amg_kwargs
+
+
+def main(args: argparse.Namespace) -> None:
+ print("Loading model...")
+ sam = sam_model_registry[args.model_type](checkpoint=args.checkpoint)
+ _ = sam.to(device=args.device)
+ output_mode = "coco_rle" if args.convert_to_rle else "binary_mask"
+ amg_kwargs = get_amg_kwargs(args)
+ generator = SamAutomaticMaskGenerator(sam, output_mode=output_mode, **amg_kwargs)
+
+ if not os.path.isdir(args.input):
+ targets = [args.input]
+ else:
+ targets = [
+ f for f in os.listdir(args.input) if not os.path.isdir(os.path.join(args.input, f))
+ ]
+ targets = [os.path.join(args.input, f) for f in targets]
+
+ os.makedirs(args.output, exist_ok=True)
+
+ for t in targets:
+ print(f"Processing '{t}'...")
+ image = cv2.imread(t)
+ if image is None:
+ print(f"Could not load '{t}' as an image, skipping...")
+ continue
+ image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
+
+ masks = generator.generate(image)
+
+ base = os.path.basename(t)
+ base = os.path.splitext(base)[0]
+ save_base = os.path.join(args.output, base)
+ if output_mode == "binary_mask":
+ os.makedirs(save_base, exist_ok=False)
+ write_masks_to_folder(masks, save_base)
+ else:
+ save_file = save_base + ".json"
+ with open(save_file, "w") as f:
+ json.dump(masks, f)
+ print("Done!")
+
+
+if __name__ == "__main__":
+ args = parser.parse_args()
+ main(args)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/export_onnx_model.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/export_onnx_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..8ec5c2ec24fc53cd9fdf66564cfe163b9eb26c24
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/scripts/export_onnx_model.py
@@ -0,0 +1,204 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+
+from segment_anything import build_sam, build_sam_vit_b, build_sam_vit_l
+from segment_anything.utils.onnx import SamOnnxModel
+
+import argparse
+import warnings
+
+try:
+ import onnxruntime # type: ignore
+
+ onnxruntime_exists = True
+except ImportError:
+ onnxruntime_exists = False
+
+parser = argparse.ArgumentParser(
+ description="Export the SAM prompt encoder and mask decoder to an ONNX model."
+)
+
+parser.add_argument(
+ "--checkpoint", type=str, required=True, help="The path to the SAM model checkpoint."
+)
+
+parser.add_argument(
+ "--output", type=str, required=True, help="The filename to save the ONNX model to."
+)
+
+parser.add_argument(
+ "--model-type",
+ type=str,
+ default="default",
+ help="In ['default', 'vit_b', 'vit_l']. Which type of SAM model to export.",
+)
+
+parser.add_argument(
+ "--return-single-mask",
+ action="store_true",
+ help=(
+ "If true, the exported ONNX model will only return the best mask, "
+ "instead of returning multiple masks. For high resolution images "
+ "this can improve runtime when upscaling masks is expensive."
+ ),
+)
+
+parser.add_argument(
+ "--opset",
+ type=int,
+ default=17,
+ help="The ONNX opset version to use. Must be >=11",
+)
+
+parser.add_argument(
+ "--quantize-out",
+ type=str,
+ default=None,
+ help=(
+ "If set, will quantize the model and save it with this name. "
+ "Quantization is performed with quantize_dynamic from onnxruntime.quantization.quantize."
+ ),
+)
+
+parser.add_argument(
+ "--gelu-approximate",
+ action="store_true",
+ help=(
+ "Replace GELU operations with approximations using tanh. Useful "
+ "for some runtimes that have slow or unimplemented erf ops, used in GELU."
+ ),
+)
+
+parser.add_argument(
+ "--use-stability-score",
+ action="store_true",
+ help=(
+ "Replaces the model's predicted mask quality score with the stability "
+ "score calculated on the low resolution masks using an offset of 1.0. "
+ ),
+)
+
+parser.add_argument(
+ "--return-extra-metrics",
+ action="store_true",
+ help=(
+ "The model will return five results: (masks, scores, stability_scores, "
+ "areas, low_res_logits) instead of the usual three. This can be "
+ "significantly slower for high resolution outputs."
+ ),
+)
+
+
+def run_export(
+ model_type: str,
+ checkpoint: str,
+ output: str,
+ opset: int,
+ return_single_mask: bool,
+ gelu_approximate: bool = False,
+ use_stability_score: bool = False,
+ return_extra_metrics=False,
+):
+ print("Loading model...")
+ if model_type == "vit_b":
+ sam = build_sam_vit_b(checkpoint)
+ elif model_type == "vit_l":
+ sam = build_sam_vit_l(checkpoint)
+ else:
+ sam = build_sam(checkpoint)
+
+ onnx_model = SamOnnxModel(
+ model=sam,
+ return_single_mask=return_single_mask,
+ use_stability_score=use_stability_score,
+ return_extra_metrics=return_extra_metrics,
+ )
+
+ if gelu_approximate:
+ for n, m in onnx_model.named_modules():
+ if isinstance(m, torch.nn.GELU):
+ m.approximate = "tanh"
+
+ dynamic_axes = {
+ "point_coords": {1: "num_points"},
+ "point_labels": {1: "num_points"},
+ }
+
+ embed_dim = sam.prompt_encoder.embed_dim
+ embed_size = sam.prompt_encoder.image_embedding_size
+ mask_input_size = [4 * x for x in embed_size]
+ dummy_inputs = {
+ "image_embeddings": torch.randn(1, embed_dim, *embed_size, dtype=torch.float),
+ "point_coords": torch.randint(low=0, high=1024, size=(1, 5, 2), dtype=torch.float),
+ "point_labels": torch.randint(low=0, high=4, size=(1, 5), dtype=torch.float),
+ "mask_input": torch.randn(1, 1, *mask_input_size, dtype=torch.float),
+ "has_mask_input": torch.tensor([1], dtype=torch.float),
+ "orig_im_size": torch.tensor([1500, 2250], dtype=torch.float),
+ }
+
+ _ = onnx_model(**dummy_inputs)
+
+ output_names = ["masks", "iou_predictions", "low_res_masks"]
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", category=torch.jit.TracerWarning)
+ warnings.filterwarnings("ignore", category=UserWarning)
+ with open(output, "wb") as f:
+ print(f"Exporing onnx model to {output}...")
+ torch.onnx.export(
+ onnx_model,
+ tuple(dummy_inputs.values()),
+ f,
+ export_params=True,
+ verbose=False,
+ opset_version=opset,
+ do_constant_folding=True,
+ input_names=list(dummy_inputs.keys()),
+ output_names=output_names,
+ dynamic_axes=dynamic_axes,
+ )
+
+ if onnxruntime_exists:
+ ort_inputs = {k: to_numpy(v) for k, v in dummy_inputs.items()}
+ ort_session = onnxruntime.InferenceSession(output)
+ _ = ort_session.run(None, ort_inputs)
+ print("Model has successfully been run with ONNXRuntime.")
+
+
+def to_numpy(tensor):
+ return tensor.cpu().numpy()
+
+
+if __name__ == "__main__":
+ args = parser.parse_args()
+ run_export(
+ model_type=args.model_type,
+ checkpoint=args.checkpoint,
+ output=args.output,
+ opset=args.opset,
+ return_single_mask=args.return_single_mask,
+ gelu_approximate=args.gelu_approximate,
+ use_stability_score=args.use_stability_score,
+ return_extra_metrics=args.return_extra_metrics,
+ )
+
+ if args.quantize_out is not None:
+ assert onnxruntime_exists, "onnxruntime is required to quantize the model."
+ from onnxruntime.quantization import QuantType # type: ignore
+ from onnxruntime.quantization.quantize import quantize_dynamic # type: ignore
+
+ print(f"Quantizing model and writing to {args.quantize_out}...")
+ quantize_dynamic(
+ model_input=args.output,
+ model_output=args.quantize_out,
+ optimize_model=True,
+ per_channel=False,
+ reduce_range=False,
+ weight_type=QuantType.QUInt8,
+ )
+ print("Done!")
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..34383d83f5e76bc801f31b20e5651e383be348b6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/__init__.py
@@ -0,0 +1,15 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .build_sam import (
+ build_sam,
+ build_sam_vit_h,
+ build_sam_vit_l,
+ build_sam_vit_b,
+ sam_model_registry,
+)
+from .predictor import SamPredictor
+from .automatic_mask_generator import SamAutomaticMaskGenerator
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/automatic_mask_generator.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/automatic_mask_generator.py
new file mode 100644
index 0000000000000000000000000000000000000000..23264971b7ff5aa0b4f499ade7773b68dce984b6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/automatic_mask_generator.py
@@ -0,0 +1,372 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+from torchvision.ops.boxes import batched_nms, box_area # type: ignore
+
+from typing import Any, Dict, List, Optional, Tuple
+
+from .modeling import Sam
+from .predictor import SamPredictor
+from .utils.amg import (
+ MaskData,
+ area_from_rle,
+ batch_iterator,
+ batched_mask_to_box,
+ box_xyxy_to_xywh,
+ build_all_layer_point_grids,
+ calculate_stability_score,
+ coco_encode_rle,
+ generate_crop_boxes,
+ is_box_near_crop_edge,
+ mask_to_rle_pytorch,
+ remove_small_regions,
+ rle_to_mask,
+ uncrop_boxes_xyxy,
+ uncrop_masks,
+ uncrop_points,
+)
+
+
+class SamAutomaticMaskGenerator:
+ def __init__(
+ self,
+ model: Sam,
+ points_per_side: Optional[int] = 32,
+ points_per_batch: int = 64,
+ pred_iou_thresh: float = 0.88,
+ stability_score_thresh: float = 0.95,
+ stability_score_offset: float = 1.0,
+ box_nms_thresh: float = 0.7,
+ crop_n_layers: int = 0,
+ crop_nms_thresh: float = 0.7,
+ crop_overlap_ratio: float = 512 / 1500,
+ crop_n_points_downscale_factor: int = 1,
+ point_grids: Optional[List[np.ndarray]] = None,
+ min_mask_region_area: int = 0,
+ output_mode: str = "binary_mask",
+ ) -> None:
+ """
+ Using a SAM model, generates masks for the entire image.
+ Generates a grid of point prompts over the image, then filters
+ low quality and duplicate masks. The default settings are chosen
+ for SAM with a ViT-H backbone.
+
+ Arguments:
+ model (Sam): The SAM model to use for mask prediction.
+ points_per_side (int or None): The number of points to be sampled
+ along one side of the image. The total number of points is
+ points_per_side**2. If None, 'point_grids' must provide explicit
+ point sampling.
+ points_per_batch (int): Sets the number of points run simultaneously
+ by the model. Higher numbers may be faster but use more GPU memory.
+ pred_iou_thresh (float): A filtering threshold in [0,1], using the
+ model's predicted mask quality.
+ stability_score_thresh (float): A filtering threshold in [0,1], using
+ the stability of the mask under changes to the cutoff used to binarize
+ the model's mask predictions.
+ stability_score_offset (float): The amount to shift the cutoff when
+ calculated the stability score.
+ box_nms_thresh (float): The box IoU cutoff used by non-maximal
+ suppression to filter duplicate masks.
+ crops_n_layers (int): If >0, mask prediction will be run again on
+ crops of the image. Sets the number of layers to run, where each
+ layer has 2**i_layer number of image crops.
+ crops_nms_thresh (float): The box IoU cutoff used by non-maximal
+ suppression to filter duplicate masks between different crops.
+ crop_overlap_ratio (float): Sets the degree to which crops overlap.
+ In the first crop layer, crops will overlap by this fraction of
+ the image length. Later layers with more crops scale down this overlap.
+ crop_n_points_downscale_factor (int): The number of points-per-side
+ sampled in layer n is scaled down by crop_n_points_downscale_factor**n.
+ point_grids (list(np.ndarray) or None): A list over explicit grids
+ of points used for sampling, normalized to [0,1]. The nth grid in the
+ list is used in the nth crop layer. Exclusive with points_per_side.
+ min_mask_region_area (int): If >0, postprocessing will be applied
+ to remove disconnected regions and holes in masks with area smaller
+ than min_mask_region_area. Requires opencv.
+ output_mode (str): The form masks are returned in. Can be 'binary_mask',
+ 'uncompressed_rle', or 'coco_rle'. 'coco_rle' requires pycocotools.
+ For large resolutions, 'binary_mask' may consume large amounts of
+ memory.
+ """
+
+ assert (points_per_side is None) != (
+ point_grids is None
+ ), "Exactly one of points_per_side or point_grid must be provided."
+ if points_per_side is not None:
+ self.point_grids = build_all_layer_point_grids(
+ points_per_side,
+ crop_n_layers,
+ crop_n_points_downscale_factor,
+ )
+ elif point_grids is not None:
+ self.point_grids = point_grids
+ else:
+ raise ValueError("Can't have both points_per_side and point_grid be None.")
+
+ assert output_mode in [
+ "binary_mask",
+ "uncompressed_rle",
+ "coco_rle",
+ ], f"Unknown output_mode {output_mode}."
+ if output_mode == "coco_rle":
+ from pycocotools import mask as mask_utils # type: ignore # noqa: F401
+
+ if min_mask_region_area > 0:
+ import cv2 # type: ignore # noqa: F401
+
+ self.predictor = SamPredictor(model)
+ self.points_per_batch = points_per_batch
+ self.pred_iou_thresh = pred_iou_thresh
+ self.stability_score_thresh = stability_score_thresh
+ self.stability_score_offset = stability_score_offset
+ self.box_nms_thresh = box_nms_thresh
+ self.crop_n_layers = crop_n_layers
+ self.crop_nms_thresh = crop_nms_thresh
+ self.crop_overlap_ratio = crop_overlap_ratio
+ self.crop_n_points_downscale_factor = crop_n_points_downscale_factor
+ self.min_mask_region_area = min_mask_region_area
+ self.output_mode = output_mode
+
+ @torch.no_grad()
+ def generate(self, image: np.ndarray) -> List[Dict[str, Any]]:
+ """
+ Generates masks for the given image.
+
+ Arguments:
+ image (np.ndarray): The image to generate masks for, in HWC uint8 format.
+
+ Returns:
+ list(dict(str, any)): A list over records for masks. Each record is
+ a dict containing the following keys:
+ segmentation (dict(str, any) or np.ndarray): The mask. If
+ output_mode='binary_mask', is an array of shape HW. Otherwise,
+ is a dictionary containing the RLE.
+ bbox (list(float)): The box around the mask, in XYWH format.
+ area (int): The area in pixels of the mask.
+ predicted_iou (float): The model's own prediction of the mask's
+ quality. This is filtered by the pred_iou_thresh parameter.
+ point_coords (list(list(float))): The point coordinates input
+ to the model to generate this mask.
+ stability_score (float): A measure of the mask's quality. This
+ is filtered on using the stability_score_thresh parameter.
+ crop_box (list(float)): The crop of the image used to generate
+ the mask, given in XYWH format.
+ """
+
+ # Generate masks
+ mask_data = self._generate_masks(image)
+
+ # Filter small disconnected regions and holes in masks
+ if self.min_mask_region_area > 0:
+ mask_data = self.postprocess_small_regions(
+ mask_data,
+ self.min_mask_region_area,
+ max(self.box_nms_thresh, self.crop_nms_thresh),
+ )
+
+ # Encode masks
+ if self.output_mode == "coco_rle":
+ mask_data["segmentations"] = [coco_encode_rle(rle) for rle in mask_data["rles"]]
+ elif self.output_mode == "binary_mask":
+ mask_data["segmentations"] = [rle_to_mask(rle) for rle in mask_data["rles"]]
+ else:
+ mask_data["segmentations"] = mask_data["rles"]
+
+ # Write mask records
+ curr_anns = []
+ for idx in range(len(mask_data["segmentations"])):
+ ann = {
+ "segmentation": mask_data["segmentations"][idx],
+ "area": area_from_rle(mask_data["rles"][idx]),
+ "bbox": box_xyxy_to_xywh(mask_data["boxes"][idx]).tolist(),
+ "predicted_iou": mask_data["iou_preds"][idx].item(),
+ "point_coords": [mask_data["points"][idx].tolist()],
+ "stability_score": mask_data["stability_score"][idx].item(),
+ "crop_box": box_xyxy_to_xywh(mask_data["crop_boxes"][idx]).tolist(),
+ }
+ curr_anns.append(ann)
+
+ return curr_anns
+
+ def _generate_masks(self, image: np.ndarray) -> MaskData:
+ orig_size = image.shape[:2]
+ crop_boxes, layer_idxs = generate_crop_boxes(
+ orig_size, self.crop_n_layers, self.crop_overlap_ratio
+ )
+
+ # Iterate over image crops
+ data = MaskData()
+ for crop_box, layer_idx in zip(crop_boxes, layer_idxs):
+ crop_data = self._process_crop(image, crop_box, layer_idx, orig_size)
+ data.cat(crop_data)
+
+ # Remove duplicate masks between crops
+ if len(crop_boxes) > 1:
+ # Prefer masks from smaller crops
+ scores = 1 / box_area(data["crop_boxes"])
+ scores = scores.to(data["boxes"].device)
+ keep_by_nms = batched_nms(
+ data["boxes"].float(),
+ scores,
+ torch.zeros(len(data["boxes"])), # categories
+ iou_threshold=self.crop_nms_thresh,
+ )
+ data.filter(keep_by_nms)
+
+ data.to_numpy()
+ return data
+
+ def _process_crop(
+ self,
+ image: np.ndarray,
+ crop_box: List[int],
+ crop_layer_idx: int,
+ orig_size: Tuple[int, ...],
+ ) -> MaskData:
+ # Crop the image and calculate embeddings
+ x0, y0, x1, y1 = crop_box
+ cropped_im = image[y0:y1, x0:x1, :]
+ cropped_im_size = cropped_im.shape[:2]
+ self.predictor.set_image(cropped_im)
+
+ # Get points for this crop
+ points_scale = np.array(cropped_im_size)[None, ::-1]
+ points_for_image = self.point_grids[crop_layer_idx] * points_scale
+
+ # Generate masks for this crop in batches
+ data = MaskData()
+ for (points,) in batch_iterator(self.points_per_batch, points_for_image):
+ batch_data = self._process_batch(points, cropped_im_size, crop_box, orig_size)
+ data.cat(batch_data)
+ del batch_data
+ self.predictor.reset_image()
+
+ # Remove duplicates within this crop.
+ keep_by_nms = batched_nms(
+ data["boxes"].float(),
+ data["iou_preds"],
+ torch.zeros(len(data["boxes"])), # categories
+ iou_threshold=self.box_nms_thresh,
+ )
+ data.filter(keep_by_nms)
+
+ # Return to the original image frame
+ data["boxes"] = uncrop_boxes_xyxy(data["boxes"], crop_box)
+ data["points"] = uncrop_points(data["points"], crop_box)
+ data["crop_boxes"] = torch.tensor([crop_box for _ in range(len(data["rles"]))])
+
+ return data
+
+ def _process_batch(
+ self,
+ points: np.ndarray,
+ im_size: Tuple[int, ...],
+ crop_box: List[int],
+ orig_size: Tuple[int, ...],
+ ) -> MaskData:
+ orig_h, orig_w = orig_size
+
+ # Run model on this batch
+ transformed_points = self.predictor.transform.apply_coords(points, im_size)
+ in_points = torch.as_tensor(transformed_points, device=self.predictor.device)
+ in_labels = torch.ones(in_points.shape[0], dtype=torch.int, device=in_points.device)
+ masks, iou_preds, _ = self.predictor.predict_torch(
+ in_points[:, None, :],
+ in_labels[:, None],
+ multimask_output=True,
+ return_logits=True,
+ )
+
+ # Serialize predictions and store in MaskData
+ data = MaskData(
+ masks=masks.flatten(0, 1),
+ iou_preds=iou_preds.flatten(0, 1),
+ points=torch.as_tensor(points.repeat(masks.shape[1], axis=0)),
+ )
+ del masks
+
+ # Filter by predicted IoU
+ if self.pred_iou_thresh > 0.0:
+ keep_mask = data["iou_preds"] > self.pred_iou_thresh
+ data.filter(keep_mask)
+
+ # Calculate stability score
+ data["stability_score"] = calculate_stability_score(
+ data["masks"], self.predictor.model.mask_threshold, self.stability_score_offset
+ )
+ if self.stability_score_thresh > 0.0:
+ keep_mask = data["stability_score"] >= self.stability_score_thresh
+ data.filter(keep_mask)
+
+ # Threshold masks and calculate boxes
+ data["masks"] = data["masks"] > self.predictor.model.mask_threshold
+ data["boxes"] = batched_mask_to_box(data["masks"])
+
+ # Filter boxes that touch crop boundaries
+ keep_mask = ~is_box_near_crop_edge(data["boxes"], crop_box, [0, 0, orig_w, orig_h])
+ if not torch.all(keep_mask):
+ data.filter(keep_mask)
+
+ # Compress to RLE
+ data["masks"] = uncrop_masks(data["masks"], crop_box, orig_h, orig_w)
+ data["rles"] = mask_to_rle_pytorch(data["masks"])
+ del data["masks"]
+
+ return data
+
+ @staticmethod
+ def postprocess_small_regions(
+ mask_data: MaskData, min_area: int, nms_thresh: float
+ ) -> MaskData:
+ """
+ Removes small disconnected regions and holes in masks, then reruns
+ box NMS to remove any new duplicates.
+
+ Edits mask_data in place.
+
+ Requires open-cv as a dependency.
+ """
+ if len(mask_data["rles"]) == 0:
+ return mask_data
+
+ # Filter small disconnected regions and holes
+ new_masks = []
+ scores = []
+ for rle in mask_data["rles"]:
+ mask = rle_to_mask(rle)
+
+ mask, changed = remove_small_regions(mask, min_area, mode="holes")
+ unchanged = not changed
+ mask, changed = remove_small_regions(mask, min_area, mode="islands")
+ unchanged = unchanged and not changed
+
+ new_masks.append(torch.as_tensor(mask).unsqueeze(0))
+ # Give score=0 to changed masks and score=1 to unchanged masks
+ # so NMS will prefer ones that didn't need postprocessing
+ scores.append(float(unchanged))
+
+ # Recalculate boxes and remove any new duplicates
+ masks = torch.cat(new_masks, dim=0)
+ boxes = batched_mask_to_box(masks)
+ keep_by_nms = batched_nms(
+ boxes.float(),
+ torch.as_tensor(scores),
+ torch.zeros(len(boxes)), # categories
+ iou_threshold=nms_thresh,
+ )
+
+ # Only recalculate RLEs for masks that have changed
+ for i_mask in keep_by_nms:
+ if scores[i_mask] == 0.0:
+ mask_torch = masks[i_mask].unsqueeze(0)
+ mask_data["rles"][i_mask] = mask_to_rle_pytorch(mask_torch)[0]
+ mask_data["boxes"][i_mask] = boxes[i_mask] # update res directly
+ mask_data.filter(keep_by_nms)
+
+ return mask_data
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/build_sam.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/build_sam.py
new file mode 100644
index 0000000000000000000000000000000000000000..07abfca24e96eced7f13bdefd3212ce1b77b8999
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/build_sam.py
@@ -0,0 +1,107 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+
+from functools import partial
+
+from .modeling import ImageEncoderViT, MaskDecoder, PromptEncoder, Sam, TwoWayTransformer
+
+
+def build_sam_vit_h(checkpoint=None):
+ return _build_sam(
+ encoder_embed_dim=1280,
+ encoder_depth=32,
+ encoder_num_heads=16,
+ encoder_global_attn_indexes=[7, 15, 23, 31],
+ checkpoint=checkpoint,
+ )
+
+
+build_sam = build_sam_vit_h
+
+
+def build_sam_vit_l(checkpoint=None):
+ return _build_sam(
+ encoder_embed_dim=1024,
+ encoder_depth=24,
+ encoder_num_heads=16,
+ encoder_global_attn_indexes=[5, 11, 17, 23],
+ checkpoint=checkpoint,
+ )
+
+
+def build_sam_vit_b(checkpoint=None):
+ return _build_sam(
+ encoder_embed_dim=768,
+ encoder_depth=12,
+ encoder_num_heads=12,
+ encoder_global_attn_indexes=[2, 5, 8, 11],
+ checkpoint=checkpoint,
+ )
+
+
+sam_model_registry = {
+ "default": build_sam,
+ "vit_h": build_sam,
+ "vit_l": build_sam_vit_l,
+ "vit_b": build_sam_vit_b,
+}
+
+
+def _build_sam(
+ encoder_embed_dim,
+ encoder_depth,
+ encoder_num_heads,
+ encoder_global_attn_indexes,
+ checkpoint=None,
+):
+ prompt_embed_dim = 256
+ image_size = 1024
+ vit_patch_size = 16
+ image_embedding_size = image_size // vit_patch_size
+ sam = Sam(
+ image_encoder=ImageEncoderViT(
+ depth=encoder_depth,
+ embed_dim=encoder_embed_dim,
+ img_size=image_size,
+ mlp_ratio=4,
+ norm_layer=partial(torch.nn.LayerNorm, eps=1e-6),
+ num_heads=encoder_num_heads,
+ patch_size=vit_patch_size,
+ qkv_bias=True,
+ use_rel_pos=True,
+ global_attn_indexes=encoder_global_attn_indexes,
+ window_size=14,
+ out_chans=prompt_embed_dim,
+ ),
+ prompt_encoder=PromptEncoder(
+ embed_dim=prompt_embed_dim,
+ image_embedding_size=(image_embedding_size, image_embedding_size),
+ input_image_size=(image_size, image_size),
+ mask_in_chans=16,
+ ),
+ mask_decoder=MaskDecoder(
+ num_multimask_outputs=3,
+ transformer=TwoWayTransformer(
+ depth=2,
+ embedding_dim=prompt_embed_dim,
+ mlp_dim=2048,
+ num_heads=8,
+ ),
+ transformer_dim=prompt_embed_dim,
+ iou_head_depth=3,
+ iou_head_hidden_dim=256,
+ ),
+ pixel_mean=[123.675, 116.28, 103.53],
+ pixel_std=[58.395, 57.12, 57.375],
+ )
+ sam.eval()
+ if checkpoint is not None:
+ with open(checkpoint, "rb") as f:
+ state_dict = torch.load(f)
+ sam.load_state_dict(state_dict)
+ return sam
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..38e906243d898d7fc071c0fe218338c5cace3ea1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/__init__.py
@@ -0,0 +1,11 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from .sam import Sam
+from .image_encoder import ImageEncoderViT
+from .mask_decoder import MaskDecoder
+from .prompt_encoder import PromptEncoder
+from .transformer import TwoWayTransformer
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/common.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..2bf15236a3eb24d8526073bc4fa2b274cccb3f96
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/common.py
@@ -0,0 +1,43 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+
+from typing import Type
+
+
+class MLPBlock(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ mlp_dim: int,
+ act: Type[nn.Module] = nn.GELU,
+ ) -> None:
+ super().__init__()
+ self.lin1 = nn.Linear(embedding_dim, mlp_dim)
+ self.lin2 = nn.Linear(mlp_dim, embedding_dim)
+ self.act = act()
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.lin2(self.act(self.lin1(x)))
+
+
+# From https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/batch_norm.py # noqa
+# Itself from https://github.com/facebookresearch/ConvNeXt/blob/d1fa8f6fef0a165b27399986cc2bdacc92777e40/models/convnext.py#L119 # noqa
+class LayerNorm2d(nn.Module):
+ def __init__(self, num_channels: int, eps: float = 1e-6) -> None:
+ super().__init__()
+ self.weight = nn.Parameter(torch.ones(num_channels))
+ self.bias = nn.Parameter(torch.zeros(num_channels))
+ self.eps = eps
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ u = x.mean(1, keepdim=True)
+ s = (x - u).pow(2).mean(1, keepdim=True)
+ x = (x - u) / torch.sqrt(s + self.eps)
+ x = self.weight[:, None, None] * x + self.bias[:, None, None]
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/image_encoder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/image_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6ad9ad2938842308e482a05c9d35ab08db9b2c3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/image_encoder.py
@@ -0,0 +1,395 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from typing import Optional, Tuple, Type
+
+from .common import LayerNorm2d, MLPBlock
+
+
+# This class and its supporting functions below lightly adapted from the ViTDet backbone available at: https://github.com/facebookresearch/detectron2/blob/main/detectron2/modeling/backbone/vit.py # noqa
+class ImageEncoderViT(nn.Module):
+ def __init__(
+ self,
+ img_size: int = 1024,
+ patch_size: int = 16,
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ depth: int = 12,
+ num_heads: int = 12,
+ mlp_ratio: float = 4.0,
+ out_chans: int = 256,
+ qkv_bias: bool = True,
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
+ act_layer: Type[nn.Module] = nn.GELU,
+ use_abs_pos: bool = True,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ window_size: int = 0,
+ global_attn_indexes: Tuple[int, ...] = (),
+ ) -> None:
+ """
+ Args:
+ img_size (int): Input image size.
+ patch_size (int): Patch size.
+ in_chans (int): Number of input image channels.
+ embed_dim (int): Patch embedding dimension.
+ depth (int): Depth of ViT.
+ num_heads (int): Number of attention heads in each ViT block.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
+ norm_layer (nn.Module): Normalization layer.
+ act_layer (nn.Module): Activation layer.
+ use_abs_pos (bool): If True, use absolute positional embeddings.
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+ window_size (int): Window size for window attention blocks.
+ global_attn_indexes (list): Indexes for blocks using global attention.
+ """
+ super().__init__()
+ self.img_size = img_size
+
+ self.patch_embed = PatchEmbed(
+ kernel_size=(patch_size, patch_size),
+ stride=(patch_size, patch_size),
+ in_chans=in_chans,
+ embed_dim=embed_dim,
+ )
+
+ self.pos_embed: Optional[nn.Parameter] = None
+ if use_abs_pos:
+ # Initialize absolute positional embedding with pretrain image size.
+ self.pos_embed = nn.Parameter(
+ torch.zeros(1, img_size // patch_size, img_size // patch_size, embed_dim)
+ )
+
+ self.blocks = nn.ModuleList()
+ for i in range(depth):
+ block = Block(
+ dim=embed_dim,
+ num_heads=num_heads,
+ mlp_ratio=mlp_ratio,
+ qkv_bias=qkv_bias,
+ norm_layer=norm_layer,
+ act_layer=act_layer,
+ use_rel_pos=use_rel_pos,
+ rel_pos_zero_init=rel_pos_zero_init,
+ window_size=window_size if i not in global_attn_indexes else 0,
+ input_size=(img_size // patch_size, img_size // patch_size),
+ )
+ self.blocks.append(block)
+
+ self.neck = nn.Sequential(
+ nn.Conv2d(
+ embed_dim,
+ out_chans,
+ kernel_size=1,
+ bias=False,
+ ),
+ LayerNorm2d(out_chans),
+ nn.Conv2d(
+ out_chans,
+ out_chans,
+ kernel_size=3,
+ padding=1,
+ bias=False,
+ ),
+ LayerNorm2d(out_chans),
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.patch_embed(x)
+ if self.pos_embed is not None:
+ x = x + self.pos_embed
+
+ for blk in self.blocks:
+ x = blk(x)
+
+ x = self.neck(x.permute(0, 3, 1, 2))
+
+ return x
+
+
+class Block(nn.Module):
+ """Transformer blocks with support of window attention and residual propagation blocks"""
+
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int,
+ mlp_ratio: float = 4.0,
+ qkv_bias: bool = True,
+ norm_layer: Type[nn.Module] = nn.LayerNorm,
+ act_layer: Type[nn.Module] = nn.GELU,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ window_size: int = 0,
+ input_size: Optional[Tuple[int, int]] = None,
+ ) -> None:
+ """
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of attention heads in each ViT block.
+ mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
+ qkv_bias (bool): If True, add a learnable bias to query, key, value.
+ norm_layer (nn.Module): Normalization layer.
+ act_layer (nn.Module): Activation layer.
+ use_rel_pos (bool): If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+ window_size (int): Window size for window attention blocks. If it equals 0, then
+ use global attention.
+ input_size (int or None): Input resolution for calculating the relative positional
+ parameter size.
+ """
+ super().__init__()
+ self.norm1 = norm_layer(dim)
+ self.attn = Attention(
+ dim,
+ num_heads=num_heads,
+ qkv_bias=qkv_bias,
+ use_rel_pos=use_rel_pos,
+ rel_pos_zero_init=rel_pos_zero_init,
+ input_size=input_size if window_size == 0 else (window_size, window_size),
+ )
+
+ self.norm2 = norm_layer(dim)
+ self.mlp = MLPBlock(embedding_dim=dim, mlp_dim=int(dim * mlp_ratio), act=act_layer)
+
+ self.window_size = window_size
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ shortcut = x
+ x = self.norm1(x)
+ # Window partition
+ if self.window_size > 0:
+ H, W = x.shape[1], x.shape[2]
+ x, pad_hw = window_partition(x, self.window_size)
+
+ x = self.attn(x)
+ # Reverse window partition
+ if self.window_size > 0:
+ x = window_unpartition(x, self.window_size, pad_hw, (H, W))
+
+ x = shortcut + x
+ x = x + self.mlp(self.norm2(x))
+
+ return x
+
+
+class Attention(nn.Module):
+ """Multi-head Attention block with relative position embeddings."""
+
+ def __init__(
+ self,
+ dim: int,
+ num_heads: int = 8,
+ qkv_bias: bool = True,
+ use_rel_pos: bool = False,
+ rel_pos_zero_init: bool = True,
+ input_size: Optional[Tuple[int, int]] = None,
+ ) -> None:
+ """
+ Args:
+ dim (int): Number of input channels.
+ num_heads (int): Number of attention heads.
+ qkv_bias (bool: If True, add a learnable bias to query, key, value.
+ rel_pos (bool): If True, add relative positional embeddings to the attention map.
+ rel_pos_zero_init (bool): If True, zero initialize relative positional parameters.
+ input_size (int or None): Input resolution for calculating the relative positional
+ parameter size.
+ """
+ super().__init__()
+ self.num_heads = num_heads
+ head_dim = dim // num_heads
+ self.scale = head_dim**-0.5
+
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
+ self.proj = nn.Linear(dim, dim)
+
+ self.use_rel_pos = use_rel_pos
+ if self.use_rel_pos:
+ assert (
+ input_size is not None
+ ), "Input size must be provided if using relative positional encoding."
+ # initialize relative positional embeddings
+ self.rel_pos_h = nn.Parameter(torch.zeros(2 * input_size[0] - 1, head_dim))
+ self.rel_pos_w = nn.Parameter(torch.zeros(2 * input_size[1] - 1, head_dim))
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ B, H, W, _ = x.shape
+ # qkv with shape (3, B, nHead, H * W, C)
+ qkv = self.qkv(x).reshape(B, H * W, 3, self.num_heads, -1).permute(2, 0, 3, 1, 4)
+ # q, k, v with shape (B * nHead, H * W, C)
+ q, k, v = qkv.reshape(3, B * self.num_heads, H * W, -1).unbind(0)
+
+ attn = (q * self.scale) @ k.transpose(-2, -1)
+
+ if self.use_rel_pos:
+ attn = add_decomposed_rel_pos(attn, q, self.rel_pos_h, self.rel_pos_w, (H, W), (H, W))
+
+ attn = attn.softmax(dim=-1)
+ x = (attn @ v).view(B, self.num_heads, H, W, -1).permute(0, 2, 3, 1, 4).reshape(B, H, W, -1)
+ x = self.proj(x)
+
+ return x
+
+
+def window_partition(x: torch.Tensor, window_size: int) -> Tuple[torch.Tensor, Tuple[int, int]]:
+ """
+ Partition into non-overlapping windows with padding if needed.
+ Args:
+ x (tensor): input tokens with [B, H, W, C].
+ window_size (int): window size.
+
+ Returns:
+ windows: windows after partition with [B * num_windows, window_size, window_size, C].
+ (Hp, Wp): padded height and width before partition
+ """
+ B, H, W, C = x.shape
+
+ pad_h = (window_size - H % window_size) % window_size
+ pad_w = (window_size - W % window_size) % window_size
+ if pad_h > 0 or pad_w > 0:
+ x = F.pad(x, (0, 0, 0, pad_w, 0, pad_h))
+ Hp, Wp = H + pad_h, W + pad_w
+
+ x = x.view(B, Hp // window_size, window_size, Wp // window_size, window_size, C)
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C)
+ return windows, (Hp, Wp)
+
+
+def window_unpartition(
+ windows: torch.Tensor, window_size: int, pad_hw: Tuple[int, int], hw: Tuple[int, int]
+) -> torch.Tensor:
+ """
+ Window unpartition into original sequences and removing padding.
+ Args:
+ x (tensor): input tokens with [B * num_windows, window_size, window_size, C].
+ window_size (int): window size.
+ pad_hw (Tuple): padded height and width (Hp, Wp).
+ hw (Tuple): original height and width (H, W) before padding.
+
+ Returns:
+ x: unpartitioned sequences with [B, H, W, C].
+ """
+ Hp, Wp = pad_hw
+ H, W = hw
+ B = windows.shape[0] // (Hp * Wp // window_size // window_size)
+ x = windows.view(B, Hp // window_size, Wp // window_size, window_size, window_size, -1)
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, Hp, Wp, -1)
+
+ if Hp > H or Wp > W:
+ x = x[:, :H, :W, :].contiguous()
+ return x
+
+
+def get_rel_pos(q_size: int, k_size: int, rel_pos: torch.Tensor) -> torch.Tensor:
+ """
+ Get relative positional embeddings according to the relative positions of
+ query and key sizes.
+ Args:
+ q_size (int): size of query q.
+ k_size (int): size of key k.
+ rel_pos (Tensor): relative position embeddings (L, C).
+
+ Returns:
+ Extracted positional embeddings according to relative positions.
+ """
+ max_rel_dist = int(2 * max(q_size, k_size) - 1)
+ # Interpolate rel pos if needed.
+ if rel_pos.shape[0] != max_rel_dist:
+ # Interpolate rel pos.
+ rel_pos_resized = F.interpolate(
+ rel_pos.reshape(1, rel_pos.shape[0], -1).permute(0, 2, 1),
+ size=max_rel_dist,
+ mode="linear",
+ )
+ rel_pos_resized = rel_pos_resized.reshape(-1, max_rel_dist).permute(1, 0)
+ else:
+ rel_pos_resized = rel_pos
+
+ # Scale the coords with short length if shapes for q and k are different.
+ q_coords = torch.arange(q_size)[:, None] * max(k_size / q_size, 1.0)
+ k_coords = torch.arange(k_size)[None, :] * max(q_size / k_size, 1.0)
+ relative_coords = (q_coords - k_coords) + (k_size - 1) * max(q_size / k_size, 1.0)
+
+ return rel_pos_resized[relative_coords.long()]
+
+
+def add_decomposed_rel_pos(
+ attn: torch.Tensor,
+ q: torch.Tensor,
+ rel_pos_h: torch.Tensor,
+ rel_pos_w: torch.Tensor,
+ q_size: Tuple[int, int],
+ k_size: Tuple[int, int],
+) -> torch.Tensor:
+ """
+ Calculate decomposed Relative Positional Embeddings from :paper:`mvitv2`.
+ https://github.com/facebookresearch/mvit/blob/19786631e330df9f3622e5402b4a419a263a2c80/mvit/models/attention.py # noqa B950
+ Args:
+ attn (Tensor): attention map.
+ q (Tensor): query q in the attention layer with shape (B, q_h * q_w, C).
+ rel_pos_h (Tensor): relative position embeddings (Lh, C) for height axis.
+ rel_pos_w (Tensor): relative position embeddings (Lw, C) for width axis.
+ q_size (Tuple): spatial sequence size of query q with (q_h, q_w).
+ k_size (Tuple): spatial sequence size of key k with (k_h, k_w).
+
+ Returns:
+ attn (Tensor): attention map with added relative positional embeddings.
+ """
+ q_h, q_w = q_size
+ k_h, k_w = k_size
+ Rh = get_rel_pos(q_h, k_h, rel_pos_h)
+ Rw = get_rel_pos(q_w, k_w, rel_pos_w)
+
+ B, _, dim = q.shape
+ r_q = q.reshape(B, q_h, q_w, dim)
+ rel_h = torch.einsum("bhwc,hkc->bhwk", r_q, Rh)
+ rel_w = torch.einsum("bhwc,wkc->bhwk", r_q, Rw)
+
+ attn = (
+ attn.view(B, q_h, q_w, k_h, k_w) + rel_h[:, :, :, :, None] + rel_w[:, :, :, None, :]
+ ).view(B, q_h * q_w, k_h * k_w)
+
+ return attn
+
+
+class PatchEmbed(nn.Module):
+ """
+ Image to Patch Embedding.
+ """
+
+ def __init__(
+ self,
+ kernel_size: Tuple[int, int] = (16, 16),
+ stride: Tuple[int, int] = (16, 16),
+ padding: Tuple[int, int] = (0, 0),
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ ) -> None:
+ """
+ Args:
+ kernel_size (Tuple): kernel size of the projection layer.
+ stride (Tuple): stride of the projection layer.
+ padding (Tuple): padding size of the projection layer.
+ in_chans (int): Number of input image channels.
+ embed_dim (int): embed_dim (int): Patch embedding dimension.
+ """
+ super().__init__()
+
+ self.proj = nn.Conv2d(
+ in_chans, embed_dim, kernel_size=kernel_size, stride=stride, padding=padding
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.proj(x)
+ # B C H W -> B H W C
+ x = x.permute(0, 2, 3, 1)
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/mask_decoder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/mask_decoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e86f7cc9ad95582a08ef2531c68d03fa4af8d99
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/mask_decoder.py
@@ -0,0 +1,176 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from typing import List, Tuple, Type
+
+from .common import LayerNorm2d
+
+
+class MaskDecoder(nn.Module):
+ def __init__(
+ self,
+ *,
+ transformer_dim: int,
+ transformer: nn.Module,
+ num_multimask_outputs: int = 3,
+ activation: Type[nn.Module] = nn.GELU,
+ iou_head_depth: int = 3,
+ iou_head_hidden_dim: int = 256,
+ ) -> None:
+ """
+ Predicts masks given an image and prompt embeddings, using a
+ tranformer architecture.
+
+ Arguments:
+ transformer_dim (int): the channel dimension of the transformer
+ transformer (nn.Module): the transformer used to predict masks
+ num_multimask_outputs (int): the number of masks to predict
+ when disambiguating masks
+ activation (nn.Module): the type of activation to use when
+ upscaling masks
+ iou_head_depth (int): the depth of the MLP used to predict
+ mask quality
+ iou_head_hidden_dim (int): the hidden dimension of the MLP
+ used to predict mask quality
+ """
+ super().__init__()
+ self.transformer_dim = transformer_dim
+ self.transformer = transformer
+
+ self.num_multimask_outputs = num_multimask_outputs
+
+ self.iou_token = nn.Embedding(1, transformer_dim)
+ self.num_mask_tokens = num_multimask_outputs + 1
+ self.mask_tokens = nn.Embedding(self.num_mask_tokens, transformer_dim)
+
+ self.output_upscaling = nn.Sequential(
+ nn.ConvTranspose2d(transformer_dim, transformer_dim // 4, kernel_size=2, stride=2),
+ LayerNorm2d(transformer_dim // 4),
+ activation(),
+ nn.ConvTranspose2d(transformer_dim // 4, transformer_dim // 8, kernel_size=2, stride=2),
+ activation(),
+ )
+ self.output_hypernetworks_mlps = nn.ModuleList(
+ [
+ MLP(transformer_dim, transformer_dim, transformer_dim // 8, 3)
+ for i in range(self.num_mask_tokens)
+ ]
+ )
+
+ self.iou_prediction_head = MLP(
+ transformer_dim, iou_head_hidden_dim, self.num_mask_tokens, iou_head_depth
+ )
+
+ def forward(
+ self,
+ image_embeddings: torch.Tensor,
+ image_pe: torch.Tensor,
+ sparse_prompt_embeddings: torch.Tensor,
+ dense_prompt_embeddings: torch.Tensor,
+ multimask_output: bool,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Predict masks given image and prompt embeddings.
+
+ Arguments:
+ image_embeddings (torch.Tensor): the embeddings from the image encoder
+ image_pe (torch.Tensor): positional encoding with the shape of image_embeddings
+ sparse_prompt_embeddings (torch.Tensor): the embeddings of the points and boxes
+ dense_prompt_embeddings (torch.Tensor): the embeddings of the mask inputs
+ multimask_output (bool): Whether to return multiple masks or a single
+ mask.
+
+ Returns:
+ torch.Tensor: batched predicted masks
+ torch.Tensor: batched predictions of mask quality
+ """
+ masks, iou_pred = self.predict_masks(
+ image_embeddings=image_embeddings,
+ image_pe=image_pe,
+ sparse_prompt_embeddings=sparse_prompt_embeddings,
+ dense_prompt_embeddings=dense_prompt_embeddings,
+ )
+
+ # Select the correct mask or masks for outptu
+ if multimask_output:
+ mask_slice = slice(1, None)
+ else:
+ mask_slice = slice(0, 1)
+ masks = masks[:, mask_slice, :, :]
+ iou_pred = iou_pred[:, mask_slice]
+
+ # Prepare output
+ return masks, iou_pred
+
+ def predict_masks(
+ self,
+ image_embeddings: torch.Tensor,
+ image_pe: torch.Tensor,
+ sparse_prompt_embeddings: torch.Tensor,
+ dense_prompt_embeddings: torch.Tensor,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Predicts masks. See 'forward' for more details."""
+ # Concatenate output tokens
+ output_tokens = torch.cat([self.iou_token.weight, self.mask_tokens.weight], dim=0)
+ output_tokens = output_tokens.unsqueeze(0).expand(sparse_prompt_embeddings.size(0), -1, -1)
+ tokens = torch.cat((output_tokens, sparse_prompt_embeddings), dim=1)
+
+ # Expand per-image data in batch direction to be per-mask
+ src = torch.repeat_interleave(image_embeddings, tokens.shape[0], dim=0)
+ src = src + dense_prompt_embeddings
+ pos_src = torch.repeat_interleave(image_pe, tokens.shape[0], dim=0)
+ b, c, h, w = src.shape
+
+ # Run the transformer
+ hs, src = self.transformer(src, pos_src, tokens)
+ iou_token_out = hs[:, 0, :]
+ mask_tokens_out = hs[:, 1 : (1 + self.num_mask_tokens), :]
+
+ # Upscale mask embeddings and predict masks using the mask tokens
+ src = src.transpose(1, 2).view(b, c, h, w)
+ upscaled_embedding = self.output_upscaling(src)
+ hyper_in_list: List[torch.Tensor] = []
+ for i in range(self.num_mask_tokens):
+ hyper_in_list.append(self.output_hypernetworks_mlps[i](mask_tokens_out[:, i, :]))
+ hyper_in = torch.stack(hyper_in_list, dim=1)
+ b, c, h, w = upscaled_embedding.shape
+ masks = (hyper_in @ upscaled_embedding.view(b, c, h * w)).view(b, -1, h, w)
+
+ # Generate mask quality predictions
+ iou_pred = self.iou_prediction_head(iou_token_out)
+
+ return masks, iou_pred
+
+
+# Lightly adapted from
+# https://github.com/facebookresearch/MaskFormer/blob/main/mask_former/modeling/transformer/transformer_predictor.py # noqa
+class MLP(nn.Module):
+ def __init__(
+ self,
+ input_dim: int,
+ hidden_dim: int,
+ output_dim: int,
+ num_layers: int,
+ sigmoid_output: bool = False,
+ ) -> None:
+ super().__init__()
+ self.num_layers = num_layers
+ h = [hidden_dim] * (num_layers - 1)
+ self.layers = nn.ModuleList(
+ nn.Linear(n, k) for n, k in zip([input_dim] + h, h + [output_dim])
+ )
+ self.sigmoid_output = sigmoid_output
+
+ def forward(self, x):
+ for i, layer in enumerate(self.layers):
+ x = F.relu(layer(x)) if i < self.num_layers - 1 else layer(x)
+ if self.sigmoid_output:
+ x = F.sigmoid(x)
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/prompt_encoder.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/prompt_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..c3143f4f8e02ddd7ca8587b40ff5d47c3a6b7ef3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/prompt_encoder.py
@@ -0,0 +1,214 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+from torch import nn
+
+from typing import Any, Optional, Tuple, Type
+
+from .common import LayerNorm2d
+
+
+class PromptEncoder(nn.Module):
+ def __init__(
+ self,
+ embed_dim: int,
+ image_embedding_size: Tuple[int, int],
+ input_image_size: Tuple[int, int],
+ mask_in_chans: int,
+ activation: Type[nn.Module] = nn.GELU,
+ ) -> None:
+ """
+ Encodes prompts for input to SAM's mask decoder.
+
+ Arguments:
+ embed_dim (int): The prompts' embedding dimension
+ image_embedding_size (tuple(int, int)): The spatial size of the
+ image embedding, as (H, W).
+ input_image_size (int): The padded size of the image as input
+ to the image encoder, as (H, W).
+ mask_in_chans (int): The number of hidden channels used for
+ encoding input masks.
+ activation (nn.Module): The activation to use when encoding
+ input masks.
+ """
+ super().__init__()
+ self.embed_dim = embed_dim
+ self.input_image_size = input_image_size
+ self.image_embedding_size = image_embedding_size
+ self.pe_layer = PositionEmbeddingRandom(embed_dim // 2)
+
+ self.num_point_embeddings: int = 4 # pos/neg point + 2 box corners
+ point_embeddings = [nn.Embedding(1, embed_dim) for i in range(self.num_point_embeddings)]
+ self.point_embeddings = nn.ModuleList(point_embeddings)
+ self.not_a_point_embed = nn.Embedding(1, embed_dim)
+
+ self.mask_input_size = (4 * image_embedding_size[0], 4 * image_embedding_size[1])
+ self.mask_downscaling = nn.Sequential(
+ nn.Conv2d(1, mask_in_chans // 4, kernel_size=2, stride=2),
+ LayerNorm2d(mask_in_chans // 4),
+ activation(),
+ nn.Conv2d(mask_in_chans // 4, mask_in_chans, kernel_size=2, stride=2),
+ LayerNorm2d(mask_in_chans),
+ activation(),
+ nn.Conv2d(mask_in_chans, embed_dim, kernel_size=1),
+ )
+ self.no_mask_embed = nn.Embedding(1, embed_dim)
+
+ def get_dense_pe(self) -> torch.Tensor:
+ """
+ Returns the positional encoding used to encode point prompts,
+ applied to a dense set of points the shape of the image encoding.
+
+ Returns:
+ torch.Tensor: Positional encoding with shape
+ 1x(embed_dim)x(embedding_h)x(embedding_w)
+ """
+ return self.pe_layer(self.image_embedding_size).unsqueeze(0)
+
+ def _embed_points(
+ self,
+ points: torch.Tensor,
+ labels: torch.Tensor,
+ pad: bool,
+ ) -> torch.Tensor:
+ """Embeds point prompts."""
+ points = points + 0.5 # Shift to center of pixel
+ if pad:
+ padding_point = torch.zeros((points.shape[0], 1, 2), device=points.device)
+ padding_label = -torch.ones((labels.shape[0], 1), device=labels.device)
+ points = torch.cat([points, padding_point], dim=1)
+ labels = torch.cat([labels, padding_label], dim=1)
+ point_embedding = self.pe_layer.forward_with_coords(points, self.input_image_size)
+ point_embedding[labels == -1] = 0.0
+ point_embedding[labels == -1] += self.not_a_point_embed.weight
+ point_embedding[labels == 0] += self.point_embeddings[0].weight
+ point_embedding[labels == 1] += self.point_embeddings[1].weight
+ return point_embedding
+
+ def _embed_boxes(self, boxes: torch.Tensor) -> torch.Tensor:
+ """Embeds box prompts."""
+ boxes = boxes + 0.5 # Shift to center of pixel
+ coords = boxes.reshape(-1, 2, 2)
+ corner_embedding = self.pe_layer.forward_with_coords(coords, self.input_image_size)
+ corner_embedding[:, 0, :] += self.point_embeddings[2].weight
+ corner_embedding[:, 1, :] += self.point_embeddings[3].weight
+ return corner_embedding
+
+ def _embed_masks(self, masks: torch.Tensor) -> torch.Tensor:
+ """Embeds mask inputs."""
+ mask_embedding = self.mask_downscaling(masks)
+ return mask_embedding
+
+ def _get_batch_size(
+ self,
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
+ boxes: Optional[torch.Tensor],
+ masks: Optional[torch.Tensor],
+ ) -> int:
+ """
+ Gets the batch size of the output given the batch size of the input prompts.
+ """
+ if points is not None:
+ return points[0].shape[0]
+ elif boxes is not None:
+ return boxes.shape[0]
+ elif masks is not None:
+ return masks.shape[0]
+ else:
+ return 1
+
+ def _get_device(self) -> torch.device:
+ return self.point_embeddings[0].weight.device
+
+ def forward(
+ self,
+ points: Optional[Tuple[torch.Tensor, torch.Tensor]],
+ boxes: Optional[torch.Tensor],
+ masks: Optional[torch.Tensor],
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Embeds different types of prompts, returning both sparse and dense
+ embeddings.
+
+ Arguments:
+ points (tuple(torch.Tensor, torch.Tensor) or none): point coordinates
+ and labels to embed.
+ boxes (torch.Tensor or none): boxes to embed
+ masks (torch.Tensor or none): masks to embed
+
+ Returns:
+ torch.Tensor: sparse embeddings for the points and boxes, with shape
+ BxNx(embed_dim), where N is determined by the number of input points
+ and boxes.
+ torch.Tensor: dense embeddings for the masks, in the shape
+ Bx(embed_dim)x(embed_H)x(embed_W)
+ """
+ bs = self._get_batch_size(points, boxes, masks)
+ sparse_embeddings = torch.empty((bs, 0, self.embed_dim), device=self._get_device())
+ if points is not None:
+ coords, labels = points
+ point_embeddings = self._embed_points(coords, labels, pad=(boxes is None))
+ sparse_embeddings = torch.cat([sparse_embeddings, point_embeddings], dim=1)
+ if boxes is not None:
+ box_embeddings = self._embed_boxes(boxes)
+ sparse_embeddings = torch.cat([sparse_embeddings, box_embeddings], dim=1)
+
+ if masks is not None:
+ dense_embeddings = self._embed_masks(masks)
+ else:
+ dense_embeddings = self.no_mask_embed.weight.reshape(1, -1, 1, 1).expand(
+ bs, -1, self.image_embedding_size[0], self.image_embedding_size[1]
+ )
+
+ return sparse_embeddings, dense_embeddings
+
+
+class PositionEmbeddingRandom(nn.Module):
+ """
+ Positional encoding using random spatial frequencies.
+ """
+
+ def __init__(self, num_pos_feats: int = 64, scale: Optional[float] = None) -> None:
+ super().__init__()
+ if scale is None or scale <= 0.0:
+ scale = 1.0
+ self.register_buffer(
+ "positional_encoding_gaussian_matrix",
+ scale * torch.randn((2, num_pos_feats)),
+ )
+
+ def _pe_encoding(self, coords: torch.Tensor) -> torch.Tensor:
+ """Positionally encode points that are normalized to [0,1]."""
+ # assuming coords are in [0, 1]^2 square and have d_1 x ... x d_n x 2 shape
+ coords = 2 * coords - 1
+ coords = coords @ self.positional_encoding_gaussian_matrix
+ coords = 2 * np.pi * coords
+ # outputs d_1 x ... x d_n x C shape
+ return torch.cat([torch.sin(coords), torch.cos(coords)], dim=-1)
+
+ def forward(self, size: Tuple[int, int]) -> torch.Tensor:
+ """Generate positional encoding for a grid of the specified size."""
+ h, w = size
+ device: Any = self.positional_encoding_gaussian_matrix.device
+ grid = torch.ones((h, w), device=device, dtype=torch.float32)
+ y_embed = grid.cumsum(dim=0) - 0.5
+ x_embed = grid.cumsum(dim=1) - 0.5
+ y_embed = y_embed / h
+ x_embed = x_embed / w
+
+ pe = self._pe_encoding(torch.stack([x_embed, y_embed], dim=-1))
+ return pe.permute(2, 0, 1) # C x H x W
+
+ def forward_with_coords(
+ self, coords_input: torch.Tensor, image_size: Tuple[int, int]
+ ) -> torch.Tensor:
+ """Positionally encode points that are not normalized to [0,1]."""
+ coords = coords_input.clone()
+ coords[:, :, 0] = coords[:, :, 0] / image_size[1]
+ coords[:, :, 1] = coords[:, :, 1] / image_size[0]
+ return self._pe_encoding(coords.to(torch.float)) # B x N x C
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/sam.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/sam.py
new file mode 100644
index 0000000000000000000000000000000000000000..303bc2f40c3dbc84f5d4286bb73336e075a86589
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/sam.py
@@ -0,0 +1,174 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from typing import Any, Dict, List, Tuple
+
+from .image_encoder import ImageEncoderViT
+from .mask_decoder import MaskDecoder
+from .prompt_encoder import PromptEncoder
+
+
+class Sam(nn.Module):
+ mask_threshold: float = 0.0
+ image_format: str = "RGB"
+
+ def __init__(
+ self,
+ image_encoder: ImageEncoderViT,
+ prompt_encoder: PromptEncoder,
+ mask_decoder: MaskDecoder,
+ pixel_mean: List[float] = [123.675, 116.28, 103.53],
+ pixel_std: List[float] = [58.395, 57.12, 57.375],
+ ) -> None:
+ """
+ SAM predicts object masks from an image and input prompts.
+
+ Arguments:
+ image_encoder (ImageEncoderViT): The backbone used to encode the
+ image into image embeddings that allow for efficient mask prediction.
+ prompt_encoder (PromptEncoder): Encodes various types of input prompts.
+ mask_decoder (MaskDecoder): Predicts masks from the image embeddings
+ and encoded prompts.
+ pixel_mean (list(float)): Mean values for normalizing pixels in the input image.
+ pixel_std (list(float)): Std values for normalizing pixels in the input image.
+ """
+ super().__init__()
+ self.image_encoder = image_encoder
+ self.prompt_encoder = prompt_encoder
+ self.mask_decoder = mask_decoder
+ self.register_buffer("pixel_mean", torch.Tensor(pixel_mean).view(-1, 1, 1), False)
+ self.register_buffer("pixel_std", torch.Tensor(pixel_std).view(-1, 1, 1), False)
+
+ @property
+ def device(self) -> Any:
+ return self.pixel_mean.device
+
+ @torch.no_grad()
+ def forward(
+ self,
+ batched_input: List[Dict[str, Any]],
+ multimask_output: bool,
+ ) -> List[Dict[str, torch.Tensor]]:
+ """
+ Predicts masks end-to-end from provided images and prompts.
+ If prompts are not known in advance, using SamPredictor is
+ recommended over calling the model directly.
+
+ Arguments:
+ batched_input (list(dict)): A list over input images, each a
+ dictionary with the following keys. A prompt key can be
+ excluded if it is not present.
+ 'image': The image as a torch tensor in 3xHxW format,
+ already transformed for input to the model.
+ 'original_size': (tuple(int, int)) The original size of
+ the image before transformation, as (H, W).
+ 'point_coords': (torch.Tensor) Batched point prompts for
+ this image, with shape BxNx2. Already transformed to the
+ input frame of the model.
+ 'point_labels': (torch.Tensor) Batched labels for point prompts,
+ with shape BxN.
+ 'boxes': (torch.Tensor) Batched box inputs, with shape Bx4.
+ Already transformed to the input frame of the model.
+ 'mask_inputs': (torch.Tensor) Batched mask inputs to the model,
+ in the form Bx1xHxW.
+ multimask_output (bool): Whether the model should predict multiple
+ disambiguating masks, or return a single mask.
+
+ Returns:
+ (list(dict)): A list over input images, where each element is
+ as dictionary with the following keys.
+ 'masks': (torch.Tensor) Batched binary mask predictions,
+ with shape BxCxHxW, where B is the number of input promts,
+ C is determiend by multimask_output, and (H, W) is the
+ original size of the image.
+ 'iou_predictions': (torch.Tensor) The model's predictions
+ of mask quality, in shape BxC.
+ 'low_res_logits': (torch.Tensor) Low resolution logits with
+ shape BxCxHxW, where H=W=256. Can be passed as mask input
+ to subsequent iterations of prediction.
+ """
+ input_images = torch.stack([self.preprocess(x["image"]) for x in batched_input], dim=0)
+ image_embeddings = self.image_encoder(input_images)
+
+ outputs = []
+ for image_record, curr_embedding in zip(batched_input, image_embeddings):
+ if "point_coords" in image_record:
+ points = (image_record["point_coords"], image_record["point_labels"])
+ else:
+ points = None
+ sparse_embeddings, dense_embeddings = self.prompt_encoder(
+ points=points,
+ boxes=image_record.get("boxes", None),
+ masks=image_record.get("mask_inputs", None),
+ )
+ low_res_masks, iou_predictions = self.mask_decoder(
+ image_embeddings=curr_embedding.unsqueeze(0),
+ image_pe=self.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ )
+ masks = self.postprocess_masks(
+ low_res_masks,
+ input_size=image_record["image"].shape[-2:],
+ original_size=image_record["original_size"],
+ )
+ masks = masks > self.mask_threshold
+ outputs.append(
+ {
+ "masks": masks,
+ "iou_predictions": iou_predictions,
+ "low_res_logits": low_res_masks,
+ }
+ )
+ return outputs
+
+ def postprocess_masks(
+ self,
+ masks: torch.Tensor,
+ input_size: Tuple[int, ...],
+ original_size: Tuple[int, ...],
+ ) -> torch.Tensor:
+ """
+ Remove padding and upscale masks to the original image size.
+
+ Arguments:
+ masks (torch.Tensor): Batched masks from the mask_decoder,
+ in BxCxHxW format.
+ input_size (tuple(int, int)): The size of the image input to the
+ model, in (H, W) format. Used to remove padding.
+ original_size (tuple(int, int)): The original size of the image
+ before resizing for input to the model, in (H, W) format.
+
+ Returns:
+ (torch.Tensor): Batched masks in BxCxHxW format, where (H, W)
+ is given by original_size.
+ """
+ masks = F.interpolate(
+ masks,
+ (self.image_encoder.img_size, self.image_encoder.img_size),
+ mode="bilinear",
+ align_corners=False,
+ )
+ masks = masks[..., : input_size[0], : input_size[1]]
+ masks = F.interpolate(masks, original_size, mode="bilinear", align_corners=False)
+ return masks
+
+ def preprocess(self, x: torch.Tensor) -> torch.Tensor:
+ """Normalize pixel values and pad to a square input."""
+ # Normalize colors
+ x = (x - self.pixel_mean) / self.pixel_std
+
+ # Pad
+ h, w = x.shape[-2:]
+ padh = self.image_encoder.img_size - h
+ padw = self.image_encoder.img_size - w
+ x = F.pad(x, (0, padw, 0, padh))
+ return x
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/transformer.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/transformer.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1a2812f613cc55b1d0b3e3e1d0c84a760d1fb87
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/modeling/transformer.py
@@ -0,0 +1,240 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+from torch import Tensor, nn
+
+import math
+from typing import Tuple, Type
+
+from .common import MLPBlock
+
+
+class TwoWayTransformer(nn.Module):
+ def __init__(
+ self,
+ depth: int,
+ embedding_dim: int,
+ num_heads: int,
+ mlp_dim: int,
+ activation: Type[nn.Module] = nn.ReLU,
+ attention_downsample_rate: int = 2,
+ ) -> None:
+ """
+ A transformer decoder that attends to an input image using
+ queries whose positional embedding is supplied.
+
+ Args:
+ depth (int): number of layers in the transformer
+ embedding_dim (int): the channel dimension for the input embeddings
+ num_heads (int): the number of heads for multihead attention. Must
+ divide embedding_dim
+ mlp_dim (int): the channel dimension internal to the MLP block
+ activation (nn.Module): the activation to use in the MLP block
+ """
+ super().__init__()
+ self.depth = depth
+ self.embedding_dim = embedding_dim
+ self.num_heads = num_heads
+ self.mlp_dim = mlp_dim
+ self.layers = nn.ModuleList()
+
+ for i in range(depth):
+ self.layers.append(
+ TwoWayAttentionBlock(
+ embedding_dim=embedding_dim,
+ num_heads=num_heads,
+ mlp_dim=mlp_dim,
+ activation=activation,
+ attention_downsample_rate=attention_downsample_rate,
+ skip_first_layer_pe=(i == 0),
+ )
+ )
+
+ self.final_attn_token_to_image = Attention(
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+ )
+ self.norm_final_attn = nn.LayerNorm(embedding_dim)
+
+ def forward(
+ self,
+ image_embedding: Tensor,
+ image_pe: Tensor,
+ point_embedding: Tensor,
+ ) -> Tuple[Tensor, Tensor]:
+ """
+ Args:
+ image_embedding (torch.Tensor): image to attend to. Should be shape
+ B x embedding_dim x h x w for any h and w.
+ image_pe (torch.Tensor): the positional encoding to add to the image. Must
+ have the same shape as image_embedding.
+ point_embedding (torch.Tensor): the embedding to add to the query points.
+ Must have shape B x N_points x embedding_dim for any N_points.
+
+ Returns:
+ torch.Tensor: the processed point_embedding
+ torch.Tensor: the processed image_embedding
+ """
+ # BxCxHxW -> BxHWxC == B x N_image_tokens x C
+ bs, c, h, w = image_embedding.shape
+ image_embedding = image_embedding.flatten(2).permute(0, 2, 1)
+ image_pe = image_pe.flatten(2).permute(0, 2, 1)
+
+ # Prepare queries
+ queries = point_embedding
+ keys = image_embedding
+
+ # Apply transformer blocks and final layernorm
+ for layer in self.layers:
+ queries, keys = layer(
+ queries=queries,
+ keys=keys,
+ query_pe=point_embedding,
+ key_pe=image_pe,
+ )
+
+ # Apply the final attenion layer from the points to the image
+ q = queries + point_embedding
+ k = keys + image_pe
+ attn_out = self.final_attn_token_to_image(q=q, k=k, v=keys)
+ queries = queries + attn_out
+ queries = self.norm_final_attn(queries)
+
+ return queries, keys
+
+
+class TwoWayAttentionBlock(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ num_heads: int,
+ mlp_dim: int = 2048,
+ activation: Type[nn.Module] = nn.ReLU,
+ attention_downsample_rate: int = 2,
+ skip_first_layer_pe: bool = False,
+ ) -> None:
+ """
+ A transformer block with four layers: (1) self-attention of sparse
+ inputs, (2) cross attention of sparse inputs to dense inputs, (3) mlp
+ block on sparse inputs, and (4) cross attention of dense inputs to sparse
+ inputs.
+
+ Arguments:
+ embedding_dim (int): the channel dimension of the embeddings
+ num_heads (int): the number of heads in the attention layers
+ mlp_dim (int): the hidden dimension of the mlp block
+ activation (nn.Module): the activation of the mlp block
+ skip_first_layer_pe (bool): skip the PE on the first layer
+ """
+ super().__init__()
+ self.self_attn = Attention(embedding_dim, num_heads)
+ self.norm1 = nn.LayerNorm(embedding_dim)
+
+ self.cross_attn_token_to_image = Attention(
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+ )
+ self.norm2 = nn.LayerNorm(embedding_dim)
+
+ self.mlp = MLPBlock(embedding_dim, mlp_dim, activation)
+ self.norm3 = nn.LayerNorm(embedding_dim)
+
+ self.norm4 = nn.LayerNorm(embedding_dim)
+ self.cross_attn_image_to_token = Attention(
+ embedding_dim, num_heads, downsample_rate=attention_downsample_rate
+ )
+
+ self.skip_first_layer_pe = skip_first_layer_pe
+
+ def forward(
+ self, queries: Tensor, keys: Tensor, query_pe: Tensor, key_pe: Tensor
+ ) -> Tuple[Tensor, Tensor]:
+ # Self attention block
+ if self.skip_first_layer_pe:
+ queries = self.self_attn(q=queries, k=queries, v=queries)
+ else:
+ q = queries + query_pe
+ attn_out = self.self_attn(q=q, k=q, v=queries)
+ queries = queries + attn_out
+ queries = self.norm1(queries)
+
+ # Cross attention block, tokens attending to image embedding
+ q = queries + query_pe
+ k = keys + key_pe
+ attn_out = self.cross_attn_token_to_image(q=q, k=k, v=keys)
+ queries = queries + attn_out
+ queries = self.norm2(queries)
+
+ # MLP block
+ mlp_out = self.mlp(queries)
+ queries = queries + mlp_out
+ queries = self.norm3(queries)
+
+ # Cross attention block, image embedding attending to tokens
+ q = queries + query_pe
+ k = keys + key_pe
+ attn_out = self.cross_attn_image_to_token(q=k, k=q, v=queries)
+ keys = keys + attn_out
+ keys = self.norm4(keys)
+
+ return queries, keys
+
+
+class Attention(nn.Module):
+ """
+ An attention layer that allows for downscaling the size of the embedding
+ after projection to queries, keys, and values.
+ """
+
+ def __init__(
+ self,
+ embedding_dim: int,
+ num_heads: int,
+ downsample_rate: int = 1,
+ ) -> None:
+ super().__init__()
+ self.embedding_dim = embedding_dim
+ self.internal_dim = embedding_dim // downsample_rate
+ self.num_heads = num_heads
+ assert self.internal_dim % num_heads == 0, "num_heads must divide embedding_dim."
+
+ self.q_proj = nn.Linear(embedding_dim, self.internal_dim)
+ self.k_proj = nn.Linear(embedding_dim, self.internal_dim)
+ self.v_proj = nn.Linear(embedding_dim, self.internal_dim)
+ self.out_proj = nn.Linear(self.internal_dim, embedding_dim)
+
+ def _separate_heads(self, x: Tensor, num_heads: int) -> Tensor:
+ b, n, c = x.shape
+ x = x.reshape(b, n, num_heads, c // num_heads)
+ return x.transpose(1, 2) # B x N_heads x N_tokens x C_per_head
+
+ def _recombine_heads(self, x: Tensor) -> Tensor:
+ b, n_heads, n_tokens, c_per_head = x.shape
+ x = x.transpose(1, 2)
+ return x.reshape(b, n_tokens, n_heads * c_per_head) # B x N_tokens x C
+
+ def forward(self, q: Tensor, k: Tensor, v: Tensor) -> Tensor:
+ # Input projections
+ q = self.q_proj(q)
+ k = self.k_proj(k)
+ v = self.v_proj(v)
+
+ # Separate into heads
+ q = self._separate_heads(q, self.num_heads)
+ k = self._separate_heads(k, self.num_heads)
+ v = self._separate_heads(v, self.num_heads)
+
+ # Attention
+ _, _, _, c_per_head = q.shape
+ attn = q @ k.permute(0, 1, 3, 2) # B x N_heads x N_tokens x N_tokens
+ attn = attn / math.sqrt(c_per_head)
+ attn = torch.softmax(attn, dim=-1)
+
+ # Get output
+ out = attn @ v
+ out = self._recombine_heads(out)
+ out = self.out_proj(out)
+
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/predictor.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/predictor.py
new file mode 100644
index 0000000000000000000000000000000000000000..57c089d1fc4a6bbf5786e1ef62c59e22d582f5aa
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/predictor.py
@@ -0,0 +1,269 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+
+from segment_anything.modeling import Sam
+
+from typing import Optional, Tuple
+
+from .utils.transforms import ResizeLongestSide
+
+
+class SamPredictor:
+ def __init__(
+ self,
+ sam_model: Sam,
+ ) -> None:
+ """
+ Uses SAM to calculate the image embedding for an image, and then
+ allow repeated, efficient mask prediction given prompts.
+
+ Arguments:
+ sam_model (Sam): The model to use for mask prediction.
+ """
+ super().__init__()
+ self.model = sam_model
+ self.transform = ResizeLongestSide(sam_model.image_encoder.img_size)
+ self.reset_image()
+
+ def set_image(
+ self,
+ image: np.ndarray,
+ image_format: str = "RGB",
+ ) -> None:
+ """
+ Calculates the image embeddings for the provided image, allowing
+ masks to be predicted with the 'predict' method.
+
+ Arguments:
+ image (np.ndarray): The image for calculating masks. Expects an
+ image in HWC uint8 format, with pixel values in [0, 255].
+ image_format (str): The color format of the image, in ['RGB', 'BGR'].
+ """
+ assert image_format in [
+ "RGB",
+ "BGR",
+ ], f"image_format must be in ['RGB', 'BGR'], is {image_format}."
+ if image_format != self.model.image_format:
+ image = image[..., ::-1]
+
+ # Transform the image to the form expected by the model
+ input_image = self.transform.apply_image(image)
+ input_image_torch = torch.as_tensor(input_image, device=self.device)
+ input_image_torch = input_image_torch.permute(2, 0, 1).contiguous()[None, :, :, :]
+
+ self.set_torch_image(input_image_torch, image.shape[:2])
+
+ @torch.no_grad()
+ def set_torch_image(
+ self,
+ transformed_image: torch.Tensor,
+ original_image_size: Tuple[int, ...],
+ ) -> None:
+ """
+ Calculates the image embeddings for the provided image, allowing
+ masks to be predicted with the 'predict' method. Expects the input
+ image to be already transformed to the format expected by the model.
+
+ Arguments:
+ transformed_image (torch.Tensor): The input image, with shape
+ 1x3xHxW, which has been transformed with ResizeLongestSide.
+ original_image_size (tuple(int, int)): The size of the image
+ before transformation, in (H, W) format.
+ """
+ assert (
+ len(transformed_image.shape) == 4
+ and transformed_image.shape[1] == 3
+ and max(*transformed_image.shape[2:]) == self.model.image_encoder.img_size
+ ), f"set_torch_image input must be BCHW with long side {self.model.image_encoder.img_size}."
+ self.reset_image()
+
+ self.original_size = original_image_size
+ self.input_size = tuple(transformed_image.shape[-2:])
+ input_image = self.model.preprocess(transformed_image)
+ self.features = self.model.image_encoder(input_image)
+ self.is_image_set = True
+
+ def predict(
+ self,
+ point_coords: Optional[np.ndarray] = None,
+ point_labels: Optional[np.ndarray] = None,
+ box: Optional[np.ndarray] = None,
+ mask_input: Optional[np.ndarray] = None,
+ multimask_output: bool = True,
+ return_logits: bool = False,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Predict masks for the given input prompts, using the currently set image.
+
+ Arguments:
+ point_coords (np.ndarray or None): A Nx2 array of point prompts to the
+ model. Each point is in (X,Y) in pixels.
+ point_labels (np.ndarray or None): A length N array of labels for the
+ point prompts. 1 indicates a foreground point and 0 indicates a
+ background point.
+ box (np.ndarray or None): A length 4 array given a box prompt to the
+ model, in XYXY format.
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
+ coming from a previous prediction iteration. Has form 1xHxW, where
+ for SAM, H=W=256.
+ multimask_output (bool): If true, the model will return three masks.
+ For ambiguous input prompts (such as a single click), this will often
+ produce better masks than a single prediction. If only a single
+ mask is needed, the model's predicted quality score can be used
+ to select the best mask. For non-ambiguous prompts, such as multiple
+ input prompts, multimask_output=False can give better results.
+ return_logits (bool): If true, returns un-thresholded masks logits
+ instead of a binary mask.
+
+ Returns:
+ (np.ndarray): The output masks in CxHxW format, where C is the
+ number of masks, and (H, W) is the original image size.
+ (np.ndarray): An array of length C containing the model's
+ predictions for the quality of each mask.
+ (np.ndarray): An array of shape CxHxW, where C is the number
+ of masks and H=W=256. These low resolution logits can be passed to
+ a subsequent iteration as mask input.
+ """
+ if not self.is_image_set:
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
+
+ # Transform input prompts
+ coords_torch, labels_torch, box_torch, mask_input_torch = None, None, None, None
+ if point_coords is not None:
+ assert (
+ point_labels is not None
+ ), "point_labels must be supplied if point_coords is supplied."
+ point_coords = self.transform.apply_coords(point_coords, self.original_size)
+ coords_torch = torch.as_tensor(point_coords, dtype=torch.float, device=self.device)
+ labels_torch = torch.as_tensor(point_labels, dtype=torch.int, device=self.device)
+ coords_torch, labels_torch = coords_torch[None, :, :], labels_torch[None, :]
+ if box is not None:
+ box = self.transform.apply_boxes(box, self.original_size)
+ box_torch = torch.as_tensor(box, dtype=torch.float, device=self.device)
+ box_torch = box_torch[None, :]
+ if mask_input is not None:
+ mask_input_torch = torch.as_tensor(mask_input, dtype=torch.float, device=self.device)
+ mask_input_torch = mask_input_torch[None, :, :, :]
+
+ masks, iou_predictions, low_res_masks = self.predict_torch(
+ coords_torch,
+ labels_torch,
+ box_torch,
+ mask_input_torch,
+ multimask_output,
+ return_logits=return_logits,
+ )
+
+ masks = masks[0].detach().cpu().numpy()
+ iou_predictions = iou_predictions[0].detach().cpu().numpy()
+ low_res_masks = low_res_masks[0].detach().cpu().numpy()
+ return masks, iou_predictions, low_res_masks
+
+ @torch.no_grad()
+ def predict_torch(
+ self,
+ point_coords: Optional[torch.Tensor],
+ point_labels: Optional[torch.Tensor],
+ boxes: Optional[torch.Tensor] = None,
+ mask_input: Optional[torch.Tensor] = None,
+ multimask_output: bool = True,
+ return_logits: bool = False,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+ """
+ Predict masks for the given input prompts, using the currently set image.
+ Input prompts are batched torch tensors and are expected to already be
+ transformed to the input frame using ResizeLongestSide.
+
+ Arguments:
+ point_coords (torch.Tensor or None): A BxNx2 array of point prompts to the
+ model. Each point is in (X,Y) in pixels.
+ point_labels (torch.Tensor or None): A BxN array of labels for the
+ point prompts. 1 indicates a foreground point and 0 indicates a
+ background point.
+ box (np.ndarray or None): A Bx4 array given a box prompt to the
+ model, in XYXY format.
+ mask_input (np.ndarray): A low resolution mask input to the model, typically
+ coming from a previous prediction iteration. Has form Bx1xHxW, where
+ for SAM, H=W=256. Masks returned by a previous iteration of the
+ predict method do not need further transformation.
+ multimask_output (bool): If true, the model will return three masks.
+ For ambiguous input prompts (such as a single click), this will often
+ produce better masks than a single prediction. If only a single
+ mask is needed, the model's predicted quality score can be used
+ to select the best mask. For non-ambiguous prompts, such as multiple
+ input prompts, multimask_output=False can give better results.
+ return_logits (bool): If true, returns un-thresholded masks logits
+ instead of a binary mask.
+
+ Returns:
+ (torch.Tensor): The output masks in BxCxHxW format, where C is the
+ number of masks, and (H, W) is the original image size.
+ (torch.Tensor): An array of shape BxC containing the model's
+ predictions for the quality of each mask.
+ (torch.Tensor): An array of shape BxCxHxW, where C is the number
+ of masks and H=W=256. These low res logits can be passed to
+ a subsequent iteration as mask input.
+ """
+ if not self.is_image_set:
+ raise RuntimeError("An image must be set with .set_image(...) before mask prediction.")
+
+ if point_coords is not None:
+ points = (point_coords, point_labels)
+ else:
+ points = None
+
+ # Embed prompts
+ sparse_embeddings, dense_embeddings = self.model.prompt_encoder(
+ points=points,
+ boxes=boxes,
+ masks=mask_input,
+ )
+
+ # Predict masks
+ low_res_masks, iou_predictions = self.model.mask_decoder(
+ image_embeddings=self.features,
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embeddings,
+ dense_prompt_embeddings=dense_embeddings,
+ multimask_output=multimask_output,
+ )
+
+ # Upscale the masks to the original image resolution
+ masks = self.model.postprocess_masks(low_res_masks, self.input_size, self.original_size)
+
+ if not return_logits:
+ masks = masks > self.model.mask_threshold
+
+ return masks, iou_predictions, low_res_masks
+
+ def get_image_embedding(self) -> torch.Tensor:
+ """
+ Returns the image embeddings for the currently set image, with
+ shape 1xCxHxW, where C is the embedding dimension and (H,W) are
+ the embedding spatial dimension of SAM (typically C=256, H=W=64).
+ """
+ if not self.is_image_set:
+ raise RuntimeError(
+ "An image must be set with .set_image(...) to generate an embedding."
+ )
+ assert self.features is not None, "Features must exist if an image has been set."
+ return self.features
+
+ @property
+ def device(self) -> torch.device:
+ return self.model.device
+
+ def reset_image(self) -> None:
+ """Resets the currently set image."""
+ self.is_image_set = False
+ self.features = None
+ self.orig_h = None
+ self.orig_w = None
+ self.input_h = None
+ self.input_w = None
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5277f46157403e47fd830fc519144b97ef69d4ae
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/__init__.py
@@ -0,0 +1,5 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/amg.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/amg.py
new file mode 100644
index 0000000000000000000000000000000000000000..3a137778e45c464c079658ecb87ec53270e789f7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/amg.py
@@ -0,0 +1,346 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+
+import math
+from copy import deepcopy
+from itertools import product
+from typing import Any, Dict, Generator, ItemsView, List, Tuple
+
+
+class MaskData:
+ """
+ A structure for storing masks and their related data in batched format.
+ Implements basic filtering and concatenation.
+ """
+
+ def __init__(self, **kwargs) -> None:
+ for v in kwargs.values():
+ assert isinstance(
+ v, (list, np.ndarray, torch.Tensor)
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
+ self._stats = dict(**kwargs)
+
+ def __setitem__(self, key: str, item: Any) -> None:
+ assert isinstance(
+ item, (list, np.ndarray, torch.Tensor)
+ ), "MaskData only supports list, numpy arrays, and torch tensors."
+ self._stats[key] = item
+
+ def __delitem__(self, key: str) -> None:
+ del self._stats[key]
+
+ def __getitem__(self, key: str) -> Any:
+ return self._stats[key]
+
+ def items(self) -> ItemsView[str, Any]:
+ return self._stats.items()
+
+ def filter(self, keep: torch.Tensor) -> None:
+ for k, v in self._stats.items():
+ if v is None:
+ self._stats[k] = None
+ elif isinstance(v, torch.Tensor):
+ self._stats[k] = v[torch.as_tensor(keep, device=v.device)]
+ elif isinstance(v, np.ndarray):
+ self._stats[k] = v[keep.detach().cpu().numpy()]
+ elif isinstance(v, list) and keep.dtype == torch.bool:
+ self._stats[k] = [a for i, a in enumerate(v) if keep[i]]
+ elif isinstance(v, list):
+ self._stats[k] = [v[i] for i in keep]
+ else:
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
+
+ def cat(self, new_stats: "MaskData") -> None:
+ for k, v in new_stats.items():
+ if k not in self._stats or self._stats[k] is None:
+ self._stats[k] = deepcopy(v)
+ elif isinstance(v, torch.Tensor):
+ self._stats[k] = torch.cat([self._stats[k], v], dim=0)
+ elif isinstance(v, np.ndarray):
+ self._stats[k] = np.concatenate([self._stats[k], v], axis=0)
+ elif isinstance(v, list):
+ self._stats[k] = self._stats[k] + deepcopy(v)
+ else:
+ raise TypeError(f"MaskData key {k} has an unsupported type {type(v)}.")
+
+ def to_numpy(self) -> None:
+ for k, v in self._stats.items():
+ if isinstance(v, torch.Tensor):
+ self._stats[k] = v.detach().cpu().numpy()
+
+
+def is_box_near_crop_edge(
+ boxes: torch.Tensor, crop_box: List[int], orig_box: List[int], atol: float = 20.0
+) -> torch.Tensor:
+ """Filter masks at the edge of a crop, but not at the edge of the original image."""
+ crop_box_torch = torch.as_tensor(crop_box, dtype=torch.float, device=boxes.device)
+ orig_box_torch = torch.as_tensor(orig_box, dtype=torch.float, device=boxes.device)
+ boxes = uncrop_boxes_xyxy(boxes, crop_box).float()
+ near_crop_edge = torch.isclose(boxes, crop_box_torch[None, :], atol=atol, rtol=0)
+ near_image_edge = torch.isclose(boxes, orig_box_torch[None, :], atol=atol, rtol=0)
+ near_crop_edge = torch.logical_and(near_crop_edge, ~near_image_edge)
+ return torch.any(near_crop_edge, dim=1)
+
+
+def box_xyxy_to_xywh(box_xyxy: torch.Tensor) -> torch.Tensor:
+ box_xywh = deepcopy(box_xyxy)
+ box_xywh[2] = box_xywh[2] - box_xywh[0]
+ box_xywh[3] = box_xywh[3] - box_xywh[1]
+ return box_xywh
+
+
+def batch_iterator(batch_size: int, *args) -> Generator[List[Any], None, None]:
+ assert len(args) > 0 and all(
+ len(a) == len(args[0]) for a in args
+ ), "Batched iteration must have inputs of all the same size."
+ n_batches = len(args[0]) // batch_size + int(len(args[0]) % batch_size != 0)
+ for b in range(n_batches):
+ yield [arg[b * batch_size : (b + 1) * batch_size] for arg in args]
+
+
+def mask_to_rle_pytorch(tensor: torch.Tensor) -> List[Dict[str, Any]]:
+ """
+ Encodes masks to an uncompressed RLE, in the format expected by
+ pycoco tools.
+ """
+ # Put in fortran order and flatten h,w
+ b, h, w = tensor.shape
+ tensor = tensor.permute(0, 2, 1).flatten(1)
+
+ # Compute change indices
+ diff = tensor[:, 1:] ^ tensor[:, :-1]
+ change_indices = diff.nonzero()
+
+ # Encode run length
+ out = []
+ for i in range(b):
+ cur_idxs = change_indices[change_indices[:, 0] == i, 1]
+ cur_idxs = torch.cat(
+ [
+ torch.tensor([0], dtype=cur_idxs.dtype, device=cur_idxs.device),
+ cur_idxs + 1,
+ torch.tensor([h * w], dtype=cur_idxs.dtype, device=cur_idxs.device),
+ ]
+ )
+ btw_idxs = cur_idxs[1:] - cur_idxs[:-1]
+ counts = [] if tensor[i, 0] == 0 else [0]
+ counts.extend(btw_idxs.detach().cpu().tolist())
+ out.append({"size": [h, w], "counts": counts})
+ return out
+
+
+def rle_to_mask(rle: Dict[str, Any]) -> np.ndarray:
+ """Compute a binary mask from an uncompressed RLE."""
+ h, w = rle["size"]
+ mask = np.empty(h * w, dtype=bool)
+ idx = 0
+ parity = False
+ for count in rle["counts"]:
+ mask[idx : idx + count] = parity
+ idx += count
+ parity ^= True
+ mask = mask.reshape(w, h)
+ return mask.transpose() # Put in C order
+
+
+def area_from_rle(rle: Dict[str, Any]) -> int:
+ return sum(rle["counts"][1::2])
+
+
+def calculate_stability_score(
+ masks: torch.Tensor, mask_threshold: float, threshold_offset: float
+) -> torch.Tensor:
+ """
+ Computes the stability score for a batch of masks. The stability
+ score is the IoU between the binary masks obtained by thresholding
+ the predicted mask logits at high and low values.
+ """
+ # One mask is always contained inside the other.
+ # Save memory by preventing unnecesary cast to torch.int64
+ intersections = (
+ (masks > (mask_threshold + threshold_offset))
+ .sum(-1, dtype=torch.int16)
+ .sum(-1, dtype=torch.int32)
+ )
+ unions = (
+ (masks > (mask_threshold - threshold_offset))
+ .sum(-1, dtype=torch.int16)
+ .sum(-1, dtype=torch.int32)
+ )
+ return intersections / unions
+
+
+def build_point_grid(n_per_side: int) -> np.ndarray:
+ """Generates a 2D grid of points evenly spaced in [0,1]x[0,1]."""
+ offset = 1 / (2 * n_per_side)
+ points_one_side = np.linspace(offset, 1 - offset, n_per_side)
+ points_x = np.tile(points_one_side[None, :], (n_per_side, 1))
+ points_y = np.tile(points_one_side[:, None], (1, n_per_side))
+ points = np.stack([points_x, points_y], axis=-1).reshape(-1, 2)
+ return points
+
+
+def build_all_layer_point_grids(
+ n_per_side: int, n_layers: int, scale_per_layer: int
+) -> List[np.ndarray]:
+ """Generates point grids for all crop layers."""
+ points_by_layer = []
+ for i in range(n_layers + 1):
+ n_points = int(n_per_side / (scale_per_layer**i))
+ points_by_layer.append(build_point_grid(n_points))
+ return points_by_layer
+
+
+def generate_crop_boxes(
+ im_size: Tuple[int, ...], n_layers: int, overlap_ratio: float
+) -> Tuple[List[List[int]], List[int]]:
+ """
+ Generates a list of crop boxes of different sizes. Each layer
+ has (2**i)**2 boxes for the ith layer.
+ """
+ crop_boxes, layer_idxs = [], []
+ im_h, im_w = im_size
+ short_side = min(im_h, im_w)
+
+ # Original image
+ crop_boxes.append([0, 0, im_w, im_h])
+ layer_idxs.append(0)
+
+ def crop_len(orig_len, n_crops, overlap):
+ return int(math.ceil((overlap * (n_crops - 1) + orig_len) / n_crops))
+
+ for i_layer in range(n_layers):
+ n_crops_per_side = 2 ** (i_layer + 1)
+ overlap = int(overlap_ratio * short_side * (2 / n_crops_per_side))
+
+ crop_w = crop_len(im_w, n_crops_per_side, overlap)
+ crop_h = crop_len(im_h, n_crops_per_side, overlap)
+
+ crop_box_x0 = [int((crop_w - overlap) * i) for i in range(n_crops_per_side)]
+ crop_box_y0 = [int((crop_h - overlap) * i) for i in range(n_crops_per_side)]
+
+ # Crops in XYWH format
+ for x0, y0 in product(crop_box_x0, crop_box_y0):
+ box = [x0, y0, min(x0 + crop_w, im_w), min(y0 + crop_h, im_h)]
+ crop_boxes.append(box)
+ layer_idxs.append(i_layer + 1)
+
+ return crop_boxes, layer_idxs
+
+
+def uncrop_boxes_xyxy(boxes: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
+ x0, y0, _, _ = crop_box
+ offset = torch.tensor([[x0, y0, x0, y0]], device=boxes.device)
+ # Check if boxes has a channel dimension
+ if len(boxes.shape) == 3:
+ offset = offset.unsqueeze(1)
+ return boxes + offset
+
+
+def uncrop_points(points: torch.Tensor, crop_box: List[int]) -> torch.Tensor:
+ x0, y0, _, _ = crop_box
+ offset = torch.tensor([[x0, y0]], device=points.device)
+ # Check if points has a channel dimension
+ if len(points.shape) == 3:
+ offset = offset.unsqueeze(1)
+ return points + offset
+
+
+def uncrop_masks(
+ masks: torch.Tensor, crop_box: List[int], orig_h: int, orig_w: int
+) -> torch.Tensor:
+ x0, y0, x1, y1 = crop_box
+ if x0 == 0 and y0 == 0 and x1 == orig_w and y1 == orig_h:
+ return masks
+ # Coordinate transform masks
+ pad_x, pad_y = orig_w - (x1 - x0), orig_h - (y1 - y0)
+ pad = (x0, pad_x - x0, y0, pad_y - y0)
+ return torch.nn.functional.pad(masks, pad, value=0)
+
+
+def remove_small_regions(
+ mask: np.ndarray, area_thresh: float, mode: str
+) -> Tuple[np.ndarray, bool]:
+ """
+ Removes small disconnected regions and holes in a mask. Returns the
+ mask and an indicator of if the mask has been modified.
+ """
+ import cv2 # type: ignore
+
+ assert mode in ["holes", "islands"]
+ correct_holes = mode == "holes"
+ working_mask = (correct_holes ^ mask).astype(np.uint8)
+ n_labels, regions, stats, _ = cv2.connectedComponentsWithStats(working_mask, 8)
+ sizes = stats[:, -1][1:] # Row 0 is background label
+ small_regions = [i + 1 for i, s in enumerate(sizes) if s < area_thresh]
+ if len(small_regions) == 0:
+ return mask, False
+ fill_labels = [0] + small_regions
+ if not correct_holes:
+ fill_labels = [i for i in range(n_labels) if i not in fill_labels]
+ # If every region is below threshold, keep largest
+ if len(fill_labels) == 0:
+ fill_labels = [int(np.argmax(sizes)) + 1]
+ mask = np.isin(regions, fill_labels)
+ return mask, True
+
+
+def coco_encode_rle(uncompressed_rle: Dict[str, Any]) -> Dict[str, Any]:
+ from pycocotools import mask as mask_utils # type: ignore
+
+ h, w = uncompressed_rle["size"]
+ rle = mask_utils.frPyObjects(uncompressed_rle, h, w)
+ rle["counts"] = rle["counts"].decode("utf-8") # Necessary to serialize with json
+ return rle
+
+
+def batched_mask_to_box(masks: torch.Tensor) -> torch.Tensor:
+ """
+ Calculates boxes in XYXY format around masks. Return [0,0,0,0] for
+ an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
+ """
+ # torch.max below raises an error on empty inputs, just skip in this case
+ if torch.numel(masks) == 0:
+ return torch.zeros(*masks.shape[:-2], 4, device=masks.device)
+
+ # Normalize shape to CxHxW
+ shape = masks.shape
+ h, w = shape[-2:]
+ if len(shape) > 2:
+ masks = masks.flatten(0, -3)
+ else:
+ masks = masks.unsqueeze(0)
+
+ # Get top and bottom edges
+ in_height, _ = torch.max(masks, dim=-1)
+ in_height_coords = in_height * torch.arange(h, device=in_height.device)[None, :]
+ bottom_edges, _ = torch.max(in_height_coords, dim=-1)
+ in_height_coords = in_height_coords + h * (~in_height)
+ top_edges, _ = torch.min(in_height_coords, dim=-1)
+
+ # Get left and right edges
+ in_width, _ = torch.max(masks, dim=-2)
+ in_width_coords = in_width * torch.arange(w, device=in_width.device)[None, :]
+ right_edges, _ = torch.max(in_width_coords, dim=-1)
+ in_width_coords = in_width_coords + w * (~in_width)
+ left_edges, _ = torch.min(in_width_coords, dim=-1)
+
+ # If the mask is empty the right edge will be to the left of the left edge.
+ # Replace these boxes with [0, 0, 0, 0]
+ empty_filter = (right_edges < left_edges) | (bottom_edges < top_edges)
+ out = torch.stack([left_edges, top_edges, right_edges, bottom_edges], dim=-1)
+ out = out * (~empty_filter).unsqueeze(-1)
+
+ # Return to original shape
+ if len(shape) > 2:
+ out = out.reshape(*shape[:-2], 4)
+ else:
+ out = out[0]
+
+ return out
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/onnx.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/onnx.py
new file mode 100644
index 0000000000000000000000000000000000000000..4297b31291e036700d6ad0b818afb7dd72da3054
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/onnx.py
@@ -0,0 +1,144 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+
+from typing import Tuple
+
+from ..modeling import Sam
+from .amg import calculate_stability_score
+
+
+class SamOnnxModel(nn.Module):
+ """
+ This model should not be called directly, but is used in ONNX export.
+ It combines the prompt encoder, mask decoder, and mask postprocessing of Sam,
+ with some functions modified to enable model tracing. Also supports extra
+ options controlling what information. See the ONNX export script for details.
+ """
+
+ def __init__(
+ self,
+ model: Sam,
+ return_single_mask: bool,
+ use_stability_score: bool = False,
+ return_extra_metrics: bool = False,
+ ) -> None:
+ super().__init__()
+ self.mask_decoder = model.mask_decoder
+ self.model = model
+ self.img_size = model.image_encoder.img_size
+ self.return_single_mask = return_single_mask
+ self.use_stability_score = use_stability_score
+ self.stability_score_offset = 1.0
+ self.return_extra_metrics = return_extra_metrics
+
+ @staticmethod
+ def resize_longest_image_size(
+ input_image_size: torch.Tensor, longest_side: int
+ ) -> torch.Tensor:
+ input_image_size = input_image_size.to(torch.float32)
+ scale = longest_side / torch.max(input_image_size)
+ transformed_size = scale * input_image_size
+ transformed_size = torch.floor(transformed_size + 0.5).to(torch.int64)
+ return transformed_size
+
+ def _embed_points(self, point_coords: torch.Tensor, point_labels: torch.Tensor) -> torch.Tensor:
+ point_coords = point_coords + 0.5
+ point_coords = point_coords / self.img_size
+ point_embedding = self.model.prompt_encoder.pe_layer._pe_encoding(point_coords)
+ point_labels = point_labels.unsqueeze(-1).expand_as(point_embedding)
+
+ point_embedding = point_embedding * (point_labels != -1)
+ point_embedding = point_embedding + self.model.prompt_encoder.not_a_point_embed.weight * (
+ point_labels == -1
+ )
+
+ for i in range(self.model.prompt_encoder.num_point_embeddings):
+ point_embedding = point_embedding + self.model.prompt_encoder.point_embeddings[
+ i
+ ].weight * (point_labels == i)
+
+ return point_embedding
+
+ def _embed_masks(self, input_mask: torch.Tensor, has_mask_input: torch.Tensor) -> torch.Tensor:
+ mask_embedding = has_mask_input * self.model.prompt_encoder.mask_downscaling(input_mask)
+ mask_embedding = mask_embedding + (
+ 1 - has_mask_input
+ ) * self.model.prompt_encoder.no_mask_embed.weight.reshape(1, -1, 1, 1)
+ return mask_embedding
+
+ def mask_postprocessing(self, masks: torch.Tensor, orig_im_size: torch.Tensor) -> torch.Tensor:
+ masks = F.interpolate(
+ masks,
+ size=(self.img_size, self.img_size),
+ mode="bilinear",
+ align_corners=False,
+ )
+
+ prepadded_size = self.resize_longest_image_size(orig_im_size, self.img_size)
+ masks = masks[..., : int(prepadded_size[0]), : int(prepadded_size[1])]
+
+ orig_im_size = orig_im_size.to(torch.int64)
+ h, w = orig_im_size[0], orig_im_size[1]
+ masks = F.interpolate(masks, size=(h, w), mode="bilinear", align_corners=False)
+ return masks
+
+ def select_masks(
+ self, masks: torch.Tensor, iou_preds: torch.Tensor, num_points: int
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ # Determine if we should return the multiclick mask or not from the number of points.
+ # The reweighting is used to avoid control flow.
+ score_reweight = torch.tensor(
+ [[1000] + [0] * (self.model.mask_decoder.num_mask_tokens - 1)]
+ ).to(iou_preds.device)
+ score = iou_preds + (num_points - 2.5) * score_reweight
+ best_idx = torch.argmax(score, dim=1)
+ masks = masks[torch.arange(masks.shape[0]), best_idx, :, :].unsqueeze(1)
+ iou_preds = iou_preds[torch.arange(masks.shape[0]), best_idx].unsqueeze(1)
+
+ return masks, iou_preds
+
+ @torch.no_grad()
+ def forward(
+ self,
+ image_embeddings: torch.Tensor,
+ point_coords: torch.Tensor,
+ point_labels: torch.Tensor,
+ mask_input: torch.Tensor,
+ has_mask_input: torch.Tensor,
+ orig_im_size: torch.Tensor,
+ ):
+ sparse_embedding = self._embed_points(point_coords, point_labels)
+ dense_embedding = self._embed_masks(mask_input, has_mask_input)
+
+ masks, scores = self.model.mask_decoder.predict_masks(
+ image_embeddings=image_embeddings,
+ image_pe=self.model.prompt_encoder.get_dense_pe(),
+ sparse_prompt_embeddings=sparse_embedding,
+ dense_prompt_embeddings=dense_embedding,
+ )
+
+ if self.use_stability_score:
+ scores = calculate_stability_score(
+ masks, self.model.mask_threshold, self.stability_score_offset
+ )
+
+ if self.return_single_mask:
+ masks, scores = self.select_masks(masks, scores, point_coords.shape[1])
+
+ upscaled_masks = self.mask_postprocessing(masks, orig_im_size)
+
+ if self.return_extra_metrics:
+ stability_scores = calculate_stability_score(
+ upscaled_masks, self.model.mask_threshold, self.stability_score_offset
+ )
+ areas = (upscaled_masks > self.model.mask_threshold).sum(-1).sum(-1)
+ return upscaled_masks, scores, stability_scores, areas, masks
+
+ return upscaled_masks, scores, masks
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/transforms.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ad346661f84b0647026e130a552c4b38b83e2ac
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/segment_anything/utils/transforms.py
@@ -0,0 +1,102 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+import numpy as np
+import torch
+from torch.nn import functional as F
+from torchvision.transforms.functional import resize, to_pil_image # type: ignore
+
+from copy import deepcopy
+from typing import Tuple
+
+
+class ResizeLongestSide:
+ """
+ Resizes images to longest side 'target_length', as well as provides
+ methods for resizing coordinates and boxes. Provides methods for
+ transforming both numpy array and batched torch tensors.
+ """
+
+ def __init__(self, target_length: int) -> None:
+ self.target_length = target_length
+
+ def apply_image(self, image: np.ndarray) -> np.ndarray:
+ """
+ Expects a numpy array with shape HxWxC in uint8 format.
+ """
+ target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
+ return np.array(resize(to_pil_image(image), target_size))
+
+ def apply_coords(self, coords: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
+ """
+ Expects a numpy array of length 2 in the final dimension. Requires the
+ original image size in (H, W) format.
+ """
+ old_h, old_w = original_size
+ new_h, new_w = self.get_preprocess_shape(
+ original_size[0], original_size[1], self.target_length
+ )
+ coords = deepcopy(coords).astype(float)
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
+ return coords
+
+ def apply_boxes(self, boxes: np.ndarray, original_size: Tuple[int, ...]) -> np.ndarray:
+ """
+ Expects a numpy array shape Bx4. Requires the original image size
+ in (H, W) format.
+ """
+ boxes = self.apply_coords(boxes.reshape(-1, 2, 2), original_size)
+ return boxes.reshape(-1, 4)
+
+ def apply_image_torch(self, image: torch.Tensor) -> torch.Tensor:
+ """
+ Expects batched images with shape BxCxHxW and float format. This
+ transformation may not exactly match apply_image. apply_image is
+ the transformation expected by the model.
+ """
+ # Expects an image in BCHW format. May not exactly match apply_image.
+ target_size = self.get_preprocess_shape(image.shape[0], image.shape[1], self.target_length)
+ return F.interpolate(
+ image, target_size, mode="bilinear", align_corners=False, antialias=True
+ )
+
+ def apply_coords_torch(
+ self, coords: torch.Tensor, original_size: Tuple[int, ...]
+ ) -> torch.Tensor:
+ """
+ Expects a torch tensor with length 2 in the last dimension. Requires the
+ original image size in (H, W) format.
+ """
+ old_h, old_w = original_size
+ new_h, new_w = self.get_preprocess_shape(
+ original_size[0], original_size[1], self.target_length
+ )
+ coords = deepcopy(coords).to(torch.float)
+ coords[..., 0] = coords[..., 0] * (new_w / old_w)
+ coords[..., 1] = coords[..., 1] * (new_h / old_h)
+ return coords
+
+ def apply_boxes_torch(
+ self, boxes: torch.Tensor, original_size: Tuple[int, ...]
+ ) -> torch.Tensor:
+ """
+ Expects a torch tensor with shape Bx4. Requires the original image
+ size in (H, W) format.
+ """
+ boxes = self.apply_coords_torch(boxes.reshape(-1, 2, 2), original_size)
+ return boxes.reshape(-1, 4)
+
+ @staticmethod
+ def get_preprocess_shape(oldh: int, oldw: int, long_side_length: int) -> Tuple[int, int]:
+ """
+ Compute the output size given input size and target long side length.
+ """
+ scale = long_side_length * 1.0 / max(oldh, oldw)
+ newh, neww = oldh * scale, oldw * scale
+ neww = int(neww + 0.5)
+ newh = int(newh + 0.5)
+ return (newh, neww)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.cfg b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.cfg
new file mode 100644
index 0000000000000000000000000000000000000000..0eee130ba71d14ec260d33a8ebd96a6491079a54
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.cfg
@@ -0,0 +1,11 @@
+[isort]
+line_length=100
+multi_line_output=3
+include_trailing_comma=True
+known_standard_library=numpy,setuptools
+skip_glob=*/__init__.py
+known_myself=segment_anything
+known_third_party=matplotlib,cv2,torch,torchvision,pycocotools,onnx,black,isort
+no_lines_before=STDLIB,THIRDPARTY
+sections=FUTURE,STDLIB,THIRDPARTY,MYSELF,FIRSTPARTY,LOCALFOLDER
+default_section=FIRSTPARTY
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.py b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.py
new file mode 100644
index 0000000000000000000000000000000000000000..2c0986317eb576a14ec774205c88fdee3cc6c0b3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/grounded-sam/segment_anything/setup.py
@@ -0,0 +1,18 @@
+# Copyright (c) Meta Platforms, Inc. and affiliates.
+# All rights reserved.
+
+# This source code is licensed under the license found in the
+# LICENSE file in the root directory of this source tree.
+
+from setuptools import find_packages, setup
+
+setup(
+ name="segment_anything",
+ version="1.0",
+ install_requires=[],
+ packages=find_packages(exclude="notebooks"),
+ extras_require={
+ "all": ["matplotlib", "pycocotools", "opencv-python", "onnx", "onnxruntime"],
+ "dev": ["flake8", "isort", "black", "mypy"],
+ },
+)
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/__init__.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c26f1b37dae854f51da938da2fa67a8ef48ce5a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/__init__.py
@@ -0,0 +1,44 @@
+import os
+os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
+
+import torch
+import numpy as np
+from . import util
+from .body import Body
+from .hand import Hand
+from annotator.util import annotator_ckpts_path
+
+
+body_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/body_pose_model.pth"
+hand_model_path = "https://huggingface.co/lllyasviel/ControlNet/resolve/main/annotator/ckpts/hand_pose_model.pth"
+
+
+class OpenposeDetector:
+ def __init__(self):
+ body_modelpath = os.path.join(annotator_ckpts_path, "body_pose_model.pth")
+ hand_modelpath = os.path.join(annotator_ckpts_path, "hand_pose_model.pth")
+
+ if not os.path.exists(hand_modelpath):
+ from basicsr.utils.download_util import load_file_from_url
+ load_file_from_url(body_model_path, model_dir=annotator_ckpts_path)
+ load_file_from_url(hand_model_path, model_dir=annotator_ckpts_path)
+
+ self.body_estimation = Body(body_modelpath)
+ self.hand_estimation = Hand(hand_modelpath)
+
+ def __call__(self, oriImg, hand=False):
+ oriImg = oriImg[:, :, ::-1].copy()
+ with torch.no_grad():
+ candidate, subset = self.body_estimation(oriImg)
+ canvas = np.zeros_like(oriImg)
+ canvas = util.draw_bodypose(canvas, candidate, subset)
+ if hand:
+ hands_list = util.handDetect(candidate, subset, oriImg)
+ all_hand_peaks = []
+ for x, y, w, is_left in hands_list:
+ peaks = self.hand_estimation(oriImg[y:y+w, x:x+w, :])
+ peaks[:, 0] = np.where(peaks[:, 0] == 0, peaks[:, 0], peaks[:, 0] + x)
+ peaks[:, 1] = np.where(peaks[:, 1] == 0, peaks[:, 1], peaks[:, 1] + y)
+ all_hand_peaks.append(peaks)
+ canvas = util.draw_handpose(canvas, all_hand_peaks)
+ return canvas, dict(candidate=candidate.tolist(), subset=subset.tolist())
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/body.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/body.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c3cf7a388b4ac81004524e64125e383bdd455bd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/body.py
@@ -0,0 +1,219 @@
+import cv2
+import numpy as np
+import math
+import time
+from scipy.ndimage.filters import gaussian_filter
+import matplotlib.pyplot as plt
+import matplotlib
+import torch
+from torchvision import transforms
+
+from . import util
+from .model import bodypose_model
+
+class Body(object):
+ def __init__(self, model_path):
+ self.model = bodypose_model()
+ if torch.cuda.is_available():
+ self.model = self.model.cuda()
+ print('cuda')
+ model_dict = util.transfer(self.model, torch.load(model_path))
+ self.model.load_state_dict(model_dict)
+ self.model.eval()
+
+ def __call__(self, oriImg):
+ # scale_search = [0.5, 1.0, 1.5, 2.0]
+ scale_search = [0.5]
+ boxsize = 368
+ stride = 8
+ padValue = 128
+ thre1 = 0.1
+ thre2 = 0.05
+ multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
+ heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 19))
+ paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
+
+ for m in range(len(multiplier)):
+ scale = multiplier[m]
+ imageToTest = cv2.resize(oriImg, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
+ imageToTest_padded, pad = util.padRightDownCorner(imageToTest, stride, padValue)
+ im = np.transpose(np.float32(imageToTest_padded[:, :, :, np.newaxis]), (3, 2, 0, 1)) / 256 - 0.5
+ im = np.ascontiguousarray(im)
+
+ data = torch.from_numpy(im).float()
+ if torch.cuda.is_available():
+ data = data.cuda()
+ # data = data.permute([2, 0, 1]).unsqueeze(0).float()
+ with torch.no_grad():
+ Mconv7_stage6_L1, Mconv7_stage6_L2 = self.model(data)
+ Mconv7_stage6_L1 = Mconv7_stage6_L1.cpu().numpy()
+ Mconv7_stage6_L2 = Mconv7_stage6_L2.cpu().numpy()
+
+ # extract outputs, resize, and remove padding
+ # heatmap = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[1]].data), (1, 2, 0)) # output 1 is heatmaps
+ heatmap = np.transpose(np.squeeze(Mconv7_stage6_L2), (1, 2, 0)) # output 1 is heatmaps
+ heatmap = cv2.resize(heatmap, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
+ heatmap = heatmap[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
+ heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC)
+
+ # paf = np.transpose(np.squeeze(net.blobs[output_blobs.keys()[0]].data), (1, 2, 0)) # output 0 is PAFs
+ paf = np.transpose(np.squeeze(Mconv7_stage6_L1), (1, 2, 0)) # output 0 is PAFs
+ paf = cv2.resize(paf, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
+ paf = paf[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
+ paf = cv2.resize(paf, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC)
+
+ heatmap_avg += heatmap_avg + heatmap / len(multiplier)
+ paf_avg += + paf / len(multiplier)
+
+ all_peaks = []
+ peak_counter = 0
+
+ for part in range(18):
+ map_ori = heatmap_avg[:, :, part]
+ one_heatmap = gaussian_filter(map_ori, sigma=3)
+
+ map_left = np.zeros(one_heatmap.shape)
+ map_left[1:, :] = one_heatmap[:-1, :]
+ map_right = np.zeros(one_heatmap.shape)
+ map_right[:-1, :] = one_heatmap[1:, :]
+ map_up = np.zeros(one_heatmap.shape)
+ map_up[:, 1:] = one_heatmap[:, :-1]
+ map_down = np.zeros(one_heatmap.shape)
+ map_down[:, :-1] = one_heatmap[:, 1:]
+
+ peaks_binary = np.logical_and.reduce(
+ (one_heatmap >= map_left, one_heatmap >= map_right, one_heatmap >= map_up, one_heatmap >= map_down, one_heatmap > thre1))
+ peaks = list(zip(np.nonzero(peaks_binary)[1], np.nonzero(peaks_binary)[0])) # note reverse
+ peaks_with_score = [x + (map_ori[x[1], x[0]],) for x in peaks]
+ peak_id = range(peak_counter, peak_counter + len(peaks))
+ peaks_with_score_and_id = [peaks_with_score[i] + (peak_id[i],) for i in range(len(peak_id))]
+
+ all_peaks.append(peaks_with_score_and_id)
+ peak_counter += len(peaks)
+
+ # find connection in the specified sequence, center 29 is in the position 15
+ limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+ # the middle joints heatmap correpondence
+ mapIdx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44], [19, 20], [21, 22], \
+ [23, 24], [25, 26], [27, 28], [29, 30], [47, 48], [49, 50], [53, 54], [51, 52], \
+ [55, 56], [37, 38], [45, 46]]
+
+ connection_all = []
+ special_k = []
+ mid_num = 10
+
+ for k in range(len(mapIdx)):
+ score_mid = paf_avg[:, :, [x - 19 for x in mapIdx[k]]]
+ candA = all_peaks[limbSeq[k][0] - 1]
+ candB = all_peaks[limbSeq[k][1] - 1]
+ nA = len(candA)
+ nB = len(candB)
+ indexA, indexB = limbSeq[k]
+ if (nA != 0 and nB != 0):
+ connection_candidate = []
+ for i in range(nA):
+ for j in range(nB):
+ vec = np.subtract(candB[j][:2], candA[i][:2])
+ norm = math.sqrt(vec[0] * vec[0] + vec[1] * vec[1])
+ norm = max(0.001, norm)
+ vec = np.divide(vec, norm)
+
+ startend = list(zip(np.linspace(candA[i][0], candB[j][0], num=mid_num), \
+ np.linspace(candA[i][1], candB[j][1], num=mid_num)))
+
+ vec_x = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 0] \
+ for I in range(len(startend))])
+ vec_y = np.array([score_mid[int(round(startend[I][1])), int(round(startend[I][0])), 1] \
+ for I in range(len(startend))])
+
+ score_midpts = np.multiply(vec_x, vec[0]) + np.multiply(vec_y, vec[1])
+ score_with_dist_prior = sum(score_midpts) / len(score_midpts) + min(
+ 0.5 * oriImg.shape[0] / norm - 1, 0)
+ criterion1 = len(np.nonzero(score_midpts > thre2)[0]) > 0.8 * len(score_midpts)
+ criterion2 = score_with_dist_prior > 0
+ if criterion1 and criterion2:
+ connection_candidate.append(
+ [i, j, score_with_dist_prior, score_with_dist_prior + candA[i][2] + candB[j][2]])
+
+ connection_candidate = sorted(connection_candidate, key=lambda x: x[2], reverse=True)
+ connection = np.zeros((0, 5))
+ for c in range(len(connection_candidate)):
+ i, j, s = connection_candidate[c][0:3]
+ if (i not in connection[:, 3] and j not in connection[:, 4]):
+ connection = np.vstack([connection, [candA[i][3], candB[j][3], s, i, j]])
+ if (len(connection) >= min(nA, nB)):
+ break
+
+ connection_all.append(connection)
+ else:
+ special_k.append(k)
+ connection_all.append([])
+
+ # last number in each row is the total parts number of that person
+ # the second last number in each row is the score of the overall configuration
+ subset = -1 * np.ones((0, 20))
+ candidate = np.array([item for sublist in all_peaks for item in sublist])
+
+ for k in range(len(mapIdx)):
+ if k not in special_k:
+ partAs = connection_all[k][:, 0]
+ partBs = connection_all[k][:, 1]
+ indexA, indexB = np.array(limbSeq[k]) - 1
+
+ for i in range(len(connection_all[k])): # = 1:size(temp,1)
+ found = 0
+ subset_idx = [-1, -1]
+ for j in range(len(subset)): # 1:size(subset,1):
+ if subset[j][indexA] == partAs[i] or subset[j][indexB] == partBs[i]:
+ subset_idx[found] = j
+ found += 1
+
+ if found == 1:
+ j = subset_idx[0]
+ if subset[j][indexB] != partBs[i]:
+ subset[j][indexB] = partBs[i]
+ subset[j][-1] += 1
+ subset[j][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
+ elif found == 2: # if found 2 and disjoint, merge them
+ j1, j2 = subset_idx
+ membership = ((subset[j1] >= 0).astype(int) + (subset[j2] >= 0).astype(int))[:-2]
+ if len(np.nonzero(membership == 2)[0]) == 0: # merge
+ subset[j1][:-2] += (subset[j2][:-2] + 1)
+ subset[j1][-2:] += subset[j2][-2:]
+ subset[j1][-2] += connection_all[k][i][2]
+ subset = np.delete(subset, j2, 0)
+ else: # as like found == 1
+ subset[j1][indexB] = partBs[i]
+ subset[j1][-1] += 1
+ subset[j1][-2] += candidate[partBs[i].astype(int), 2] + connection_all[k][i][2]
+
+ # if find no partA in the subset, create a new subset
+ elif not found and k < 17:
+ row = -1 * np.ones(20)
+ row[indexA] = partAs[i]
+ row[indexB] = partBs[i]
+ row[-1] = 2
+ row[-2] = sum(candidate[connection_all[k][i, :2].astype(int), 2]) + connection_all[k][i][2]
+ subset = np.vstack([subset, row])
+ # delete some rows of subset which has few parts occur
+ deleteIdx = []
+ for i in range(len(subset)):
+ if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4:
+ deleteIdx.append(i)
+ subset = np.delete(subset, deleteIdx, axis=0)
+
+ # subset: n*20 array, 0-17 is the index in candidate, 18 is the total score, 19 is the total parts
+ # candidate: x, y, score, id
+ return candidate, subset
+
+if __name__ == "__main__":
+ body_estimation = Body('../model/body_pose_model.pth')
+
+ test_image = '../images/ski.jpg'
+ oriImg = cv2.imread(test_image) # B,G,R order
+ candidate, subset = body_estimation(oriImg)
+ canvas = util.draw_bodypose(oriImg, candidate, subset)
+ plt.imshow(canvas[:, :, [2, 1, 0]])
+ plt.show()
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/hand.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/hand.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d0bf17165ad7eb225332b51f4a2aa16718664b2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/hand.py
@@ -0,0 +1,86 @@
+import cv2
+import json
+import numpy as np
+import math
+import time
+from scipy.ndimage.filters import gaussian_filter
+import matplotlib.pyplot as plt
+import matplotlib
+import torch
+from skimage.measure import label
+
+from .model import handpose_model
+from . import util
+
+class Hand(object):
+ def __init__(self, model_path):
+ self.model = handpose_model()
+ if torch.cuda.is_available():
+ self.model = self.model.cuda()
+ print('cuda')
+ model_dict = util.transfer(self.model, torch.load(model_path))
+ self.model.load_state_dict(model_dict)
+ self.model.eval()
+
+ def __call__(self, oriImg):
+ scale_search = [0.5, 1.0, 1.5, 2.0]
+ # scale_search = [0.5]
+ boxsize = 368
+ stride = 8
+ padValue = 128
+ thre = 0.05
+ multiplier = [x * boxsize / oriImg.shape[0] for x in scale_search]
+ heatmap_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 22))
+ # paf_avg = np.zeros((oriImg.shape[0], oriImg.shape[1], 38))
+
+ for m in range(len(multiplier)):
+ scale = multiplier[m]
+ imageToTest = cv2.resize(oriImg, (0, 0), fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC)
+ imageToTest_padded, pad = util.padRightDownCorner(imageToTest, stride, padValue)
+ im = np.transpose(np.float32(imageToTest_padded[:, :, :, np.newaxis]), (3, 2, 0, 1)) / 256 - 0.5
+ im = np.ascontiguousarray(im)
+
+ data = torch.from_numpy(im).float()
+ if torch.cuda.is_available():
+ data = data.cuda()
+ # data = data.permute([2, 0, 1]).unsqueeze(0).float()
+ with torch.no_grad():
+ output = self.model(data).cpu().numpy()
+ # output = self.model(data).numpy()q
+
+ # extract outputs, resize, and remove padding
+ heatmap = np.transpose(np.squeeze(output), (1, 2, 0)) # output 1 is heatmaps
+ heatmap = cv2.resize(heatmap, (0, 0), fx=stride, fy=stride, interpolation=cv2.INTER_CUBIC)
+ heatmap = heatmap[:imageToTest_padded.shape[0] - pad[2], :imageToTest_padded.shape[1] - pad[3], :]
+ heatmap = cv2.resize(heatmap, (oriImg.shape[1], oriImg.shape[0]), interpolation=cv2.INTER_CUBIC)
+
+ heatmap_avg += heatmap / len(multiplier)
+
+ all_peaks = []
+ for part in range(21):
+ map_ori = heatmap_avg[:, :, part]
+ one_heatmap = gaussian_filter(map_ori, sigma=3)
+ binary = np.ascontiguousarray(one_heatmap > thre, dtype=np.uint8)
+ # 全部小于阈值
+ if np.sum(binary) == 0:
+ all_peaks.append([0, 0])
+ continue
+ label_img, label_numbers = label(binary, return_num=True, connectivity=binary.ndim)
+ max_index = np.argmax([np.sum(map_ori[label_img == i]) for i in range(1, label_numbers + 1)]) + 1
+ label_img[label_img != max_index] = 0
+ map_ori[label_img == 0] = 0
+
+ y, x = util.npmax(map_ori)
+ all_peaks.append([x, y])
+ return np.array(all_peaks)
+
+if __name__ == "__main__":
+ hand_estimation = Hand('../model/hand_pose_model.pth')
+
+ # test_image = '../images/hand.jpg'
+ test_image = '../images/hand.jpg'
+ oriImg = cv2.imread(test_image) # B,G,R order
+ peaks = hand_estimation(oriImg)
+ canvas = util.draw_handpose(oriImg, peaks, True)
+ cv2.imshow('', canvas)
+ cv2.waitKey(0)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/model.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/model.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dfc80de827a17beccb9b0f3f7588545be78c9de
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/model.py
@@ -0,0 +1,219 @@
+import torch
+from collections import OrderedDict
+
+import torch
+import torch.nn as nn
+
+def make_layers(block, no_relu_layers):
+ layers = []
+ for layer_name, v in block.items():
+ if 'pool' in layer_name:
+ layer = nn.MaxPool2d(kernel_size=v[0], stride=v[1],
+ padding=v[2])
+ layers.append((layer_name, layer))
+ else:
+ conv2d = nn.Conv2d(in_channels=v[0], out_channels=v[1],
+ kernel_size=v[2], stride=v[3],
+ padding=v[4])
+ layers.append((layer_name, conv2d))
+ if layer_name not in no_relu_layers:
+ layers.append(('relu_'+layer_name, nn.ReLU(inplace=True)))
+
+ return nn.Sequential(OrderedDict(layers))
+
+class bodypose_model(nn.Module):
+ def __init__(self):
+ super(bodypose_model, self).__init__()
+
+ # these layers have no relu layer
+ no_relu_layers = ['conv5_5_CPM_L1', 'conv5_5_CPM_L2', 'Mconv7_stage2_L1',\
+ 'Mconv7_stage2_L2', 'Mconv7_stage3_L1', 'Mconv7_stage3_L2',\
+ 'Mconv7_stage4_L1', 'Mconv7_stage4_L2', 'Mconv7_stage5_L1',\
+ 'Mconv7_stage5_L2', 'Mconv7_stage6_L1', 'Mconv7_stage6_L1']
+ blocks = {}
+ block0 = OrderedDict([
+ ('conv1_1', [3, 64, 3, 1, 1]),
+ ('conv1_2', [64, 64, 3, 1, 1]),
+ ('pool1_stage1', [2, 2, 0]),
+ ('conv2_1', [64, 128, 3, 1, 1]),
+ ('conv2_2', [128, 128, 3, 1, 1]),
+ ('pool2_stage1', [2, 2, 0]),
+ ('conv3_1', [128, 256, 3, 1, 1]),
+ ('conv3_2', [256, 256, 3, 1, 1]),
+ ('conv3_3', [256, 256, 3, 1, 1]),
+ ('conv3_4', [256, 256, 3, 1, 1]),
+ ('pool3_stage1', [2, 2, 0]),
+ ('conv4_1', [256, 512, 3, 1, 1]),
+ ('conv4_2', [512, 512, 3, 1, 1]),
+ ('conv4_3_CPM', [512, 256, 3, 1, 1]),
+ ('conv4_4_CPM', [256, 128, 3, 1, 1])
+ ])
+
+
+ # Stage 1
+ block1_1 = OrderedDict([
+ ('conv5_1_CPM_L1', [128, 128, 3, 1, 1]),
+ ('conv5_2_CPM_L1', [128, 128, 3, 1, 1]),
+ ('conv5_3_CPM_L1', [128, 128, 3, 1, 1]),
+ ('conv5_4_CPM_L1', [128, 512, 1, 1, 0]),
+ ('conv5_5_CPM_L1', [512, 38, 1, 1, 0])
+ ])
+
+ block1_2 = OrderedDict([
+ ('conv5_1_CPM_L2', [128, 128, 3, 1, 1]),
+ ('conv5_2_CPM_L2', [128, 128, 3, 1, 1]),
+ ('conv5_3_CPM_L2', [128, 128, 3, 1, 1]),
+ ('conv5_4_CPM_L2', [128, 512, 1, 1, 0]),
+ ('conv5_5_CPM_L2', [512, 19, 1, 1, 0])
+ ])
+ blocks['block1_1'] = block1_1
+ blocks['block1_2'] = block1_2
+
+ self.model0 = make_layers(block0, no_relu_layers)
+
+ # Stages 2 - 6
+ for i in range(2, 7):
+ blocks['block%d_1' % i] = OrderedDict([
+ ('Mconv1_stage%d_L1' % i, [185, 128, 7, 1, 3]),
+ ('Mconv2_stage%d_L1' % i, [128, 128, 7, 1, 3]),
+ ('Mconv3_stage%d_L1' % i, [128, 128, 7, 1, 3]),
+ ('Mconv4_stage%d_L1' % i, [128, 128, 7, 1, 3]),
+ ('Mconv5_stage%d_L1' % i, [128, 128, 7, 1, 3]),
+ ('Mconv6_stage%d_L1' % i, [128, 128, 1, 1, 0]),
+ ('Mconv7_stage%d_L1' % i, [128, 38, 1, 1, 0])
+ ])
+
+ blocks['block%d_2' % i] = OrderedDict([
+ ('Mconv1_stage%d_L2' % i, [185, 128, 7, 1, 3]),
+ ('Mconv2_stage%d_L2' % i, [128, 128, 7, 1, 3]),
+ ('Mconv3_stage%d_L2' % i, [128, 128, 7, 1, 3]),
+ ('Mconv4_stage%d_L2' % i, [128, 128, 7, 1, 3]),
+ ('Mconv5_stage%d_L2' % i, [128, 128, 7, 1, 3]),
+ ('Mconv6_stage%d_L2' % i, [128, 128, 1, 1, 0]),
+ ('Mconv7_stage%d_L2' % i, [128, 19, 1, 1, 0])
+ ])
+
+ for k in blocks.keys():
+ blocks[k] = make_layers(blocks[k], no_relu_layers)
+
+ self.model1_1 = blocks['block1_1']
+ self.model2_1 = blocks['block2_1']
+ self.model3_1 = blocks['block3_1']
+ self.model4_1 = blocks['block4_1']
+ self.model5_1 = blocks['block5_1']
+ self.model6_1 = blocks['block6_1']
+
+ self.model1_2 = blocks['block1_2']
+ self.model2_2 = blocks['block2_2']
+ self.model3_2 = blocks['block3_2']
+ self.model4_2 = blocks['block4_2']
+ self.model5_2 = blocks['block5_2']
+ self.model6_2 = blocks['block6_2']
+
+
+ def forward(self, x):
+
+ out1 = self.model0(x)
+
+ out1_1 = self.model1_1(out1)
+ out1_2 = self.model1_2(out1)
+ out2 = torch.cat([out1_1, out1_2, out1], 1)
+
+ out2_1 = self.model2_1(out2)
+ out2_2 = self.model2_2(out2)
+ out3 = torch.cat([out2_1, out2_2, out1], 1)
+
+ out3_1 = self.model3_1(out3)
+ out3_2 = self.model3_2(out3)
+ out4 = torch.cat([out3_1, out3_2, out1], 1)
+
+ out4_1 = self.model4_1(out4)
+ out4_2 = self.model4_2(out4)
+ out5 = torch.cat([out4_1, out4_2, out1], 1)
+
+ out5_1 = self.model5_1(out5)
+ out5_2 = self.model5_2(out5)
+ out6 = torch.cat([out5_1, out5_2, out1], 1)
+
+ out6_1 = self.model6_1(out6)
+ out6_2 = self.model6_2(out6)
+
+ return out6_1, out6_2
+
+class handpose_model(nn.Module):
+ def __init__(self):
+ super(handpose_model, self).__init__()
+
+ # these layers have no relu layer
+ no_relu_layers = ['conv6_2_CPM', 'Mconv7_stage2', 'Mconv7_stage3',\
+ 'Mconv7_stage4', 'Mconv7_stage5', 'Mconv7_stage6']
+ # stage 1
+ block1_0 = OrderedDict([
+ ('conv1_1', [3, 64, 3, 1, 1]),
+ ('conv1_2', [64, 64, 3, 1, 1]),
+ ('pool1_stage1', [2, 2, 0]),
+ ('conv2_1', [64, 128, 3, 1, 1]),
+ ('conv2_2', [128, 128, 3, 1, 1]),
+ ('pool2_stage1', [2, 2, 0]),
+ ('conv3_1', [128, 256, 3, 1, 1]),
+ ('conv3_2', [256, 256, 3, 1, 1]),
+ ('conv3_3', [256, 256, 3, 1, 1]),
+ ('conv3_4', [256, 256, 3, 1, 1]),
+ ('pool3_stage1', [2, 2, 0]),
+ ('conv4_1', [256, 512, 3, 1, 1]),
+ ('conv4_2', [512, 512, 3, 1, 1]),
+ ('conv4_3', [512, 512, 3, 1, 1]),
+ ('conv4_4', [512, 512, 3, 1, 1]),
+ ('conv5_1', [512, 512, 3, 1, 1]),
+ ('conv5_2', [512, 512, 3, 1, 1]),
+ ('conv5_3_CPM', [512, 128, 3, 1, 1])
+ ])
+
+ block1_1 = OrderedDict([
+ ('conv6_1_CPM', [128, 512, 1, 1, 0]),
+ ('conv6_2_CPM', [512, 22, 1, 1, 0])
+ ])
+
+ blocks = {}
+ blocks['block1_0'] = block1_0
+ blocks['block1_1'] = block1_1
+
+ # stage 2-6
+ for i in range(2, 7):
+ blocks['block%d' % i] = OrderedDict([
+ ('Mconv1_stage%d' % i, [150, 128, 7, 1, 3]),
+ ('Mconv2_stage%d' % i, [128, 128, 7, 1, 3]),
+ ('Mconv3_stage%d' % i, [128, 128, 7, 1, 3]),
+ ('Mconv4_stage%d' % i, [128, 128, 7, 1, 3]),
+ ('Mconv5_stage%d' % i, [128, 128, 7, 1, 3]),
+ ('Mconv6_stage%d' % i, [128, 128, 1, 1, 0]),
+ ('Mconv7_stage%d' % i, [128, 22, 1, 1, 0])
+ ])
+
+ for k in blocks.keys():
+ blocks[k] = make_layers(blocks[k], no_relu_layers)
+
+ self.model1_0 = blocks['block1_0']
+ self.model1_1 = blocks['block1_1']
+ self.model2 = blocks['block2']
+ self.model3 = blocks['block3']
+ self.model4 = blocks['block4']
+ self.model5 = blocks['block5']
+ self.model6 = blocks['block6']
+
+ def forward(self, x):
+ out1_0 = self.model1_0(x)
+ out1_1 = self.model1_1(out1_0)
+ concat_stage2 = torch.cat([out1_1, out1_0], 1)
+ out_stage2 = self.model2(concat_stage2)
+ concat_stage3 = torch.cat([out_stage2, out1_0], 1)
+ out_stage3 = self.model3(concat_stage3)
+ concat_stage4 = torch.cat([out_stage3, out1_0], 1)
+ out_stage4 = self.model4(concat_stage4)
+ concat_stage5 = torch.cat([out_stage4, out1_0], 1)
+ out_stage5 = self.model5(concat_stage5)
+ concat_stage6 = torch.cat([out_stage5, out1_0], 1)
+ out_stage6 = self.model6(concat_stage6)
+ return out_stage6
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/run.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/run.py
new file mode 100644
index 0000000000000000000000000000000000000000..15998f6b2d5a740758e030429fc9b402cbd1b3df
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/run.py
@@ -0,0 +1,132 @@
+import argparse
+import glob
+import json
+import os
+import sys
+pythonpath = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+print(pythonpath)
+sys.path.insert(0, pythonpath)
+
+
+import torch
+import code
+import cv2
+import matplotlib.pyplot as plt
+import copy
+import numpy as np
+from tqdm import tqdm
+import util
+import model
+from body import Body
+
+
+openpose2coco_order = [0, 15, 14, 17, 16, 5, 2, 6, 3, 7, 4, 11, 8, 12, 9, 13, 10]
+
+def mkdir(path):
+ # if it is the current folder, skip.
+ # otherwise the original code will raise FileNotFoundError
+ if path == '':
+ return
+ try:
+ os.makedirs(path)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+
+def output_json(candidate, subset, fname='out.json'):
+ num_skeleton = subset.shape[0]
+ skeleton_results = []
+ for i in range(num_skeleton):
+ skeleton = []
+ for j in openpose2coco_order:
+ if int(subset[i][j])==-1:
+ x, y, confidence = -1, -1, -1
+ else:
+ x, y, confidence, index = candidate[int(subset[i][j])]
+ skeleton.append([int(x),int(y),confidence])
+ skeleton_results.append({'keypoints':skeleton})
+ with open(fname, 'w') as f:
+ json.dump(skeleton_results, f)
+ return skeleton_results
+
+def inference(body_estimation, test_image, image_out_name, json_out_name):
+ oriImg = cv2.imread(test_image) # B,G,R order
+ candidate, subset = body_estimation(oriImg)
+ canvas = copy.deepcopy(oriImg)
+ canvas = util.draw_bodypose(canvas, candidate, subset)
+ cv2.imwrite(image_out_name,canvas)
+ skeleton_results = output_json(candidate, subset, fname=json_out_name)
+
+
+def cli():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--dataset_root', type=str, default='/blob/linjli/debug_output/video_sythesis/dataset/toy_dataset', help='dataset root')
+ parser.add_argument('--checkpoint_path', type=str, default='body_pose_model.pth') # wholebody
+
+ args = parser.parse_args()
+ # add args.device
+ args.device = torch.device('cpu')
+ args.pin_memory = False
+ if torch.cuda.is_available():
+ args.device = torch.device('cuda')
+ args.pin_memory = True
+ print('neural network device: %s (CUDA available: %s, count: %d)',
+ args.device, torch.cuda.is_available(), torch.cuda.device_count())
+
+ return args
+
+def get_vid_folders(args):
+ vid_folders = os.listdir(args.dataset_root)
+ return vid_folders
+
+def get_img_list(args, vid_folders, i):
+ vid_name = vid_folders[i]
+ folder_path = os.path.join(args.dataset_root, vid_name)
+ files = os.listdir(folder_path)
+ # Filter the list to only include image files
+ image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ return folder_path, image_files
+
+def main():
+ args = cli()
+ print('LOAD: OpenPose Model')
+ body_estimation = Body(args.checkpoint_path)
+
+ todo_list = get_vid_folders(args)
+ print('total videos:', len(todo_list))
+
+ for index in range(len(todo_list)):
+ print('processing video ID: {:05d}'.format(index))
+ try:
+ dir_path, img_list = get_img_list(args, todo_list, index)
+
+ json_out_folder_name = '{}/openpose_json'.format(dir_path)
+ os.makedirs(json_out_folder_name, exist_ok=True)
+ image_out_folder_name = '{}/openpose_vis'.format(dir_path)
+ os.makedirs(image_out_folder_name, exist_ok=True)
+
+ for item in tqdm(img_list):
+ filename = item
+ image_path = os.path.join(dir_path, filename)
+ # Add the new folder to the directory path
+ new_dir_path = os.path.join(dir_path, 'openpose_json')
+ # Combine the new directory path with the filename to form the new file path
+ json_out_name = os.path.join(new_dir_path, filename) + '.json'
+ # Add the new folder to the directory path
+ new_dir_path = os.path.join(dir_path, 'openpose_vis')
+ # Combine the new directory path with the filename to form the new file path
+ image_out_name = os.path.join(new_dir_path, filename) + '.jpg'
+
+ if not os.path.isfile(json_out_name):
+ inference(body_estimation, image_path, image_out_name, json_out_name)
+ else:
+ print('Found file exist:', json_out_name)
+
+ except Exception as e:
+ print(e)
+ pass
+
+if __name__ == '__main__':
+ main()
+
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/openpose/util.py b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f91ae0e65abaf0cbd62d803f56498991141e61b
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/openpose/util.py
@@ -0,0 +1,164 @@
+import math
+import numpy as np
+import matplotlib
+import cv2
+
+
+def padRightDownCorner(img, stride, padValue):
+ h = img.shape[0]
+ w = img.shape[1]
+
+ pad = 4 * [None]
+ pad[0] = 0 # up
+ pad[1] = 0 # left
+ pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
+ pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
+
+ img_padded = img
+ pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))
+ img_padded = np.concatenate((pad_up, img_padded), axis=0)
+ pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))
+ img_padded = np.concatenate((pad_left, img_padded), axis=1)
+ pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))
+ img_padded = np.concatenate((img_padded, pad_down), axis=0)
+ pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))
+ img_padded = np.concatenate((img_padded, pad_right), axis=1)
+
+ return img_padded, pad
+
+# transfer caffe model to pytorch which will match the layer name
+def transfer(model, model_weights):
+ transfered_model_weights = {}
+ for weights_name in model.state_dict().keys():
+ transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])]
+ return transfered_model_weights
+
+# draw the body keypoint and lims
+def draw_bodypose(canvas, candidate, subset):
+ stickwidth = 4
+ limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+ for i in range(18):
+ for n in range(len(subset)):
+ index = int(subset[n][i])
+ if index == -1:
+ continue
+ x, y = candidate[index][0:2]
+ cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
+ for i in range(17):
+ for n in range(len(subset)):
+ index = subset[n][np.array(limbSeq[i]) - 1]
+ if -1 in index:
+ continue
+ cur_canvas = canvas.copy()
+ Y = candidate[index.astype(int), 0]
+ X = candidate[index.astype(int), 1]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, colors[i])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # plt.imsave("preview.jpg", canvas[:, :, [2, 1, 0]])
+ # plt.imshow(canvas[:, :, [2, 1, 0]])
+ return canvas
+
+
+# image drawed by opencv is not good.
+def draw_handpose(canvas, all_hand_peaks, show_number=False):
+ edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
+ [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
+
+ for peaks in all_hand_peaks:
+ for ie, e in enumerate(edges):
+ if np.sum(np.all(peaks[e], axis=1)==0)==0:
+ x1, y1 = peaks[e[0]]
+ x2, y2 = peaks[e[1]]
+ cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie/float(len(edges)), 1.0, 1.0])*255, thickness=2)
+
+ for i, keyponit in enumerate(peaks):
+ x, y = keyponit
+ cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)
+ if show_number:
+ cv2.putText(canvas, str(i), (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.3, (0, 0, 0), lineType=cv2.LINE_AA)
+ return canvas
+
+# detect hand according to body pose keypoints
+# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp
+def handDetect(candidate, subset, oriImg):
+ # right hand: wrist 4, elbow 3, shoulder 2
+ # left hand: wrist 7, elbow 6, shoulder 5
+ ratioWristElbow = 0.33
+ detect_result = []
+ image_height, image_width = oriImg.shape[0:2]
+ for person in subset.astype(int):
+ # if any of three not detected
+ has_left = np.sum(person[[5, 6, 7]] == -1) == 0
+ has_right = np.sum(person[[2, 3, 4]] == -1) == 0
+ if not (has_left or has_right):
+ continue
+ hands = []
+ #left hand
+ if has_left:
+ left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]]
+ x1, y1 = candidate[left_shoulder_index][:2]
+ x2, y2 = candidate[left_elbow_index][:2]
+ x3, y3 = candidate[left_wrist_index][:2]
+ hands.append([x1, y1, x2, y2, x3, y3, True])
+ # right hand
+ if has_right:
+ right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]]
+ x1, y1 = candidate[right_shoulder_index][:2]
+ x2, y2 = candidate[right_elbow_index][:2]
+ x3, y3 = candidate[right_wrist_index][:2]
+ hands.append([x1, y1, x2, y2, x3, y3, False])
+
+ for x1, y1, x2, y2, x3, y3, is_left in hands:
+ # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox
+ # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);
+ # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);
+ # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);
+ # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);
+ # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);
+ x = x3 + ratioWristElbow * (x3 - x2)
+ y = y3 + ratioWristElbow * (y3 - y2)
+ distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)
+ distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
+ width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)
+ # x-y refers to the center --> offset to topLeft point
+ # handRectangle.x -= handRectangle.width / 2.f;
+ # handRectangle.y -= handRectangle.height / 2.f;
+ x -= width / 2
+ y -= width / 2 # width = height
+ # overflow the image
+ if x < 0: x = 0
+ if y < 0: y = 0
+ width1 = width
+ width2 = width
+ if x + width > image_width: width1 = image_width - x
+ if y + width > image_height: width2 = image_height - y
+ width = min(width1, width2)
+ # the max hand box value is 20 pixels
+ if width >= 20:
+ detect_result.append([int(x), int(y), int(width), is_left])
+
+ '''
+ return value: [[x, y, w, True if left hand else False]].
+ width=height since the network require squared input.
+ x, y is the coordinate of top left
+ '''
+ return detect_result
+
+# get max index of 2d array
+def npmax(array):
+ arrayindex = array.argmax(1)
+ arrayvalue = array.max(1)
+ i = arrayvalue.argmax()
+ j = arrayindex[i]
+ return i, j
diff --git a/One-to-All-Animation/benchmark/DisCo/annotator/util.py b/One-to-All-Animation/benchmark/DisCo/annotator/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ddeb55616237718c6c02fec65afe16f5e564bbd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/annotator/util.py
@@ -0,0 +1,39 @@
+import numpy as np
+import cv2
+import os
+
+
+# annotator_ckpts_path = os.path.join(os.path.dirname(__file__), 'ckpts')
+annotator_ckpts_path = "./blob_dir/debug_output/video_sythesis/diffusers/controlnet_annotators"
+
+
+def HWC3(x):
+ assert x.dtype == np.uint8
+ if x.ndim == 2:
+ x = x[:, :, None]
+ assert x.ndim == 3
+ H, W, C = x.shape
+ assert C == 1 or C == 3 or C == 4
+ if C == 3:
+ return x
+ if C == 1:
+ return np.concatenate([x, x, x], axis=2)
+ if C == 4:
+ color = x[:, :, 0:3].astype(np.float32)
+ alpha = x[:, :, 3:4].astype(np.float32) / 255.0
+ y = color * alpha + 255.0 * (1.0 - alpha)
+ y = y.clip(0, 255).astype(np.uint8)
+ return y
+
+
+def resize_image(input_image, resolution):
+ H, W, C = input_image.shape
+ H = float(H)
+ W = float(W)
+ k = float(resolution) / min(H, W)
+ H *= k
+ W *= k
+ H = int(np.round(H / 64.0)) * 64
+ W = int(np.round(W / 64.0)) * 64
+ img = cv2.resize(input_image, (W, H), interpolation=cv2.INTER_LANCZOS4 if k > 1 else cv2.INTER_AREA)
+ return img
diff --git a/One-to-All-Animation/benchmark/DisCo/config/__init__.py b/One-to-All-Animation/benchmark/DisCo/config/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..165dbdc4a43fb330697710cd529cebe977834ccc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/__init__.py
@@ -0,0 +1,99 @@
+from utils.wutils import * # infinity way
+# from wutils_ori import * # VQGAN
+# from wutils_tmp import * # Global Optimize
+
+
+class BasicArgs:
+ # default settings
+ resume = True
+ use_tqdm = True
+ debug = False
+
+ # Chenfei's personal Nodes
+ if platform.node() == 'Moymix-PC':
+ logger.info("检测到实验室台式机%s" % platform.node())
+ root_dir = '/root/data/G'
+ debug = True
+
+ elif platform.node() == 'chenfei':
+ logger.info("检测到笔记本%s" % platform.node())
+ root_dir = 'E:/data/G'
+ debug = True
+
+ elif platform.node() == 'MININT-UG6RO8P':
+ logger.info("Detected MSRA PC Node %s." % platform.node())
+ root_dir = 'D:/data/G'
+ debug = True
+
+ # PAI Platform Nodes
+ elif platform.node().startswith('gcr-openpai'):
+ logger.info("Detected PAI V100 Node %s. This is a one-node for debugging." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+ elif platform.node().startswith('a100compute'):
+ logger.info("Detected PAI A100 Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+ # ITP Platform Nodes
+ elif platform.node().endswith('master-0') or \
+ platform.node().startswith('phlrr') or \
+ platform.node().startswith('PHLRR'):
+ logger.info("Detected ITP Common Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+ os.environ['MASTER_ADDR'] = os.environ['MASTER_IP']
+ os.environ['MASTER_PORT'] = '12306'
+
+ elif platform.node().startswith('az-eus-v100-16gb') or platform.node().startswith('az-sea-v100-16gb'):
+ logger.info("Detected ITP Common Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+ os.environ['MASTER_ADDR'] = os.environ['MASTER_IP']
+ os.environ['MASTER_PORT'] = '12306'
+
+ elif platform.node().startswith('msrit'):
+ logger.info("Detected ITP Hyper A100 Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+ elif platform.node().startswith('GCRHYP'):
+ logger.info("Detected ITP Hyper V100 Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+ # Singularity Nodes / A100
+ elif platform.node().startswith('node'):
+ logger.info("Detected Singularity Node %s." % platform.node())
+ root_dir = '/scratch/f_ndata/G/'
+
+ # System Super Bench Nodes
+ elif platform.node().startswith('sb-nlp'):
+ logger.info("Detected System SuperBench Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+ else:
+ logger.info("Detected unknown Node %s." % platform.node())
+ root_dir = '/f_ndata/G/'
+
+
+ @staticmethod
+ def parse_config_name(config_filename):
+ """
+ Example:
+ Args:
+ config_filename: 'config/t2i/t2i4ccF8S256.py'
+ Return:
+ task_name: 't2i'
+ model_name: 't2i4ccF8S256'
+ """
+ task_name, filename = os.path.normpath(config_filename).split(os.path.sep)[-2:]
+ model_name = filename.split('.')[0]
+ return task_name, model_name
+
+def init_model_from_config(cfg_path='config/vae_kl/VAE_KL_F8D4.py'):
+ cfg = import_filename(cfg_path)
+ Model_net, Args_net = cfg.Net, cfg.args
+ model = Model_net(Args_net)
+
+ pretrained_model = getattr(Args_net, 'pretrained_path', None)
+ if pretrained_model:
+ print(f"load pretrained model: {pretrained_model} for config {cfg_path}...")
+ model.load_state_dict(file2data(pretrained_model, map_location='cpu'), strict=False)
+
+ return model
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/bash_command/moretiktok_cfg.sh b/One-to-All-Animation/benchmark/DisCo/config/bash_command/moretiktok_cfg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..5e096be89d3900bca2137b00862c40ffaa699526
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/bash_command/moretiktok_cfg.sh
@@ -0,0 +1,27 @@
+## visualization command for more tiktok data (cfg)
+## you need to revise the path in command to your own path
+export WANDB_ENABLE=0
+NCCL_ASYNC_ERROR_HANDLING=0 mpirun -np 8 python finetune_sdm_yaml.py \
+--cf config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py \
+--eval_visu --root_dir /home4/wangtan/disco_new/DisControl/output \
+--local_train_batch_size 64 \
+--local_eval_batch_size 64 \
+--log_dir exp_test/moretiktok_ft_cfg \
+--epochs 20 --deepspeed --eval_step 500 --save_step 500 \
+--gradient_accumulate_steps 1 \
+--learning_rate 2e-4 \
+--fix_dist_seed \
+--loss_target "noise" \
+--tiktok_data_root ./tiktok_datasets \
+--train_yaml /home4/wangtan/disco_data_online/TSV_data/composite_offset/train_TiktokDance-poses-masks.yaml \
+--val_yaml /home4/wangtan/disco_data_online/TSV_data/composite_offset/new10val_TiktokDance-poses-masks.yaml \
+--unet_unfreeze_type "null" \
+--guidance_scale 1.5 \
+--drop_ref 0.05 \
+--refer_sdvae \
+--ref_null_caption False \
+--combine_clip_local \
+--combine_use_mask \
+--conds "poses" "masks" \
+--pretrained_model /home4/wangtan/home3_file/disco_data_online/pretrain_model/checkpoint_ft/moretiktok_cfg/mp_rank_00_model_states.pt \
+--eval_save_filename MoreTikTok_cfg
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/bash_command/tiktok_cfg.sh b/One-to-All-Animation/benchmark/DisCo/config/bash_command/tiktok_cfg.sh
new file mode 100644
index 0000000000000000000000000000000000000000..ff487d386547ad141eadef2e7b4edc27b5701abd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/bash_command/tiktok_cfg.sh
@@ -0,0 +1,16 @@
+## visualization command for tiktok data (cfg)
+## Reproduction results: FID 30.72; FVD 60.16; FID-VID 294.89
+## you need to revise the path in command to your own path
+export WANDB_ENABLE=0
+NCCL_ASYNC_ERROR_HANDLING=0 mpirun -np 8 python finetune_sdm_yaml.py \
+--cf config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py \
+--eval_visu --root_dir /home/kevintw/code/disco --local_train_batch_size 64 --local_eval_batch_size 64 \
+--log_dir /home/kevintw/code/disco/github2/DisCo/save_results \
+--epochs 20 --deepspeed --eval_step 500 --save_step 500 --gradient_accumulate_steps 1 \
+--learning_rate 2e-4 --fix_dist_seed --loss_target "noise" \
+--train_yaml /home/kevintw/code/disco/disco_data/composite_offset/train_TiktokDance-Lindsey_0411_youtube_single_keepcloth-poses-masks.yaml \
+--val_yaml /home/kevintw/code/disco/disco_data/composite_offset/new10val_TiktokDance-poses-masks.yaml \
+--unet_unfreeze_type "null" --guidance_scale 1.5 --drop_ref 0.05 --refer_sdvae --ref_null_caption False \
+--combine_clip_local --combine_use_mask --conds "poses" "masks" \
+--pretrained_model /home/kevintw/code/disco/github/DisCo/pretrain_model/cfg/mp_rank_00_model_states.pt \
+--eval_save_filename TikTok_cfg_check
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/__init__.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..24b4a3fb3860426535c92cf6b814a98044776506
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/__init__.py
@@ -0,0 +1,2 @@
+from .net import TemConvNet, inner_collect_fn
+from .unet_3d_condition import UNet3DConditionModel
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/attention.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..c581105db81dfabd633ceb5b6c451202bc7b4201
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/attention.py
@@ -0,0 +1,304 @@
+# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
+
+from copy import deepcopy
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.attention import AdaLayerNorm, CrossAttention, FeedForward
+from diffusers.models.embeddings import CombinedTimestepLabelEmbeddings
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import BaseOutput
+from diffusers.utils.import_utils import is_xformers_available
+from einops import rearrange, repeat
+from torch import nn
+
+from .utils import zero_module
+
+if is_xformers_available():
+ import xformers
+ import xformers.ops
+else:
+ xformers = None
+
+
+class BasicTransformerBlock(nn.Module):
+ r"""
+ A basic Transformer block.
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm (:
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
+ attention_bias (:
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm",
+ final_dropout: bool = False,
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+
+ self.use_ada_layer_norm_zero = (
+ num_embeds_ada_norm is not None
+ ) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (
+ num_embeds_ada_norm is not None
+ ) and norm_type == "ada_norm"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
+ )
+
+ # 1. Spatial Self-Attn
+ self.attn1 = CrossAttention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ )
+
+ # 2. Temporal Self-Attn
+ self.tem_attn = CrossAttention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ )
+ self.tem_norm = (
+ AdaLayerNorm(dim, num_embeds_ada_norm)
+ if self.use_ada_layer_norm
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ )
+ nn.init.zeros_(self.tem_attn.to_out[0].weight.data)
+ try:
+ nn.init.zeros_(self.tem_attn.to_out[0].bias.data)
+ except:
+ print("No bias term in temporal self-attn")
+
+ self.ff = FeedForward(
+ dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ final_dropout=final_dropout,
+ )
+
+ # 2. Cross-Attn
+ if cross_attention_dim is not None:
+ self.attn2 = CrossAttention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ ) # is self-attn if encoder_hidden_states is none
+ else:
+ self.attn2 = None
+
+ if self.use_ada_layer_norm:
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif self.use_ada_layer_norm_zero:
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+
+ if cross_attention_dim is not None:
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
+ # the second cross attention block.
+ self.norm2 = (
+ AdaLayerNorm(dim, num_embeds_ada_norm)
+ if self.use_ada_layer_norm
+ else nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+ )
+ else:
+ self.norm2 = None
+
+ # 3. Feed-forward
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine)
+
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states=None,
+ timestep=None,
+ attention_mask=None,
+ cross_attention_kwargs=None,
+ class_labels=None,
+ nframes: int = 1,
+ ):
+ if self.use_ada_layer_norm:
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.use_ada_layer_norm_zero:
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ else:
+ norm_hidden_states = self.norm1(hidden_states)
+
+ # 1. Spatial Self-Attention
+ cross_attention_kwargs = (
+ cross_attention_kwargs if cross_attention_kwargs is not None else {}
+ )
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states
+ if self.only_cross_attention
+ else None,
+ attention_mask=attention_mask,
+ **cross_attention_kwargs,
+ )
+ if self.use_ada_layer_norm_zero:
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = attn_output + hidden_states
+
+ # 2. Temporal Self-Attention
+ d = hidden_states.shape[1]
+ hidden_states = rearrange(hidden_states, "(b f) d c -> (b d) f c", f=nframes)
+ norm_hidden_states = (
+ self.norm2(hidden_states, timestep)
+ if self.use_ada_layer_norm
+ else self.norm2(hidden_states)
+ )
+ attn_output = self.tem_attn(norm_hidden_states)
+ hidden_states = attn_output + hidden_states
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
+
+ if self.attn2 is not None:
+ norm_hidden_states = (
+ self.norm2(hidden_states, timestep)
+ if self.use_ada_layer_norm
+ else self.norm2(hidden_states)
+ )
+
+ # 2. Cross-Attention
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+
+ # 3. Feed-forward
+ norm_hidden_states = self.norm3(hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ norm_hidden_states = (
+ norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+ )
+
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.use_ada_layer_norm_zero:
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+
+ hidden_states = ff_output + hidden_states
+
+ return hidden_states
+
+
+class SparseCausalAttention(CrossAttention):
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states=None,
+ attention_mask=None,
+ video_length=None,
+ ):
+ batch_size, sequence_length, _ = hidden_states.shape
+ attention_mask = self.prepare_attention_mask(
+ attention_mask, sequence_length, batch_size
+ )
+ query = self.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif self.cross_attention_norm:
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
+
+ key = self.to_k(encoder_hidden_states)
+ value = self.to_v(encoder_hidden_states)
+
+ former_frame_index = torch.arange(video_length) - 1
+ former_frame_index[0] = 0
+
+ key = rearrange(key, "(b f) d c -> b f d c", f=video_length)
+ key = torch.cat([key[:, [0] * video_length], key[:, former_frame_index]], dim=2)
+ key = rearrange(key, "b f d c -> (b f) d c")
+
+ value = rearrange(value, "(b f) d c -> b f d c", f=video_length)
+ value = torch.cat(
+ [value[:, [0] * video_length], value[:, former_frame_index]], dim=2
+ )
+ value = rearrange(value, "b f d c -> (b f) d c")
+
+ query = self.head_to_batch_dim(query)
+ key = self.head_to_batch_dim(key)
+ value = self.head_to_batch_dim(value)
+
+ attention_probs = self.get_attention_scores(query, key, attention_mask)
+ hidden_states = torch.bmm(attention_probs, value)
+ hidden_states = self.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = self.to_out[0](hidden_states)
+ # dropout
+ hidden_states = self.to_out[1](hidden_states)
+ return hidden_states
+
+
+class AdaLayerNormZero(nn.Module):
+ """
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+ """
+
+ def __init__(self, embedding_dim, num_embeddings):
+ super().__init__()
+
+ self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+
+ def forward(self, x, timestep, class_labels, hidden_dtype=None):
+ emb = self.linear(
+ self.silu(self.emb(timestep, class_labels, hidden_dtype=hidden_dtype))
+ )
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(
+ 6, dim=1
+ )
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/controlnet_3d.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/controlnet_3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..d5a4f13b7ac55d44f7212042cf99158f69561ab2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/controlnet_3d.py
@@ -0,0 +1,809 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.utils import BaseOutput, logging
+from torch import nn
+from torch.nn import functional as F
+
+from .resnet import InflatedConv3d
+from .unet_3d_condition import UNet3DConditionModel
+from .unet_blocks import (
+ CrossAttnDownBlock3D,
+ CrossAttnUpBlock3D,
+ DownBlock3D,
+ UNetMidBlock3DCrossAttn,
+ UpBlock3D,
+ get_down_block,
+ get_up_block,
+)
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = InflatedConv3d(
+ conditioning_channels, block_out_channels[0], kernel_size=3, padding=1
+ )
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(
+ InflatedConv3d(channel_in, channel_in, kernel_size=3, padding=1)
+ )
+ self.blocks.append(
+ InflatedConv3d(
+ channel_in, channel_out, kernel_size=3, padding=1, stride=2
+ )
+ )
+
+ self.conv_out = zero_module(
+ InflatedConv3d(
+ block_out_channels[-1],
+ conditioning_embedding_channels,
+ kernel_size=3,
+ padding=1,
+ )
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetConditioningConvin(nn.Module):
+ """
+ only reserve the conv_in of the original controlnet conditioning embeddinglayer
+ accept image tensor after the SD vae
+ """
+
+ def __init__(
+ self,
+ in_channels: int = 4,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ ):
+ super().__init__()
+
+ # self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = InflatedConv3d(
+ in_channels,
+ block_out_channels[0],
+ kernel_size=conv_in_kernel,
+ padding=conv_in_padding,
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ return embedding
+
+
+class ControlNetModel3D(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ args=None,
+ use_sd_vae=False,
+ ):
+ super().__init__()
+
+ self.args = args
+ self.use_sd_vae = use_sd_vae
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(
+ only_cross_attention
+ ) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(
+ down_block_types
+ ):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = InflatedConv3d(
+ in_channels,
+ block_out_channels[0],
+ kernel_size=conv_in_kernel,
+ padding=conv_in_padding,
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(
+ projection_class_embeddings_input_dim, time_embed_dim
+ )
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ if self.args and self.args.refer_sdvae and use_sd_vae:
+ print("use sd vae to init the controlnet condition embedding")
+ self.controlnet_cond_embedding = ControlNetConditioningConvin(
+ in_channels=in_channels, block_out_channels=block_out_channels
+ )
+ else:
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = InflatedConv3d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = InflatedConv3d(
+ output_channel, output_channel, kernel_size=1
+ )
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = InflatedConv3d(
+ output_channel, output_channel, kernel_size=1
+ )
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = InflatedConv3d(
+ mid_block_channel, mid_block_channel, kernel_size=1
+ )
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock3DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+ @classmethod
+ def from_unet_2d(
+ cls,
+ unet: UNet3DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ args=None,
+ use_sd_vae=False,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet3DConditionModel.
+
+ Parameters:
+ unet (`UNet3DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ down_block_types = [
+ "CrossAttnDownBlock3D",
+ "CrossAttnDownBlock3D",
+ "CrossAttnDownBlock3D",
+ "DownBlock3D",
+ ]
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ args=args,
+ use_sd_vae=use_sd_vae,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(
+ unet.class_embedding.state_dict()
+ )
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ if (
+ controlnet.args
+ and controlnet.args.refer_sdvae
+ and controlnet.use_sd_vae
+ ): # init controlnet condition embedding with unet convin
+ controlnet.controlnet_cond_embedding.conv_in.load_state_dict(
+ unet.conv_in.state_dict()
+ )
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(
+ name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]
+ ):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(
+ self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]
+ ):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = (
+ num_slicable_layers * [slice_size]
+ if not isinstance(slice_size, list)
+ else slice_size
+ )
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(
+ module: torch.nn.Module, slice_size: List[int]
+ ):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(
+ f"unknown `controlnet_conditioning_channel_order`: {channel_order}"
+ )
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError(
+ "class_labels should be provided when num_class_embeds > 0"
+ )
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if (
+ hasattr(downsample_block, "has_cross_attention")
+ and downsample_block.has_cross_attention
+ ):
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(
+ down_block_res_samples, self.controlnet_down_blocks
+ ):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [
+ sample * conditioning_scale for sample in down_block_res_samples
+ ]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples,
+ mid_block_res_sample=mid_block_res_sample,
+ )
+
+
+class MultiControlNetModel(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List, Tuple]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet) in enumerate(
+ zip(controlnet_cond, conditioning_scale, self.nets)
+ ):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ encoder_hidden_states,
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(
+ down_block_res_samples, down_samples
+ )
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+class MultiControlNetModel_MultiHiddenStates(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List, Tuple]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: List[
+ torch.Tensor
+ ], # Different from the original multicontrolnet implementation, here the encode hidden states can also be revised
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ nframes: int,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet, each_hidden_state) in enumerate(
+ zip(controlnet_cond, conditioning_scale, self.nets, encoder_hidden_states)
+ ):
+ if len(image.shape) == 4:
+ image = image.unsqueeze(2)
+ image = image.repeat(1, 1, nframes, 1, 1)
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ each_hidden_state, # each hidden state input
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(
+ down_block_res_samples, down_samples
+ )
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/net.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/net.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1a5a727b4607206ab0ccf2b73ae80ae8f49a259
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/net.py
@@ -0,0 +1,926 @@
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL
+from diffusers.models.embeddings import get_2d_sincos_pos_embed
+from diffusers.schedulers import DDIMScheduler, DDPMScheduler, PNDMScheduler
+from diffusers.utils import PIL_INTERPOLATION, deprecate
+from diffusers.utils.import_utils import is_xformers_available
+from einops import rearrange, repeat
+from packaging import version
+from tqdm.auto import tqdm
+from transformers import (
+ CLIPImageProcessor,
+ CLIPTextModel,
+ CLIPTokenizer,
+ CLIPVisionModelWithProjection,
+)
+
+from config import *
+from config.ref_attn_clip_combine_controlnet.net import Net
+from utils.dist import get_rank, synchronize
+
+from .controlnet_3d import ControlNetModel3D, MultiControlNetModel_MultiHiddenStates
+from .unet_3d_condition import UNet3DConditionModel
+
+
+class TemConvNet(Net):
+ def __init__(self, args):
+ super(Net, self).__init__()
+ self.args = args
+
+ tr_noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler"
+ )
+ if self.args.eval_scheduler == "ddpm":
+ noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler"
+ )
+ elif self.args.eval_scheduler == "ddim":
+ noise_scheduler = DDIMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler"
+ )
+ else:
+ noise_scheduler = PNDMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler"
+ )
+ # tokenizer = CLIPTokenizer.from_pretrained(
+ # args.pretrained_model_path, subfolder="tokenizer")
+ feature_extractor = CLIPImageProcessor.from_pretrained(
+ args.pretrained_model_path, subfolder="feature_extractor"
+ )
+ print(
+ f"Loading pre-trained image_encoder from {args.pretrained_model_path}/image_encoder"
+ )
+ clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(
+ args.pretrained_model_path, subfolder="image_encoder"
+ )
+ print(f"Loading pre-trained vae from {args.pretrained_model_path}/vae")
+ vae = AutoencoderKL.from_pretrained(args.pretrained_model_path, subfolder="vae")
+ print(f"Loading pre-trained unet from {self.args.pretrained_model_path}/unet")
+ unet = UNet3DConditionModel.from_pretrained_2d(
+ self.args.pretrained_model_path, subfolder="unet"
+ )
+
+ if (
+ hasattr(noise_scheduler.config, "steps_offset")
+ and noise_scheduler.config.steps_offset != 1
+ ):
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {noise_scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate(
+ "steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False
+ )
+ new_config = dict(self.noise_scheduler.config)
+ new_config["steps_offset"] = 1
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ if (
+ hasattr(noise_scheduler.config, "clip_sample")
+ and noise_scheduler.config.clip_sample is True
+ ):
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate(
+ "clip_sample not set", "1.0.0", deprecation_message, standard_warn=False
+ )
+ new_config = dict(noise_scheduler.config)
+ new_config["clip_sample"] = False
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ is_unet_version_less_0_9_0 = hasattr(
+ unet.config, "_diffusers_version"
+ ) and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse(
+ "0.9.0.dev0"
+ )
+ is_unet_sample_size_less_64 = (
+ hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ )
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate(
+ "sample_size<64", "1.0.0", deprecation_message, standard_warn=False
+ )
+ new_config = dict(self.unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ if self.args.enable_xformers_memory_efficient_attention:
+ if is_xformers_available():
+ unet.enable_xformers_memory_efficient_attention()
+ else:
+ print("xformers is not available, therefore not enabled")
+
+ # WT: initialize controlnet from the pretrained image variation SD model
+ # pose controlnet
+ controlnet_list = []
+ controlnet_pose = ControlNetModel3D.from_unet_2d(unet=unet, args=self.args)
+ controlnet_list.append(controlnet_pose)
+
+ # background controlnet
+ if args.ref_null_caption: # default to False
+ raise NotImplementedError
+ tokenizer = CLIPTokenizer.from_pretrained(
+ self.args.sd15_path, subfolder="tokenizer"
+ )
+ self.tokenizer = tokenizer
+ print(
+ f"Loading pre-trained text_encoder from {self.args.sd15_path}/text_encoder"
+ )
+ text_encoder = CLIPTextModel.from_pretrained(
+ self.args.sd15_path + "/text_encoder"
+ )
+ self.text_encoder = text_encoder
+ unet_sd15 = UNet2DConditionModel.from_pretrained(
+ self.args.sd15_path, subfolder="unet"
+ )
+ controlnet_background = ControlNetModel2D.from_unet(
+ unet=unet_sd15, args=self.args, use_sd_vae=True
+ ) # initialize ref controlnet path from the SD pretrained model
+ del unet_sd15
+ else: # initialize controlnet from the variation SD
+ controlnet_background = ControlNetModel3D.from_unet_2d(
+ unet=unet, args=self.args, use_sd_vae=True
+ )
+ controlnet_list.append(controlnet_background)
+
+ if self.args.gradient_checkpointing:
+ for i in range(len(controlnet_list)):
+ controlnet_list[i].enable_gradient_checkpointing()
+ controlnet_unit = MultiControlNetModel_MultiHiddenStates(controlnet_list)
+
+ self.tr_noise_scheduler = tr_noise_scheduler
+ self.noise_scheduler = noise_scheduler
+ self.vae = vae
+ self.controlnet = controlnet_unit
+ self.unet = unet
+ self.feature_extractor = feature_extractor
+ self.clip_image_encoder = clip_image_encoder
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ self.drop_text_prob = args.drop_text
+ self.device = torch.device("cpu")
+ self.dtype = torch.float32
+
+ self.scale_factor = self.args.scale_factor
+ self.guidance_scale = self.args.guidance_scale
+ self.controlnet_conditioning_scale = getattr(
+ self.args, "controlnet_conditioning_scale", 1.0
+ )
+ self.controlnet_conditioning_scale_cond = getattr(
+ self.args, "controlnet_conditioning_scale_cond", 1.0
+ )
+ self.controlnet_conditioning_scale_ref = getattr(
+ self.args, "controlnet_conditioning_scale_ref", 1.0
+ )
+
+ if getattr(self.args, "combine_clip_local", None) and not getattr(
+ self.args, "refer_clip_proj", None
+ ): # not use clip pretrained visual projection (but initialize from it)
+ self.refer_clip_proj = torch.nn.Linear(
+ clip_image_encoder.visual_projection.in_features,
+ clip_image_encoder.visual_projection.out_features,
+ bias=False,
+ )
+ self.refer_clip_proj.load_state_dict(
+ clip_image_encoder.visual_projection.state_dict()
+ )
+ self.refer_clip_proj.requires_grad_(True)
+
+ def freeze_pretrained_part_in_ddpm(self):
+ if getattr(self.args, "stage2_only_pose", False):
+ print("Only train the pose path, and freeze all the other params")
+ # freeze all the param, only without the pose controlnet
+ self.args.freeze_unet = True
+ self.args.unet_unfreeze_type = None # freeze all the
+
+ # for background controlnet
+ for param_name, param in self.controlnet.named_parameters():
+ if not "nets.0" in param_name:
+ param.requires_grad_(False)
+
+ # for clip projector
+ if hasattr(self, "refer_clip_proj"):
+ for param_name, param in self.refer_clip_proj.named_parameters():
+ param.requires_grad_(False)
+
+ if self.args.freeze_unet:
+ # b self.unet.eval()
+ param_unfreeze_num = 0
+ if self.args.unet_unfreeze_type == "crossattn-kv":
+ for (
+ param_name,
+ param,
+ ) in (
+ self.unet.named_parameters()
+ ): # only to set attn2 k, v to be requires_grad
+ if "transformer_blocks" not in param_name:
+ param.requires_grad_(False)
+ elif not ("attn2.to_k" in param_name or "attn2.to_v" in param_name):
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == "crossattn":
+ for (
+ param_name,
+ param,
+ ) in (
+ self.unet.named_parameters()
+ ): # only to set attn2 k, v to be requires_grad
+ if "transformer_blocks" not in param_name:
+ param.requires_grad_(False)
+ elif not "attn2" in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == "tem":
+ for param_name, param in self.unet.named_parameters():
+ if "tem_" not in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == "transblocks":
+ for param_name, param in self.unet.named_parameters():
+ if "transformer_blocks" not in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == "all":
+ for param_name, param in self.unet.named_parameters():
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ else: # freeze all the unet
+ print("Unmatch to any option, freeze all the unet")
+ self.unet.eval()
+ self.unet.requires_grad_(False)
+
+ print(
+ f"Mode [{self.args.unet_unfreeze_type}]: There are {param_unfreeze_num} modules in unet to be set as requires_grad=True."
+ )
+
+ self.vae.eval()
+ self.clip_image_encoder.eval()
+ self.vae.requires_grad_(False)
+ self.clip_image_encoder.requires_grad_(False)
+ if hasattr(self, "text_encoder"):
+ self.text_encoder.eval()
+ self.text_encoder.requires_grad_(False)
+
+ def forward_train_multicontrol(self, inputs, outputs):
+ # use CFG
+ if self.args.drop_ref > 0:
+ p = random.random()
+ if p <= self.args.drop_ref: # dropout ref image
+ inputs["reference_img"] = torch.zeros_like(inputs["reference_img"])
+
+ loss_target = self.args.loss_target
+ image_seq = inputs["label_img_seq"] # (B, C, T, H, W)
+ ref_image = inputs["reference_img"]
+ bsz = image_seq.shape[0]
+
+ # drop pose
+ if self.args.drop_pose_ratio > 0:
+ for t in range(self.args.nframes):
+ p = random.random()
+ if p <= self.args.drop_pose_ratio:
+ inputs["cond_img_seq"][:, :, t] = torch.ones_like(
+ inputs["cond_img_seq"][:, :, t]
+ ) * inputs["cond_img_seq"][:, :, t, 0, 0].unsqueeze(2).unsqueeze(2)
+
+ if self.args.ref_null_caption: # default to False
+ text = inputs["input_text"]
+ if random.random() < self.args.drop_text: # drop text w.r.t the prob
+ text = ["" for i in text]
+ z_text = self.text_encode(text)
+
+ # text SD input --> reference image input (clip global embedding)
+ if self.args.combine_clip_local: # default to True
+ refer_latents = self.clip_encode_image_local(ref_image).to(dtype=self.dtype)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image).to(
+ dtype=self.dtype
+ )
+
+ image_seq = rearrange(image_seq, "b c t h w -> (b t) c h w")
+ latents = self.image_encoder(image_seq)
+ latents = rearrange(latents, "(b t) c h w -> b c t h w", t=self.args.nframes)
+
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0,
+ self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,),
+ device=latents.device,
+ )
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(
+ f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}"
+ )
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+ # TODO: @tan, change cond_imgs in dataloadser to pose or other conditions.
+ # Prepare reference image
+ if self.args.refer_sdvae: # default to True
+ reference_latents_controlnet = self.image_encoder(
+ inputs["reference_img_controlnet"]
+ ) # controlnet path input
+ reference_latents_controlnet = reference_latents_controlnet.to(
+ dtype=self.dtype
+ )
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"]
+ controlnet_image = [
+ inputs["cond_img_seq"],
+ reference_latents_controlnet,
+ ] # [pose image, ref image]
+
+ # controlnet get the input of (a. ref image clip embedding; b. pose cond image; c. [optional] depth; d. [optional] previous frame)
+ if self.args.ref_null_caption: # default to False
+ raise NotImplementedError
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents,
+ timesteps,
+ [refer_latents, z_text], # reference controlnet path use null caption
+ controlnet_cond=controlnet_image,
+ conditioning_scale=[1.0, 1.0],
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents,
+ timesteps,
+ [refer_latents]
+ * len(self.args.conds), # both controlnet path use the refer latents
+ controlnet_cond=controlnet_image,
+ conditioning_scale=[1.0, 1.0],
+ nframes=self.args.nframes,
+ return_dict=False,
+ )
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=refer_latents, # refer latents
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(
+ noisy_latents, model_pred, timesteps
+ )
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(
+ f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}"
+ )
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs["loss_total"] = loss
+ return outputs
+
+ def prepare_latents(
+ self,
+ batch_size,
+ num_channels_latents,
+ nframes,
+ height,
+ width,
+ generator,
+ latents=None,
+ ):
+ shape = (
+ batch_size,
+ num_channels_latents,
+ nframes,
+ height // self.vae_scale_factor,
+ width // self.vae_scale_factor,
+ )
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ if isinstance(generator, list):
+ shape = (1,) + shape[1:]
+ latents = [
+ torch.randn(shape, generator=generator[i], dtype=self.dtype)
+ for i in range(batch_size)
+ ]
+ latents = torch.cat(latents, dim=0).to(self.device)
+ else:
+ latents = torch.randn(
+ shape, generator=generator, device=self.device, dtype=self.dtype
+ )
+ else:
+ if latents.shape != shape:
+ raise ValueError(
+ f"Unexpected latents shape, got {latents.shape}, expected {shape}"
+ )
+ latents = latents.to(device=self.device, dtype=self.dtype)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.noise_scheduler.init_noise_sigma
+ return latents
+
+ @torch.no_grad()
+ def forward_sample_multicontrol(self, inputs, outputs):
+ gt_image_seq = inputs["label_img_seq"]
+ b, c, t, h, w = gt_image_seq.size()
+ ref_image = inputs["reference_img"]
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+
+ if self.args.combine_clip_local:
+ if self.args.drop_ref > 0:
+ refer_latents = self.clip_encode_image_local_uncond(
+ ref_image,
+ self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance,
+ )
+ else:
+ refer_latents = self.clip_encode_image_local(
+ ref_image,
+ self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance,
+ )
+ else:
+ refer_latents = self.clip_encode_image_global(
+ ref_image,
+ self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance,
+ )
+
+ if self.args.ref_null_caption: # test must use null caption
+ text = inputs["input_text"]
+ text = ["" for i in text]
+ text_embeddings = self.text_encode(
+ text,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None,
+ )
+
+ controlnet_cond_list = []
+ controlnet_conditioning_scale_list = []
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ controlnet_conditioning_scale_cond = self.controlnet_conditioning_scale_cond
+ controlnet_conditioning_scale_ref = self.controlnet_conditioning_scale_ref
+ image_pose = self.prepare_image(
+ image=inputs["cond_img_seq"].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+ controlnet_cond_list.append(image_pose)
+ controlnet_conditioning_scale_list.append(controlnet_conditioning_scale_cond)
+
+ # Prepare ref image
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(
+ inputs["reference_img_controlnet"]
+ )
+ reference_latents_controlnet = reference_latents_controlnet.to(
+ dtype=self.dtype
+ )
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"].to(
+ dtype=self.dtype
+ )
+
+ reference_latents_controlnet = self.prepare_image(
+ image=reference_latents_controlnet,
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+ controlnet_cond_list.append(reference_latents_controlnet)
+ controlnet_conditioning_scale_list.append(controlnet_conditioning_scale_ref)
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device
+ )
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs["generator"]
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ self.args.nframes,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = (
+ len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ )
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = (
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ )
+ latent_model_input = self.noise_scheduler.scale_model_input(
+ latent_model_input, t
+ )
+
+ # controlnet(s) inference
+ if (
+ self.args.ref_null_caption
+ ): # null caption input for ref controlnet path
+ raise NotImplementedError
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[
+ refer_latents,
+ text_embeddings,
+ refer_latents,
+ ],
+ controlnet_cond=[
+ image_pose,
+ reference_latents_controlnet,
+ depth_image,
+ ],
+ conditioning_scale=[
+ controlnet_conditioning_scale_cond,
+ controlnet_conditioning_scale_ref,
+ controlnet_conditioning_scale,
+ ],
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents] * len(self.args.conds),
+ controlnet_cond=controlnet_cond_list,
+ conditioning_scale=controlnet_conditioning_scale_list,
+ nframes=self.args.nframes,
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (
+ noise_pred_text - noise_pred_uncond
+ )
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(
+ noise_pred, t, latents, **extra_step_kwargs
+ ).prev_sample
+
+ if i == len(timesteps) - 1 or (
+ (i + 1) > num_warmup_steps
+ and (i + 1) % self.noise_scheduler.order == 0
+ ):
+ progress_bar.update()
+
+ # Post-processing
+ latents = rearrange(latents, "b c t h w -> (b t) c h w")
+ gen_img = self.image_decoder(latents)
+ gen_img = rearrange(gen_img, "(b t) c h w -> b c t h w", t=self.args.nframes)
+
+ outputs["logits_img_seq"] = gen_img
+ return outputs
+
+
+def inner_collect_fn(
+ args, inputs, outputs, log_dir, global_step, eval_save_filename="eval_visu"
+):
+ visu_save = getattr(args, "visu_save", False)
+
+ rank = get_rank()
+ if rank == -1:
+ splice = ""
+ else:
+ splice = "_" + str(rank)
+ if global_step <= 0:
+ eval_log_dir = os.path.join(log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(log_dir, "eval_step_%d" % (global_step))
+ ensure_dirname(eval_log_dir)
+
+ if not visu_save: # for every different combination, we build a new dir to save
+ gt_save_path = os.path.join(eval_log_dir, "gt")
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(
+ eval_log_dir,
+ f"pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}",
+ )
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir, "cond")
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir, "ref")
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir, "ref_control")
+ ensure_dirname(ref_control_save_path)
+
+ if rank in [-1, 0]:
+ logger.warning(eval_log_dir)
+
+ # Save Model Setting
+ type_output = [
+ int,
+ float,
+ str,
+ bool,
+ tuple,
+ dict,
+ type(None),
+ ]
+ setting_output = {
+ item: getattr(args, item)
+ for item in dir(args)
+ if type(getattr(args, item)) in type_output and not item.startswith("__")
+ }
+ data2file(setting_output, os.path.join(eval_log_dir, "Model_Setting.json"))
+
+ dl = {**inputs, **{k: v for k, v in outputs.items() if k.split("_")[0] == "logits"}}
+ ld = dl2ld(dl)
+
+ # l = ld[0]["logits_imgs"].shape[0]
+
+ for _, sample in enumerate(ld):
+ if visu_save:
+ save_filename = sample["save_filename"]
+ eval_log_dir_filename = os.path.join(eval_log_dir, save_filename)
+
+ gt_save_path = os.path.join(eval_log_dir_filename, "gt")
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(
+ eval_log_dir_filename,
+ f"pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}",
+ )
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir_filename, "cond")
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir_filename, "ref")
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir_filename, "ref_control")
+ ensure_dirname(ref_control_save_path)
+
+ _name = "nuwa"
+ if "input_text" in sample:
+ _name = sample["input_text"][:200]
+ if "img_key" in sample:
+ _name = sample["img_key"]
+ elif "img_key_seq" in sample:
+ sample["img_key_seq"] = sample["img_key_seq"].split(";")
+ _name = sample["img_key_seq"][0]
+ char_remov = [os.sep, ".", "/"]
+ for c in char_remov:
+ _name = _name.replace(c, "")
+ prefix = "_".join(_name.split(" "))
+ # prefix += splice
+ # postfix = '_' + str(round(time.time() * 10))
+ postfix = ""
+
+ try:
+ ref_img_size = sample["reference_img_size"]
+ except:
+ ref_img_size = None
+
+ if "label_imgs" in sample:
+ image = sample["label_imgs"]
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(os.path.join(gt_save_path, prefix + postfix + ".png"))
+ except Exception as e:
+ print(f"some errors happened in saving label_imgs: {e}")
+ if "label_img_seq" in sample:
+ os.makedirs(os.path.join(gt_save_path, prefix + postfix), exist_ok=True)
+ for i in range(sample["label_img_seq"].shape[1]):
+ image = sample["label_img_seq"][:, i]
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(
+ os.path.join(
+ gt_save_path, prefix + postfix, sample["img_key_seq"][i]
+ )
+ )
+ except Exception:
+ try:
+ image.save(
+ os.path.join(
+ gt_save_path,
+ prefix + postfix,
+ sample["img_key_seq"][i] + ".png",
+ )
+ )
+ except Exception as e:
+ print(
+ f"some errors happened in saving label_img_seq {os.path.join(gt_save_path, prefix + postfix, sample['img_key_seq'][i])}: {e}"
+ )
+
+ if "logits_imgs" in sample:
+ image = tensor2pil(
+ sample["logits_imgs"],
+ resize_img=args.pos_resize_img,
+ img_target_size=ref_img_size,
+ )[0]
+ try:
+ image.save(os.path.join(pred_save_path, prefix + postfix + ".png"))
+ except Exception as e:
+ print(f"some errors happened in saving logits_imgs: {e}")
+ if "logits_img_seq" in sample:
+ os.makedirs(os.path.join(pred_save_path, prefix + postfix), exist_ok=True)
+ for i in range(sample["logits_img_seq"].shape[1]):
+ image = sample["logits_img_seq"][:, i]
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(
+ os.path.join(
+ pred_save_path, prefix + postfix, sample["img_key_seq"][i]
+ )
+ )
+ except Exception:
+ try:
+ image.save(
+ os.path.join(
+ pred_save_path,
+ prefix + postfix,
+ sample["img_key_seq"][i] + ".png",
+ )
+ )
+ except Exception as e:
+ print(f"some errors happened in saving logits_imgs: {e}")
+ if "cond_imgs" in sample: # pose
+ image = tensor2pil(
+ sample["cond_imgs"],
+ resize_img=args.pos_resize_img,
+ img_target_size=ref_img_size,
+ )[0]
+ try:
+ image.save(os.path.join(cond_save_path, prefix + postfix + ".png"))
+ except Exception as e:
+ print(f"some errors happened in saving cond_imgs: {e}")
+ if "cond_img_seq" in sample:
+ os.makedirs(os.path.join(cond_save_path, prefix + postfix), exist_ok=True)
+ for i in range(sample["cond_img_seq"].shape[1]):
+ image = sample["cond_img_seq"][:, i]
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(
+ os.path.join(
+ cond_save_path, prefix + postfix, sample["img_key_seq"][i]
+ )
+ )
+ except Exception:
+ try:
+ image.save(
+ os.path.join(
+ cond_save_path,
+ prefix + postfix,
+ sample["img_key_seq"][i] + ".png",
+ )
+ )
+ except Exception as e:
+ print(f"some errors happened in saving cond_img_seq: {e}")
+ if "reference_img" in sample:
+ image = sample["reference_img"]
+ image = (
+ image
+ * torch.tensor(
+ [0.26862954, 0.26130258, 0.27577711], device=image.device
+ ).view(3, 1, 1)
+ + torch.tensor(
+ [0.48145466, 0.4578275, 0.40821073], device=image.device
+ ).view(3, 1, 1)
+ ).clamp(0, 1)
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(os.path.join(ref_save_path, prefix + postfix + ".png"))
+ except Exception as e:
+ print(f"some errors happened in saving reference_imgs: {e}")
+ if "reference_img_controlnet" in sample:
+ image = sample["reference_img_controlnet"]
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(
+ image, resize_img=args.pos_resize_img, img_target_size=ref_img_size
+ )[0]
+ try:
+ image.save(
+ os.path.join(ref_control_save_path, prefix + postfix + ".png")
+ )
+ except Exception as e:
+ print(f"some errors happened in saving reference_img_controlnet: {e}")
+ return gt_save_path, pred_save_path
+
+
+def tensor2pil(images, resize_img=False, img_target_size=None):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [
+ Image.fromarray(image.squeeze(), mode="L").resize(img_target_size)
+ for image in images
+ ]
+ else:
+ pil_images = [
+ Image.fromarray(image.squeeze(), mode="L") for image in images
+ ]
+ else:
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [
+ Image.fromarray(image).resize(img_target_size) for image in images
+ ]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/resnet.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/resnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..7d4250a99ef3ab7fc6cf0dd36699d9df44cf70e7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/resnet.py
@@ -0,0 +1,262 @@
+# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+
+from .utils import zero_module
+
+
+class InflatedConv3d(nn.Conv2d):
+ def forward(self, x):
+ video_length = x.shape[2]
+
+ x = rearrange(x, "b c f h w -> (b f) c h w")
+ x = super().forward(x)
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
+
+ return x
+
+
+class Upsample3D(nn.Module):
+ def __init__(
+ self,
+ channels,
+ use_conv=False,
+ use_conv_transpose=False,
+ out_channels=None,
+ name="conv",
+ ):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels or channels
+ self.use_conv = use_conv
+ self.use_conv_transpose = use_conv_transpose
+ self.name = name
+
+ conv = None
+ if use_conv_transpose:
+ raise NotImplementedError
+ elif use_conv:
+ conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
+
+ if name == "conv":
+ self.conv = conv
+ else:
+ self.Conv2d_0 = conv
+
+ def forward(self, hidden_states, output_size=None):
+ assert hidden_states.shape[1] == self.channels
+
+ if self.use_conv_transpose:
+ raise NotImplementedError
+
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
+ dtype = hidden_states.dtype
+ if dtype == torch.bfloat16:
+ hidden_states = hidden_states.to(torch.float32)
+
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
+ if hidden_states.shape[0] >= 64:
+ hidden_states = hidden_states.contiguous()
+
+ # if `output_size` is passed we force the interpolation output
+ # size and do not make use of `scale_factor=2`
+ if output_size is None:
+ hidden_states = F.interpolate(
+ hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest"
+ )
+ else:
+ hidden_states = F.interpolate(
+ hidden_states, size=output_size, mode="nearest"
+ )
+
+ # If the input is bfloat16, we cast back to bfloat16
+ if dtype == torch.bfloat16:
+ hidden_states = hidden_states.to(dtype)
+
+ if self.use_conv:
+ if self.name == "conv":
+ hidden_states = self.conv(hidden_states)
+ else:
+ hidden_states = self.Conv2d_0(hidden_states)
+
+ return hidden_states
+
+
+class Downsample3D(nn.Module):
+ def __init__(
+ self, channels, use_conv=False, out_channels=None, padding=1, name="conv"
+ ):
+ super().__init__()
+ self.channels = channels
+ self.out_channels = out_channels or channels
+ self.use_conv = use_conv
+ self.padding = padding
+ stride = 2
+ self.name = name
+
+ if use_conv:
+ conv = InflatedConv3d(
+ self.channels, self.out_channels, 3, stride=stride, padding=padding
+ )
+ else:
+ raise NotImplementedError
+
+ if name == "conv":
+ self.Conv2d_0 = conv
+ self.conv = conv
+ elif name == "Conv2d_0":
+ self.conv = conv
+ else:
+ self.conv = conv
+
+ def forward(self, hidden_states):
+ assert hidden_states.shape[1] == self.channels
+ if self.use_conv and self.padding == 0:
+ raise NotImplementedError
+
+ assert hidden_states.shape[1] == self.channels
+ hidden_states = self.conv(hidden_states)
+
+ return hidden_states
+
+
+class ResnetBlock3D(nn.Module):
+ def __init__(
+ self,
+ *,
+ in_channels,
+ out_channels=None,
+ conv_shortcut=False,
+ dropout=0.0,
+ temb_channels=512,
+ groups=32,
+ groups_out=None,
+ pre_norm=True,
+ eps=1e-6,
+ non_linearity="swish",
+ time_embedding_norm="default",
+ output_scale_factor=1.0,
+ use_in_shortcut=None,
+ ):
+ super().__init__()
+ self.pre_norm = pre_norm
+ self.pre_norm = True
+ self.in_channels = in_channels
+ out_channels = in_channels if out_channels is None else out_channels
+ self.out_channels = out_channels
+ self.use_conv_shortcut = conv_shortcut
+ self.time_embedding_norm = time_embedding_norm
+ self.output_scale_factor = output_scale_factor
+
+ if groups_out is None:
+ groups_out = groups
+
+ self.norm1 = torch.nn.GroupNorm(
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
+ )
+
+ self.conv1 = InflatedConv3d(
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+
+ if temb_channels is not None:
+ if self.time_embedding_norm == "default":
+ time_emb_proj_out_channels = out_channels
+ elif self.time_embedding_norm == "scale_shift":
+ time_emb_proj_out_channels = out_channels * 2
+ else:
+ raise ValueError(
+ f"unknown time_embedding_norm : {self.time_embedding_norm} "
+ )
+
+ self.time_emb_proj = torch.nn.Linear(
+ temb_channels, time_emb_proj_out_channels
+ )
+ else:
+ self.time_emb_proj = None
+
+ self.norm2 = torch.nn.GroupNorm(
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
+ )
+ self.dropout = torch.nn.Dropout(dropout)
+ self.conv2 = InflatedConv3d(
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+
+ # temporal conv
+ self.tem_norm = torch.nn.GroupNorm(
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
+ )
+ self.tem_conv = nn.Conv1d(
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+ zero_module(self.tem_conv)
+
+ if non_linearity == "swish":
+ self.nonlinearity = lambda x: F.silu(x)
+ elif non_linearity == "mish":
+ self.nonlinearity = Mish()
+ elif non_linearity == "silu":
+ self.nonlinearity = nn.SiLU()
+
+ self.use_in_shortcut = (
+ self.in_channels != self.out_channels
+ if use_in_shortcut is None
+ else use_in_shortcut
+ )
+
+ self.conv_shortcut = None
+ if self.use_in_shortcut:
+ self.conv_shortcut = InflatedConv3d(
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
+ )
+
+ def forward(self, input_tensor, temb):
+ hidden_states = input_tensor
+
+ hidden_states = self.norm1(hidden_states)
+ hidden_states = self.nonlinearity(hidden_states)
+
+ hidden_states = self.conv1(hidden_states)
+
+ if temb is not None:
+ temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
+
+ if temb is not None and self.time_embedding_norm == "default":
+ hidden_states = hidden_states + temb
+
+ hidden_states = self.norm2(hidden_states)
+
+ if temb is not None and self.time_embedding_norm == "scale_shift":
+ scale, shift = torch.chunk(temb, 2, dim=1)
+ hidden_states = hidden_states * (1 + scale) + shift
+
+ hidden_states = self.nonlinearity(hidden_states)
+
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+
+ # temporal conv
+ tem_residual = hidden_states
+ hidden_states = self.tem_norm(hidden_states)
+ hidden_states = self.nonlinearity(hidden_states)
+ h, w = hidden_states.shape[-2:]
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b h w) c f")
+ hidden_states = self.tem_conv(hidden_states)
+ hidden_states = rearrange(hidden_states, "(b h w) c f -> b c f h w", h=h, w=w)
+ hidden_states = hidden_states + tem_residual
+
+ if self.conv_shortcut is not None:
+ input_tensor = self.conv_shortcut(input_tensor)
+
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
+
+ return output_tensor
+
+
+class Mish(torch.nn.Module):
+ def forward(self, hidden_states):
+ return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/transformer_3d.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/transformer_3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..409b0c9ea40a7a8cd75b6257d9727dfdeccf59be
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/transformer_3d.py
@@ -0,0 +1,344 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Optional
+
+import torch
+import torch.nn.functional as F
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.embeddings import ImagePositionalEmbeddings, PatchEmbed
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import BaseOutput, deprecate
+from einops import rearrange, repeat
+from torch import nn
+
+from .attention import BasicTransformerBlock
+
+
+@dataclass
+class Transformer3DModelOutput(BaseOutput):
+ """
+ Args:
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
+ Hidden states conditioned on `encoder_hidden_states` input. If discrete, returns probability distributions
+ for the unnoised latent pixels.
+ """
+
+ sample: torch.FloatTensor
+
+
+class Transformer3DModel(ModelMixin, ConfigMixin):
+ """
+ Transformer model for image-like data. Takes either discrete (classes of vector embeddings) or continuous (actual
+ embeddings) inputs.
+
+ When input is continuous: First, project the input (aka embedding) and reshape to b, t, d. Then apply standard
+ transformer action. Finally, reshape to image.
+
+ When input is discrete: First, input (classes of latent pixels) is converted to embeddings and has positional
+ embeddings applied, see `ImagePositionalEmbeddings`. Then apply standard transformer action. Finally, predict
+ classes of unnoised image.
+
+ Note that it is assumed one of the input classes is the masked latent pixel. The predicted classes of the unnoised
+ image do not contain a prediction for the masked pixel as the unnoised image cannot be masked.
+
+ Parameters:
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
+ in_channels (`int`, *optional*):
+ Pass if the input is continuous. The number of channels in the input and output.
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The number of encoder_hidden_states dimensions to use.
+ sample_size (`int`, *optional*): Pass if the input is discrete. The width of the latent images.
+ Note that this is fixed at training time as it is used for learning a number of position embeddings. See
+ `ImagePositionalEmbeddings`.
+ num_vector_embeds (`int`, *optional*):
+ Pass if the input is discrete. The number of classes of the vector embeddings of the latent pixels.
+ Includes the class for the masked latent pixel.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm ( `int`, *optional*): Pass if at least one of the norm_layers is `AdaLayerNorm`.
+ The number of diffusion steps used during training. Note that this is fixed at training time as it is used
+ to learn a number of embeddings that are added to the hidden states. During inference, you can denoise for
+ up to but not more than steps than `num_embeds_ada_norm`.
+ attention_bias (`bool`, *optional*):
+ Configure if the TransformerBlocks' attention should contain a bias parameter.
+ """
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 16,
+ attention_head_dim: int = 88,
+ in_channels: Optional[int] = None,
+ out_channels: Optional[int] = None,
+ num_layers: int = 1,
+ dropout: float = 0.0,
+ norm_num_groups: int = 32,
+ cross_attention_dim: Optional[int] = None,
+ attention_bias: bool = False,
+ sample_size: Optional[int] = None,
+ num_vector_embeds: Optional[int] = None,
+ patch_size: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ use_linear_projection: bool = False,
+ only_cross_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_type: str = "layer_norm",
+ norm_elementwise_affine: bool = True,
+ ):
+ super().__init__()
+ self.use_linear_projection = use_linear_projection
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_dim = attention_head_dim
+ inner_dim = num_attention_heads * attention_head_dim
+
+ # 1. Transformer2DModel can process both standard continous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
+ # Define whether input is continuous or discrete depending on configuration
+ self.is_input_continuous = (in_channels is not None) and (patch_size is None)
+ self.is_input_vectorized = num_vector_embeds is not None
+ self.is_input_patches = in_channels is not None and patch_size is not None
+
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
+ deprecation_message = (
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
+ " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
+ )
+ deprecate(
+ "norm_type!=num_embeds_ada_norm",
+ "1.0.0",
+ deprecation_message,
+ standard_warn=False,
+ )
+ norm_type = "ada_norm"
+
+ if self.is_input_continuous and self.is_input_vectorized:
+ raise ValueError(
+ f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
+ " sure that either `in_channels` or `num_vector_embeds` is None."
+ )
+ elif self.is_input_vectorized and self.is_input_patches:
+ raise ValueError(
+ f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
+ " sure that either `num_vector_embeds` or `num_patches` is None."
+ )
+ elif (
+ not self.is_input_continuous
+ and not self.is_input_vectorized
+ and not self.is_input_patches
+ ):
+ raise ValueError(
+ f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
+ f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
+ )
+
+ # 2. Define input layers
+ if self.is_input_continuous:
+ self.in_channels = in_channels
+
+ self.norm = nn.GroupNorm(
+ num_groups=norm_num_groups,
+ num_channels=in_channels,
+ eps=1e-6,
+ affine=True,
+ )
+ if use_linear_projection:
+ self.proj_in = nn.Linear(in_channels, inner_dim)
+ else:
+ self.proj_in = nn.Conv2d(
+ in_channels, inner_dim, kernel_size=1, stride=1, padding=0
+ )
+ elif self.is_input_vectorized:
+ assert (
+ sample_size is not None
+ ), "Transformer2DModel over discrete input must provide sample_size"
+ assert (
+ num_vector_embeds is not None
+ ), "Transformer2DModel over discrete input must provide num_embed"
+
+ self.height = sample_size
+ self.width = sample_size
+ self.num_vector_embeds = num_vector_embeds
+ self.num_latent_pixels = self.height * self.width
+
+ self.latent_image_embedding = ImagePositionalEmbeddings(
+ num_embed=num_vector_embeds,
+ embed_dim=inner_dim,
+ height=self.height,
+ width=self.width,
+ )
+ elif self.is_input_patches:
+ assert (
+ sample_size is not None
+ ), "Transformer2DModel over patched input must provide sample_size"
+
+ self.height = sample_size
+ self.width = sample_size
+
+ self.patch_size = patch_size
+ self.pos_embed = PatchEmbed(
+ height=sample_size,
+ width=sample_size,
+ patch_size=patch_size,
+ in_channels=in_channels,
+ embed_dim=inner_dim,
+ )
+
+ # 3. Define transformers blocks
+ self.transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ inner_dim,
+ num_attention_heads,
+ attention_head_dim,
+ dropout=dropout,
+ cross_attention_dim=cross_attention_dim,
+ activation_fn=activation_fn,
+ num_embeds_ada_norm=num_embeds_ada_norm,
+ attention_bias=attention_bias,
+ only_cross_attention=only_cross_attention,
+ upcast_attention=upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=norm_elementwise_affine,
+ )
+ for d in range(num_layers)
+ ]
+ )
+
+ # 4. Define output layers
+ self.out_channels = in_channels if out_channels is None else out_channels
+ if self.is_input_continuous:
+ # TODO: should use out_channels for continous projections
+ if use_linear_projection:
+ self.proj_out = nn.Linear(inner_dim, in_channels)
+ else:
+ self.proj_out = nn.Conv2d(
+ inner_dim, in_channels, kernel_size=1, stride=1, padding=0
+ )
+ elif self.is_input_vectorized:
+ self.norm_out = nn.LayerNorm(inner_dim)
+ self.out = nn.Linear(inner_dim, self.num_vector_embeds - 1)
+ elif self.is_input_patches:
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out_1 = nn.Linear(inner_dim, 2 * inner_dim)
+ self.proj_out_2 = nn.Linear(
+ inner_dim, patch_size * patch_size * self.out_channels
+ )
+
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states=None,
+ timestep=None,
+ class_labels=None,
+ cross_attention_kwargs=None,
+ return_dict: bool = True,
+ ):
+ """
+ Args:
+ hidden_states ( When discrete, `torch.LongTensor` of shape `(batch size, num latent pixels)`.
+ When continous, `torch.FloatTensor` of shape `(batch size, channel, height, width)`): Input
+ hidden_states
+ encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
+ self-attention.
+ timestep ( `torch.long`, *optional*):
+ Optional timestep to be applied as an embedding in AdaLayerNorm's. Used to indicate denoising step.
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
+ Optional class labels to be applied as an embedding in AdaLayerZeroNorm. Used to indicate class labels
+ conditioning.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
+
+ Returns:
+ [`~models.transformer_2d.Transformer2DModelOutput`] or `tuple`:
+ [`~models.transformer_2d.Transformer2DModelOutput`] if `return_dict` is True, otherwise a `tuple`. When
+ returning a tuple, the first element is the sample tensor.
+ """
+ # 0. Reshape
+ assert (
+ hidden_states.dim() == 5
+ ), f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
+ nframes = hidden_states.shape[2]
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
+ if encoder_hidden_states is not None:
+ encoder_hidden_states = repeat(
+ encoder_hidden_states, "b n c -> (b f) n c", f=nframes
+ )
+
+ # 1. Input
+ if self.is_input_continuous:
+ batch, _, height, width = hidden_states.shape
+ residual = hidden_states
+
+ hidden_states = self.norm(hidden_states)
+ if not self.use_linear_projection:
+ hidden_states = self.proj_in(hidden_states)
+ inner_dim = hidden_states.shape[1]
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
+ batch, height * width, inner_dim
+ )
+ else:
+ inner_dim = hidden_states.shape[1]
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
+ batch, height * width, inner_dim
+ )
+ hidden_states = self.proj_in(hidden_states)
+ else:
+ raise NotImplementedError
+
+ # 2. Blocks
+ for block in self.transformer_blocks:
+ hidden_states = block(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ timestep=timestep,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ nframes=nframes,
+ )
+
+ # 3. Output
+ if self.is_input_continuous:
+ if not self.use_linear_projection:
+ hidden_states = (
+ hidden_states.reshape(batch, height, width, inner_dim)
+ .permute(0, 3, 1, 2)
+ .contiguous()
+ )
+ hidden_states = self.proj_out(hidden_states)
+ else:
+ hidden_states = self.proj_out(hidden_states)
+ hidden_states = (
+ hidden_states.reshape(batch, height, width, inner_dim)
+ .permute(0, 3, 1, 2)
+ .contiguous()
+ )
+
+ output = hidden_states + residual
+
+ else:
+ raise NotImplementedError
+
+ # 4. Reshape back
+ output = rearrange(output, "(b f) c h w -> b c f h w", f=nframes)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer3DModelOutput(sample=output)
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_3d_condition.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_3d_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..b29f57ba31c18495d4c0f0421b32fde09cd85abc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_3d_condition.py
@@ -0,0 +1,740 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import json
+import os
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import UNet2DConditionLoadersMixin
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import (
+ GaussianFourierProjection,
+ TimestepEmbedding,
+ Timesteps,
+)
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import BaseOutput, logging
+
+from .resnet import InflatedConv3d
+from .unet_blocks import (
+ CrossAttnDownBlock3D,
+ CrossAttnUpBlock3D,
+ DownBlock3D,
+ UNetMidBlock3DCrossAttn,
+ UpBlock3D,
+ get_down_block,
+ get_up_block,
+)
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class UNet3DConditionOutput(BaseOutput):
+ """
+ Args:
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model.
+ """
+
+ sample: torch.FloatTensor
+
+
+class UNet3DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
+ r"""
+ UNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep
+ and returns sample shaped output.
+
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
+ implements for all the models (such as downloading or saving, etc.)
+
+ Parameters:
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
+ Height and width of input/output sample.
+ in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
+ out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
+ Whether to flip the sin to cos in the time embedding.
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
+ The tuple of downsample blocks to use.
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
+ The mid block type. Choose from `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`, will skip the
+ mid block layer if `None`.
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`):
+ The tuple of upsample blocks to use.
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
+ Whether to include self-attention in the basic transformer blocks, see
+ [`~models.attention.BasicTransformerBlock`].
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
+ The tuple of output channels for each block.
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
+ If `None`, it will skip the normalization and activation layers in post-processing
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
+ cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
+ for resnet blocks, see [`~models.resnet.ResnetBlock2D`]. Choose from `default` or `scale_shift`.
+ class_embed_type (`str`, *optional*, defaults to None): The type of class embedding to use which is ultimately
+ summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, or `"projection"`.
+ num_class_embeds (`int`, *optional*, defaults to None):
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
+ class conditioning with `class_embed_type` equal to `None`.
+ time_embedding_type (`str`, *optional*, default to `positional`):
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
+ timestep_post_act (`str, *optional*, default to `None`):
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
+ time_cond_proj_dim (`int`, *optional*, default to `None`):
+ The dimension of `cond_proj` layer in timestep embedding.
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
+ using the "projection" `class_embed_type`. Required when using the "projection" `class_embed_type`.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ sample_size: Optional[int] = None,
+ in_channels: int = 4,
+ out_channels: int = 4,
+ center_input_sample: bool = False,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
+ up_block_types: Tuple[str] = (
+ "UpBlock2D",
+ "CrossAttnUpBlock2D",
+ "CrossAttnUpBlock2D",
+ "CrossAttnUpBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ dual_cross_attention: bool = False,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ time_embedding_type: str = "positional",
+ timestep_post_act: Optional[str] = None,
+ time_cond_proj_dim: Optional[int] = None,
+ conv_in_kernel: int = 3,
+ conv_out_kernel: int = 3,
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.sample_size = sample_size
+
+ # Check inputs
+ if len(down_block_types) != len(up_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(
+ only_cross_attention
+ ) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(
+ down_block_types
+ ):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = InflatedConv3d(
+ in_channels,
+ block_out_channels[0],
+ kernel_size=conv_in_kernel,
+ padding=conv_in_padding,
+ )
+
+ # time
+ if time_embedding_type == "fourier":
+ time_embed_dim = block_out_channels[0] * 2
+ if time_embed_dim % 2 != 0:
+ raise ValueError(
+ f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}."
+ )
+ self.time_proj = GaussianFourierProjection(
+ time_embed_dim // 2,
+ set_W_to_weight=False,
+ log=False,
+ flip_sin_to_cos=flip_sin_to_cos,
+ )
+ timestep_input_dim = time_embed_dim
+ elif time_embedding_type == "positional":
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(
+ block_out_channels[0], flip_sin_to_cos, freq_shift
+ )
+ timestep_input_dim = block_out_channels[0]
+ else:
+ raise ValueError(
+ f"{time_embedding_type} does not exist. Pleaes make sure to use one of `fourier` or `positional`."
+ )
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ post_act_fn=timestep_post_act,
+ cond_proj_dim=time_cond_proj_dim,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(
+ projection_class_embeddings_input_dim, time_embed_dim
+ )
+ else:
+ self.class_embedding = None
+
+ self.down_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ # mid
+ if mid_block_type == "UNetMidBlock3DCrossAttn":
+ self.mid_block = UNetMidBlock3DCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+ else:
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
+
+ # count how many layers upsample the images
+ self.num_upsamplers = 0
+
+ # up
+ reversed_block_out_channels = list(reversed(block_out_channels))
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
+ only_cross_attention = list(reversed(only_cross_attention))
+
+ output_channel = reversed_block_out_channels[0]
+ for i, up_block_type in enumerate(up_block_types):
+ is_final_block = i == len(block_out_channels) - 1
+
+ prev_output_channel = output_channel
+ output_channel = reversed_block_out_channels[i]
+ input_channel = reversed_block_out_channels[
+ min(i + 1, len(block_out_channels) - 1)
+ ]
+
+ # add upsample block for all BUT final layer
+ if not is_final_block:
+ add_upsample = True
+ self.num_upsamplers += 1
+ else:
+ add_upsample = False
+
+ up_block = get_up_block(
+ up_block_type,
+ num_layers=layers_per_block + 1,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ prev_output_channel=prev_output_channel,
+ temb_channels=time_embed_dim,
+ add_upsample=add_upsample,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=reversed_attention_head_dim[i],
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.up_blocks.append(up_block)
+ prev_output_channel = output_channel
+
+ # out
+ if norm_num_groups is not None:
+ self.conv_norm_out = nn.GroupNorm(
+ num_channels=block_out_channels[0],
+ num_groups=norm_num_groups,
+ eps=norm_eps,
+ )
+ self.conv_act = nn.SiLU()
+ else:
+ self.conv_norm_out = None
+ self.conv_act = None
+
+ conv_out_padding = (conv_out_kernel - 1) // 2
+ self.conv_out = InflatedConv3d(
+ block_out_channels[0],
+ out_channels,
+ kernel_size=conv_out_kernel,
+ padding=conv_out_padding,
+ )
+
+ @property
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(
+ name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]
+ ):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ def set_attn_processor(
+ self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]
+ ):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = (
+ num_slicable_layers * [slice_size]
+ if not isinstance(slice_size, list)
+ else slice_size
+ )
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(
+ module: torch.nn.Module, slice_size: List[int]
+ ):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(
+ module, (CrossAttnDownBlock3D, DownBlock3D, CrossAttnUpBlock3D, UpBlock3D)
+ ):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ) -> Union[UNet3DConditionOutput, Tuple]:
+ r"""
+ Args:
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processor` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Returns:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
+ returning a tuple, the first element is the sample tensor.
+ """
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
+ # on the fly if necessary.
+ default_overall_up_factor = 2**self.num_upsamplers
+
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
+ forward_upsample_size = False
+ upsample_size = None
+
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
+ logger.info("Forward upsample size to force interpolation output size.")
+ forward_upsample_size = True
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 0. center input if necessary
+ if self.config.center_input_sample:
+ sample = 2 * sample - 1.0
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError(
+ "class_labels should be provided when num_class_embeds > 0"
+ )
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if (
+ hasattr(downsample_block, "has_cross_attention")
+ and downsample_block.has_cross_attention
+ ):
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ if down_block_additional_residuals is not None:
+ new_down_block_res_samples = ()
+
+ for down_block_res_sample, down_block_additional_residual in zip(
+ down_block_res_samples, down_block_additional_residuals
+ ):
+ down_block_res_sample = (
+ down_block_res_sample + down_block_additional_residual
+ )
+ new_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = new_down_block_res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ if mid_block_additional_residual is not None:
+ sample = sample + mid_block_additional_residual
+
+ # 5. up
+ for i, upsample_block in enumerate(self.up_blocks):
+ is_final_block = i == len(self.up_blocks) - 1
+
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
+ down_block_res_samples = down_block_res_samples[
+ : -len(upsample_block.resnets)
+ ]
+
+ # if we have not reached the final block and need to forward the
+ # upsample size, we do it here
+ if not is_final_block and forward_upsample_size:
+ upsample_size = down_block_res_samples[-1].shape[2:]
+
+ if (
+ hasattr(upsample_block, "has_cross_attention")
+ and upsample_block.has_cross_attention
+ ):
+ sample = upsample_block(
+ hidden_states=sample,
+ temb=emb,
+ res_hidden_states_tuple=res_samples,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ upsample_size=upsample_size,
+ attention_mask=attention_mask,
+ )
+ else:
+ sample = upsample_block(
+ hidden_states=sample,
+ temb=emb,
+ res_hidden_states_tuple=res_samples,
+ upsample_size=upsample_size,
+ )
+
+ # 6. post-process
+ if self.conv_norm_out:
+ sample = self.conv_norm_out(sample)
+ sample = self.conv_act(sample)
+ sample = self.conv_out(sample)
+
+ if not return_dict:
+ return (sample,)
+
+ return UNet3DConditionOutput(sample=sample)
+
+ @classmethod
+ def from_pretrained_2d(cls, pretrained_model_path, subfolder=None):
+ if subfolder is not None:
+ pretrained_model_path = os.path.join(pretrained_model_path, subfolder)
+
+ config_file = os.path.join(pretrained_model_path, "config.json")
+ if not os.path.isfile(config_file):
+ raise RuntimeError(f"{config_file} does not exist")
+ with open(config_file, "r") as f:
+ config = json.load(f)
+ config["_class_name"] = cls.__name__
+ config["down_block_types"] = [
+ "CrossAttnDownBlock3D",
+ "CrossAttnDownBlock3D",
+ "CrossAttnDownBlock3D",
+ "DownBlock3D",
+ ]
+ config["mid_block_type"] = "UNetMidBlock3DCrossAttn"
+ config["up_block_types"] = [
+ "UpBlock3D",
+ "CrossAttnUpBlock3D",
+ "CrossAttnUpBlock3D",
+ "CrossAttnUpBlock3D",
+ ]
+
+ from diffusers.utils import WEIGHTS_NAME
+
+ model = cls.from_config(config)
+ model_file = os.path.join(pretrained_model_path, WEIGHTS_NAME)
+ if not os.path.isfile(model_file):
+ raise RuntimeError(f"{model_file} does not exist")
+ state_dict = torch.load(model_file, map_location="cpu")
+ for k, v in model.state_dict().items():
+ if "_temp." in k:
+ state_dict.update({k: v})
+ status = model.load_state_dict(state_dict, strict=False)
+ # print(status)
+
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_blocks.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_blocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..70241f7f4caec087d9119525d2d5eb84cdc1aa52
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/unet_blocks.py
@@ -0,0 +1,653 @@
+# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py
+
+import torch
+from torch import nn
+
+from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
+from .transformer_3d import Transformer3DModel
+
+
+def get_down_block(
+ down_block_type,
+ num_layers,
+ in_channels,
+ out_channels,
+ temb_channels,
+ add_downsample,
+ resnet_eps,
+ resnet_act_fn,
+ attn_num_head_channels,
+ resnet_groups=None,
+ cross_attention_dim=None,
+ downsample_padding=None,
+ dual_cross_attention=False,
+ use_linear_projection=False,
+ only_cross_attention=False,
+ upcast_attention=False,
+ resnet_time_scale_shift="default",
+):
+ down_block_type = (
+ down_block_type[7:]
+ if down_block_type.startswith("UNetRes")
+ else down_block_type
+ )
+ if down_block_type == "DownBlock3D":
+ return DownBlock3D(
+ num_layers=num_layers,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ add_downsample=add_downsample,
+ resnet_eps=resnet_eps,
+ resnet_act_fn=resnet_act_fn,
+ resnet_groups=resnet_groups,
+ downsample_padding=downsample_padding,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ elif down_block_type == "CrossAttnDownBlock3D":
+ if cross_attention_dim is None:
+ raise ValueError(
+ "cross_attention_dim must be specified for CrossAttnDownBlock3D"
+ )
+ return CrossAttnDownBlock3D(
+ num_layers=num_layers,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ add_downsample=add_downsample,
+ resnet_eps=resnet_eps,
+ resnet_act_fn=resnet_act_fn,
+ resnet_groups=resnet_groups,
+ downsample_padding=downsample_padding,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attn_num_head_channels,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention,
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ raise ValueError(f"{down_block_type} does not exist.")
+
+
+def get_up_block(
+ up_block_type,
+ num_layers,
+ in_channels,
+ out_channels,
+ prev_output_channel,
+ temb_channels,
+ add_upsample,
+ resnet_eps,
+ resnet_act_fn,
+ attn_num_head_channels,
+ resnet_groups=None,
+ cross_attention_dim=None,
+ dual_cross_attention=False,
+ use_linear_projection=False,
+ only_cross_attention=False,
+ upcast_attention=False,
+ resnet_time_scale_shift="default",
+):
+ up_block_type = (
+ up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
+ )
+ if up_block_type == "UpBlock3D":
+ return UpBlock3D(
+ num_layers=num_layers,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ prev_output_channel=prev_output_channel,
+ temb_channels=temb_channels,
+ add_upsample=add_upsample,
+ resnet_eps=resnet_eps,
+ resnet_act_fn=resnet_act_fn,
+ resnet_groups=resnet_groups,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ elif up_block_type == "CrossAttnUpBlock3D":
+ if cross_attention_dim is None:
+ raise ValueError(
+ "cross_attention_dim must be specified for CrossAttnUpBlock3D"
+ )
+ return CrossAttnUpBlock3D(
+ num_layers=num_layers,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ prev_output_channel=prev_output_channel,
+ temb_channels=temb_channels,
+ add_upsample=add_upsample,
+ resnet_eps=resnet_eps,
+ resnet_act_fn=resnet_act_fn,
+ resnet_groups=resnet_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attn_num_head_channels,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention,
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ raise ValueError(f"{up_block_type} does not exist.")
+
+
+class UNetMidBlock3DCrossAttn(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ temb_channels: int,
+ dropout: float = 0.0,
+ num_layers: int = 1,
+ resnet_eps: float = 1e-6,
+ resnet_time_scale_shift: str = "default",
+ resnet_act_fn: str = "swish",
+ resnet_groups: int = 32,
+ resnet_pre_norm: bool = True,
+ attn_num_head_channels=1,
+ output_scale_factor=1.0,
+ cross_attention_dim=1280,
+ dual_cross_attention=False,
+ use_linear_projection=False,
+ upcast_attention=False,
+ ):
+ super().__init__()
+
+ self.has_cross_attention = True
+ self.attn_num_head_channels = attn_num_head_channels
+ resnet_groups = (
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
+ )
+
+ # there is always at least one resnet
+ resnets = [
+ ResnetBlock3D(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ ]
+ attentions = []
+
+ for _ in range(num_layers):
+ if dual_cross_attention:
+ raise NotImplementedError
+ attentions.append(
+ Transformer3DModel(
+ attn_num_head_channels,
+ in_channels // attn_num_head_channels,
+ in_channels=in_channels,
+ num_layers=1,
+ cross_attention_dim=cross_attention_dim,
+ norm_num_groups=resnet_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+ )
+ resnets.append(
+ ResnetBlock3D(
+ in_channels=in_channels,
+ out_channels=in_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ )
+
+ self.attentions = nn.ModuleList(attentions)
+ self.resnets = nn.ModuleList(resnets)
+
+ def forward(
+ self,
+ hidden_states,
+ temb=None,
+ encoder_hidden_states=None,
+ attention_mask=None,
+ cross_attention_kwargs=None,
+ ):
+ hidden_states = self.resnets[0](hidden_states, temb)
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
+ hidden_states = attn(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+ hidden_states = resnet(hidden_states, temb)
+
+ return hidden_states
+
+
+class CrossAttnDownBlock3D(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ temb_channels: int,
+ dropout: float = 0.0,
+ num_layers: int = 1,
+ resnet_eps: float = 1e-6,
+ resnet_time_scale_shift: str = "default",
+ resnet_act_fn: str = "swish",
+ resnet_groups: int = 32,
+ resnet_pre_norm: bool = True,
+ attn_num_head_channels=1,
+ cross_attention_dim=1280,
+ output_scale_factor=1.0,
+ downsample_padding=1,
+ add_downsample=True,
+ dual_cross_attention=False,
+ use_linear_projection=False,
+ only_cross_attention=False,
+ upcast_attention=False,
+ ):
+ super().__init__()
+ resnets = []
+ attentions = []
+
+ self.has_cross_attention = True
+ self.attn_num_head_channels = attn_num_head_channels
+
+ for i in range(num_layers):
+ in_channels = in_channels if i == 0 else out_channels
+ resnets.append(
+ ResnetBlock3D(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ )
+ if dual_cross_attention:
+ raise NotImplementedError
+ attentions.append(
+ Transformer3DModel(
+ attn_num_head_channels,
+ out_channels // attn_num_head_channels,
+ in_channels=out_channels,
+ num_layers=1,
+ cross_attention_dim=cross_attention_dim,
+ norm_num_groups=resnet_groups,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention,
+ upcast_attention=upcast_attention,
+ )
+ )
+ self.attentions = nn.ModuleList(attentions)
+ self.resnets = nn.ModuleList(resnets)
+
+ if add_downsample:
+ self.downsamplers = nn.ModuleList(
+ [
+ Downsample3D(
+ out_channels,
+ use_conv=True,
+ out_channels=out_channels,
+ padding=downsample_padding,
+ name="op",
+ )
+ ]
+ )
+ else:
+ self.downsamplers = None
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ temb=None,
+ encoder_hidden_states=None,
+ attention_mask=None,
+ cross_attention_kwargs=None,
+ ):
+ # TODO(Patrick, William) - attention mask is not used
+ output_states = ()
+
+ for resnet, attn in zip(self.resnets, self.attentions):
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(resnet), hidden_states, temb
+ )
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(attn, return_dict=False),
+ hidden_states,
+ encoder_hidden_states,
+ cross_attention_kwargs,
+ )[0]
+ else:
+ hidden_states = resnet(hidden_states, temb)
+ hidden_states = attn(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+
+ output_states += (hidden_states,)
+
+ if self.downsamplers is not None:
+ for downsampler in self.downsamplers:
+ hidden_states = downsampler(hidden_states)
+
+ output_states += (hidden_states,)
+
+ return hidden_states, output_states
+
+
+class DownBlock3D(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ temb_channels: int,
+ dropout: float = 0.0,
+ num_layers: int = 1,
+ resnet_eps: float = 1e-6,
+ resnet_time_scale_shift: str = "default",
+ resnet_act_fn: str = "swish",
+ resnet_groups: int = 32,
+ resnet_pre_norm: bool = True,
+ output_scale_factor=1.0,
+ add_downsample=True,
+ downsample_padding=1,
+ ):
+ super().__init__()
+ resnets = []
+
+ for i in range(num_layers):
+ in_channels = in_channels if i == 0 else out_channels
+ resnets.append(
+ ResnetBlock3D(
+ in_channels=in_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ )
+
+ self.resnets = nn.ModuleList(resnets)
+
+ if add_downsample:
+ self.downsamplers = nn.ModuleList(
+ [
+ Downsample3D(
+ out_channels,
+ use_conv=True,
+ out_channels=out_channels,
+ padding=downsample_padding,
+ name="op",
+ )
+ ]
+ )
+ else:
+ self.downsamplers = None
+
+ self.gradient_checkpointing = False
+
+ def forward(self, hidden_states, temb=None):
+ output_states = ()
+
+ for resnet in self.resnets:
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(resnet), hidden_states, temb
+ )
+ else:
+ hidden_states = resnet(hidden_states, temb)
+
+ output_states += (hidden_states,)
+
+ if self.downsamplers is not None:
+ for downsampler in self.downsamplers:
+ hidden_states = downsampler(hidden_states)
+
+ output_states += (hidden_states,)
+
+ return hidden_states, output_states
+
+
+class CrossAttnUpBlock3D(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ prev_output_channel: int,
+ temb_channels: int,
+ dropout: float = 0.0,
+ num_layers: int = 1,
+ resnet_eps: float = 1e-6,
+ resnet_time_scale_shift: str = "default",
+ resnet_act_fn: str = "swish",
+ resnet_groups: int = 32,
+ resnet_pre_norm: bool = True,
+ attn_num_head_channels=1,
+ cross_attention_dim=1280,
+ output_scale_factor=1.0,
+ add_upsample=True,
+ dual_cross_attention=False,
+ use_linear_projection=False,
+ only_cross_attention=False,
+ upcast_attention=False,
+ ):
+ super().__init__()
+ resnets = []
+ attentions = []
+
+ self.has_cross_attention = True
+ self.attn_num_head_channels = attn_num_head_channels
+
+ for i in range(num_layers):
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
+
+ resnets.append(
+ ResnetBlock3D(
+ in_channels=resnet_in_channels + res_skip_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ )
+ if dual_cross_attention:
+ raise NotImplementedError
+ attentions.append(
+ Transformer3DModel(
+ attn_num_head_channels,
+ out_channels // attn_num_head_channels,
+ in_channels=out_channels,
+ num_layers=1,
+ cross_attention_dim=cross_attention_dim,
+ norm_num_groups=resnet_groups,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention,
+ upcast_attention=upcast_attention,
+ )
+ )
+
+ self.attentions = nn.ModuleList(attentions)
+ self.resnets = nn.ModuleList(resnets)
+
+ if add_upsample:
+ self.upsamplers = nn.ModuleList(
+ [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)]
+ )
+ else:
+ self.upsamplers = None
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states,
+ res_hidden_states_tuple,
+ temb=None,
+ encoder_hidden_states=None,
+ cross_attention_kwargs=None,
+ upsample_size=None,
+ attention_mask=None,
+ ):
+ # TODO(Patrick, William) - attention mask is not used
+ for resnet, attn in zip(self.resnets, self.attentions):
+ # pop res hidden states
+ res_hidden_states = res_hidden_states_tuple[-1]
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
+
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(resnet), hidden_states, temb
+ )
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(attn, return_dict=False),
+ hidden_states,
+ encoder_hidden_states,
+ cross_attention_kwargs,
+ )[0]
+ else:
+ hidden_states = resnet(hidden_states, temb)
+ hidden_states = attn(
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ ).sample
+
+ if self.upsamplers is not None:
+ for upsampler in self.upsamplers:
+ hidden_states = upsampler(hidden_states, upsample_size)
+
+ return hidden_states
+
+
+class UpBlock3D(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ prev_output_channel: int,
+ out_channels: int,
+ temb_channels: int,
+ dropout: float = 0.0,
+ num_layers: int = 1,
+ resnet_eps: float = 1e-6,
+ resnet_time_scale_shift: str = "default",
+ resnet_act_fn: str = "swish",
+ resnet_groups: int = 32,
+ resnet_pre_norm: bool = True,
+ output_scale_factor=1.0,
+ add_upsample=True,
+ ):
+ super().__init__()
+ resnets = []
+
+ for i in range(num_layers):
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
+
+ resnets.append(
+ ResnetBlock3D(
+ in_channels=resnet_in_channels + res_skip_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ groups=resnet_groups,
+ dropout=dropout,
+ time_embedding_norm=resnet_time_scale_shift,
+ non_linearity=resnet_act_fn,
+ output_scale_factor=output_scale_factor,
+ pre_norm=resnet_pre_norm,
+ )
+ )
+
+ self.resnets = nn.ModuleList(resnets)
+
+ if add_upsample:
+ self.upsamplers = nn.ModuleList(
+ [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)]
+ )
+ else:
+ self.upsamplers = None
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None
+ ):
+ for resnet in self.resnets:
+ # pop res hidden states
+ res_hidden_states = res_hidden_states_tuple[-1]
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
+
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(resnet), hidden_states, temb
+ )
+ else:
+ hidden_states = resnet(hidden_states, temb)
+
+ if self.upsamplers is not None:
+ for upsampler in self.upsamplers:
+ hidden_states = upsampler(hidden_states, upsample_size)
+
+ return hidden_states
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/utils.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..be1ff4c0744e475c011b6d2daaf4f10efd186359
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/tem_disco_temp_attn/utils.py
@@ -0,0 +1,7 @@
+import torch.nn as nn
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab62b2b48dd3c45d5903676717ccc378d7cbfe97
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv.py
@@ -0,0 +1,76 @@
+from pathlib import Path
+
+from config import *
+
+
+class Args(BasicArgs):
+ root_dir = BasicArgs.root_dir
+ if not Path(BasicArgs.root_dir).exists():
+ root_dir = "./blob_dir/debug_output/video_sythesis"
+
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = "dataset/tiktok_video_dataset.py"
+ max_train_samples = None
+ max_eval_samples = None
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/debug_output/video_sythesis/dataset"
+ debug_train_yaml = "./blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml"
+ debug_val_yaml = "./blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml"
+ train_yaml = "./blob_dir/debug_output/video_sythesis/dataset/composite_offset/train_TiktokDance-poses-masks-depth.yaml"
+ val_yaml = "./blob_dir/debug_output/video_sythesis/dataset/composite_offset/new10val_TiktokDance-poses-masks-depth.yaml"
+
+ tiktok_data_root = "./tiktok_datasets"
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 2e-5
+ null_caption = False
+ refer_sdvae = True
+ combine_clip_local = True
+ combine_use_mask = True
+ gradient_accumulate_steps = 1
+ unet_unfreeze_type = "all"
+ ref_null_caption = False
+
+ # output except for the synthesized image
+ outs = [""]
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+
+ pretrained_model_path = os.path.join(
+ root_dir, "diffusers/sd-image-variations-diffusers"
+ )
+ sd15_path = os.path.join(root_dir, "diffusers/stable-diffusion-v1-5-2")
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet = True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ deepspeed = True
+ fix_dist_seed = True
+
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv_temdisco_temp_attn.py b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv_temdisco_temp_attn.py
new file mode 100644
index 0000000000000000000000000000000000000000..7fd04df92efee1bffe67ffc6c12d4aa06f6ffe0e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/disco_w_tm/yz_tiktok_S256L16_xformers_tsv_temdisco_temp_attn.py
@@ -0,0 +1,3 @@
+from config.disco_w_tm.tem_disco_temp_attn import TemConvNet as Net
+from config.disco_w_tm.tem_disco_temp_attn import inner_collect_fn
+from config.disco_w_tm.yz_tiktok_S256L16_xformers_tsv import Args, args
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py
new file mode 100644
index 0000000000000000000000000000000000000000..60787264b2f3808e2e39c716b2abdc079bd758f7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py
@@ -0,0 +1,67 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ # dataset_cf = 'dataset/app_demo_human_image_edit_gradio.py'
+ dataset_cf = 'dataset/app_demo_human_image_edit_singleinput.py'
+ # dataset_cf = 'dataset/for_vis/tiktok_controlnet_t2i_imagevar_combine_evalwebattr_pose_specific.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/data/mtp_vlp_ray/debug/debug_pretrain"
+ debug_train_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml'
+ debug_val_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml'
+ web_data_root = '/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ab0406a6eaa564859203bfcd21a8719c70b6b1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet.py
@@ -0,0 +1,723 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetConditioningConvin(nn.Module):
+ """
+ only reserve the conv_in of the original controlnet conditioning embeddinglayer
+ accept image tensor after the SD vae
+ """
+
+ def __init__(
+ self,
+ in_channels: int = 4,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ ):
+ super().__init__()
+
+ # self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ return embedding
+
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ args = None,
+ use_sd_vae = False,
+ ):
+ super().__init__()
+
+ self.args = args
+ self.use_sd_vae = use_sd_vae
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ if self.args and self.args.refer_sdvae and use_sd_vae:
+ print('use sd vae to init the controlnet condition embedding')
+ self.controlnet_cond_embedding = ControlNetConditioningConvin(in_channels=in_channels,
+ block_out_channels=block_out_channels)
+ else:
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ args = None,
+ use_sd_vae=False,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ args=args,
+ use_sd_vae=use_sd_vae,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ if controlnet.args and controlnet.args.refer_sdvae and controlnet.use_sd_vae: # init controlnet condition embedding with unet convin
+ controlnet.controlnet_cond_embedding.conv_in.load_state_dict(unet.conv_in.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+class MultiControlNetModel(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ encoder_hidden_states,
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+class MultiControlNetModel_MultiHiddenStates(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: List[torch.Tensor], # Different from the original multicontrolnet implementation, here the encode hidden states can also be revised
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet, each_hidden_state) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets, encoder_hidden_states)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ #encoder_hidden_states,
+ each_hidden_state, # each hidden state input
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet_main.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..29935b7af98357f688ebf4df92d53119ad945c06
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/controlnet_main.py
@@ -0,0 +1,573 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `Attention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
+ def set_default_attn_processor(self):
+ """
+ Disables custom attention processors and sets the default attention implementation.
+ """
+ self.set_attn_processor(AttnProcessor())
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_sliceable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_sliceable_dims(module)
+
+ num_sliceable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_sliceable_layers * [1]
+
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/net.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/net.py
new file mode 100644
index 0000000000000000000000000000000000000000..47eea625f413ea92792e0583006b3d0f453b7e61
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/net.py
@@ -0,0 +1,1130 @@
+import torch
+from utils.dist import synchronize, get_rank
+
+from config import *
+from typing import Callable, List, Optional, Union
+
+import inspect
+from typing import Callable, List, Optional, Union
+
+import torch
+import random
+from packaging import version
+from transformers import CLIPTokenizer, CLIPVisionModelWithProjection, CLIPImageProcessor, CLIPTextModel
+from tqdm.auto import tqdm
+
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL
+from diffusers.schedulers import DDIMScheduler, PNDMScheduler, DDPMScheduler, UniPCMultistepScheduler
+
+from diffusers.utils import deprecate, PIL_INTERPOLATION
+from diffusers.utils.import_utils import is_xformers_available
+
+# from diffusers.models import UNet2DConditionModel
+from .unet_2d_condition import UNet2DConditionModel
+import PIL.Image
+from .controlnet import ControlNetModel, MultiControlNetModel_MultiHiddenStates
+
+# import sys
+# sys.path.append("...")
+# from utils.wutils_ldm import file2data, adaptively_load_state_dict
+
+class Net(nn.Module):
+ def __init__(
+ self, args
+ ):
+ super().__init__()
+ self.args = args
+
+ tr_noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ if self.args.eval_scheduler == "ddpm":
+ noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ elif self.args.eval_scheduler == "ddim":
+ noise_scheduler = DDIMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ else:
+ noise_scheduler = PNDMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ # tokenizer = CLIPTokenizer.from_pretrained(
+ # args.pretrained_model_path, subfolder="tokenizer")
+ feature_extractor = CLIPImageProcessor.from_pretrained(args.pretrained_model_path, subfolder="feature_extractor")
+ print(f"Loading pre-trained image_encoder from {args.pretrained_model_path}/image_encoder")
+ clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.pretrained_model_path, subfolder="image_encoder")
+ print(f"Loading pre-trained vae from {args.pretrained_model_path}/vae")
+ vae = AutoencoderKL.from_pretrained(
+ args.pretrained_model_path, subfolder="vae")
+ print(f"Loading pre-trained unet from {self.args.pretrained_model_path}/unet")
+ unet = UNet2DConditionModel.from_pretrained(
+ self.args.pretrained_model_path, subfolder="unet")
+ # if self.args.stage1_pretrain_path is not None:
+ # pretrain_model_state = file2data(self.args.stage1_pretrain_path, map_location='cpu')
+ # adaptively_load_state_dict(unet, pretrain_model_state['module'])
+
+ if hasattr(noise_scheduler.config, "steps_offset") and noise_scheduler.config.steps_offset != 1:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {noise_scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.noise_scheduler.config)
+ new_config["steps_offset"] = 1
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ if hasattr(noise_scheduler.config, "clip_sample") and noise_scheduler.config.clip_sample is True:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(noise_scheduler.config)
+ new_config["clip_sample"] = False
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse("0.9.0.dev0")
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ if self.args.enable_xformers_memory_efficient_attention:
+ if is_xformers_available():
+ unet.enable_xformers_memory_efficient_attention()
+ else:
+ print("xformers is not available, therefore not enabled")
+
+
+ # WT: initialize controlnet from the pretrained image variation SD model
+ controlnet_pose = ControlNetModel.from_unet(unet=unet, args=self.args)
+ # print('use pretrained controlnet pose: {} to init pose branch'.format(args.pretrained_model_controlnet))
+ # controlnet_pose = ControlNetModel.from_pretrained(args.pretrained_model_controlnet) # ablation, load the controlnet from pretrained controlnet openpose model
+ if args.ref_null_caption:
+ tokenizer = CLIPTokenizer.from_pretrained(self.args.sd15_path, subfolder="tokenizer")
+ self.tokenizer = tokenizer
+ print(f"Loading pre-trained text_encoder from {self.args.sd15_path}/text_encoder")
+ text_encoder = CLIPTextModel.from_pretrained(self.args.sd15_path + "/text_encoder")
+ self.text_encoder = text_encoder
+ unet_sd15 = UNet2DConditionModel.from_pretrained(self.args.sd15_path, subfolder="unet")
+ controlnet_background = ControlNetModel.from_unet(unet=unet_sd15, args=self.args, use_sd_vae=True) # initialize ref controlnet path from the SD pretrained model
+ del unet_sd15
+ else: # initialize controlnet from the variation SD
+ controlnet_background = ControlNetModel.from_unet(unet=unet, args=self.args, use_sd_vae=True)
+
+ if self.args.gradient_checkpointing:
+ controlnet_pose.enable_gradient_checkpointing()
+ controlnet_background.enable_gradient_checkpointing()
+ controlnet_unit = MultiControlNetModel_MultiHiddenStates([controlnet_pose, controlnet_background])
+
+ self.tr_noise_scheduler = tr_noise_scheduler
+ self.noise_scheduler = noise_scheduler
+ self.vae = vae
+ self.controlnet = controlnet_unit
+ self.unet = unet
+ self.feature_extractor = feature_extractor
+ self.clip_image_encoder = clip_image_encoder
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ self.drop_text_prob = args.drop_text
+ self.device = torch.device('cpu')
+ self.dtype = torch.float32
+
+ self.scale_factor = self.args.scale_factor
+ self.guidance_scale = self.args.guidance_scale
+ self.controlnet_conditioning_scale = getattr(self.args, "controlnet_conditioning_scale", 1.0)
+ self.controlnet_conditioning_scale_cond = getattr(self.args, "controlnet_conditioning_scale_cond", 1.0)
+ self.controlnet_conditioning_scale_ref = getattr(self.args, "controlnet_conditioning_scale_ref", 1.0)
+
+ if getattr(self.args, 'combine_clip_local', None) and not getattr(self.args, 'refer_clip_proj', None): # not use clip pretrained visual projection (but initialize from it)
+ self.refer_clip_proj = torch.nn.Linear(clip_image_encoder.visual_projection.in_features, clip_image_encoder.visual_projection.out_features, bias=False)
+ self.refer_clip_proj.load_state_dict(clip_image_encoder.visual_projection.state_dict())
+ self.refer_clip_proj.requires_grad_(True)
+
+
+ def enable_vae_slicing(self):
+ self.vae.enable_slicing()
+
+ def disable_vae_slicing(self):
+ self.vae.disable_slicing()
+
+ def init_ddpm(self):
+ self.freeze_pretrained_part_in_ddpm()
+ return
+
+ def freeze_pretrained_part_in_ddpm(self):
+ if getattr(self.args, 'stage2_only_pose', False):
+ print('Only train the pose path, and freeze all the other params')
+ # freeze all the param, only without the pose controlnet
+ self.args.freeze_unet = True
+ self.args.unet_unfreeze_type = None # freeze all the
+
+ # for background controlnet
+ for param_name, param in self.controlnet.named_parameters():
+ if not 'nets.0' in param_name:
+ param.requires_grad_(False)
+
+ # for clip projector
+ if hasattr(self, 'refer_clip_proj'):
+ for param_name, param in self.refer_clip_proj.named_parameters():
+ param.requires_grad_(False)
+
+
+ if self.args.freeze_unet:
+ #b self.unet.eval()
+ param_unfreeze_num = 0
+ if self.args.unet_unfreeze_type == 'crossattn-kv':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not ('attn2.to_k' in param_name or 'attn2.to_v' in param_name):
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'crossattn':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not 'attn2' in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'transblocks':
+ for param_name, param in self.unet.named_parameters():
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'all':
+ for param_name, param in self.unet.named_parameters():
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ else: # freeze all the unet
+ print('Unmatch to any option, freeze all the unet')
+ self.unet.eval()
+ self.unet.requires_grad_(False)
+
+ print(f"Mode [{self.args.unet_unfreeze_type}]: There are {param_unfreeze_num} modules in unet to be set as requires_grad=True.")
+
+ self.vae.eval()
+ self.clip_image_encoder.eval()
+ self.vae.requires_grad_(False)
+ self.clip_image_encoder.requires_grad_(False)
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.eval()
+ self.text_encoder.requires_grad_(False)
+
+ def to(self, *args, **kwargs):
+ model_converted = super().to(*args, **kwargs)
+ self.device = next(self.parameters()).device
+ self.dtype = next(self.unet.parameters()).dtype
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return model_converted
+
+ def half(self, *args, **kwargs):
+ super().half(*args, **kwargs)
+ self.dtype = torch.float16
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return
+
+ def train(self, *args):
+ super().train(*args)
+ self.freeze_pretrained_part_in_ddpm()
+
+ def image_encoder(self, image):
+ b, c, h, w = image.size()
+ latents = self.vae.encode(image).latent_dist.sample()
+ latents = latents * self.scale_factor
+ latents = latents.to(dtype=self.dtype)
+ return latents
+
+ def image_decoder(self, latents):
+ latents = 1/self.scale_factor * latents
+ dec = self.vae.decode(latents).sample
+ image = (dec / 2 + 0.5).clamp(0, 1)
+ return image
+
+ def forward(self, inputs):
+ outputs = dict()
+
+ generator = torch.Generator(device=self.device)
+ generator.manual_seed(self.args.seed)
+ inputs['generator'] = generator
+
+ if self.training:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_train(inputs, outputs)
+ outputs = self.forward_train_multicontrol(inputs, outputs)
+ elif 'enc_dec_only' in inputs and inputs['enc_dec_only']:
+ outputs = self.forward_enc_dec(inputs, outputs)
+ else:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_sample(inputs, outputs)
+ outputs = self.forward_sample_multicontrol(inputs, outputs)
+ removed_key = inputs.pop("generator", None)
+ return outputs
+
+ def text_encode(
+ self, prompt, num_images_per_prompt=1,
+ do_classifier_free_guidance=False, negative_prompt=None):
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ text_embeddings = self.text_encoder(
+ text_input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ text_embeddings = text_embeddings[0]
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = text_embeddings.shape
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = text_input_ids.shape[-1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ uncond_embeddings = self.text_encoder(
+ uncond_input.input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ uncond_embeddings = uncond_embeddings[0]
+
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = uncond_embeddings.shape[1]
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ text_embeddings = torch.cat(
+ [uncond_embeddings, text_embeddings]
+ )
+ text_embeddings = text_embeddings.to(dtype=self.dtype)
+ return text_embeddings
+
+
+ def clip_encode_image_global(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip global feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ image_embeddings = self.clip_image_encoder(image).image_embeds
+ image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def clip_encode_image_local(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip local feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ last_hidden_states = self.clip_image_encoder(image).last_hidden_state
+ last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ image_embeddings = self.clip_image_encoder.visual_projection(last_hidden_states_norm)
+ else:
+ image_embeddings = self.refer_clip_proj(last_hidden_states_norm.to(dtype=self.dtype))
+ # image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def clip_encode_image_local_uncond(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip local feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ last_hidden_states = self.clip_image_encoder(image).last_hidden_state
+ last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ image_embeddings = self.clip_image_encoder.visual_projection(last_hidden_states_norm)
+ else:
+ image_embeddings = self.refer_clip_proj(last_hidden_states_norm.to(dtype=self.dtype))
+ # image_embeddings = image_embeddings.unsqueeze(1)
+
+ ## uncond image
+ uncond_image = torch.zeros_like(image)
+ uncond_last_hidden_states = self.clip_image_encoder(uncond_image).last_hidden_state
+ uncond_last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(uncond_last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ uncond_image_embeddings = self.clip_image_encoder.visual_projection(uncond_last_hidden_states_norm) # b, c, 768
+ else:
+ uncond_image_embeddings = self.refer_clip_proj(uncond_last_hidden_states_norm.to(dtype=self.dtype)) # b, c, 768
+
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ bs_embed, seq_len, _ = uncond_image_embeddings.shape
+ uncond_image_embeddings = uncond_image_embeddings.repeat(1, num_images_per_prompt, 1)
+ uncond_image_embeddings = uncond_image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ # negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([uncond_image_embeddings, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+
+ def decode_latents(self, latents):
+ latents = 1 / 0.18215 * latents
+ image = self.vae.decode(latents).sample
+ image = (image / 2 + 0.5).clamp(0, 1)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
+ image = image.cpu().float().numpy()
+ return image
+
+ def prepare_extra_step_kwargs(self, generator, eta=0.0):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def prepare_latents(
+ self, batch_size, num_channels_latents,
+ height, width, generator, latents=None):
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ if isinstance(generator, list):
+ shape = (1,) + shape[1:]
+ latents = [
+ torch.randn(shape, generator=generator[i], dtype=self.dtype)
+ for i in range(batch_size)
+ ]
+ latents = torch.cat(latents, dim=0).to(self.device)
+ else:
+ latents = torch.randn(shape, generator=generator, device=self.device, dtype=self.dtype)
+ else:
+ if latents.shape != shape:
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
+ latents = latents.to(device=self.device, dtype=self.dtype)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.noise_scheduler.init_noise_sigma
+ return latents
+
+ def forward_train(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ bsz = image.shape[0]
+ text = inputs['input_text']
+ z_text = self.text_encode(text)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+ # conditioning pixel value
+ # TODO: @tan, change cond_imgs in dataloader to pose or other conditions.
+ # WT: controlnet_image should be a list of multiple condition ([pose, ref_image])
+ controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, z_text,
+ controlnet_cond=controlnet_image, return_dict=False)
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=z_text,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def forward_train_multicontrol(self, inputs, outputs):
+
+ # use CFG
+ if self.args.drop_ref > 0:
+ p = random.random()
+ if p <= self.args.drop_ref: # dropout ref image
+ inputs['reference_img'] = torch.zeros_like(inputs['reference_img'])
+
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ ref_image = inputs['reference_img']
+ bsz = image.shape[0]
+
+ if self.args.ref_null_caption:
+ text = inputs['input_text']
+ if random.random() < self.args.drop_text: # drop text w.r.t the prob
+ text = ["" for i in text]
+ z_text = self.text_encode(text)
+
+ # text SD input --> reference image input (clip global embedding)
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image).to(dtype=self.dtype)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image).to(dtype=self.dtype)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+
+ # TODO: @tan, change cond_imgs in dataloadser to pose or other conditions.
+ # controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"]) # controlnet path input
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"]
+ controlnet_image = [inputs["cond_imgs"], reference_latents_controlnet] # [pose image, ref image]
+
+ # controlnet get the input of (a. ref image clip embedding; b. pose cond image)
+ if self.args.ref_null_caption:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, z_text], # reference controlnet path use null caption
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, refer_latents], # both controlnet path use the refer latents
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=refer_latents, # refer latents
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def prepare_image(
+ self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance
+ ):
+ if not isinstance(image, torch.Tensor):
+ if isinstance(image, PIL.Image.Image):
+ image = [image]
+
+ if isinstance(image[0], PIL.Image.Image):
+ images = []
+
+ for image_ in image:
+ image_ = image_.convert("RGB")
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
+ image_ = np.array(image_)
+ image_ = image_[None, :]
+ images.append(image_)
+
+ image = images
+
+ image = np.concatenate(image, axis=0)
+ image = np.array(image).astype(np.float32) / 255.0
+ image = image.transpose(0, 3, 1, 2)
+ image = torch.from_numpy(image)
+ elif isinstance(image[0], torch.Tensor):
+ image = torch.cat(image, dim=0)
+
+ image_batch_size = image.shape[0]
+
+ if image_batch_size == 1:
+ repeat_by = batch_size
+ else:
+ # image batch size is the same as prompt batch size
+ repeat_by = num_images_per_prompt
+
+ image = image.repeat_interleave(repeat_by, dim=0)
+
+ image = image.to(device=device, dtype=dtype)
+
+ if do_classifier_free_guidance:
+ image = torch.cat([image] * 2)
+
+ return image
+
+ @torch.no_grad()
+ def forward_sample(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+
+ # Encode input prompt
+ text = inputs['input_text']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ image = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ controlnet_cond=image,
+ conditioning_scale=controlnet_conditioning_scale,
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ @torch.no_grad()
+ def forward_sample_multicontrol(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+ ref_image = inputs['reference_img']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+
+ if self.args.combine_clip_local:
+ if self.args.drop_ref > 0:
+ refer_latents = self.clip_encode_image_local_uncond(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+ else:
+ refer_latents = self.clip_encode_image_local(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+
+
+ if self.args.ref_null_caption: # test must use null caption
+ text = inputs['input_text']
+ text = ["" for i in text]
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ controlnet_conditioning_scale_cond = self.controlnet_conditioning_scale_cond
+ controlnet_conditioning_scale_ref = self.controlnet_conditioning_scale_ref
+ image_pose = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare ref image
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"])
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs['reference_img_controlnet'].to(dtype=self.dtype)
+
+ reference_latents_controlnet = self.prepare_image(
+ image=reference_latents_controlnet,
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ if self.args.ref_null_caption: # null caption input for ref controlnet path
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, text_embeddings],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, refer_latents],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or (
+ (i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+
+ @torch.no_grad()
+ def forward_enc_dec(self, inputs, outputs):
+ image = inputs['label_imgs']
+ latent = self.image_encoder(image)
+ gen_img = self.image_decoder(latent)
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ def progress_bar(self, iterable=None, total=None):
+ if not hasattr(self, "_progress_bar_config"):
+ self._progress_bar_config = {}
+ elif not isinstance(self._progress_bar_config, dict):
+ raise ValueError(
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
+ )
+
+ if iterable is not None:
+ return tqdm(iterable, **self._progress_bar_config)
+ elif total is not None:
+ return tqdm(total=total, **self._progress_bar_config)
+ else:
+ raise ValueError("Either `total` or `iterable` has to be defined.")
+
+ def set_progress_bar_config(self, **kwargs):
+ self._progress_bar_config = kwargs
+
+
+def inner_collect_fn(args, inputs, outputs, log_dir, global_step, eval_save_filename='eval_visu'):
+ visu_save = getattr(args, 'visu_save', False)
+
+ rank = get_rank()
+ if rank == -1:
+ splice = ''
+ else:
+ splice = '_' + str(rank)
+ if global_step <= 0:
+ eval_log_dir = os.path.join(log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(log_dir, 'eval_step_%d' % (global_step))
+ ensure_dirname(eval_log_dir)
+
+ if not visu_save: # for every different combination, we build a new dir to save
+ gt_save_path = os.path.join(eval_log_dir, 'gt')
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir, f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir, 'cond')
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir, 'ref')
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir, 'ref_control')
+ ensure_dirname(ref_control_save_path)
+
+ if rank in [-1, 0]:
+ logger.warning(eval_log_dir)
+
+ # Save Model Setting
+ type_output = [int, float, str, bool, tuple, dict, type(None), ]
+ setting_output = {item: getattr(args, item) for item in dir(args) if
+ type(getattr(args, item)) in type_output and not item.startswith('__')}
+ data2file(setting_output, os.path.join(eval_log_dir, 'Model_Setting.json'))
+
+ dl = {**inputs, **{k: v for k, v in outputs.items() if k.split('_')[0] == 'logits'}}
+ ld = dl2ld(dl)
+
+ l = ld[0]['logits_imgs'].shape[0]
+
+ for _, sample in enumerate(ld):
+
+ if visu_save:
+ save_filename = sample['save_filename']
+ eval_log_dir_filename = os.path.join(eval_log_dir, save_filename)
+
+ gt_save_path = os.path.join(eval_log_dir_filename, 'gt')
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir_filename,
+ f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir_filename, 'cond')
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir_filename, 'ref')
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir_filename, 'ref_control')
+ ensure_dirname(ref_control_save_path)
+
+
+ _name = 'nuwa'
+ if 'input_text' in sample:
+ _name = sample['input_text'][:200]
+ if 'img_key' in sample:
+ _name = sample['img_key']
+ char_remov = [os.sep, '.', '/']
+ for c in char_remov:
+ _name = _name.replace(c, '')
+ prefix = "_".join(_name.split(" "))
+ # prefix += splice
+ # postfix = '_' + str(round(time.time() * 10))
+ postfix = ''
+
+ try:
+ ref_img_size = sample['reference_img_size']
+ except:
+ ref_img_size = None
+
+ if 'label_imgs' in sample:
+ image = sample['label_imgs']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(gt_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'logits_imgs' in sample:
+ image = tensor2pil(sample['logits_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(pred_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'cond_imgs' in sample: # pose
+ image = tensor2pil(sample['cond_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(cond_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'reference_img' in sample:
+ image = sample['reference_img']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'reference_img_controlnet' in sample:
+ image = sample['reference_img_controlnet']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_control_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ return gt_save_path, pred_save_path
+
+def tensor2pil(images, resize_img=False, img_target_size=None):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image.squeeze(), mode="L").resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
+ else:
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image).resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_mask.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..0bc90e1369b68118a04ff7e4b4464f3ad7cdd38f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_mask.py
@@ -0,0 +1,64 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_mask.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/data/mtp_vlp_ray/debug/debug_pretrain"
+ debug_train_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml'
+ debug_val_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa97f9d5df5a20c9f11478b6f39b897a15d57195
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/tiktok_S256L16_xformers_tsv.py
@@ -0,0 +1,64 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_tsv.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/debug_output/video_sythesis/dataset"
+ debug_train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ debug_val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_TiktokDance-poses.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/unet_2d_condition.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/unet_2d_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4207226d2f46c21cc85b649c91c391b0b0f2441
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet/unet_2d_condition.py
@@ -0,0 +1,654 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import UNet2DConditionLoadersMixin
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ CrossAttnUpBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ UNetMidBlock2DSimpleCrossAttn,
+ UpBlock2D,
+ get_down_block,
+ get_up_block,
+)
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class UNet2DConditionOutput(BaseOutput):
+ """
+ Args:
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model.
+ """
+
+ sample: torch.FloatTensor
+
+
+class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
+ r"""
+ UNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep
+ and returns sample shaped output.
+
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
+ implements for all the models (such as downloading or saving, etc.)
+
+ Parameters:
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
+ Height and width of input/output sample.
+ in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
+ out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
+ Whether to flip the sin to cos in the time embedding.
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
+ The tuple of downsample blocks to use.
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
+ The mid block type. Choose from `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`, will skip the
+ mid block layer if `None`.
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`):
+ The tuple of upsample blocks to use.
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
+ Whether to include self-attention in the basic transformer blocks, see
+ [`~models.attention.BasicTransformerBlock`].
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
+ The tuple of output channels for each block.
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
+ If `None`, it will skip the normalization and activation layers in post-processing
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
+ cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
+ for resnet blocks, see [`~models.resnet.ResnetBlock2D`]. Choose from `default` or `scale_shift`.
+ class_embed_type (`str`, *optional*, defaults to None): The type of class embedding to use which is ultimately
+ summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, or `"projection"`.
+ num_class_embeds (`int`, *optional*, defaults to None):
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
+ class conditioning with `class_embed_type` equal to `None`.
+ time_embedding_type (`str`, *optional*, default to `positional`):
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
+ timestep_post_act (`str, *optional*, default to `None`):
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
+ time_cond_proj_dim (`int`, *optional*, default to `None`):
+ The dimension of `cond_proj` layer in timestep embedding.
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
+ using the "projection" `class_embed_type`. Required when using the "projection" `class_embed_type`.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ sample_size: Optional[int] = None,
+ in_channels: int = 4,
+ out_channels: int = 4,
+ center_input_sample: bool = False,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ dual_cross_attention: bool = False,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ time_embedding_type: str = "positional",
+ timestep_post_act: Optional[str] = None,
+ time_cond_proj_dim: Optional[int] = None,
+ conv_in_kernel: int = 3,
+ conv_out_kernel: int = 3,
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.sample_size = sample_size
+
+ # Check inputs
+ if len(down_block_types) != len(up_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ if time_embedding_type == "fourier":
+ time_embed_dim = block_out_channels[0] * 2
+ if time_embed_dim % 2 != 0:
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
+ self.time_proj = GaussianFourierProjection(
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
+ )
+ timestep_input_dim = time_embed_dim
+ elif time_embedding_type == "positional":
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+ else:
+ raise ValueError(
+ f"{time_embedding_type} does not exist. Pleaes make sure to use one of `fourier` or `positional`."
+ )
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ post_act_fn=timestep_post_act,
+ cond_proj_dim=time_cond_proj_dim,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ self.down_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ # mid
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+ elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
+ self.mid_block = UNetMidBlock2DSimpleCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ elif mid_block_type is None:
+ self.mid_block = None
+ else:
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
+
+ # count how many layers upsample the images
+ self.num_upsamplers = 0
+
+ # up
+ reversed_block_out_channels = list(reversed(block_out_channels))
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
+ only_cross_attention = list(reversed(only_cross_attention))
+
+ output_channel = reversed_block_out_channels[0]
+ for i, up_block_type in enumerate(up_block_types):
+ is_final_block = i == len(block_out_channels) - 1
+
+ prev_output_channel = output_channel
+ output_channel = reversed_block_out_channels[i]
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
+
+ # add upsample block for all BUT final layer
+ if not is_final_block:
+ add_upsample = True
+ self.num_upsamplers += 1
+ else:
+ add_upsample = False
+
+ up_block = get_up_block(
+ up_block_type,
+ num_layers=layers_per_block + 1,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ prev_output_channel=prev_output_channel,
+ temb_channels=time_embed_dim,
+ add_upsample=add_upsample,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=reversed_attention_head_dim[i],
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.up_blocks.append(up_block)
+ prev_output_channel = output_channel
+
+ # out
+ if norm_num_groups is not None:
+ self.conv_norm_out = nn.GroupNorm(
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
+ )
+ self.conv_act = nn.SiLU()
+ else:
+ self.conv_norm_out = None
+ self.conv_act = None
+
+ conv_out_padding = (conv_out_kernel - 1) // 2
+ self.conv_out = nn.Conv2d(
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
+ )
+
+ @property
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D, CrossAttnUpBlock2D, UpBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ) -> Union[UNet2DConditionOutput, Tuple]:
+ r"""
+ Args:
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processor` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Returns:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
+ returning a tuple, the first element is the sample tensor.
+ """
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
+ # on the fly if necessary.
+ default_overall_up_factor = 2**self.num_upsamplers
+
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
+ forward_upsample_size = False
+ upsample_size = None
+
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
+ logger.info("Forward upsample size to force interpolation output size.")
+ forward_upsample_size = True
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 0. center input if necessary
+ if self.config.center_input_sample:
+ sample = 2 * sample - 1.0
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ if down_block_additional_residuals is not None:
+ new_down_block_res_samples = ()
+
+ for down_block_res_sample, down_block_additional_residual in zip(
+ down_block_res_samples, down_block_additional_residuals
+ ):
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
+ new_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = new_down_block_res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ if mid_block_additional_residual is not None:
+ sample = sample + mid_block_additional_residual
+
+ # 5. up
+ for i, upsample_block in enumerate(self.up_blocks):
+ is_final_block = i == len(self.up_blocks) - 1
+
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
+
+ # if we have not reached the final block and need to forward the
+ # upsample size, we do it here
+ if not is_final_block and forward_upsample_size:
+ upsample_size = down_block_res_samples[-1].shape[2:]
+
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
+ sample = upsample_block(
+ hidden_states=sample,
+ temb=emb,
+ res_hidden_states_tuple=res_samples,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ upsample_size=upsample_size,
+ attention_mask=attention_mask,
+ )
+ else:
+ sample = upsample_block(
+ hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
+ )
+
+ # 6. post-process
+ if self.conv_norm_out:
+ sample = self.conv_norm_out(sample)
+ sample = self.conv_act(sample)
+ sample = self.conv_out(sample)
+
+ if not return_dict:
+ return (sample,)
+
+ return UNet2DConditionOutput(sample=sample)
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..b046864a1963520479c8217f6ebbed2d2f01f693
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv.py
@@ -0,0 +1,64 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet_attr_pretraining.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/coco_controlnet_t2i_imagevar_combine_tsv.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/debug_output/video_sythesis/dataset"
+ debug_train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ debug_val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_TiktokDance-poses.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv_strongrand.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv_strongrand.py
new file mode 100644
index 0000000000000000000000000000000000000000..72cd769796aa725ae8864c60913ecca9b75afd51
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/coco_S256_xformers_tsv_strongrand.py
@@ -0,0 +1,64 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet_attr_pretraining.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/coco_controlnet_t2i_imagevar_combine_tsv_strongrand.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/debug_output/video_sythesis/dataset"
+ debug_train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ debug_val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_TiktokDance-poses.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ab0406a6eaa564859203bfcd21a8719c70b6b1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet.py
@@ -0,0 +1,723 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetConditioningConvin(nn.Module):
+ """
+ only reserve the conv_in of the original controlnet conditioning embeddinglayer
+ accept image tensor after the SD vae
+ """
+
+ def __init__(
+ self,
+ in_channels: int = 4,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ ):
+ super().__init__()
+
+ # self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ return embedding
+
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ args = None,
+ use_sd_vae = False,
+ ):
+ super().__init__()
+
+ self.args = args
+ self.use_sd_vae = use_sd_vae
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ if self.args and self.args.refer_sdvae and use_sd_vae:
+ print('use sd vae to init the controlnet condition embedding')
+ self.controlnet_cond_embedding = ControlNetConditioningConvin(in_channels=in_channels,
+ block_out_channels=block_out_channels)
+ else:
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ args = None,
+ use_sd_vae=False,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ args=args,
+ use_sd_vae=use_sd_vae,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ if controlnet.args and controlnet.args.refer_sdvae and controlnet.use_sd_vae: # init controlnet condition embedding with unet convin
+ controlnet.controlnet_cond_embedding.conv_in.load_state_dict(unet.conv_in.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+class MultiControlNetModel(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ encoder_hidden_states,
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+class MultiControlNetModel_MultiHiddenStates(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: List[torch.Tensor], # Different from the original multicontrolnet implementation, here the encode hidden states can also be revised
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet, each_hidden_state) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets, encoder_hidden_states)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ #encoder_hidden_states,
+ each_hidden_state, # each hidden state input
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet_main.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..29935b7af98357f688ebf4df92d53119ad945c06
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/controlnet_main.py
@@ -0,0 +1,573 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `Attention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
+ def set_default_attn_processor(self):
+ """
+ Disables custom attention processors and sets the default attention implementation.
+ """
+ self.set_attn_processor(AttnProcessor())
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_sliceable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_sliceable_dims(module)
+
+ num_sliceable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_sliceable_layers * [1]
+
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/net.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/net.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6c7c5b4ab529f702b222530362b009d54135d88
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/net.py
@@ -0,0 +1,874 @@
+import torch
+from utils.dist import synchronize, get_rank
+
+from config import *
+from typing import Callable, List, Optional, Union
+
+import inspect
+from typing import Callable, List, Optional, Union
+
+import torch
+import random
+from packaging import version
+from transformers import CLIPTokenizer, CLIPVisionModelWithProjection, CLIPImageProcessor, CLIPTextModel
+from tqdm.auto import tqdm
+
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL
+from diffusers.schedulers import DDIMScheduler, PNDMScheduler, DDPMScheduler, UniPCMultistepScheduler
+
+from diffusers.utils import deprecate, PIL_INTERPOLATION
+from diffusers.utils.import_utils import is_xformers_available
+
+# from diffusers.models import UNet2DConditionModel
+from .unet_2d_condition import UNet2DConditionModel
+import PIL.Image
+from .controlnet import ControlNetModel, MultiControlNetModel_MultiHiddenStates
+# from PIL import Image
+from utils.common import ensure_directory
+from utils.dist import synchronize
+
+class Net(nn.Module):
+ def __init__(
+ self, args
+ ):
+ super().__init__()
+ self.args = args
+
+ tr_noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ if self.args.eval_scheduler == "ddpm":
+ noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ elif self.args.eval_scheduler == "ddim":
+ noise_scheduler = DDIMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ else:
+ noise_scheduler = PNDMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ # tokenizer = CLIPTokenizer.from_pretrained(
+ # args.pretrained_model_path, subfolder="tokenizer")
+ feature_extractor = CLIPImageProcessor.from_pretrained(args.pretrained_model_path, subfolder="feature_extractor")
+ print(f"Loading pre-trained image_encoder from {args.pretrained_model_path}/image_encoder")
+ clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.pretrained_model_path, subfolder="image_encoder")
+ print(f"Loading pre-trained vae from {args.pretrained_model_path}/vae")
+ vae = AutoencoderKL.from_pretrained(
+ args.pretrained_model_path, subfolder="vae")
+ print(f"Loading pre-trained unet from {self.args.pretrained_model_path}/unet")
+ unet = UNet2DConditionModel.from_pretrained(
+ self.args.pretrained_model_path, subfolder="unet")
+
+ if hasattr(noise_scheduler.config, "steps_offset") and noise_scheduler.config.steps_offset != 1:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {noise_scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.noise_scheduler.config)
+ new_config["steps_offset"] = 1
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ if hasattr(noise_scheduler.config, "clip_sample") and noise_scheduler.config.clip_sample is True:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(noise_scheduler.config)
+ new_config["clip_sample"] = False
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse("0.9.0.dev0")
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ if self.args.enable_xformers_memory_efficient_attention:
+ if is_xformers_available():
+ unet.enable_xformers_memory_efficient_attention()
+ else:
+ print("xformers is not available, therefore not enabled")
+
+
+ # WT: initialize controlnet from the pretrained image variation SD model
+ # controlnet_pose = ControlNetModel.from_unet(unet=unet, args=self.args)
+ if args.ref_null_caption:
+ tokenizer = CLIPTokenizer.from_pretrained(self.args.sd15_path, subfolder="tokenizer")
+ self.tokenizer = tokenizer
+ print(f"Loading pre-trained text_encoder from {self.args.sd15_path}/text_encoder")
+ text_encoder = CLIPTextModel.from_pretrained(self.args.sd15_path + "/text_encoder")
+ self.text_encoder = text_encoder
+ unet_sd15 = UNet2DConditionModel.from_pretrained(self.args.sd15_path, subfolder="unet")
+ controlnet_background = ControlNetModel.from_unet(unet=unet_sd15, args=self.args, use_sd_vae=True) # initialize ref controlnet path from the SD pretrained model
+ del unet_sd15
+ else: # initialize controlnet from the variation SD
+ controlnet_background = ControlNetModel.from_unet(unet=unet, args=self.args, use_sd_vae=True)
+
+ if self.args.gradient_checkpointing:
+ # controlnet_pose.enable_gradient_checkpointing()
+ controlnet_background.enable_gradient_checkpointing()
+ # controlnet_unit = MultiControlNetModel_MultiHiddenStates([controlnet_pose, controlnet_background])
+ controlnet_unit = controlnet_background
+
+ self.tr_noise_scheduler = tr_noise_scheduler
+ self.noise_scheduler = noise_scheduler
+ self.vae = vae
+ self.controlnet = controlnet_unit
+ self.unet = unet
+ self.feature_extractor = feature_extractor
+ self.clip_image_encoder = clip_image_encoder
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ self.drop_text_prob = args.drop_text
+ self.device = torch.device('cpu')
+ self.dtype = torch.float32
+
+ self.scale_factor = self.args.scale_factor
+ self.guidance_scale = self.args.guidance_scale
+ self.controlnet_conditioning_scale = getattr(self.args, "controlnet_conditioning_scale", 1.0)
+ self.controlnet_conditioning_scale_cond = getattr(self.args, "controlnet_conditioning_scale_cond", 1.0)
+ self.controlnet_conditioning_scale_ref = getattr(self.args, "controlnet_conditioning_scale_ref", 1.0)
+
+ if getattr(self.args, 'combine_clip_local', None) and not getattr(self.args, 'refer_clip_proj', None): # not use clip pretrained visual projection (but initialize from it)
+ self.refer_clip_proj = torch.nn.Linear(clip_image_encoder.visual_projection.in_features, clip_image_encoder.visual_projection.out_features, bias=False)
+ self.refer_clip_proj.load_state_dict(clip_image_encoder.visual_projection.state_dict())
+ self.refer_clip_proj.requires_grad_(True)
+
+
+ def enable_vae_slicing(self):
+ self.vae.enable_slicing()
+
+ def disable_vae_slicing(self):
+ self.vae.disable_slicing()
+
+ def init_ddpm(self):
+ self.freeze_pretrained_part_in_ddpm()
+ return
+
+ def freeze_pretrained_part_in_ddpm(self):
+ if self.args.freeze_unet:
+ #b self.unet.eval()
+ param_unfreeze_num = 0
+ if self.args.unet_unfreeze_type == 'crossattn-kv':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not ('attn2.to_k' in param_name or 'attn2.to_v' in param_name):
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'crossattn':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not 'attn2' in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'transblocks':
+ for param_name, param in self.unet.named_parameters():
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'all':
+ for param_name, param in self.unet.named_parameters():
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ else: # freeze all the unet
+ print('Unmatch to any option, freeze all the unet')
+ self.unet.eval()
+ self.unet.requires_grad_(False)
+
+ print(f"Mode [{self.args.unet_unfreeze_type}]: There are {param_unfreeze_num} modules in unet to be set as requires_grad=True.")
+
+ self.vae.eval()
+ self.clip_image_encoder.eval()
+ self.vae.requires_grad_(False)
+ self.clip_image_encoder.requires_grad_(False)
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.eval()
+ self.text_encoder.requires_grad_(False)
+
+ def to(self, *args, **kwargs):
+ model_converted = super().to(*args, **kwargs)
+ self.device = next(self.parameters()).device
+ self.dtype = next(self.unet.parameters()).dtype
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return model_converted
+
+ def half(self, *args, **kwargs):
+ super().half(*args, **kwargs)
+ self.dtype = torch.float16
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return
+
+ def train(self, *args):
+ super().train(*args)
+ self.freeze_pretrained_part_in_ddpm()
+
+ def image_encoder(self, image):
+ b, c, h, w = image.size()
+ latents = self.vae.encode(image).latent_dist.sample()
+ latents = latents * self.scale_factor
+ latents = latents.to(dtype=self.dtype)
+ return latents
+
+ def image_decoder(self, latents):
+ latents = 1/self.scale_factor * latents
+ dec = self.vae.decode(latents).sample
+ image = (dec / 2 + 0.5).clamp(0, 1)
+ return image
+
+ def forward(self, inputs):
+ outputs = dict()
+
+ generator = torch.Generator(device=self.device)
+ generator.manual_seed(self.args.seed)
+ inputs['generator'] = generator
+
+ if self.training:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_train(inputs, outputs)
+ outputs = self.forward_train_multicontrol(inputs, outputs)
+ elif 'enc_dec_only' in inputs and inputs['enc_dec_only']:
+ outputs = self.forward_enc_dec(inputs, outputs)
+ else:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_sample(inputs, outputs)
+ outputs = self.forward_sample_multicontrol(inputs, outputs)
+ removed_key = inputs.pop("generator", None)
+ return outputs
+
+ def text_encode(
+ self, prompt, num_images_per_prompt=1,
+ do_classifier_free_guidance=False, negative_prompt=None):
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ text_embeddings = self.text_encoder(
+ text_input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ text_embeddings = text_embeddings[0]
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = text_embeddings.shape
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = text_input_ids.shape[-1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ uncond_embeddings = self.text_encoder(
+ uncond_input.input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ uncond_embeddings = uncond_embeddings[0]
+
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = uncond_embeddings.shape[1]
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ text_embeddings = torch.cat(
+ [uncond_embeddings, text_embeddings]
+ )
+ text_embeddings = text_embeddings.to(dtype=self.dtype)
+ return text_embeddings
+
+
+ def clip_encode_image_global(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip global feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ image_embeddings = self.clip_image_encoder(image).image_embeds
+ image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def clip_encode_image_local(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip local feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ last_hidden_states = self.clip_image_encoder(image).last_hidden_state
+ last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ image_embeddings = self.clip_image_encoder.visual_projection(last_hidden_states_norm)
+ else:
+ image_embeddings = self.refer_clip_proj(last_hidden_states_norm.to(dtype=self.dtype))
+ # image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def decode_latents(self, latents):
+ latents = 1 / 0.18215 * latents
+ image = self.vae.decode(latents).sample
+ image = (image / 2 + 0.5).clamp(0, 1)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
+ image = image.cpu().float().numpy()
+ return image
+
+ def prepare_extra_step_kwargs(self, generator, eta=0.0):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def prepare_latents(
+ self, batch_size, num_channels_latents,
+ height, width, generator, latents=None):
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ if isinstance(generator, list):
+ shape = (1,) + shape[1:]
+ latents = [
+ torch.randn(shape, generator=generator[i], dtype=self.dtype)
+ for i in range(batch_size)
+ ]
+ latents = torch.cat(latents, dim=0).to(self.device)
+ else:
+ latents = torch.randn(shape, generator=generator, device=self.device, dtype=self.dtype)
+ else:
+ if latents.shape != shape:
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
+ latents = latents.to(device=self.device, dtype=self.dtype)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.noise_scheduler.init_noise_sigma
+ return latents
+
+ def forward_train_multicontrol(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ ref_image = inputs['reference_img']
+ bsz = image.shape[0]
+
+ if self.args.ref_null_caption:
+ text = inputs['input_text']
+ if random.random() < self.args.drop_text: # drop text w.r.t the prob
+ text = ["" for i in text]
+ z_text = self.text_encode(text)
+
+ # text SD input --> reference image input (clip global embedding)
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image).to(dtype=self.dtype)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image).to(dtype=self.dtype)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+
+ # TODO: @tan, change cond_imgs in dataloadser to pose or other conditions.
+ # controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"]) # controlnet path input
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"]
+ # controlnet_image = [inputs["cond_imgs"], reference_latents_controlnet] # [pose image, ref image]
+ controlnet_image = reference_latents_controlnet # [ref image]
+
+ # controlnet get the input of (a. ref image clip embedding; b. pose cond image)
+ if self.args.ref_null_caption:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, z_text, # reference controlnet path use null caption
+ controlnet_cond=controlnet_image, return_dict=False)
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, refer_latents, # both controlnet path use the refer latents
+ controlnet_cond=controlnet_image, return_dict=False)
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=refer_latents, # refer latents
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+
+ def prepare_image(
+ self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance
+ ):
+ if not isinstance(image, torch.Tensor):
+ if isinstance(image, PIL.Image.Image):
+ image = [image]
+
+ if isinstance(image[0], PIL.Image.Image):
+ images = []
+
+ for image_ in image:
+ image_ = image_.convert("RGB")
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
+ image_ = np.array(image_)
+ image_ = image_[None, :]
+ images.append(image_)
+
+ image = images
+
+ image = np.concatenate(image, axis=0)
+ image = np.array(image).astype(np.float32) / 255.0
+ image = image.transpose(0, 3, 1, 2)
+ image = torch.from_numpy(image)
+ elif isinstance(image[0], torch.Tensor):
+ image = torch.cat(image, dim=0)
+
+ image_batch_size = image.shape[0]
+
+ if image_batch_size == 1:
+ repeat_by = batch_size
+ else:
+ # image batch size is the same as prompt batch size
+ repeat_by = num_images_per_prompt
+
+ image = image.repeat_interleave(repeat_by, dim=0)
+
+ image = image.to(device=device, dtype=dtype)
+
+ if do_classifier_free_guidance:
+ image = torch.cat([image] * 2)
+
+ return image
+
+ @torch.no_grad()
+ def forward_sample_multicontrol(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+ ref_image = inputs['reference_img']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+
+ if self.args.ref_null_caption: # test must use null caption
+ text = inputs['input_text']
+ text = ["" for i in text]
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ controlnet_conditioning_scale_cond = self.controlnet_conditioning_scale_cond
+ controlnet_conditioning_scale_ref = self.controlnet_conditioning_scale_ref
+ # image_pose = self.prepare_image(
+ # image=inputs['cond_imgs'].to(dtype=self.dtype),
+ # width=w,
+ # height=h,
+ # batch_size=b * self.args.num_inf_images_per_prompt,
+ # num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ # device=self.device,
+ # dtype=self.controlnet.dtype,
+ # do_classifier_free_guidance=do_classifier_free_guidance,
+ # )
+
+ # Prepare ref image
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"])
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs['reference_img_controlnet'].to(dtype=self.dtype)
+
+ reference_latents_controlnet = self.prepare_image(
+ image=reference_latents_controlnet,
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ if self.args.ref_null_caption: # null caption input for ref controlnet path
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ controlnet_cond=reference_latents_controlnet,
+ conditioning_scale=controlnet_conditioning_scale_ref,
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ controlnet_cond=reference_latents_controlnet,
+ conditioning_scale=controlnet_conditioning_scale_ref,
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or (
+ (i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+
+ @torch.no_grad()
+ def forward_enc_dec(self, inputs, outputs):
+ image = inputs['label_imgs']
+ latent = self.image_encoder(image)
+ gen_img = self.image_decoder(latent)
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ def progress_bar(self, iterable=None, total=None):
+ if not hasattr(self, "_progress_bar_config"):
+ self._progress_bar_config = {}
+ elif not isinstance(self._progress_bar_config, dict):
+ raise ValueError(
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
+ )
+
+ if iterable is not None:
+ return tqdm(iterable, **self._progress_bar_config)
+ elif total is not None:
+ return tqdm(total=total, **self._progress_bar_config)
+ else:
+ raise ValueError("Either `total` or `iterable` has to be defined.")
+
+ def set_progress_bar_config(self, **kwargs):
+ self._progress_bar_config = kwargs
+
+
+def inner_collect_fn(args, inputs, outputs, log_dir, global_step, eval_save_filename='eval_visu'):
+ rank = get_rank()
+ if rank == -1:
+ splice = ''
+ else:
+ splice = '_' + str(rank)
+ if global_step <= 0:
+ eval_log_dir = os.path.join(log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(log_dir, 'eval_step_%d' % (global_step))
+ ensure_directory(eval_log_dir)
+
+ gt_save_path = os.path.join(eval_log_dir, 'gt')
+ ensure_directory(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir, f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_directory(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir, 'cond')
+ ensure_directory(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir, 'ref')
+ ensure_directory(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir, 'ref_control')
+ ensure_directory(ref_control_save_path)
+
+ synchronize()
+ if rank in [-1, 0]:
+ logger.warning(eval_log_dir)
+
+ # Save Model Setting
+ type_output = [int, float, str, bool, tuple, dict, type(None), ]
+ setting_output = {item: getattr(args, item) for item in dir(args) if
+ type(getattr(args, item)) in type_output and not item.startswith('__')}
+ data2file(setting_output, os.path.join(eval_log_dir, 'Model_Setting.json'))
+
+ dl = {**inputs, **{k: v for k, v in outputs.items() if k.split('_')[0] == 'logits'}}
+ ## WT DEBUG
+ # print('just for debug')
+ # if 'cond_img_pose' in dl:
+ # del dl['cond_img_pose']
+ # del dl['cond_img_attr']
+ ld = dl2ld(dl)
+
+ l = ld[0]['logits_imgs'].shape[0]
+
+ for _, sample in enumerate(ld):
+ _name = 'nuwa'
+ if 'input_text' in sample:
+ _name = sample['input_text'][:200]
+ if 'img_key' in sample:
+ _name = sample['img_key']
+ char_remov = [os.sep, '.', '/']
+ for c in char_remov:
+ _name = _name.replace(c, '')
+ prefix = "_".join(_name.split(" "))
+ # prefix += splice
+ # postfix = '_' + str(round(time.time() * 10))
+ postfix = ''
+
+ if 'label_imgs' in sample:
+ image = sample['label_imgs']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image)[0]
+ try:
+ image.save(os.path.join(gt_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'logits_imgs' in sample:
+ image = tensor2pil(sample['logits_imgs'])[0]
+ try:
+ image.save(os.path.join(pred_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'cond_imgs' in sample and sample['cond_imgs'] is not None: # pose
+ image = tensor2pil(sample['cond_imgs'])[0]
+ try:
+ image.save(os.path.join(cond_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'reference_img' in sample:
+ image = sample['reference_img']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image)[0]
+ try:
+ image.save(os.path.join(ref_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'reference_img_controlnet' in sample:
+ image = sample['reference_img_controlnet']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image)[0]
+ try:
+ image.save(os.path.join(ref_control_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ return gt_save_path, pred_save_path
+
+def tensor2pil(images):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/unet_2d_condition.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/unet_2d_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4207226d2f46c21cc85b649c91c391b0b0f2441
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_attr_pretraining/unet_2d_condition.py
@@ -0,0 +1,654 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import UNet2DConditionLoadersMixin
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ CrossAttnUpBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ UNetMidBlock2DSimpleCrossAttn,
+ UpBlock2D,
+ get_down_block,
+ get_up_block,
+)
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class UNet2DConditionOutput(BaseOutput):
+ """
+ Args:
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model.
+ """
+
+ sample: torch.FloatTensor
+
+
+class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
+ r"""
+ UNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep
+ and returns sample shaped output.
+
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
+ implements for all the models (such as downloading or saving, etc.)
+
+ Parameters:
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
+ Height and width of input/output sample.
+ in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
+ out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
+ Whether to flip the sin to cos in the time embedding.
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
+ The tuple of downsample blocks to use.
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
+ The mid block type. Choose from `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`, will skip the
+ mid block layer if `None`.
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`):
+ The tuple of upsample blocks to use.
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
+ Whether to include self-attention in the basic transformer blocks, see
+ [`~models.attention.BasicTransformerBlock`].
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
+ The tuple of output channels for each block.
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
+ If `None`, it will skip the normalization and activation layers in post-processing
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
+ cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
+ for resnet blocks, see [`~models.resnet.ResnetBlock2D`]. Choose from `default` or `scale_shift`.
+ class_embed_type (`str`, *optional*, defaults to None): The type of class embedding to use which is ultimately
+ summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, or `"projection"`.
+ num_class_embeds (`int`, *optional*, defaults to None):
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
+ class conditioning with `class_embed_type` equal to `None`.
+ time_embedding_type (`str`, *optional*, default to `positional`):
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
+ timestep_post_act (`str, *optional*, default to `None`):
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
+ time_cond_proj_dim (`int`, *optional*, default to `None`):
+ The dimension of `cond_proj` layer in timestep embedding.
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
+ using the "projection" `class_embed_type`. Required when using the "projection" `class_embed_type`.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ sample_size: Optional[int] = None,
+ in_channels: int = 4,
+ out_channels: int = 4,
+ center_input_sample: bool = False,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ dual_cross_attention: bool = False,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ time_embedding_type: str = "positional",
+ timestep_post_act: Optional[str] = None,
+ time_cond_proj_dim: Optional[int] = None,
+ conv_in_kernel: int = 3,
+ conv_out_kernel: int = 3,
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.sample_size = sample_size
+
+ # Check inputs
+ if len(down_block_types) != len(up_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ if time_embedding_type == "fourier":
+ time_embed_dim = block_out_channels[0] * 2
+ if time_embed_dim % 2 != 0:
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
+ self.time_proj = GaussianFourierProjection(
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
+ )
+ timestep_input_dim = time_embed_dim
+ elif time_embedding_type == "positional":
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+ else:
+ raise ValueError(
+ f"{time_embedding_type} does not exist. Pleaes make sure to use one of `fourier` or `positional`."
+ )
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ post_act_fn=timestep_post_act,
+ cond_proj_dim=time_cond_proj_dim,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ self.down_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ # mid
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+ elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
+ self.mid_block = UNetMidBlock2DSimpleCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ elif mid_block_type is None:
+ self.mid_block = None
+ else:
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
+
+ # count how many layers upsample the images
+ self.num_upsamplers = 0
+
+ # up
+ reversed_block_out_channels = list(reversed(block_out_channels))
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
+ only_cross_attention = list(reversed(only_cross_attention))
+
+ output_channel = reversed_block_out_channels[0]
+ for i, up_block_type in enumerate(up_block_types):
+ is_final_block = i == len(block_out_channels) - 1
+
+ prev_output_channel = output_channel
+ output_channel = reversed_block_out_channels[i]
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
+
+ # add upsample block for all BUT final layer
+ if not is_final_block:
+ add_upsample = True
+ self.num_upsamplers += 1
+ else:
+ add_upsample = False
+
+ up_block = get_up_block(
+ up_block_type,
+ num_layers=layers_per_block + 1,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ prev_output_channel=prev_output_channel,
+ temb_channels=time_embed_dim,
+ add_upsample=add_upsample,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=reversed_attention_head_dim[i],
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.up_blocks.append(up_block)
+ prev_output_channel = output_channel
+
+ # out
+ if norm_num_groups is not None:
+ self.conv_norm_out = nn.GroupNorm(
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
+ )
+ self.conv_act = nn.SiLU()
+ else:
+ self.conv_norm_out = None
+ self.conv_act = None
+
+ conv_out_padding = (conv_out_kernel - 1) // 2
+ self.conv_out = nn.Conv2d(
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
+ )
+
+ @property
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D, CrossAttnUpBlock2D, UpBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ) -> Union[UNet2DConditionOutput, Tuple]:
+ r"""
+ Args:
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processor` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Returns:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
+ returning a tuple, the first element is the sample tensor.
+ """
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
+ # on the fly if necessary.
+ default_overall_up_factor = 2**self.num_upsamplers
+
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
+ forward_upsample_size = False
+ upsample_size = None
+
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
+ logger.info("Forward upsample size to force interpolation output size.")
+ forward_upsample_size = True
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 0. center input if necessary
+ if self.config.center_input_sample:
+ sample = 2 * sample - 1.0
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ if down_block_additional_residuals is not None:
+ new_down_block_res_samples = ()
+
+ for down_block_res_sample, down_block_additional_residual in zip(
+ down_block_res_samples, down_block_additional_residuals
+ ):
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
+ new_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = new_down_block_res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ if mid_block_additional_residual is not None:
+ sample = sample + mid_block_additional_residual
+
+ # 5. up
+ for i, upsample_block in enumerate(self.up_blocks):
+ is_final_block = i == len(self.up_blocks) - 1
+
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
+
+ # if we have not reached the final block and need to forward the
+ # upsample size, we do it here
+ if not is_final_block and forward_upsample_size:
+ upsample_size = down_block_res_samples[-1].shape[2:]
+
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
+ sample = upsample_block(
+ hidden_states=sample,
+ temb=emb,
+ res_hidden_states_tuple=res_samples,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ upsample_size=upsample_size,
+ attention_mask=attention_mask,
+ )
+ else:
+ sample = upsample_block(
+ hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
+ )
+
+ # 6. post-process
+ if self.conv_norm_out:
+ sample = self.conv_norm_out(sample)
+ sample = self.conv_act(sample)
+ sample = self.conv_out(sample)
+
+ if not return_dict:
+ return (sample,)
+
+ return UNet2DConditionOutput(sample=sample)
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ab0406a6eaa564859203bfcd21a8719c70b6b1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet.py
@@ -0,0 +1,723 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetConditioningConvin(nn.Module):
+ """
+ only reserve the conv_in of the original controlnet conditioning embeddinglayer
+ accept image tensor after the SD vae
+ """
+
+ def __init__(
+ self,
+ in_channels: int = 4,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ ):
+ super().__init__()
+
+ # self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ return embedding
+
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ args = None,
+ use_sd_vae = False,
+ ):
+ super().__init__()
+
+ self.args = args
+ self.use_sd_vae = use_sd_vae
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ if self.args and self.args.refer_sdvae and use_sd_vae:
+ print('use sd vae to init the controlnet condition embedding')
+ self.controlnet_cond_embedding = ControlNetConditioningConvin(in_channels=in_channels,
+ block_out_channels=block_out_channels)
+ else:
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ args = None,
+ use_sd_vae=False,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ args=args,
+ use_sd_vae=use_sd_vae,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ if controlnet.args and controlnet.args.refer_sdvae and controlnet.use_sd_vae: # init controlnet condition embedding with unet convin
+ controlnet.controlnet_cond_embedding.conv_in.load_state_dict(unet.conv_in.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+class MultiControlNetModel(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ encoder_hidden_states,
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+class MultiControlNetModel_MultiHiddenStates(ModelMixin):
+ r"""
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
+ compatible with `ControlNetModel`.
+ Args:
+ controlnets (`List[ControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `ControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: List[torch.Tensor], # Different from the original multicontrolnet implementation, here the encode hidden states can also be revised
+ controlnet_cond: List[torch.tensor],
+ conditioning_scale: List[float],
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ for i, (image, scale, controlnet, each_hidden_state) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets, encoder_hidden_states)):
+ down_samples, mid_sample = controlnet(
+ sample,
+ timestep,
+ #encoder_hidden_states,
+ each_hidden_state, # each hidden state input
+ image,
+ scale,
+ class_labels,
+ timestep_cond,
+ attention_mask,
+ cross_attention_kwargs,
+ return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
+ else:
+ down_block_res_samples = [
+ samples_prev + samples_curr
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
+ ]
+ mid_block_res_sample += mid_sample
+
+ return down_block_res_samples, mid_block_res_sample
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet_main.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet_main.py
new file mode 100644
index 0000000000000000000000000000000000000000..29935b7af98357f688ebf4df92d53119ad945c06
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/controlnet_main.py
@@ -0,0 +1,573 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor
+from diffusers.models.embeddings import TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ get_down_block,
+)
+from diffusers.models.unet_2d_condition import UNet2DConditionModel
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ down_block_res_samples: Tuple[torch.Tensor]
+ mid_block_res_sample: torch.Tensor
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+
+class ControlNetModel(ModelMixin, ConfigMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ in_channels: int = 4,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ # Check inputs
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_kernel = 3
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ # control net conditioning embedding
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=block_out_channels[0],
+ block_out_channels=conditioning_embedding_out_channels,
+ )
+
+ self.down_blocks = nn.ModuleList([])
+ self.controlnet_down_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ for _ in range(layers_per_block):
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ if not is_final_block:
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_down_blocks.append(controlnet_block)
+
+ # mid
+ mid_block_channel = block_out_channels[-1]
+
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
+ controlnet_block = zero_module(controlnet_block)
+ self.controlnet_mid_block = controlnet_block
+
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=mid_block_channel,
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+
+ @classmethod
+ def from_unet(
+ cls,
+ unet: UNet2DConditionModel,
+ controlnet_conditioning_channel_order: str = "rgb",
+ conditioning_embedding_out_channels: Optional[Tuple[int]] = (16, 32, 96, 256),
+ load_weights_from_unet: bool = True,
+ ):
+ r"""
+ Instantiate Controlnet class from UNet2DConditionModel.
+
+ Parameters:
+ unet (`UNet2DConditionModel`):
+ UNet model which weights are copied to the ControlNet. Note that all configuration options are also
+ copied where applicable.
+ """
+ controlnet = cls(
+ in_channels=unet.config.in_channels,
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
+ freq_shift=unet.config.freq_shift,
+ down_block_types=unet.config.down_block_types,
+ only_cross_attention=unet.config.only_cross_attention,
+ block_out_channels=unet.config.block_out_channels,
+ layers_per_block=unet.config.layers_per_block,
+ downsample_padding=unet.config.downsample_padding,
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
+ act_fn=unet.config.act_fn,
+ norm_num_groups=unet.config.norm_num_groups,
+ norm_eps=unet.config.norm_eps,
+ cross_attention_dim=unet.config.cross_attention_dim,
+ attention_head_dim=unet.config.attention_head_dim,
+ use_linear_projection=unet.config.use_linear_projection,
+ class_embed_type=unet.config.class_embed_type,
+ num_class_embeds=unet.config.num_class_embeds,
+ upcast_attention=unet.config.upcast_attention,
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
+ )
+
+ if load_weights_from_unet:
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
+
+ if controlnet.class_embedding:
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
+
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
+
+ return controlnet
+
+ @property
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttentionProcessor` or `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `Attention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
+ def set_default_attn_processor(self):
+ """
+ Disables custom attention processors and sets the default attention implementation.
+ """
+ self.set_attn_processor(AttnProcessor())
+
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attention_slice
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maximum amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_sliceable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_sliceable_dims(module)
+
+ num_sliceable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_sliceable_layers * [1]
+
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.FloatTensor,
+ conditioning_scale: float = 1.0,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[ControlNetOutput, Tuple]:
+ # check channel order
+ channel_order = self.config.controlnet_conditioning_channel_order
+
+ if channel_order == "rgb":
+ # in rgb order by default
+ ...
+ elif channel_order == "bgr":
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
+ else:
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
+
+ sample += controlnet_cond
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ # 5. Control net blocks
+
+ controlnet_down_block_res_samples = ()
+
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
+ down_block_res_sample = controlnet_block(down_block_res_sample)
+ controlnet_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = controlnet_down_block_res_samples
+
+ mid_block_res_sample = self.controlnet_mid_block(sample)
+
+ # 6. scaling
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
+ mid_block_res_sample *= conditioning_scale
+
+ if not return_dict:
+ return (down_block_res_samples, mid_block_res_sample)
+
+ return ControlNetOutput(
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
+ )
+
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net.py
new file mode 100644
index 0000000000000000000000000000000000000000..1da178fbab3e0b7aaef9a698670ea8bc6909cb2a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net.py
@@ -0,0 +1,1086 @@
+import torch
+from utils.dist import synchronize, get_rank
+
+from config import *
+from typing import Callable, List, Optional, Union
+
+import inspect
+from typing import Callable, List, Optional, Union
+
+import torch
+import random
+from packaging import version
+from transformers import CLIPTokenizer, CLIPVisionModelWithProjection, CLIPImageProcessor, CLIPTextModel
+from tqdm.auto import tqdm
+
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL
+from diffusers.schedulers import DDIMScheduler, PNDMScheduler, DDPMScheduler, UniPCMultistepScheduler
+
+from diffusers.utils import deprecate, PIL_INTERPOLATION
+from diffusers.utils.import_utils import is_xformers_available
+
+# from diffusers.models import UNet2DConditionModel
+from .unet_2d_condition import UNet2DConditionModel
+import PIL.Image
+from .controlnet import ControlNetModel, MultiControlNetModel_MultiHiddenStates
+
+# import sys
+# sys.path.append("...")
+# from utils.wutils_ldm import file2data, adaptively_load_state_dict
+
+class Net(nn.Module):
+ def __init__(
+ self, args
+ ):
+ super().__init__()
+ self.args = args
+
+ tr_noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ if self.args.eval_scheduler == "ddpm":
+ noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ elif self.args.eval_scheduler == "ddim":
+ noise_scheduler = DDIMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ else:
+ noise_scheduler = PNDMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ # tokenizer = CLIPTokenizer.from_pretrained(
+ # args.pretrained_model_path, subfolder="tokenizer")
+ feature_extractor = CLIPImageProcessor.from_pretrained(args.pretrained_model_path, subfolder="feature_extractor")
+ print(f"Loading pre-trained image_encoder from {args.pretrained_model_path}/image_encoder")
+ clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.pretrained_model_path, subfolder="image_encoder")
+ print(f"Loading pre-trained vae from {args.pretrained_model_path}/vae")
+ vae = AutoencoderKL.from_pretrained(
+ args.pretrained_model_path, subfolder="vae")
+ print(f"Loading pre-trained unet from {self.args.pretrained_model_path}/unet")
+ unet = UNet2DConditionModel.from_pretrained(
+ self.args.pretrained_model_path, subfolder="unet")
+ # if self.args.stage1_pretrain_path is not None:
+ # pretrain_model_state = file2data(self.args.stage1_pretrain_path, map_location='cpu')
+ # adaptively_load_state_dict(unet, pretrain_model_state['module'])
+
+ if hasattr(noise_scheduler.config, "steps_offset") and noise_scheduler.config.steps_offset != 1:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {noise_scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.noise_scheduler.config)
+ new_config["steps_offset"] = 1
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ if hasattr(noise_scheduler.config, "clip_sample") and noise_scheduler.config.clip_sample is True:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(noise_scheduler.config)
+ new_config["clip_sample"] = False
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse("0.9.0.dev0")
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ if self.args.enable_xformers_memory_efficient_attention:
+ if is_xformers_available():
+ unet.enable_xformers_memory_efficient_attention()
+ else:
+ print("xformers is not available, therefore not enabled")
+
+
+ # WT: initialize controlnet from the pretrained image variation SD model
+ controlnet_pose = ControlNetModel.from_unet(unet=unet, args=self.args)
+ if args.ref_null_caption:
+ tokenizer = CLIPTokenizer.from_pretrained(self.args.sd15_path, subfolder="tokenizer")
+ self.tokenizer = tokenizer
+ print(f"Loading pre-trained text_encoder from {self.args.sd15_path}/text_encoder")
+ text_encoder = CLIPTextModel.from_pretrained(self.args.sd15_path + "/text_encoder")
+ self.text_encoder = text_encoder
+ unet_sd15 = UNet2DConditionModel.from_pretrained(self.args.sd15_path, subfolder="unet")
+ controlnet_background = ControlNetModel.from_unet(unet=unet_sd15, args=self.args, use_sd_vae=True) # initialize ref controlnet path from the SD pretrained model
+ del unet_sd15
+ else: # initialize controlnet from the variation SD
+ controlnet_background = ControlNetModel.from_unet(unet=unet, args=self.args, use_sd_vae=True)
+
+ if self.args.gradient_checkpointing:
+ controlnet_pose.enable_gradient_checkpointing()
+ controlnet_background.enable_gradient_checkpointing()
+ controlnet_unit = MultiControlNetModel_MultiHiddenStates([controlnet_pose, controlnet_background])
+
+ self.tr_noise_scheduler = tr_noise_scheduler
+ self.noise_scheduler = noise_scheduler
+ self.vae = vae
+ self.controlnet = controlnet_unit
+ self.unet = unet
+ self.feature_extractor = feature_extractor
+ self.clip_image_encoder = clip_image_encoder
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ self.drop_text_prob = args.drop_text
+ self.device = torch.device('cpu')
+ self.dtype = torch.float32
+
+ self.scale_factor = self.args.scale_factor
+ self.guidance_scale = self.args.guidance_scale
+ self.controlnet_conditioning_scale = getattr(self.args, "controlnet_conditioning_scale", 1.0)
+ self.controlnet_conditioning_scale_cond = getattr(self.args, "controlnet_conditioning_scale_cond", 1.0)
+ self.controlnet_conditioning_scale_ref = getattr(self.args, "controlnet_conditioning_scale_ref", 1.0)
+
+ if getattr(self.args, 'combine_clip_local', None) and not getattr(self.args, 'refer_clip_proj', None): # not use clip pretrained visual projection (but initialize from it)
+ self.refer_clip_proj = torch.nn.Linear(clip_image_encoder.visual_projection.in_features, clip_image_encoder.visual_projection.out_features, bias=False)
+ self.refer_clip_proj.load_state_dict(clip_image_encoder.visual_projection.state_dict())
+ self.refer_clip_proj.requires_grad_(True)
+
+
+ def enable_vae_slicing(self):
+ self.vae.enable_slicing()
+
+ def disable_vae_slicing(self):
+ self.vae.disable_slicing()
+
+ def init_ddpm(self):
+ self.freeze_pretrained_part_in_ddpm()
+ return
+
+ def freeze_pretrained_part_in_ddpm(self):
+ if getattr(self.args, 'stage2_only_pose', False):
+ print('Only train the pose path, and freeze all the other params')
+ # freeze all the param, only without the pose controlnet
+ self.args.freeze_unet = True
+ self.args.unet_unfreeze_type = None # freeze all the
+
+ # for background controlnet
+ for param_name, param in self.controlnet.named_parameters():
+ if not 'nets.0' in param_name:
+ param.requires_grad_(False)
+
+ # for clip projector
+ if hasattr(self, 'refer_clip_proj'):
+ for param_name, param in self.refer_clip_proj.named_parameters():
+ param.requires_grad_(False)
+
+
+ if self.args.freeze_unet:
+ #b self.unet.eval()
+ param_unfreeze_num = 0
+ if self.args.unet_unfreeze_type == 'crossattn-kv':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not ('attn2.to_k' in param_name or 'attn2.to_v' in param_name):
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'crossattn':
+ for param_name, param in self.unet.named_parameters(): # only to set attn2 k, v to be requires_grad
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ elif not 'attn2' in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'transblocks':
+ for param_name, param in self.unet.named_parameters():
+ if 'transformer_blocks' not in param_name:
+ param.requires_grad_(False)
+ else:
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ elif self.args.unet_unfreeze_type == 'all':
+ for param_name, param in self.unet.named_parameters():
+ param.requires_grad_(True)
+ param_unfreeze_num += 1
+
+ else: # freeze all the unet
+ print('Unmatch to any option, freeze all the unet')
+ self.unet.eval()
+ self.unet.requires_grad_(False)
+
+ print(f"Mode [{self.args.unet_unfreeze_type}]: There are {param_unfreeze_num} modules in unet to be set as requires_grad=True.")
+
+
+ ### for stage-3 ft on specific image
+ if self.args.freeze_pose:
+ # for pose controlnet (net 0)
+ for param_name, param in self.controlnet.named_parameters():
+ if 'nets.0' in param_name:
+ param.requires_grad_(False)
+
+ if self.args.freeze_background:
+ for param_name, param in self.controlnet.named_parameters():
+ if 'nets.1' in param_name:
+ param.requires_grad_(False)
+
+ self.vae.eval()
+ self.clip_image_encoder.eval()
+ self.vae.requires_grad_(False)
+ self.clip_image_encoder.requires_grad_(False)
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.eval()
+ self.text_encoder.requires_grad_(False)
+
+ def to(self, *args, **kwargs):
+ model_converted = super().to(*args, **kwargs)
+ self.device = next(self.parameters()).device
+ self.dtype = next(self.unet.parameters()).dtype
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return model_converted
+
+ def half(self, *args, **kwargs):
+ super().half(*args, **kwargs)
+ self.dtype = torch.float16
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return
+
+ def train(self, *args):
+ super().train(*args)
+ self.freeze_pretrained_part_in_ddpm()
+
+ def image_encoder(self, image):
+ b, c, h, w = image.size()
+ latents = self.vae.encode(image).latent_dist.sample()
+ latents = latents * self.scale_factor
+ latents = latents.to(dtype=self.dtype)
+ return latents
+
+ def image_decoder(self, latents):
+ latents = 1/self.scale_factor * latents
+ dec = self.vae.decode(latents).sample
+ image = (dec / 2 + 0.5).clamp(0, 1)
+ return image
+
+ def forward(self, inputs):
+ outputs = dict()
+
+ generator = torch.Generator(device=self.device)
+ generator.manual_seed(self.args.seed)
+ inputs['generator'] = generator
+
+ if self.training:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_train(inputs, outputs)
+ outputs = self.forward_train_multicontrol(inputs, outputs)
+ elif 'enc_dec_only' in inputs and inputs['enc_dec_only']:
+ outputs = self.forward_enc_dec(inputs, outputs)
+ else:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_sample(inputs, outputs)
+ outputs = self.forward_sample_multicontrol(inputs, outputs)
+ removed_key = inputs.pop("generator", None)
+ return outputs
+
+ def text_encode(
+ self, prompt, num_images_per_prompt=1,
+ do_classifier_free_guidance=False, negative_prompt=None):
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ text_embeddings = self.text_encoder(
+ text_input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ text_embeddings = text_embeddings[0]
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = text_embeddings.shape
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = text_input_ids.shape[-1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ uncond_embeddings = self.text_encoder(
+ uncond_input.input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ uncond_embeddings = uncond_embeddings[0]
+
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = uncond_embeddings.shape[1]
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ text_embeddings = torch.cat(
+ [uncond_embeddings, text_embeddings]
+ )
+ text_embeddings = text_embeddings.to(dtype=self.dtype)
+ return text_embeddings
+
+
+ def clip_encode_image_global(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip global feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ image_embeddings = self.clip_image_encoder(image).image_embeds
+ image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def clip_encode_image_local(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip local feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ last_hidden_states = self.clip_image_encoder(image).last_hidden_state
+ last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ image_embeddings = self.clip_image_encoder.visual_projection(last_hidden_states_norm)
+ else:
+ image_embeddings = self.refer_clip_proj(last_hidden_states_norm.to(dtype=self.dtype))
+ # image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def decode_latents(self, latents):
+ latents = 1 / 0.18215 * latents
+ image = self.vae.decode(latents).sample
+ image = (image / 2 + 0.5).clamp(0, 1)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
+ image = image.cpu().float().numpy()
+ return image
+
+ def prepare_extra_step_kwargs(self, generator, eta=0.0):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def prepare_latents(
+ self, batch_size, num_channels_latents,
+ height, width, generator, latents=None):
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ if isinstance(generator, list):
+ shape = (1,) + shape[1:]
+ latents = [
+ torch.randn(shape, generator=generator[i], dtype=self.dtype)
+ for i in range(batch_size)
+ ]
+ latents = torch.cat(latents, dim=0).to(self.device)
+ else:
+ latents = torch.randn(shape, generator=generator, device=self.device, dtype=self.dtype)
+ else:
+ if latents.shape != shape:
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
+ latents = latents.to(device=self.device, dtype=self.dtype)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.noise_scheduler.init_noise_sigma
+ return latents
+
+ def forward_train(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ bsz = image.shape[0]
+ text = inputs['input_text']
+ z_text = self.text_encode(text)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+ # conditioning pixel value
+ # TODO: @tan, change cond_imgs in dataloader to pose or other conditions.
+ # WT: controlnet_image should be a list of multiple condition ([pose, ref_image])
+ controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, z_text,
+ controlnet_cond=controlnet_image, return_dict=False)
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=z_text,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def forward_train_multicontrol(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ ref_image = inputs['reference_img']
+ bsz = image.shape[0]
+
+ if self.args.ref_null_caption:
+ text = inputs['input_text']
+ if random.random() < self.args.drop_text: # drop text w.r.t the prob
+ text = ["" for i in text]
+ z_text = self.text_encode(text)
+
+ # text SD input --> reference image input (clip global embedding)
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image).to(dtype=self.dtype)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image).to(dtype=self.dtype)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+
+ # TODO: @tan, change cond_imgs in dataloadser to pose or other conditions.
+ # controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"]) # controlnet path input
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"]
+ controlnet_image = [inputs["cond_imgs"], reference_latents_controlnet] # [pose image, ref image]
+
+ # controlnet get the input of (a. ref image clip embedding; b. pose cond image)
+ if self.args.ref_null_caption:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, z_text], # reference controlnet path use null caption
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, refer_latents], # both controlnet path use the refer latents
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=refer_latents, # refer latents
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def prepare_image(
+ self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance
+ ):
+ if not isinstance(image, torch.Tensor):
+ if isinstance(image, PIL.Image.Image):
+ image = [image]
+
+ if isinstance(image[0], PIL.Image.Image):
+ images = []
+
+ for image_ in image:
+ image_ = image_.convert("RGB")
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
+ image_ = np.array(image_)
+ image_ = image_[None, :]
+ images.append(image_)
+
+ image = images
+
+ image = np.concatenate(image, axis=0)
+ image = np.array(image).astype(np.float32) / 255.0
+ image = image.transpose(0, 3, 1, 2)
+ image = torch.from_numpy(image)
+ elif isinstance(image[0], torch.Tensor):
+ image = torch.cat(image, dim=0)
+
+ image_batch_size = image.shape[0]
+
+ if image_batch_size == 1:
+ repeat_by = batch_size
+ else:
+ # image batch size is the same as prompt batch size
+ repeat_by = num_images_per_prompt
+
+ image = image.repeat_interleave(repeat_by, dim=0)
+
+ image = image.to(device=device, dtype=dtype)
+
+ if do_classifier_free_guidance:
+ image = torch.cat([image] * 2)
+
+ return image
+
+ @torch.no_grad()
+ def forward_sample(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+
+ # Encode input prompt
+ text = inputs['input_text']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ image = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ controlnet_cond=image,
+ conditioning_scale=controlnet_conditioning_scale,
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ @torch.no_grad()
+ def forward_sample_multicontrol(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+ ref_image = inputs['reference_img']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+
+ if self.args.ref_null_caption: # test must use null caption
+ text = inputs['input_text']
+ text = ["" for i in text]
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ controlnet_conditioning_scale_cond = self.controlnet_conditioning_scale_cond
+ controlnet_conditioning_scale_ref = self.controlnet_conditioning_scale_ref
+ image_pose = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare ref image
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"])
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs['reference_img_controlnet'].to(dtype=self.dtype)
+
+ reference_latents_controlnet = self.prepare_image(
+ image=reference_latents_controlnet,
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ if self.args.ref_null_caption: # null caption input for ref controlnet path
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, text_embeddings],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, refer_latents],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or (
+ (i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+
+ @torch.no_grad()
+ def forward_enc_dec(self, inputs, outputs):
+ image = inputs['label_imgs']
+ latent = self.image_encoder(image)
+ gen_img = self.image_decoder(latent)
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ def progress_bar(self, iterable=None, total=None):
+ if not hasattr(self, "_progress_bar_config"):
+ self._progress_bar_config = {}
+ elif not isinstance(self._progress_bar_config, dict):
+ raise ValueError(
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
+ )
+
+ if iterable is not None:
+ return tqdm(iterable, **self._progress_bar_config)
+ elif total is not None:
+ return tqdm(total=total, **self._progress_bar_config)
+ else:
+ raise ValueError("Either `total` or `iterable` has to be defined.")
+
+ def set_progress_bar_config(self, **kwargs):
+ self._progress_bar_config = kwargs
+
+
+def inner_collect_fn(args, inputs, outputs, log_dir, global_step, eval_save_filename='eval_visu'):
+ visu_save = getattr(args, 'visu_save', False)
+
+ rank = get_rank()
+ if rank == -1:
+ splice = ''
+ else:
+ splice = '_' + str(rank)
+ if global_step <= 0:
+ eval_log_dir = os.path.join(log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(log_dir, 'eval_step_%d' % (global_step))
+ ensure_dirname(eval_log_dir)
+
+ if not visu_save: # for every different combination, we build a new dir to save
+ gt_save_path = os.path.join(eval_log_dir, 'gt')
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir, f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir, 'cond')
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir, 'ref')
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir, 'ref_control')
+ ensure_dirname(ref_control_save_path)
+
+ if rank in [-1, 0]:
+ logger.warning(eval_log_dir)
+
+ # Save Model Setting
+ type_output = [int, float, str, bool, tuple, dict, type(None), ]
+ setting_output = {item: getattr(args, item) for item in dir(args) if
+ type(getattr(args, item)) in type_output and not item.startswith('__')}
+ data2file(setting_output, os.path.join(eval_log_dir, 'Model_Setting.json'))
+
+ dl = {**inputs, **{k: v for k, v in outputs.items() if k.split('_')[0] == 'logits'}}
+ ## WT DEBUG
+ # print('just for debug')
+ # if 'cond_img_pose' in dl:
+ # del dl['cond_img_pose']
+ # del dl['cond_img_attr']
+ ld = dl2ld(dl)
+
+ l = ld[0]['logits_imgs'].shape[0]
+
+ for _, sample in enumerate(ld):
+
+ if visu_save:
+ save_filename = sample['save_filename']
+ eval_log_dir_filename = os.path.join(eval_log_dir, save_filename)
+
+ gt_save_path = os.path.join(eval_log_dir_filename, 'gt')
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir_filename,
+ f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir_filename, 'cond')
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir_filename, 'ref')
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir_filename, 'ref_control')
+ ensure_dirname(ref_control_save_path)
+
+
+ _name = 'nuwa'
+ if 'input_text' in sample:
+ _name = sample['input_text'][:200]
+ if 'img_key' in sample:
+ _name = sample['img_key']
+ char_remov = [os.sep, '.', '/']
+ for c in char_remov:
+ _name = _name.replace(c, '')
+ prefix = "_".join(_name.split(" "))
+ # prefix += splice
+ # postfix = '_' + str(round(time.time() * 10))
+ postfix = ''
+
+ try:
+ ref_img_size = sample['reference_img_size']
+ except:
+ ref_img_size = None
+
+ if 'label_imgs' in sample:
+ image = sample['label_imgs']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(gt_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'logits_imgs' in sample:
+ image = tensor2pil(sample['logits_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(pred_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'cond_imgs' in sample: # pose
+ image = tensor2pil(sample['cond_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(cond_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'reference_img' in sample:
+ image = sample['reference_img']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'reference_img_controlnet' in sample:
+ image = sample['reference_img_controlnet']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_control_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ return gt_save_path, pred_save_path
+
+def tensor2pil(images, resize_img=False, img_target_size=None):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image.squeeze(), mode="L").resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
+ else:
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image).resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net_lora.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net_lora.py
new file mode 100644
index 0000000000000000000000000000000000000000..0fad83de3ea6bea6658ffde4a098c71b0f597071
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/net_lora.py
@@ -0,0 +1,1088 @@
+import torch
+from utils.dist import synchronize, get_rank
+
+from config import *
+from typing import Callable, List, Optional, Union
+
+import inspect
+from typing import Callable, List, Optional, Union
+
+import torch
+import random
+from packaging import version
+from transformers import CLIPTokenizer, CLIPVisionModelWithProjection, CLIPImageProcessor, CLIPTextModel
+from tqdm.auto import tqdm
+
+from diffusers.configuration_utils import FrozenDict
+from diffusers.models import AutoencoderKL
+from diffusers.schedulers import DDIMScheduler, PNDMScheduler, DDPMScheduler, UniPCMultistepScheduler
+from diffusers.models.cross_attention import LoRACrossAttnProcessor
+# from diffusers.loaders import AttnProcsLayers
+
+from diffusers.utils import deprecate, PIL_INTERPOLATION
+from diffusers.utils.import_utils import is_xformers_available
+
+# from diffusers.models import UNet2DConditionModel
+from .unet_2d_condition import UNet2DConditionModel
+import PIL.Image
+from .controlnet import ControlNetModel, MultiControlNetModel_MultiHiddenStates
+from utils.wutils_ldm import file2data, adaptively_load_state_dict
+
+# import sys
+# sys.path.append("...")
+# from utils.wutils_ldm import file2data, adaptively_load_state_dict
+
+
+class AttnProcsLayers(torch.nn.Module):
+ def __init__(self, state_dict):
+ super().__init__()
+ self.layers = torch.nn.ModuleList(state_dict.values())
+ # self.mapping = {k: v for k, v in enumerate(state_dict.keys())}
+ # self.rev_mapping = {v: k for k, v in enumerate(state_dict.keys())}
+
+ # # we add a hook to state_dict() and load_state_dict() so that the
+ # # naming fits with `unet.attn_processors`
+ # def map_to(module, state_dict, *args, **kwargs):
+ # new_state_dict = {}
+ # for key, value in state_dict.items():
+ # if 'processors' in key:
+ # try:
+ # num = int(key.split(".")[1]) # 0 is always "layers"
+ # except:
+ # print(key)
+ # new_key = key.replace(f"layers.{num}", module.mapping[num])
+ # new_state_dict[new_key] = value
+ # else:
+ # new_state_dict[key] = value
+ #
+ # return new_state_dict
+ #
+ # def map_from(module, state_dict, *args, **kwargs):
+ # all_keys = list(state_dict.keys())
+ # for key in all_keys:
+ # replace_key = key.split(".processor")[0] + ".processor"
+ # new_key = key.replace(replace_key, f"layers.{module.rev_mapping[replace_key]}")
+ # state_dict[new_key] = state_dict[key]
+ # del state_dict[key]
+ #
+ # self._register_state_dict_hook(map_to)
+ # self._register_load_state_dict_pre_hook(map_from, with_module=True)
+
+
+class Net(nn.Module):
+ def __init__(
+ self, args
+ ):
+ super().__init__()
+ self.args = args
+
+ tr_noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ if self.args.eval_scheduler == "ddpm":
+ noise_scheduler = DDPMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ elif self.args.eval_scheduler == "ddim":
+ noise_scheduler = DDIMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ else:
+ noise_scheduler = PNDMScheduler.from_pretrained(
+ args.pretrained_model_path, subfolder="scheduler")
+ # tokenizer = CLIPTokenizer.from_pretrained(
+ # args.pretrained_model_path, subfolder="tokenizer")
+ feature_extractor = CLIPImageProcessor.from_pretrained(args.pretrained_model_path, subfolder="feature_extractor")
+ print(f"Loading pre-trained image_encoder from {args.pretrained_model_path}/image_encoder")
+ clip_image_encoder = CLIPVisionModelWithProjection.from_pretrained(args.pretrained_model_path, subfolder="image_encoder")
+ print(f"Loading pre-trained vae from {args.pretrained_model_path}/vae")
+ vae = AutoencoderKL.from_pretrained(
+ args.pretrained_model_path, subfolder="vae")
+ print(f"Loading pre-trained unet from {self.args.pretrained_model_path}/unet")
+ unet = UNet2DConditionModel.from_pretrained(
+ self.args.pretrained_model_path, subfolder="unet")
+ # if self.args.stage1_pretrain_path is not None:
+ # pretrain_model_state = file2data(self.args.stage1_pretrain_path, map_location='cpu')
+ # adaptively_load_state_dict(unet, pretrain_model_state['module'])
+
+ if hasattr(noise_scheduler.config, "steps_offset") and noise_scheduler.config.steps_offset != 1:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} is outdated. `steps_offset`"
+ f" should be set to 1 instead of {noise_scheduler.config.steps_offset}. Please make sure "
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
+ " file"
+ )
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.noise_scheduler.config)
+ new_config["steps_offset"] = 1
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ if hasattr(noise_scheduler.config, "clip_sample") and noise_scheduler.config.clip_sample is True:
+ deprecation_message = (
+ f"The configuration file of this scheduler: {noise_scheduler} has not set the configuration `clip_sample`."
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
+ )
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(noise_scheduler.config)
+ new_config["clip_sample"] = False
+ noise_scheduler._internal_dict = FrozenDict(new_config)
+
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_diffusers_version") and version.parse(
+ version.parse(unet.config._diffusers_version).base_version
+ ) < version.parse("0.9.0.dev0")
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
+ deprecation_message = (
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
+ " 64 which seems highly unlikely. If your checkpoint is a fine-tuned version of any of the"
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
+ " the `unet/config.json` file"
+ )
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
+ new_config = dict(self.unet.config)
+ new_config["sample_size"] = 64
+ unet._internal_dict = FrozenDict(new_config)
+
+ if self.args.enable_xformers_memory_efficient_attention:
+ if is_xformers_available():
+ unet.enable_xformers_memory_efficient_attention()
+ else:
+ print("xformers is not available, therefore not enabled")
+
+
+ # WT: initialize controlnet from the pretrained image variation SD model
+ controlnet_pose = ControlNetModel.from_unet(unet=unet, args=self.args)
+ if args.ref_null_caption:
+ tokenizer = CLIPTokenizer.from_pretrained(self.args.sd15_path, subfolder="tokenizer")
+ self.tokenizer = tokenizer
+ print(f"Loading pre-trained text_encoder from {self.args.sd15_path}/text_encoder")
+ text_encoder = CLIPTextModel.from_pretrained(self.args.sd15_path + "/text_encoder")
+ self.text_encoder = text_encoder
+ unet_sd15 = UNet2DConditionModel.from_pretrained(self.args.sd15_path, subfolder="unet")
+ controlnet_background = ControlNetModel.from_unet(unet=unet_sd15, args=self.args, use_sd_vae=True) # initialize ref controlnet path from the SD pretrained model
+ del unet_sd15
+ else: # initialize controlnet from the variation SD
+ controlnet_background = ControlNetModel.from_unet(unet=unet, args=self.args, use_sd_vae=True)
+
+ if self.args.gradient_checkpointing:
+ controlnet_pose.enable_gradient_checkpointing()
+ controlnet_background.enable_gradient_checkpointing()
+ controlnet_unit = MultiControlNetModel_MultiHiddenStates([controlnet_pose, controlnet_background])
+
+ self.tr_noise_scheduler = tr_noise_scheduler
+ self.noise_scheduler = noise_scheduler
+ self.vae = vae
+ self.unet = unet
+ self.controlnet = controlnet_unit
+ self.feature_extractor = feature_extractor
+ self.clip_image_encoder = clip_image_encoder
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
+
+ self.drop_text_prob = args.drop_text
+ self.device = torch.device('cpu')
+ self.dtype = torch.float32
+
+ self.scale_factor = self.args.scale_factor
+ self.guidance_scale = self.args.guidance_scale
+ self.controlnet_conditioning_scale = getattr(self.args, "controlnet_conditioning_scale", 1.0)
+ self.controlnet_conditioning_scale_cond = getattr(self.args, "controlnet_conditioning_scale_cond", 1.0)
+ self.controlnet_conditioning_scale_ref = getattr(self.args, "controlnet_conditioning_scale_ref", 1.0)
+
+ if getattr(self.args, 'combine_clip_local', None) and not getattr(self.args, 'refer_clip_proj', None): # not use clip pretrained visual projection (but initialize from it)
+ self.refer_clip_proj = torch.nn.Linear(clip_image_encoder.visual_projection.in_features, clip_image_encoder.visual_projection.out_features, bias=False)
+ self.refer_clip_proj.load_state_dict(clip_image_encoder.visual_projection.state_dict())
+ self.refer_clip_proj.requires_grad_(True)
+
+ # for lora, load model here
+ if args.pretrained_model_lora is not None:
+ checkpoint = file2data(args.pretrained_model_lora, map_location='cpu')
+ adaptively_load_state_dict(self, checkpoint['module'])
+
+
+ # now we will add new LoRA weights to the attention layers
+ # It's important to realize here how many attention weights will be added and of which sizes
+ # The sizes of the attention layers consist only of two different variables:
+ # 1) - the "hidden_size", which is increased according to `unet.config.block_out_channels`.
+ # 2) - the "cross attention size", which is set to `unet.config.cross_attention_dim`.
+
+ # Let's first see how many attention processors we will have to set.
+ # For Stable Diffusion, it should be equal to:
+ # - down blocks (2x attention layers) * (2x transformer layers) * (3x down blocks) = 12
+ # - mid blocks (2x attention layers) * (1x transformer layers) * (1x mid blocks) = 2
+ # - up blocks (2x attention layers) * (3x transformer layers) * (3x down blocks) = 18
+ # => 32 layers
+
+ # Set correct lora layers
+ lora_attn_procs = {}
+ for name in self.unet.attn_processors.keys():
+ cross_attention_dim = None if name.endswith("attn1.processor") else self.unet.config.cross_attention_dim
+ if name.startswith("mid_block"):
+ hidden_size = self.unet.config.block_out_channels[-1]
+ elif name.startswith("up_blocks"):
+ block_id = int(name[len("up_blocks.")])
+ hidden_size = list(reversed(self.unet.config.block_out_channels))[block_id]
+ elif name.startswith("down_blocks"):
+ block_id = int(name[len("down_blocks.")])
+ hidden_size = self.unet.config.block_out_channels[block_id]
+
+ lora_attn_procs[name] = LoRACrossAttnProcessor(
+ hidden_size=hidden_size, cross_attention_dim=cross_attention_dim
+ )
+
+ self.unet.set_attn_processor(lora_attn_procs)
+ lora_layers = AttnProcsLayers(self.unet.attn_processors)
+ self.lora_layers = lora_layers
+
+ def enable_vae_slicing(self):
+ self.vae.enable_slicing()
+
+ def disable_vae_slicing(self):
+ self.vae.disable_slicing()
+
+ def init_ddpm(self):
+ self.freeze_pretrained_part_in_ddpm()
+ return
+
+ def freeze_pretrained_part_in_ddpm(self):
+
+ # # for lora, just freeze the unet
+ # self.unet.requires_grad_(False)
+
+ ### for stage-3 ft on specific image
+ if self.args.freeze_pose:
+ # for pose controlnet (net 0)
+ for param_name, param in self.controlnet.named_parameters():
+ if 'nets.0' in param_name:
+ param.requires_grad_(False)
+
+ if self.args.freeze_background:
+ for param_name, param in self.controlnet.named_parameters():
+ if 'nets.1' in param_name:
+ param.requires_grad_(False)
+
+ self.vae.eval()
+ self.clip_image_encoder.eval()
+ self.vae.requires_grad_(False)
+ self.clip_image_encoder.requires_grad_(False)
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.eval()
+ self.text_encoder.requires_grad_(False)
+
+
+ def to(self, *args, **kwargs):
+ model_converted = super().to(*args, **kwargs)
+ self.device = next(self.parameters()).device
+ self.dtype = next(self.unet.parameters()).dtype
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return model_converted
+
+ def half(self, *args, **kwargs):
+ super().half(*args, **kwargs)
+ self.dtype = torch.float16
+ self.clip_image_encoder.float()
+ if hasattr(self, 'text_encoder'):
+ self.text_encoder.float()
+ # self.refer_clip_proj.float()
+ # self.vae.float()
+ return
+
+ def train(self, *args):
+ super().train(*args)
+ self.freeze_pretrained_part_in_ddpm()
+
+ def image_encoder(self, image):
+ b, c, h, w = image.size()
+ latents = self.vae.encode(image).latent_dist.sample()
+ latents = latents * self.scale_factor
+ latents = latents.to(dtype=self.dtype)
+ return latents
+
+ def image_decoder(self, latents):
+ latents = 1/self.scale_factor * latents
+ dec = self.vae.decode(latents).sample
+ image = (dec / 2 + 0.5).clamp(0, 1)
+ return image
+
+ def forward(self, inputs):
+ outputs = dict()
+
+ generator = torch.Generator(device=self.device)
+ generator.manual_seed(self.args.seed)
+ inputs['generator'] = generator
+
+ if self.training:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_train(inputs, outputs)
+ outputs = self.forward_train_multicontrol(inputs, outputs)
+ elif 'enc_dec_only' in inputs and inputs['enc_dec_only']:
+ outputs = self.forward_enc_dec(inputs, outputs)
+ else:
+ assert self.args.stepwise_sample_depth <= 0
+ # outputs = self.forward_sample(inputs, outputs)
+ outputs = self.forward_sample_multicontrol(inputs, outputs)
+ removed_key = inputs.pop("generator", None)
+ return outputs
+
+ def text_encode(
+ self, prompt, num_images_per_prompt=1,
+ do_classifier_free_guidance=False, negative_prompt=None):
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer.model_max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ untruncated_ids = self.tokenizer(prompt, padding="longest", return_tensors="pt").input_ids
+
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(text_input_ids, untruncated_ids):
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
+ logger.warning(
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = text_inputs.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ text_embeddings = self.text_encoder(
+ text_input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ text_embeddings = text_embeddings[0]
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = text_embeddings.shape
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ # get unconditional embeddings for classifier free guidance
+ if do_classifier_free_guidance:
+ uncond_tokens: List[str]
+ if negative_prompt is None:
+ uncond_tokens = [""] * batch_size
+ elif type(prompt) is not type(negative_prompt):
+ raise TypeError(
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
+ f" {type(prompt)}."
+ )
+ elif isinstance(negative_prompt, str):
+ uncond_tokens = [negative_prompt]
+ elif batch_size != len(negative_prompt):
+ raise ValueError(
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
+ " the batch size of `prompt`."
+ )
+ else:
+ uncond_tokens = negative_prompt
+
+ max_length = text_input_ids.shape[-1]
+ uncond_input = self.tokenizer(
+ uncond_tokens,
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ return_tensors="pt",
+ )
+
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
+ attention_mask = uncond_input.attention_mask.to(self.device)
+ else:
+ attention_mask = None
+
+ uncond_embeddings = self.text_encoder(
+ uncond_input.input_ids.to(self.device),
+ attention_mask=attention_mask,
+ )
+ uncond_embeddings = uncond_embeddings[0]
+
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
+ seq_len = uncond_embeddings.shape[1]
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ text_embeddings = torch.cat(
+ [uncond_embeddings, text_embeddings]
+ )
+ text_embeddings = text_embeddings.to(dtype=self.dtype)
+ return text_embeddings
+
+
+ def clip_encode_image_global(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip global feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ image_embeddings = self.clip_image_encoder(image).image_embeds
+ image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def clip_encode_image_local(self, image, num_images_per_prompt=1, do_classifier_free_guidance=False): # clip local feature
+ dtype = next(self.clip_image_encoder.parameters()).dtype
+
+ if not isinstance(image, torch.Tensor):
+ image = self.feature_extractor(images=image, return_tensors="pt").pixel_values
+
+ image = image.to(device=self.device, dtype=dtype)
+ last_hidden_states = self.clip_image_encoder(image).last_hidden_state
+ last_hidden_states_norm = self.clip_image_encoder.vision_model.post_layernorm(last_hidden_states)
+
+ if self.args.refer_clip_proj: # directly use clip pretrained projection layer
+ image_embeddings = self.clip_image_encoder.visual_projection(last_hidden_states_norm)
+ else:
+ image_embeddings = self.refer_clip_proj(last_hidden_states_norm.to(dtype=self.dtype))
+ # image_embeddings = image_embeddings.unsqueeze(1)
+
+ # duplicate image embeddings for each generation per prompt, using mps friendly method
+ bs_embed, seq_len, _ = image_embeddings.shape
+ image_embeddings = image_embeddings.repeat(1, num_images_per_prompt, 1)
+ image_embeddings = image_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
+
+ if do_classifier_free_guidance:
+ negative_prompt_embeds = torch.zeros_like(image_embeddings)
+
+ # For classifier free guidance, we need to do two forward passes.
+ # Here we concatenate the unconditional and text embeddings into a single batch
+ # to avoid doing two forward passes
+ image_embeddings = torch.cat([negative_prompt_embeds, image_embeddings])
+
+ return image_embeddings.to(dtype=self.dtype)
+
+
+ def decode_latents(self, latents):
+ latents = 1 / 0.18215 * latents
+ image = self.vae.decode(latents).sample
+ image = (image / 2 + 0.5).clamp(0, 1)
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
+ image = image.cpu().float().numpy()
+ return image
+
+ def prepare_extra_step_kwargs(self, generator, eta=0.0):
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
+ # and should be between [0, 1]
+
+ accepts_eta = "eta" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ extra_step_kwargs = {}
+ if accepts_eta:
+ extra_step_kwargs["eta"] = eta
+
+ # check if the scheduler accepts generator
+ accepts_generator = "generator" in set(inspect.signature(self.noise_scheduler.step).parameters.keys())
+ if accepts_generator:
+ extra_step_kwargs["generator"] = generator
+ return extra_step_kwargs
+
+ def prepare_latents(
+ self, batch_size, num_channels_latents,
+ height, width, generator, latents=None):
+ shape = (batch_size, num_channels_latents, height // self.vae_scale_factor, width // self.vae_scale_factor)
+ if isinstance(generator, list) and len(generator) != batch_size:
+ raise ValueError(
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
+ )
+
+ if latents is None:
+ if isinstance(generator, list):
+ shape = (1,) + shape[1:]
+ latents = [
+ torch.randn(shape, generator=generator[i], dtype=self.dtype)
+ for i in range(batch_size)
+ ]
+ latents = torch.cat(latents, dim=0).to(self.device)
+ else:
+ latents = torch.randn(shape, generator=generator, device=self.device, dtype=self.dtype)
+ else:
+ if latents.shape != shape:
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {shape}")
+ latents = latents.to(device=self.device, dtype=self.dtype)
+
+ # scale the initial noise by the standard deviation required by the scheduler
+ latents = latents * self.noise_scheduler.init_noise_sigma
+ return latents
+
+ def forward_train(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ bsz = image.shape[0]
+ text = inputs['input_text']
+ z_text = self.text_encode(text)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+ # conditioning pixel value
+ # TODO: @tan, change cond_imgs in dataloader to pose or other conditions.
+ # WT: controlnet_image should be a list of multiple condition ([pose, ref_image])
+ controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, z_text,
+ controlnet_cond=controlnet_image, return_dict=False)
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=z_text,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def forward_train_multicontrol(self, inputs, outputs):
+ loss_target = self.args.loss_target
+ image = inputs['label_imgs'] # (B, C, H, W)
+ ref_image = inputs['reference_img']
+ bsz = image.shape[0]
+
+ if self.args.ref_null_caption:
+ text = inputs['input_text']
+ if random.random() < self.args.drop_text: # drop text w.r.t the prob
+ text = ["" for i in text]
+ z_text = self.text_encode(text)
+
+ # text SD input --> reference image input (clip global embedding)
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image).to(dtype=self.dtype)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image).to(dtype=self.dtype)
+
+ latents = self.image_encoder(image)
+ latents = latents.to(dtype=self.dtype)
+ noise = torch.randn_like(latents)
+
+ timesteps = torch.randint(
+ 0, self.tr_noise_scheduler.num_train_timesteps,
+ (bsz,), device=latents.device)
+ timesteps = timesteps.long()
+ if self.args.debug_seed:
+ print(f"rank {get_rank()}: noise 0 mean {torch.sum(noise[0])}, noise 1 mean {torch.sum(noise[1])}")
+ print(f"timestep 0 {timesteps[0]}, timestep 1 {timesteps[1]}")
+ noisy_latents = self.tr_noise_scheduler.add_noise(latents, noise, timesteps)
+
+
+ # TODO: @tan, change cond_imgs in dataloadser to pose or other conditions.
+ # controlnet_image = inputs["cond_imgs"].to(dtype=self.dtype)
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"]) # controlnet path input
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs["reference_img_controlnet"]
+ controlnet_image = [inputs["cond_imgs"], reference_latents_controlnet] # [pose image, ref image]
+
+ # controlnet get the input of (a. ref image clip embedding; b. pose cond image)
+ if self.args.ref_null_caption:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, z_text], # reference controlnet path use null caption
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ noisy_latents, timesteps, [refer_latents, refer_latents], # both controlnet path use the refer latents
+ controlnet_cond=controlnet_image, conditioning_scale=[1.0,1.0], return_dict=False)
+
+
+ # Predict the noise residual
+ model_pred = self.unet(
+ noisy_latents,
+ timesteps,
+ encoder_hidden_states=refer_latents, # refer latents
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample,
+ ).sample
+
+ if loss_target == "x0":
+ target = latents
+ x0_pred = self.tr_noise_scheduler.remove_noise(noisy_latents, model_pred, timesteps)
+ loss = F.mse_loss(x0_pred.float(), target.float(), reduction="mean")
+ else:
+ if self.tr_noise_scheduler.prediction_type == "epsilon":
+ target = noise
+ elif self.tr_noise_scheduler.prediction_type == "v_prediction":
+ target = self.tr_noise_scheduler.get_velocity(latents, noise, timesteps)
+ else:
+ raise ValueError(f"Unknown prediction type {self.tr_noise_scheduler.prediction_type}")
+ loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
+
+ outputs['loss_total'] = loss
+ return outputs
+
+ def prepare_image(
+ self, image, width, height, batch_size, num_images_per_prompt, device, dtype, do_classifier_free_guidance
+ ):
+ if not isinstance(image, torch.Tensor):
+ if isinstance(image, PIL.Image.Image):
+ image = [image]
+
+ if isinstance(image[0], PIL.Image.Image):
+ images = []
+
+ for image_ in image:
+ image_ = image_.convert("RGB")
+ image_ = image_.resize((width, height), resample=PIL_INTERPOLATION["lanczos"])
+ image_ = np.array(image_)
+ image_ = image_[None, :]
+ images.append(image_)
+
+ image = images
+
+ image = np.concatenate(image, axis=0)
+ image = np.array(image).astype(np.float32) / 255.0
+ image = image.transpose(0, 3, 1, 2)
+ image = torch.from_numpy(image)
+ elif isinstance(image[0], torch.Tensor):
+ image = torch.cat(image, dim=0)
+
+ image_batch_size = image.shape[0]
+
+ if image_batch_size == 1:
+ repeat_by = batch_size
+ else:
+ # image batch size is the same as prompt batch size
+ repeat_by = num_images_per_prompt
+
+ image = image.repeat_interleave(repeat_by, dim=0)
+
+ image = image.to(device=device, dtype=dtype)
+
+ if do_classifier_free_guidance:
+ image = torch.cat([image] * 2)
+
+ return image
+
+ @torch.no_grad()
+ def forward_sample(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+
+ # Encode input prompt
+ text = inputs['input_text']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt, do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ image = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ controlnet_cond=image,
+ conditioning_scale=controlnet_conditioning_scale,
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=text_embeddings,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ @torch.no_grad()
+ def forward_sample_multicontrol(self, inputs, outputs):
+ gt_image = inputs['label_imgs']
+ b, c, h, w = gt_image.size()
+ ref_image = inputs['reference_img']
+ do_classifier_free_guidance = self.guidance_scale > 1.0
+ if self.args.combine_clip_local:
+ refer_latents = self.clip_encode_image_local(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+ else:
+ refer_latents = self.clip_encode_image_global(ref_image, self.args.num_inf_images_per_prompt, do_classifier_free_guidance)
+
+ if self.args.ref_null_caption: # test must use null caption
+ text = inputs['input_text']
+ text = ["" for i in text]
+ text_embeddings = self.text_encode(
+ text, num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ negative_prompt=None)
+
+
+ # Prepare conditioning image
+ controlnet_conditioning_scale = self.controlnet_conditioning_scale
+ controlnet_conditioning_scale_cond = self.controlnet_conditioning_scale_cond
+ controlnet_conditioning_scale_ref = self.controlnet_conditioning_scale_ref
+ image_pose = self.prepare_image(
+ image=inputs['cond_imgs'].to(dtype=self.dtype),
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+ # Prepare ref image
+ if self.args.refer_sdvae:
+ reference_latents_controlnet = self.image_encoder(inputs["reference_img_controlnet"])
+ reference_latents_controlnet = reference_latents_controlnet.to(dtype=self.dtype)
+ else:
+ reference_latents_controlnet = inputs['reference_img_controlnet'].to(dtype=self.dtype)
+
+ reference_latents_controlnet = self.prepare_image(
+ image=reference_latents_controlnet,
+ width=w,
+ height=h,
+ batch_size=b * self.args.num_inf_images_per_prompt,
+ num_images_per_prompt=self.args.num_inf_images_per_prompt,
+ device=self.device,
+ dtype=self.controlnet.dtype,
+ do_classifier_free_guidance=do_classifier_free_guidance,
+ )
+
+
+ # Prepare timesteps
+ self.noise_scheduler.set_timesteps(
+ self.args.num_inference_steps, device=self.device)
+ timesteps = self.noise_scheduler.timesteps
+
+ # 6. Prepare latent variables
+ num_channels_latents = self.unet.in_channels
+ gen_height = h
+ gen_width = w
+ generator = inputs['generator']
+
+ latents = self.prepare_latents(
+ b * self.args.num_inf_images_per_prompt,
+ num_channels_latents,
+ gen_height,
+ gen_width,
+ generator,
+ latents=None,
+ )
+
+ # Prepare extra step kwargs.
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator)
+
+ # Denoising loop
+ num_warmup_steps = len(timesteps) - self.args.num_inference_steps * self.noise_scheduler.order
+ with self.progress_bar(total=self.args.num_inference_steps) as progress_bar:
+ for i, t in enumerate(timesteps):
+ # expand the latents if we are doing classifier free guidance
+ latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
+ latent_model_input = self.noise_scheduler.scale_model_input(latent_model_input, t)
+
+ # controlnet(s) inference
+ if self.args.ref_null_caption: # null caption input for ref controlnet path
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, text_embeddings],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+ else:
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=[refer_latents, refer_latents],
+ controlnet_cond=[image_pose, reference_latents_controlnet],
+ conditioning_scale=[controlnet_conditioning_scale_cond, controlnet_conditioning_scale_ref],
+ return_dict=False,
+ )
+
+ # predict the noise residual
+ noise_pred = self.unet(
+ latent_model_input,
+ t,
+ encoder_hidden_states=refer_latents,
+ down_block_additional_residuals=down_block_res_samples,
+ mid_block_additional_residual=mid_block_res_sample).sample.to(dtype=self.dtype)
+
+ # perform guidance
+ if do_classifier_free_guidance:
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
+ noise_pred = noise_pred_uncond + self.guidance_scale * (noise_pred_text - noise_pred_uncond)
+
+ # compute the previous noisy sample x_t -> x_t-1
+ latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step_kwargs).prev_sample
+
+ if i == len(timesteps) - 1 or (
+ (i + 1) > num_warmup_steps and (i + 1) % self.noise_scheduler.order == 0):
+ progress_bar.update()
+
+ # Post-processing
+ gen_img = self.image_decoder(latents)
+
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+
+ @torch.no_grad()
+ def forward_enc_dec(self, inputs, outputs):
+ image = inputs['label_imgs']
+ latent = self.image_encoder(image)
+ gen_img = self.image_decoder(latent)
+ outputs['logits_imgs'] = gen_img
+ return outputs
+
+ def progress_bar(self, iterable=None, total=None):
+ if not hasattr(self, "_progress_bar_config"):
+ self._progress_bar_config = {}
+ elif not isinstance(self._progress_bar_config, dict):
+ raise ValueError(
+ f"`self._progress_bar_config` should be of type `dict`, but is {type(self._progress_bar_config)}."
+ )
+
+ if iterable is not None:
+ return tqdm(iterable, **self._progress_bar_config)
+ elif total is not None:
+ return tqdm(total=total, **self._progress_bar_config)
+ else:
+ raise ValueError("Either `total` or `iterable` has to be defined.")
+
+ def set_progress_bar_config(self, **kwargs):
+ self._progress_bar_config = kwargs
+
+
+def inner_collect_fn(args, inputs, outputs, log_dir, global_step, eval_save_filename='eval_visu'):
+ rank = get_rank()
+ if rank == -1:
+ splice = ''
+ else:
+ splice = '_' + str(rank)
+ if global_step <= 0:
+ eval_log_dir = os.path.join(log_dir, eval_save_filename)
+ else:
+ eval_log_dir = os.path.join(log_dir, 'eval_step_%d' % (global_step))
+ ensure_dirname(eval_log_dir)
+
+ gt_save_path = os.path.join(eval_log_dir, 'gt')
+ ensure_dirname(gt_save_path)
+ pred_save_path = os.path.join(eval_log_dir, f'pred_gs{args.guidance_scale}_scale-cond{args.controlnet_conditioning_scale_cond}-ref{args.controlnet_conditioning_scale_ref}')
+ ensure_dirname(pred_save_path)
+ cond_save_path = os.path.join(eval_log_dir, 'cond')
+ ensure_dirname(cond_save_path)
+ ref_save_path = os.path.join(eval_log_dir, 'ref')
+ ensure_dirname(ref_save_path)
+ ref_control_save_path = os.path.join(eval_log_dir, 'ref_control')
+ ensure_dirname(ref_control_save_path)
+
+ if rank in [-1, 0]:
+ logger.warning(eval_log_dir)
+
+ # Save Model Setting
+ type_output = [int, float, str, bool, tuple, dict, type(None), ]
+ setting_output = {item: getattr(args, item) for item in dir(args) if
+ type(getattr(args, item)) in type_output and not item.startswith('__')}
+ data2file(setting_output, os.path.join(eval_log_dir, 'Model_Setting.json'))
+
+ dl = {**inputs, **{k: v for k, v in outputs.items() if k.split('_')[0] == 'logits'}}
+ ## WT DEBUG
+ # print('just for debug')
+ # if 'cond_img_pose' in dl:
+ # del dl['cond_img_pose']
+ # del dl['cond_img_attr']
+ ld = dl2ld(dl)
+
+ l = ld[0]['logits_imgs'].shape[0]
+
+ for _, sample in enumerate(ld):
+ _name = 'nuwa'
+ if 'input_text' in sample:
+ _name = sample['input_text'][:200]
+ if 'img_key' in sample:
+ _name = sample['img_key']
+ char_remov = [os.sep, '.', '/']
+ for c in char_remov:
+ _name = _name.replace(c, '')
+ prefix = "_".join(_name.split(" "))
+ # prefix += splice
+ # postfix = '_' + str(round(time.time() * 10))
+ postfix = ''
+
+ try:
+ ref_img_size = sample['reference_img_size']
+ except:
+ ref_img_size = None
+
+ if 'label_imgs' in sample:
+ image = sample['label_imgs']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(gt_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'logits_imgs' in sample:
+ image = tensor2pil(sample['logits_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(pred_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'cond_imgs' in sample: # pose
+ image = tensor2pil(sample['cond_imgs'], resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(cond_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving logits_imgs: {e}')
+ if 'reference_img' in sample:
+ image = sample['reference_img']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ if 'reference_img_controlnet' in sample:
+ image = sample['reference_img_controlnet']
+ image = (image / 2 + 0.5).clamp(0, 1)
+ image = tensor2pil(image, resize_img=args.pos_resize_img, img_target_size=ref_img_size)[0]
+ try:
+ image.save(os.path.join(ref_control_save_path, prefix + postfix + '.png'))
+ except Exception as e:
+ print(f'some errors happened in saving label_imgs: {e}')
+ return gt_save_path, pred_save_path
+
+def tensor2pil(images, resize_img=False, img_target_size=None):
+ # c, h, w
+ images = images.cpu().permute(1, 2, 0).float().numpy()
+ if images.ndim == 3:
+ images = images[None, ...]
+ images = (images * 255).round().astype("uint8")
+ if images.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image.squeeze(), mode="L").resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
+ else:
+ if resize_img:
+ assert img_target_size is not None
+ img_target_size = img_target_size.squeeze()
+ pil_images = [Image.fromarray(image).resize(img_target_size) for image in images]
+ else:
+ pil_images = [Image.fromarray(image) for image in images]
+
+ return pil_images
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/tiktok_S256L16_xformers_tsv.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/tiktok_S256L16_xformers_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa97f9d5df5a20c9f11478b6f39b897a15d57195
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/tiktok_S256L16_xformers_tsv.py
@@ -0,0 +1,64 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_tsv.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/debug_output/video_sythesis/dataset"
+ debug_train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ debug_val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_TiktokDance-poses.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_TiktokDance-poses.yaml'
+ # WT: for tiktok image data dir
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/unet_2d_condition.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/unet_2d_condition.py
new file mode 100644
index 0000000000000000000000000000000000000000..b4207226d2f46c21cc85b649c91c391b0b0f2441
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/unet_2d_condition.py
@@ -0,0 +1,654 @@
+# Copyright 2023 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.utils.checkpoint
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import UNet2DConditionLoadersMixin
+from diffusers.utils import BaseOutput, logging
+from diffusers.models.cross_attention import AttnProcessor
+from diffusers.models.embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.unet_2d_blocks import (
+ CrossAttnDownBlock2D,
+ CrossAttnUpBlock2D,
+ DownBlock2D,
+ UNetMidBlock2DCrossAttn,
+ UNetMidBlock2DSimpleCrossAttn,
+ UpBlock2D,
+ get_down_block,
+ get_up_block,
+)
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class UNet2DConditionOutput(BaseOutput):
+ """
+ Args:
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
+ Hidden states conditioned on `encoder_hidden_states` input. Output of last layer of model.
+ """
+
+ sample: torch.FloatTensor
+
+
+class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
+ r"""
+ UNet2DConditionModel is a conditional 2D UNet model that takes in a noisy sample, conditional state, and a timestep
+ and returns sample shaped output.
+
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for the generic methods the library
+ implements for all the models (such as downloading or saving, etc.)
+
+ Parameters:
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
+ Height and width of input/output sample.
+ in_channels (`int`, *optional*, defaults to 4): The number of channels in the input sample.
+ out_channels (`int`, *optional*, defaults to 4): The number of channels in the output.
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
+ Whether to flip the sin to cos in the time embedding.
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
+ The tuple of downsample blocks to use.
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
+ The mid block type. Choose from `UNetMidBlock2DCrossAttn` or `UNetMidBlock2DSimpleCrossAttn`, will skip the
+ mid block layer if `None`.
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D",)`):
+ The tuple of upsample blocks to use.
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
+ Whether to include self-attention in the basic transformer blocks, see
+ [`~models.attention.BasicTransformerBlock`].
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
+ The tuple of output channels for each block.
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
+ If `None`, it will skip the normalization and activation layers in post-processing
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
+ cross_attention_dim (`int`, *optional*, defaults to 1280): The dimension of the cross attention features.
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
+ for resnet blocks, see [`~models.resnet.ResnetBlock2D`]. Choose from `default` or `scale_shift`.
+ class_embed_type (`str`, *optional*, defaults to None): The type of class embedding to use which is ultimately
+ summed with the time embeddings. Choose from `None`, `"timestep"`, `"identity"`, or `"projection"`.
+ num_class_embeds (`int`, *optional*, defaults to None):
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
+ class conditioning with `class_embed_type` equal to `None`.
+ time_embedding_type (`str`, *optional*, default to `positional`):
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
+ timestep_post_act (`str, *optional*, default to `None`):
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
+ time_cond_proj_dim (`int`, *optional*, default to `None`):
+ The dimension of `cond_proj` layer in timestep embedding.
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.
+ conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.
+ projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when
+ using the "projection" `class_embed_type`. Required when using the "projection" `class_embed_type`.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ sample_size: Optional[int] = None,
+ in_channels: int = 4,
+ out_channels: int = 4,
+ center_input_sample: bool = False,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ down_block_types: Tuple[str] = (
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "CrossAttnDownBlock2D",
+ "DownBlock2D",
+ ),
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
+ layers_per_block: int = 2,
+ downsample_padding: int = 1,
+ mid_block_scale_factor: float = 1,
+ act_fn: str = "silu",
+ norm_num_groups: Optional[int] = 32,
+ norm_eps: float = 1e-5,
+ cross_attention_dim: int = 1280,
+ attention_head_dim: Union[int, Tuple[int]] = 8,
+ dual_cross_attention: bool = False,
+ use_linear_projection: bool = False,
+ class_embed_type: Optional[str] = None,
+ num_class_embeds: Optional[int] = None,
+ upcast_attention: bool = False,
+ resnet_time_scale_shift: str = "default",
+ time_embedding_type: str = "positional",
+ timestep_post_act: Optional[str] = None,
+ time_cond_proj_dim: Optional[int] = None,
+ conv_in_kernel: int = 3,
+ conv_out_kernel: int = 3,
+ projection_class_embeddings_input_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.sample_size = sample_size
+
+ # Check inputs
+ if len(down_block_types) != len(up_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if len(block_out_channels) != len(down_block_types):
+ raise ValueError(
+ 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}."
+ )
+
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
+ )
+
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):
+ raise ValueError(
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
+ )
+
+ # input
+ conv_in_padding = (conv_in_kernel - 1) // 2
+ self.conv_in = nn.Conv2d(
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
+ )
+
+ # time
+ if time_embedding_type == "fourier":
+ time_embed_dim = block_out_channels[0] * 2
+ if time_embed_dim % 2 != 0:
+ raise ValueError(f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.")
+ self.time_proj = GaussianFourierProjection(
+ time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
+ )
+ timestep_input_dim = time_embed_dim
+ elif time_embedding_type == "positional":
+ time_embed_dim = block_out_channels[0] * 4
+
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
+ timestep_input_dim = block_out_channels[0]
+ else:
+ raise ValueError(
+ f"{time_embedding_type} does not exist. Pleaes make sure to use one of `fourier` or `positional`."
+ )
+
+ self.time_embedding = TimestepEmbedding(
+ timestep_input_dim,
+ time_embed_dim,
+ act_fn=act_fn,
+ post_act_fn=timestep_post_act,
+ cond_proj_dim=time_cond_proj_dim,
+ )
+
+ # class embedding
+ if class_embed_type is None and num_class_embeds is not None:
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
+ elif class_embed_type == "timestep":
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
+ elif class_embed_type == "identity":
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
+ elif class_embed_type == "projection":
+ if projection_class_embeddings_input_dim is None:
+ raise ValueError(
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
+ )
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
+ # 2. it projects from an arbitrary input dimension.
+ #
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
+ else:
+ self.class_embedding = None
+
+ self.down_blocks = nn.ModuleList([])
+ self.up_blocks = nn.ModuleList([])
+
+ if isinstance(only_cross_attention, bool):
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
+
+ if isinstance(attention_head_dim, int):
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+
+ down_block = get_down_block(
+ down_block_type,
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=time_embed_dim,
+ add_downsample=not is_final_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[i],
+ downsample_padding=downsample_padding,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.down_blocks.append(down_block)
+
+ # mid
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
+ self.mid_block = UNetMidBlock2DCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ upcast_attention=upcast_attention,
+ )
+ elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
+ self.mid_block = UNetMidBlock2DSimpleCrossAttn(
+ in_channels=block_out_channels[-1],
+ temb_channels=time_embed_dim,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ output_scale_factor=mid_block_scale_factor,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=attention_head_dim[-1],
+ resnet_groups=norm_num_groups,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ elif mid_block_type is None:
+ self.mid_block = None
+ else:
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
+
+ # count how many layers upsample the images
+ self.num_upsamplers = 0
+
+ # up
+ reversed_block_out_channels = list(reversed(block_out_channels))
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
+ only_cross_attention = list(reversed(only_cross_attention))
+
+ output_channel = reversed_block_out_channels[0]
+ for i, up_block_type in enumerate(up_block_types):
+ is_final_block = i == len(block_out_channels) - 1
+
+ prev_output_channel = output_channel
+ output_channel = reversed_block_out_channels[i]
+ input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
+
+ # add upsample block for all BUT final layer
+ if not is_final_block:
+ add_upsample = True
+ self.num_upsamplers += 1
+ else:
+ add_upsample = False
+
+ up_block = get_up_block(
+ up_block_type,
+ num_layers=layers_per_block + 1,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ prev_output_channel=prev_output_channel,
+ temb_channels=time_embed_dim,
+ add_upsample=add_upsample,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ cross_attention_dim=cross_attention_dim,
+ attn_num_head_channels=reversed_attention_head_dim[i],
+ dual_cross_attention=dual_cross_attention,
+ use_linear_projection=use_linear_projection,
+ only_cross_attention=only_cross_attention[i],
+ upcast_attention=upcast_attention,
+ resnet_time_scale_shift=resnet_time_scale_shift,
+ )
+ self.up_blocks.append(up_block)
+ prev_output_channel = output_channel
+
+ # out
+ if norm_num_groups is not None:
+ self.conv_norm_out = nn.GroupNorm(
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps
+ )
+ self.conv_act = nn.SiLU()
+ else:
+ self.conv_norm_out = None
+ self.conv_act = None
+
+ conv_out_padding = (conv_out_kernel - 1) // 2
+ self.conv_out = nn.Conv2d(
+ block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding
+ )
+
+ @property
+ def attn_processors(self) -> Dict[str, AttnProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttnProcessor]):
+ if hasattr(module, "set_processor"):
+ processors[f"{name}.processor"] = module.processor
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ def set_attn_processor(self, processor: Union[AttnProcessor, Dict[str, AttnProcessor]]):
+ r"""
+ Parameters:
+ `processor (`dict` of `AttnProcessor` or `AttnProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ of **all** `CrossAttention` layers.
+ In case `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainablae attention processors.:
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ def set_attention_slice(self, slice_size):
+ r"""
+ Enable sliced attention computation.
+
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
+
+ Args:
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
+ must be a multiple of `slice_size`.
+ """
+ sliceable_head_dims = []
+
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
+ if hasattr(module, "set_attention_slice"):
+ sliceable_head_dims.append(module.sliceable_head_dim)
+
+ for child in module.children():
+ fn_recursive_retrieve_slicable_dims(child)
+
+ # retrieve number of attention layers
+ for module in self.children():
+ fn_recursive_retrieve_slicable_dims(module)
+
+ num_slicable_layers = len(sliceable_head_dims)
+
+ if slice_size == "auto":
+ # half the attention head size is usually a good trade-off between
+ # speed and memory
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
+ elif slice_size == "max":
+ # make smallest slice possible
+ slice_size = num_slicable_layers * [1]
+
+ slice_size = num_slicable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
+
+ if len(slice_size) != len(sliceable_head_dims):
+ raise ValueError(
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
+ )
+
+ for i in range(len(slice_size)):
+ size = slice_size[i]
+ dim = sliceable_head_dims[i]
+ if size is not None and size > dim:
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
+
+ # Recursively walk through all the children.
+ # Any children which exposes the set_attention_slice method
+ # gets the message
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
+ if hasattr(module, "set_attention_slice"):
+ module.set_attention_slice(slice_size.pop())
+
+ for child in module.children():
+ fn_recursive_set_attention_slice(child, slice_size)
+
+ reversed_slice_size = list(reversed(slice_size))
+ for module in self.children():
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if isinstance(module, (CrossAttnDownBlock2D, DownBlock2D, CrossAttnUpBlock2D, UpBlock2D)):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ sample: torch.FloatTensor,
+ timestep: Union[torch.Tensor, float, int],
+ encoder_hidden_states: torch.Tensor,
+ class_labels: Optional[torch.Tensor] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ) -> Union[UNet2DConditionOutput, Tuple]:
+ r"""
+ Args:
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
+ cross_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor` as defined under
+ `self.processor` in
+ [diffusers.cross_attention](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/cross_attention.py).
+
+ Returns:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
+ returning a tuple, the first element is the sample tensor.
+ """
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
+ # on the fly if necessary.
+ default_overall_up_factor = 2**self.num_upsamplers
+
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
+ forward_upsample_size = False
+ upsample_size = None
+
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
+ logger.info("Forward upsample size to force interpolation output size.")
+ forward_upsample_size = True
+
+ # prepare attention_mask
+ if attention_mask is not None:
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
+ attention_mask = attention_mask.unsqueeze(1)
+
+ # 0. center input if necessary
+ if self.config.center_input_sample:
+ sample = 2 * sample - 1.0
+
+ # 1. time
+ timesteps = timestep
+ if not torch.is_tensor(timesteps):
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
+ # This would be a good case for the `match` statement (Python 3.10+)
+ is_mps = sample.device.type == "mps"
+ if isinstance(timestep, float):
+ dtype = torch.float32 if is_mps else torch.float64
+ else:
+ dtype = torch.int32 if is_mps else torch.int64
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
+ elif len(timesteps.shape) == 0:
+ timesteps = timesteps[None].to(sample.device)
+
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
+ timesteps = timesteps.expand(sample.shape[0])
+
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=self.dtype)
+
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.class_embedding is not None:
+ if class_labels is None:
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
+
+ if self.config.class_embed_type == "timestep":
+ class_labels = self.time_proj(class_labels)
+
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
+ emb = emb + class_emb
+
+ # 2. pre-process
+ sample = self.conv_in(sample)
+
+ # 3. down
+ down_block_res_samples = (sample,)
+ for downsample_block in self.down_blocks:
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
+ sample, res_samples = downsample_block(
+ hidden_states=sample,
+ temb=emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+ else:
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
+
+ down_block_res_samples += res_samples
+
+ if down_block_additional_residuals is not None:
+ new_down_block_res_samples = ()
+
+ for down_block_res_sample, down_block_additional_residual in zip(
+ down_block_res_samples, down_block_additional_residuals
+ ):
+ down_block_res_sample = down_block_res_sample + down_block_additional_residual
+ new_down_block_res_samples += (down_block_res_sample,)
+
+ down_block_res_samples = new_down_block_res_samples
+
+ # 4. mid
+ if self.mid_block is not None:
+ sample = self.mid_block(
+ sample,
+ emb,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ cross_attention_kwargs=cross_attention_kwargs,
+ )
+
+ if mid_block_additional_residual is not None:
+ sample = sample + mid_block_additional_residual
+
+ # 5. up
+ for i, upsample_block in enumerate(self.up_blocks):
+ is_final_block = i == len(self.up_blocks) - 1
+
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
+ down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
+
+ # if we have not reached the final block and need to forward the
+ # upsample size, we do it here
+ if not is_final_block and forward_upsample_size:
+ upsample_size = down_block_res_samples[-1].shape[2:]
+
+ if hasattr(upsample_block, "has_cross_attention") and upsample_block.has_cross_attention:
+ sample = upsample_block(
+ hidden_states=sample,
+ temb=emb,
+ res_hidden_states_tuple=res_samples,
+ encoder_hidden_states=encoder_hidden_states,
+ cross_attention_kwargs=cross_attention_kwargs,
+ upsample_size=upsample_size,
+ attention_mask=attention_mask,
+ )
+ else:
+ sample = upsample_block(
+ hidden_states=sample, temb=emb, res_hidden_states_tuple=res_samples, upsample_size=upsample_size
+ )
+
+ # 6. post-process
+ if self.conv_norm_out:
+ sample = self.conv_norm_out(sample)
+ sample = self.conv_act(sample)
+ sample = self.conv_out(sample)
+
+ if not return_dict:
+ return (sample,)
+
+ return UNet2DConditionOutput(sample=sample)
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers.py
new file mode 100644
index 0000000000000000000000000000000000000000..08b359185eb50f675c9ed215bec6fdfc267fd013
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers.py
@@ -0,0 +1,66 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet_imgspecific_ft.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/data/mtp_vlp_ray/debug/debug_pretrain"
+ debug_train_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml'
+ debug_val_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml'
+ # WT: for tiktok image data dir
+ web_data_root = './blob_dir/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person'
+ # web_data_root = '/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person'
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers_lora_upsquare.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers_lora_upsquare.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bf77bad6e77ae09cdf87035cf7c839a8adbc020
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/web_S256L16_xformers_lora_upsquare.py
@@ -0,0 +1,66 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet_imgspecific_ft.net_lora import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web_upsquare.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/data/mtp_vlp_ray/debug/debug_pretrain"
+ debug_train_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml'
+ debug_val_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml'
+ # WT: for tiktok image data dir
+ web_data_root = './blob_dir/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person'
+ # web_data_root = '/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person'
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/webtan_S256L16_xformers_upsquare.py b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/webtan_S256L16_xformers_upsquare.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f778a446f90f18588298b910ada9cf28ad1f804
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/config/ref_attn_clip_combine_controlnet_imgspecific_ft/webtan_S256L16_xformers_upsquare.py
@@ -0,0 +1,66 @@
+import torch
+
+from config import *
+from config.ref_attn_clip_combine_controlnet_imgspecific_ft.net import Net, inner_collect_fn
+
+class Args(BasicArgs):
+ task_name, method_name = BasicArgs.parse_config_name(__file__)
+ log_dir = os.path.join(BasicArgs.root_dir, task_name, method_name)
+
+ # data
+ dataset_cf = 'dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web_upsquare.py'
+ max_train_samples = None
+ max_eval_samples = None
+ # max_eval_samples = 2
+ max_video_len = 1 # L=16
+ debug_max_video_len = 1
+ img_full_size = (256, 256)
+ img_size = (256, 256)
+ fps = 5
+ data_dir = "./blob_dir/data/mtp_vlp_ray/debug/debug_pretrain"
+ debug_train_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml'
+ debug_val_yaml = './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml'
+ train_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml'
+ val_yaml = './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml'
+ # WT: for tiktok image data dir
+ web_data_root = './blob_dir/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames_tan'
+ # web_data_root = '/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames_tan'
+ tiktok_data_root = 'keli/dataset/TikTok_dataset/'
+ # tiktok_ann_root = 'keli/dataset/TikTok_dataset/pair_ann'
+ refer_sdvae = False
+
+ eval_before_train = True
+ eval_enc_dec_only = False
+
+ # training
+ local_train_batch_size = 8
+ local_eval_batch_size = 8
+ learning_rate = 3e-5
+ null_caption = False
+ refer_sdvae = False
+
+
+ # max_norm = 1.0
+ epochs = 50
+ num_workers = 4
+ eval_step = 5
+ save_step = 5
+ drop_text = 1.0 # drop text only activate in args.null_caption, default=1.0
+ scale_factor = 0.18215
+ # pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v2-1')
+ pretrained_model_path = os.path.join(BasicArgs.root_dir, 'diffusers/sd-image-variations-diffusers')
+ sd15_path = os.path.join(BasicArgs.root_dir, 'diffusers/stable-diffusion-v1-5-2')
+ gradient_checkpointing = True
+ enable_xformers_memory_efficient_attention = True
+ freeze_unet=True
+
+ # sample
+ num_inf_images_per_prompt = 1
+ num_inference_steps = 50
+ guidance_scale = 7.5
+
+ # others
+ seed = 42
+ # set_seed(seed)
+
+args = Args()
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/app_demo_human_image_edit_singleinput.py b/One-to-All-Animation/benchmark/DisCo/dataset/app_demo_human_image_edit_singleinput.py
new file mode 100644
index 0000000000000000000000000000000000000000..72e513bf6b04e6f089eaaa67f82c5877979d977c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/app_demo_human_image_edit_singleinput.py
@@ -0,0 +1,471 @@
+from config import *
+import torch
+from torch.utils.data import Dataset
+from torchvision import transforms
+
+import os, math, re, json
+import numpy as np
+from tqdm import tqdm
+import PIL
+from PIL import Image
+from PIL import ImageFile, Image
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+import cv2
+import random
+
+training_templates_smallest = [
+ 'photo of a sks {}',
+]
+
+reg_templates_smallest = [
+ 'photo of a {}',
+]
+coco_joints_name = ['Nose', 'Left Eye', 'Right Eye', 'Left Ear', 'Right Ear', 'Left Shoulder', 'Right Shoulder', 'Left Elbow', 'Right Elbow', 'Left Wrist',
+ 'Right Wrist', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Left Ankle', 'Right Ankle', 'Pelvis', 'Neck']
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.dataset = "tiktok"
+ self.args = args
+ self.split = split
+ self.is_train = split == "train"
+ self.is_composite = False
+ self.on_memory = getattr(args, 'on_memory', False)
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.yaml_file = yaml_file
+ self.stickwidth = 4
+ self.preprocesser = preprocesser
+ self.limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ self.colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(1.0, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(1.0, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(1.0, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(1.0, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.total_num_videos = 340
+ self.image_path = '{}/{}'
+ self.ref_image_path = '{:05d}/images/{:04d}.png'
+ # self.anno_pose_path = '{}/openpose_json/{:04d}.jpg.json'
+ self.anno_pose_path = '{:05d}/openpose_json/{:04d}.png.json'
+ self.anno_path = 'GIT/{:05d}/labels/{:04d}.txt'
+ self.ref_mask_path = '{}/groundsam/{}.mask.jpg'
+
+ self.ref_image_path_web = '{}/{}'
+ self.anno_pose_path_web = '{}/openpose_json/{}.json'
+
+ self.image_paths_list = []
+ self.ref_image_paths_list = []
+ self.pose_image_paths_list = []
+ self.anno_list = []
+ self.anno_pose_list = []
+ self.mask_list = []
+ self.file_name_id = []
+
+ assert split == 'val'
+
+ # for specific choose the video
+ ref_fg_folder = './demo_data/fg'
+ ref_bg_folder = './demo_data/bg'
+ ref_pose_folder = './demo_data/pose'
+ bg_list = os.listdir(os.path.join(ref_bg_folder, 'images'))
+
+
+ ref_fg_files_list = os.listdir(os.path.join(ref_fg_folder, 'images'))
+ # Kevin Ver: always chooose the 1st frame as the referece image
+ # TODO: WT Revision: if t = n, then reference frm could be between frame(0)~frame(n-1)
+ for ref_img_name in ref_fg_files_list:
+ ref_image_path = os.path.join(ref_fg_folder, 'images', ref_img_name)
+ ref_mask_path = os.path.join(ref_fg_folder, 'masks', ref_img_name)
+
+ pose_files_list = os.listdir(ref_pose_folder)
+ for pose_img_name in pose_files_list:
+ pose_image_path = os.path.join(ref_pose_folder, pose_img_name)
+
+ self.pose_image_paths_list.append(pose_image_path) # actually have no gt file, just use the target pose file
+ self.ref_image_paths_list.append(ref_image_path)
+ self.mask_list.append(ref_mask_path)
+ self.file_name_id.append(f'ref{ref_img_name}--pose{pose_img_name}')
+
+ self.bgref_ref_image_paths_list = []
+ self.bgref_mask_list = []
+ for ref_bg_name in bg_list:
+ ref_image_fname = os.path.join(ref_bg_folder, 'images', ref_bg_name)
+ ref_mask_fname = os.path.join(ref_bg_folder, 'masks', ref_bg_name)
+
+ self.bgref_ref_image_paths_list.append(ref_image_fname)
+ self.bgref_mask_list.append(ref_mask_fname)
+ self.bgref_num_images = len(self.bgref_ref_image_paths_list)
+
+
+ self.num_images = len(self.ref_image_paths_list)
+ self._length = self.num_images
+ print('number of samples:',self._length)
+
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, self._length)
+ else:
+ return self._length
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, self._length)
+ else:
+ return self._length
+
+ def normalize_mask(self, mask):
+ mask[mask>=0.001] = 1
+ mask[mask<0.001] = 0
+ return mask
+
+ # draw the body keypoint and lims
+ def draw_bodypose(self, canvas, pose):
+ canvas = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
+ canvas = np.zeros_like(canvas)
+
+ for i in range(18):
+ x, y = pose[i][0:2]
+ if x>=0 and y>=0:
+ cv2.circle(canvas, (int(x), int(y)), 4, self.colors[i], thickness=-1)
+ # cv2.putText(canvas, '%d'%(i), (int(x), int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
+ for limb_idx in range(17):
+ cur_canvas = canvas.copy()
+ index_a = self.limbSeq[limb_idx][0]-1
+ index_b = self.limbSeq[limb_idx][1]-1
+
+ if pose[index_a][0]<0 or pose[index_b][0]<0 or pose[index_a][1]<0 or pose[index_b][1]<0:
+ continue
+
+ Y = [pose[index_a][0], pose[index_b][0]]
+ X = [pose[index_a][1], pose[index_b][1]]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), self.stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, self.colors[limb_idx])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # Convert color space from BGR to RGB
+ # canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
+ # Create PIL image object from numpy array
+ canvas = Image.fromarray(canvas)
+ return canvas
+
+
+ def coco2openpose(self, img, coco_keypoints):
+
+ # coco keypoints: [x1,y1,v1,...,xk,yk,vk] (k=17)
+ # ['Nose', Leye', 'Reye', 'Lear', 'Rear', 'Lsho', 'Rsho', 'Lelb',
+ # 'Relb', 'Lwri', 'Rwri', 'Lhip', 'Rhip', 'Lkne', 'Rkne', 'Lank', 'Rank']
+ # openpose keypoints: [y1,...,yk], [x1,...xk] (k=18, with Neck)
+ # ['Nose' (0), *'Neck'* (1), 'Rsho' (2), 'Relb' (3), 'Rwri' (4), 'Lsho' (5), 'Lelb' (6), 'Lwri' (7),'Rhip' (8),
+ # 'Rkne' (9), 'Rank' (10), 'Lhip' (11), 'Lkne' (12), 'Lank' (13), 'Reye' (14), 'Leye' (15), 'Rear' (16), 'Lear' (17)]
+
+ openpose_keypoints = [
+ coco_keypoints[0], # Nose (0)
+ list((np.asarray(coco_keypoints[5]) + np.asarray(coco_keypoints[6]))/2), # Neck (1)
+ coco_keypoints[6], # RShoulder (2)
+ coco_keypoints[8], # RElbow (3)
+ coco_keypoints[10], # RWrist (4)
+ coco_keypoints[5], # LShoulder (5)
+ coco_keypoints[7], # LElbow (6)
+ coco_keypoints[9], # LWrist (7)
+ coco_keypoints[12], # RHip (8)
+ coco_keypoints[14], # RKnee (9)
+ coco_keypoints[16], # RAnkle (10)
+ coco_keypoints[11], # LHip (11)
+ coco_keypoints[13], # LKnee (12)
+ coco_keypoints[15], # LAnkle (13)
+ coco_keypoints[2], # REye (14)
+ coco_keypoints[1], # LEye (15)
+ coco_keypoints[4], # REar (16)
+ coco_keypoints[3], # LEar (17)
+ ]
+ return self.draw_bodypose(img, openpose_keypoints)
+
+ def load_image(self, path):
+ if os.path.exists(path):
+ image = Image.open(path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+ else:
+ image = None
+ return image
+
+ def load_mask(self, path):
+ try:
+ if os.path.exists(path):
+ img = self.load_image(path)
+ img = np.asarray(img)
+ bk = img[:, :, :] == [68, 0, 83]
+ fg = (bk == False)
+ fg = fg * 255.0
+ mask = fg.astype(np.uint8)
+ ipl_mask = Image.fromarray(mask)
+ else:
+ ipl_mask = None
+ except Exception as e:
+ print(e)
+ ipl_mask = None
+ return ipl_mask
+
+ def load_mask_tiktok(self, path):
+ if os.path.exists(path):
+ image = Image.open(path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+ else:
+ image = None
+ return image
+
+ def load_openpose(self, anno_pose_path, ref_image):
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path, 'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d) > 0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x, y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x, y])
+
+ # convert coordinates to skeleton image
+ skeleton_img = self.coco2openpose(ref_image, pose_without_visibletag)
+ return skeleton_img
+
+ def get_img_txt_pair(self, idx):
+ img_path = self.ref_image_paths_list[idx % self.num_images]
+ ref_img_path = self.ref_image_paths_list[idx % self.num_images]
+ ref_mask_path = self.mask_list[idx % self.num_images]
+ anno_pose_path = self.pose_image_paths_list[idx % self.num_images]
+ img_key = self.file_name_id[idx % self.num_images]
+
+ ref_mask = self.load_mask_tiktok(ref_mask_path)
+ ref_image = Image.open(ref_img_path)
+ if not ref_image.mode == "RGB":
+ ref_image = ref_image.convert("RGB")
+ ref_mask = ref_mask.resize(ref_image.size) # resize the mask to img
+ img = Image.open(img_path)
+ if not img.mode == "RGB":
+ img = img.convert("RGB")
+
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path,'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d)>0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x,y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x,y])
+
+ # convert coordinates to skeleton image
+ skeleton_img = self.coco2openpose(ref_image, pose_without_visibletag)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['img'] = img
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = False
+ meta_data['skeleton_img'] = skeleton_img
+ meta_data['reference_img'] = ref_image
+ meta_data['ref_mask'] = ref_mask
+ return meta_data
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def __getitem__(self, idx):
+ raw_data = self.get_img_txt_pair(idx)
+ img = raw_data['img']
+ skeleton_img = raw_data['skeleton_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+
+
+ ### random sample background
+ ref_bg_idx = random.choice(list(range(0, self.bgref_num_images)))
+ ref_bg_img_path = self.bgref_ref_image_paths_list[ref_bg_idx]
+ ref_bg_ref_mask_path = os.path.join(self.args.web_data_root, self.bgref_mask_list[ref_bg_idx])
+ ref_bg_image = Image.open(os.path.join(self.args.web_data_root, ref_bg_img_path))
+ ref_bg_ref_mask = self.load_mask_tiktok(ref_bg_ref_mask_path)
+ if not ref_bg_image.mode == "RGB":
+ ref_bg_image = ref_bg_image.convert("RGB")
+ ref_bg_ref_mask = ref_bg_ref_mask.resize(ref_bg_image.size) # resize the mask to img
+
+ img_key = img_key + '_{}'.format(ref_bg_img_path.split('/')[-1])
+
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state)
+ ref_bg_reference_img_controlnet = self.augmentation(ref_bg_image, self.transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, self.ref_transform)
+
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['ref_mask']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ # ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(raw_data['reference_img'].size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, self.cond_transform, state) # controlnet path input
+ ref_bg_reference_img_controlnet_mask = self.augmentation(ref_bg_ref_mask, self.cond_transform, state) # controlnet path input
+
+ # linshi wangtan
+ reference_img_mask = self.normalize_mask(reference_img_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_img_controlnet_mask)
+ ref_bg_reference_img_controlnet_mask = self.normalize_mask(ref_bg_reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ # reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+ reference_img_controlnet = ref_bg_reference_img_controlnet * (1 - ref_bg_reference_img_controlnet_mask) # background
+
+ outputs = {'img_key':img_key, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+ outputs['save_filename'] = self.file_name_id[idx % self.num_images]
+
+ return outputs
+
+
+ def preprocess_input(self, reference_img, fg_mask, ref_bg_image, bg_mask, skeleton_img):
+ fg_mask = fg_mask.resize(reference_img.size)
+
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(reference_img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state)
+ ref_bg_reference_img_controlnet = self.augmentation(ref_bg_image, self.transform, state)
+ reference_img_vae = reference_img_controlnet
+ reference_img = self.augmentation(reference_img, self.ref_transform)
+
+
+ reference_fg_mask = self.augmentation(fg_mask, self.ref_transform_mask, state)
+ reference_fg_controlnet_mask = self.augmentation(fg_mask, self.cond_transform, state) # controlnet path input
+ ref_bg_reference_img_controlnet_mask = self.augmentation(bg_mask, self.cond_transform, state) # controlnet path input
+
+ # linshi wangtan
+ reference_img_mask = self.normalize_mask(reference_fg_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_fg_controlnet_mask)
+ ref_bg_reference_img_controlnet_mask = self.normalize_mask(ref_bg_reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask # foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = ref_bg_reference_img_controlnet * (1 - ref_bg_reference_img_controlnet_mask) # background
+ outputs = {'label_imgs': img.unsqueeze(0), 'cond_imgs': skeleton_img.unsqueeze(0), 'reference_img': reference_img.unsqueeze(0), 'reference_img_controlnet':reference_img_controlnet.unsqueeze(0), 'reference_img_vae':reference_img_vae.unsqueeze(0)}
+ return outputs
+
+
+ def preprocess_masked_input(self, reference_img_masked, ref_bg_image_masked, skeleton_img):
+ reference_img = reference_img_masked
+ ref_bg_image = ref_bg_image_masked
+
+ def pil2binary_fg(img):
+ xx = np.array(img.convert('L'))
+ xx[xx > 0] = 255
+ xx[xx < 255] = 0
+ return xx
+ def pil2binary_bg(img):
+ xx = np.array(img.convert('L'))
+ xx[xx == 0] = 255
+ xx[xx < 255] = 0
+ return xx
+
+ fg_mask = Image.fromarray(pil2binary_fg(reference_img)).convert('RGB')
+ bg_mask = Image.fromarray(pil2binary_bg(ref_bg_image)).convert('RGB')
+
+ fg_mask = fg_mask.resize(reference_img.size)
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(reference_img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state)
+ ref_bg_reference_img_controlnet = self.augmentation(ref_bg_image, self.transform, state)
+ reference_img_vae = reference_img_controlnet
+ reference_img = self.augmentation(reference_img, self.ref_transform)
+
+
+ reference_fg_mask = self.augmentation(fg_mask, self.ref_transform_mask, state)
+ reference_fg_controlnet_mask = self.augmentation(fg_mask, self.cond_transform, state) # controlnet path input
+ ref_bg_reference_img_controlnet_mask = self.augmentation(bg_mask, self.cond_transform, state) # controlnet path input
+
+ # linshi wangtan
+ reference_img_mask = self.normalize_mask(reference_fg_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_fg_controlnet_mask)
+ ref_bg_reference_img_controlnet_mask = self.normalize_mask(ref_bg_reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask # foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = ref_bg_reference_img_controlnet * (1 - ref_bg_reference_img_controlnet_mask) # background
+ outputs = {'label_imgs': img.unsqueeze(0), 'cond_imgs': skeleton_img.unsqueeze(0), 'reference_img': reference_img.unsqueeze(0), 'reference_img_controlnet':reference_img_controlnet.unsqueeze(0), 'reference_img_vae':reference_img_vae.unsqueeze(0)}
+ return outputs
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv.py b/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..e316980b67669cf47fd3b216e761f98ce67212ac
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv.py
@@ -0,0 +1,199 @@
+from config import *
+import torch
+import numpy as np
+from PIL import Image
+from dataset.tsv_cond_dataset import TsvCondImgCompositeDataset
+
+
+class BaseDataset(TsvCondImgCompositeDataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.basic_root_dir = BasicArgs.root_dir
+ self.max_video_len = args.max_video_len
+ assert self.max_video_len == 1
+ self.fps = args.fps
+ self.dataset = "COCO"
+ self.preprocesser = preprocesser
+ args.ref_mode = None
+
+ super().__init__(
+ args, yaml_file, split=split,
+ size_frame=args.max_video_len, tokzr=None)
+ self.data_dir = args.data_dir
+
+ min_crop_scale = 0.5 if self.args.strong_aug_stage1 else 0.9
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ try:
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.ToTensor(),
+ ])
+ except:
+ print('### Current pt version not support antialias, thus remove it! ###')
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ def add_mask_to_img(self, img, mask, img_key): #pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(img_array * (1-mask_array)) # foreground, background
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def get_metadata(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, _) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(img_idx)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = is_video # True: video data, False: image data
+ meta_data['pose_img'] = None # setting pose to None
+ if self.args.combine_use_mask:
+ meta_data['mask_img'] = self.get_cond(img_idx, 'masks')
+
+ # ref and target image are the same
+ meta_data['ref_img_key'] = img_key
+ meta_data['reference_img'] = frames
+ if self.args.combine_use_mask:
+ meta_data['mask_img_ref'] = meta_data['mask_img']
+ meta_data['img'] = frames
+ return meta_data
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(
+ f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, super().__len__())
+ else:
+ return super().__len__()
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, super().__len__())
+ else:
+ return super().__len__()
+
+ def __getitem__(self, idx):
+ # try:
+ raw_data = self.get_metadata(idx)
+ # except Exception as e:
+ # print(e, self.yaml_file)
+ img = raw_data['img']
+ skeleton_img = raw_data['pose_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+ ref_img_key = raw_data['ref_img_key']
+
+ # ## 1st TRY: First MASK, Then Aug.
+ # if self.args.combine_use_mask:
+ # mask_img_ref = raw_data['mask_img_ref']
+ # masked_foreground, masked_background = self.add_mask_to_img(reference_img, mask_img_ref, ref_img_key) # should mask reference image
+ # reference_img_controlnet = masked_background # if use mask, it should be background
+ # reference_img = masked_foreground # if use mask, it should be foreground
+ # else:
+ # reference_img_controlnet = reference_img
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, self.transform, state)
+ if skeleton_img is not None:
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state) # controlnet path input
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, self.ref_transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['mask_img_ref']
+ ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(raw_data['reference_img'].size)
+
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+ reference_img_mask = self.augmentation(mask_img_ref, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, self.cond_transform, state) # controlnet path input
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+ if skeleton_img is not None:
+ outputs.update({'cond_imgs': skeleton_img})
+
+ return outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv_strongrand.py b/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv_strongrand.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ef8c83520d8534ecbfb1d472ccc9eef4090cdae
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/coco_controlnet_t2i_imagevar_combine_tsv_strongrand.py
@@ -0,0 +1,195 @@
+from config import *
+import torch
+import numpy as np
+from PIL import Image
+from dataset.tsv_cond_dataset import TsvCondImgCompositeDataset
+
+
+class BaseDataset(TsvCondImgCompositeDataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.basic_root_dir = BasicArgs.root_dir
+ self.max_video_len = args.max_video_len
+ assert self.max_video_len == 1
+ self.fps = args.fps
+ self.dataset = "COCO"
+ self.preprocesser = preprocesser
+ args.ref_mode = None
+
+ super().__init__(
+ args, yaml_file, split=split,
+ size_frame=args.max_video_len, tokzr=None)
+ self.data_dir = args.data_dir
+
+ self.random_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int(torch.randint(0, img.height - img.width, (1,)).item()), left=0, height=img.width, width=img.width))
+ self.random_square_width = transforms.Lambda(lambda img: transforms.functional.crop(img, top=0, left=int(torch.randint(0, img.width - img.height, (1,)).item()), height=img.height, width=img.height))
+
+ min_crop_scale = 0.5 if self.args.strong_aug_stage1 else 0.9
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+
+ def add_mask_to_img(self, img, mask, img_key): #pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(img_array * (1-mask_array)) # foreground, background
+
+ def normalize_mask(self, mask):
+ mask[mask>=0.5] = 1
+ mask[mask<0.5] = 0
+ return mask
+
+ def augmentation(self, frame, transform1, transform2=None, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ frame_transform1 = transform1(frame) if transform1 is not None else frame
+ if transform2 is None:
+ return frame_transform1
+ else:
+ return transform2(frame_transform1)
+
+ def get_metadata(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, _) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(img_idx)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = is_video # True: video data, False: image data
+ meta_data['pose_img'] = None # setting pose to None
+ if self.args.combine_use_mask:
+ meta_data['mask_img'] = self.get_cond(img_idx, 'masks')
+
+ # ref and target image are the same
+ meta_data['ref_img_key'] = img_key
+ meta_data['reference_img'] = frames
+ if self.args.combine_use_mask:
+ meta_data['mask_img_ref'] = meta_data['mask_img']
+ meta_data['img'] = frames
+ return meta_data
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(
+ f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, super().__len__())
+ else:
+ return super().__len__()
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, super().__len__())
+ else:
+ return super().__len__()
+
+ def __getitem__(self, idx):
+
+ raw_data = self.get_metadata(idx)
+ img = raw_data['img']
+ skeleton_img = raw_data['pose_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+ ref_img_key = raw_data['ref_img_key']
+
+ # first check the size of the ref image
+ ref_img_size = raw_data['reference_img'].size
+ if ref_img_size[0] > ref_img_size[1]: # width > height
+ transform1 = self.random_square_width
+ elif ref_img_size[0] < ref_img_size[1]:
+ transform1 = self.random_square_height
+ else:
+ transform1 = None
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, transform1, self.transform, state)
+ if skeleton_img is not None:
+ skeleton_img = self.augmentation(skeleton_img, transform1, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, transform1, self.transform, state) # controlnet path input
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, transform1, self.ref_transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['mask_img_ref']
+ ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(ref_img_size)
+
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+ reference_img_mask = self.augmentation(mask_img_ref, transform1, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, transform1, self.cond_transform, state) # controlnet path input
+ if 'laion' in ref_img_key or 'deepfashion' in ref_img_key: # normailze mask for grounded sam mask
+ reference_img_mask = self.normalize_mask(reference_img_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+ if skeleton_img is not None:
+ outputs.update({'cond_imgs': skeleton_img})
+
+ return outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_sampler.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_sampler.py
new file mode 100644
index 0000000000000000000000000000000000000000..31f4860aac00b18febb12093a5e24752c7901521
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_sampler.py
@@ -0,0 +1,222 @@
+import math
+import random
+from datetime import datetime
+import torch
+from torch.utils.data import Sampler, Dataset
+import torch.distributed as dist
+from utils.dist import get_local_rank, get_local_size, get_rank, get_world_size
+from .data_utils.sampler_utils import PrepareData
+import logging
+logger = logging.getLogger(__name__)
+
+
+class DistributedSamplerLimited(Sampler):
+ def __init__(self, dataset: Dataset, num_replicas: int = None,
+ rank: int = None, shuffle: bool = True,
+ seed: int = 0, drop_last: bool = False, limited=-1) -> None:
+ if num_replicas is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ num_replicas = dist.get_world_size()
+ if rank is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ rank = dist.get_rank()
+ if rank >= num_replicas or rank < 0:
+ raise ValueError(
+ "Invalid rank {}, rank should be in the interval"
+ " [0, {}]".format(rank, num_replicas - 1))
+ self.dataset = dataset
+ self.num_replicas = num_replicas
+ self.rank = rank
+ self.epoch = 0
+ self.drop_last = drop_last
+ print(f'Dbg: distribeted sampler limited: rank={rank}, num_replicas={num_replicas}')
+ # If the dataset length is evenly divisible by # of replicas, then there
+ # is no need to drop any data, since the dataset will be split equally.
+ if self.drop_last and len(self.dataset) % self.num_replicas != 0: # type: ignore
+ # Split to nearest available length that is evenly divisible.
+ # This is to ensure each rank receives the same amount of data when
+ # using this Sampler.
+ self.num_samples = math.ceil(
+ # `type:ignore` is required because Dataset cannot provide a default __len__
+ # see NOTE in pytorch/torch/utils/data/sampler.py
+ (len(self.dataset) - self.num_replicas) / self.num_replicas # type: ignore
+ )
+ else:
+ self.num_samples = math.ceil(len(self.dataset) / self.num_replicas) # type: ignore
+ self.total_size = self.num_samples * self.num_replicas
+ self.shuffle = shuffle
+ self.seed = seed
+ self.limited = limited
+ if self.limited > -1:
+ self.num_samples = min(self.limited, self.num_samples)
+
+ def __iter__(self):
+ if self.shuffle:
+ # deterministically shuffle based on epoch and seed
+ g = torch.Generator()
+ g.manual_seed(self.seed + self.epoch)
+ indices = torch.randperm(len(self.dataset), generator=g).tolist() # type: ignore
+ else:
+ indices = list(range(len(self.dataset))) # type: ignore
+
+ if not self.drop_last:
+ # add extra samples to make it evenly divisible
+ padding_size = self.total_size - len(indices)
+ if padding_size <= len(indices):
+ indices += indices[:padding_size]
+ else:
+ indices += (indices * math.ceil(padding_size / len(indices)))[:padding_size]
+ else:
+ # remove tail of data to make it evenly divisible.
+ indices = indices[:self.total_size]
+ assert len(indices) == self.total_size
+
+ # subsample
+ indices = indices[self.rank:self.total_size:self.num_replicas]
+ if self.limited > -1 and len(indices) > self.limited:
+ print(f'Trim indices: {len(indices)} --> {self.limited}')
+ indices = indices[:self.limited]
+ assert len(indices) == self.num_samples
+ # shuffle subsample
+ if self.shuffle: # and self.epoch > 0:
+ # random.seed(self.seed + self.epoch)
+ random.seed(datetime.now())
+ random.shuffle(indices)
+
+ return iter(indices)
+
+ def __len__(self) -> int:
+ return self.num_samples
+
+ def set_epoch(self, epoch: int) -> None:
+ self.epoch = 0 # keep data unchanged
+ # self.epoch = epoch
+
+
+class NodeSplitSampler(Sampler):
+ def __init__(self, dataset, shuffle, random_seed,
+ first_epoch_skip_shuffle=False,
+ prepare_data=True):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_world_size()
+ self.local_size = get_local_size()
+ self.node_size = self.world_size // self.local_size
+ self.rank = get_rank()
+ self.node_idx = self.rank // self.local_size
+ self.local_rank = get_local_rank()
+ self.next_epoch_skip_shuffle = first_epoch_skip_shuffle
+
+ # only be used when shuffle = True and first_epoch_skip_shuffle = True
+ self.prepare_data = prepare_data
+ self.prepare = None
+ self.skip = 0
+
+ def get_index_on_node(self):
+ # there is no need to cache source_list as we only call this function
+ # once in the whole training life-time
+ source_list = self.dataset.get_composite_source_idx()
+ idx_split = list(enumerate(source_list))
+ idx_split = torch.tensor(idx_split)
+ if self.shuffle:
+ random_idx = self.get_shufle_idx(len(idx_split))
+ idx_split = idx_split[random_idx]
+ max_split = idx_split[:, 1].max() + 1
+ priority = self.get_shufle_idx(max_split)
+ sort_idx = torch.argsort(priority[idx_split[:, 1]])
+ idx_split = idx_split[sort_idx]
+ num_idx_on_node = (len(idx_split) + self.node_size - 1) // self.node_size
+ offset = num_idx_on_node * self.node_idx
+ offset_end = offset + num_idx_on_node
+ offset_end = min(offset_end, len(idx_split))
+ unique_split_index = list(
+ set(idx_split[offset:offset_end, 1].tolist()))
+ logger.info('calling get_index_on_node in NodeSplitSampler ....')
+ logger.info(f'dataset is {self.dataset.yaml_file}')
+ logger.info(unique_split_index)
+ if self.shuffle and self.next_epoch_skip_shuffle and self.prepare_data:
+ if get_local_rank() == 0:
+ self.prepare = PrepareData(
+ self.dataset,
+ prepare_t_versions=[],
+ fixed_samples_in_node=True)
+ for s in unique_split_index:
+ self.prepare.prepare(s)
+ return idx_split[offset:offset_end, 0]
+
+ def get_shufle_idx(self, n):
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(n, generator=g)
+ self.random_seed += 99
+ return random_idx
+
+ def get_index_on_rank(self, idx_on_node):
+ if self.shuffle:
+ if not self.next_epoch_skip_shuffle:
+ curr_idx_on_node = idx_on_node[
+ self.get_shufle_idx(len(idx_on_node))]
+ else:
+ curr_idx_on_node = idx_on_node
+ self.next_epoch_skip_shuffle = False
+ else:
+ curr_idx_on_node = idx_on_node
+ idx_rank_size = (
+ len(curr_idx_on_node) + self.local_size - 1) // self.local_size
+ offset = idx_rank_size * self.local_rank
+ offset_end = offset + idx_rank_size
+ offset_end = min(offset_end, len(curr_idx_on_node))
+ curr_idx_on_node = curr_idx_on_node.tolist()
+ for i in range(offset, offset_end):
+ yield curr_idx_on_node[i]
+
+ def skip(self, num):
+ self.skip = num
+
+ def __iter__(self):
+ self.curr_idx = 0
+ idx_on_node = self.get_index_on_node()
+ if self.skip > 0:
+ logging.info('we will skip {}'.format(self.skip))
+ while True:
+ for i in self.get_index_on_rank(idx_on_node):
+ if self.skip <= 0:
+ yield i
+ else:
+ self.skip -= 1
+
+ def __len__(self):
+ raise ValueError('should not be called')
+
+
+class IterationBasedBatchSampler(torch.utils.data.sampler.BatchSampler):
+ """
+ Wraps a BatchSampler, resampling from it until
+ a specified number of iterations have been sampled
+ """
+
+ def __init__(self, batch_sampler, num_iterations, start_iter=0):
+ self.batch_sampler = batch_sampler
+ self.num_iterations = num_iterations
+ self.start_iter = start_iter
+
+ def __iter__(self):
+ iteration = self.start_iter
+ while iteration <= self.num_iterations:
+ # if the underlying sampler has a set_epoch method, like
+ # DistributedSampler, used for making each process see
+ # a different split of the dataset, then set it
+ if hasattr(self.batch_sampler.sampler, "set_epoch"):
+ self.batch_sampler.sampler.set_epoch(iteration)
+ for batch in self.batch_sampler:
+ iteration += 1
+ if iteration > self.num_iterations:
+ break
+ yield batch
+
+ def __len__(self):
+ return self.num_iterations
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/albef_randaug.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/albef_randaug.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6808c767889c03c4007d61235819e0f646f35fd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/albef_randaug.py
@@ -0,0 +1,341 @@
+# from ALBEF (https://github.com/salesforce/ALBEF/blob/main/dataset/randaugment.py)
+import cv2
+import numpy as np
+
+
+# aug functions
+def identity_func(img):
+ return img
+
+
+def autocontrast_func(img, cutoff=0):
+ '''
+ same output as PIL.ImageOps.autocontrast
+ '''
+ n_bins = 256
+
+ def tune_channel(ch):
+ n = ch.size
+ cut = cutoff * n // 100
+ if cut == 0:
+ high, low = ch.max(), ch.min()
+ else:
+ hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
+ low = np.argwhere(np.cumsum(hist) > cut)
+ low = 0 if low.shape[0] == 0 else low[0]
+ high = np.argwhere(np.cumsum(hist[::-1]) > cut)
+ high = n_bins - 1 if high.shape[0] == 0 else n_bins - 1 - high[0]
+ if high <= low:
+ table = np.arange(n_bins)
+ else:
+ scale = (n_bins - 1) / (high - low)
+ offset = -low * scale
+ table = np.arange(n_bins) * scale + offset
+ table[table < 0] = 0
+ table[table > n_bins - 1] = n_bins - 1
+ table = table.clip(0, 255).astype(np.uint8)
+ return table[ch]
+
+ channels = [tune_channel(ch) for ch in cv2.split(img)]
+ out = cv2.merge(channels)
+ return out
+
+
+def equalize_func(img):
+ '''
+ same output as PIL.ImageOps.equalize
+ PIL's implementation is different from cv2.equalize
+ '''
+ n_bins = 256
+
+ def tune_channel(ch):
+ hist = cv2.calcHist([ch], [0], None, [n_bins], [0, n_bins])
+ non_zero_hist = hist[hist != 0].reshape(-1)
+ step = np.sum(non_zero_hist[:-1]) // (n_bins - 1)
+ if step == 0: return ch
+ n = np.empty_like(hist)
+ n[0] = step // 2
+ n[1:] = hist[:-1]
+ table = (np.cumsum(n) // step).clip(0, 255).astype(np.uint8)
+ return table[ch]
+
+ channels = [tune_channel(ch) for ch in cv2.split(img)]
+ out = cv2.merge(channels)
+ return out
+
+
+def rotate_func(img, degree, fill=(0, 0, 0)):
+ '''
+ like PIL, rotate by degree, not radians
+ '''
+ H, W = img.shape[0], img.shape[1]
+ center = W / 2, H / 2
+ M = cv2.getRotationMatrix2D(center, degree, 1)
+ out = cv2.warpAffine(img, M, (W, H), borderValue=fill)
+ return out
+
+
+def solarize_func(img, thresh=128):
+ '''
+ same output as PIL.ImageOps.posterize
+ '''
+ table = np.array([el if el < thresh else 255 - el for el in range(256)])
+ table = table.clip(0, 255).astype(np.uint8)
+ out = table[img]
+ return out
+
+
+def color_func(img, factor):
+ '''
+ same output as PIL.ImageEnhance.Color
+ '''
+ ## implementation according to PIL definition, quite slow
+ # degenerate = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)[:, :, np.newaxis]
+ # out = blend(degenerate, img, factor)
+ # M = (
+ # np.eye(3) * factor
+ # + np.float32([0.114, 0.587, 0.299]).reshape(3, 1) * (1. - factor)
+ # )[np.newaxis, np.newaxis, :]
+ M = (
+ np.float32([
+ [0.886, -0.114, -0.114],
+ [-0.587, 0.413, -0.587],
+ [-0.299, -0.299, 0.701]]) * factor
+ + np.float32([[0.114], [0.587], [0.299]])
+ )
+ out = np.matmul(img, M).clip(0, 255).astype(np.uint8)
+ return out
+
+
+def contrast_func(img, factor):
+ """
+ same output as PIL.ImageEnhance.Contrast
+ """
+ mean = np.sum(np.mean(img, axis=(0, 1)) * np.array([0.114, 0.587, 0.299]))
+ table = np.array([(
+ el - mean) * factor + mean
+ for el in range(256)
+ ]).clip(0, 255).astype(np.uint8)
+ out = table[img]
+ return out
+
+
+def brightness_func(img, factor):
+ '''
+ same output as PIL.ImageEnhance.Contrast
+ '''
+ table = (np.arange(256, dtype=np.float32) * factor).clip(0, 255).astype(np.uint8)
+ out = table[img]
+ return out
+
+
+def sharpness_func(img, factor):
+ '''
+ The differences the this result and PIL are all on the 4 boundaries, the center
+ areas are same
+ '''
+ kernel = np.ones((3, 3), dtype=np.float32)
+ kernel[1][1] = 5
+ kernel /= 13
+ degenerate = cv2.filter2D(img, -1, kernel)
+ if factor == 0.0:
+ out = degenerate
+ elif factor == 1.0:
+ out = img
+ else:
+ out = img.astype(np.float32)
+ degenerate = degenerate.astype(np.float32)[1:-1, 1:-1, :]
+ out[1:-1, 1:-1, :] = degenerate + factor * (out[1:-1, 1:-1, :] - degenerate)
+ out = out.astype(np.uint8)
+ return out
+
+
+def shear_x_func(img, factor, fill=(0, 0, 0)):
+ H, W = img.shape[0], img.shape[1]
+ M = np.float32([[1, factor, 0], [0, 1, 0]])
+ out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
+ return out
+
+
+def translate_x_func(img, offset, fill=(0, 0, 0)):
+ '''
+ same output as PIL.Image.transform
+ '''
+ H, W = img.shape[0], img.shape[1]
+ M = np.float32([[1, 0, -offset], [0, 1, 0]])
+ out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
+ return out
+
+
+def translate_y_func(img, offset, fill=(0, 0, 0)):
+ '''
+ same output as PIL.Image.transform
+ '''
+ H, W = img.shape[0], img.shape[1]
+ M = np.float32([[1, 0, 0], [0, 1, -offset]])
+ out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
+ return out
+
+
+def posterize_func(img, bits):
+ '''
+ same output as PIL.ImageOps.posterize
+ '''
+ out = np.bitwise_and(img, np.uint8(255 << (8 - bits)))
+ return out
+
+
+def shear_y_func(img, factor, fill=(0, 0, 0)):
+ H, W = img.shape[0], img.shape[1]
+ M = np.float32([[1, 0, 0], [factor, 1, 0]])
+ out = cv2.warpAffine(img, M, (W, H), borderValue=fill, flags=cv2.INTER_LINEAR).astype(np.uint8)
+ return out
+
+
+def cutout_func(img, pad_size, replace=(0, 0, 0)):
+ replace = np.array(replace, dtype=np.uint8)
+ H, W = img.shape[0], img.shape[1]
+ rh, rw = np.random.random(2)
+ pad_size = pad_size // 2
+ ch, cw = int(rh * H), int(rw * W)
+ x1, x2 = max(ch - pad_size, 0), min(ch + pad_size, H)
+ y1, y2 = max(cw - pad_size, 0), min(cw + pad_size, W)
+ out = img.copy()
+ out[x1:x2, y1:y2, :] = replace
+ return out
+
+
+### level to args
+def enhance_level_to_args(MAX_LEVEL):
+ def level_to_args(level):
+ return ((level / MAX_LEVEL) * 1.8 + 0.1,)
+ return level_to_args
+
+
+def shear_level_to_args(MAX_LEVEL, replace_value):
+ def level_to_args(level):
+ level = (level / MAX_LEVEL) * 0.3
+ if np.random.random() > 0.5: level = -level
+ return (level, replace_value)
+
+ return level_to_args
+
+
+def translate_level_to_args(translate_const, MAX_LEVEL, replace_value):
+ def level_to_args(level):
+ level = (level / MAX_LEVEL) * float(translate_const)
+ if np.random.random() > 0.5: level = -level
+ return (level, replace_value)
+
+ return level_to_args
+
+
+def cutout_level_to_args(cutout_const, MAX_LEVEL, replace_value):
+ def level_to_args(level):
+ level = int((level / MAX_LEVEL) * cutout_const)
+ return (level, replace_value)
+
+ return level_to_args
+
+
+def solarize_level_to_args(MAX_LEVEL):
+ def level_to_args(level):
+ level = int((level / MAX_LEVEL) * 256)
+ return (level, )
+ return level_to_args
+
+
+def none_level_to_args(level):
+ return ()
+
+
+def posterize_level_to_args(MAX_LEVEL):
+ def level_to_args(level):
+ level = int((level / MAX_LEVEL) * 4)
+ return (level, )
+ return level_to_args
+
+
+def rotate_level_to_args(MAX_LEVEL, replace_value):
+ def level_to_args(level):
+ level = (level / MAX_LEVEL) * 30
+ if np.random.random() < 0.5:
+ level = -level
+ return (level, replace_value)
+
+ return level_to_args
+
+
+func_dict = {
+ 'Identity': identity_func,
+ 'AutoContrast': autocontrast_func,
+ 'Equalize': equalize_func,
+ 'Rotate': rotate_func,
+ 'Solarize': solarize_func,
+ 'Color': color_func,
+ 'Contrast': contrast_func,
+ 'Brightness': brightness_func,
+ 'Sharpness': sharpness_func,
+ 'ShearX': shear_x_func,
+ 'TranslateX': translate_x_func,
+ 'TranslateY': translate_y_func,
+ 'Posterize': posterize_func,
+ 'ShearY': shear_y_func,
+}
+
+translate_const = 10
+MAX_LEVEL = 10
+replace_value = (128, 128, 128)
+arg_dict = {
+ 'Identity': none_level_to_args,
+ 'AutoContrast': none_level_to_args,
+ 'Equalize': none_level_to_args,
+ 'Rotate': rotate_level_to_args(MAX_LEVEL, replace_value),
+ 'Solarize': solarize_level_to_args(MAX_LEVEL),
+ 'Color': enhance_level_to_args(MAX_LEVEL),
+ 'Contrast': enhance_level_to_args(MAX_LEVEL),
+ 'Brightness': enhance_level_to_args(MAX_LEVEL),
+ 'Sharpness': enhance_level_to_args(MAX_LEVEL),
+ 'ShearX': shear_level_to_args(MAX_LEVEL, replace_value),
+ 'TranslateX': translate_level_to_args(
+ translate_const, MAX_LEVEL, replace_value
+ ),
+ 'TranslateY': translate_level_to_args(
+ translate_const, MAX_LEVEL, replace_value
+ ),
+ 'Posterize': posterize_level_to_args(MAX_LEVEL),
+ 'ShearY': shear_level_to_args(MAX_LEVEL, replace_value),
+}
+
+
+class RandomAugment(object):
+
+ def __init__(self, N=2, M=10, isPIL=False, augs=[]):
+ self.N = N
+ self.M = M
+ self.isPIL = isPIL
+ if augs:
+ self.augs = augs
+ else:
+ self.augs = list(arg_dict.keys())
+
+ def get_random_ops(self):
+ sampled_ops = np.random.choice(self.augs, self.N)
+ return [(op, 0.5, self.M) for op in sampled_ops]
+
+ def __call__(self, img):
+ if self.isPIL:
+ img = np.array(img)
+ ops = self.get_random_ops()
+ for name, prob, level in ops:
+ if np.random.random() > prob:
+ continue
+ args = arg_dict[name](level)
+ img = func_dict[name](img, *args)
+ return img
+
+
+if __name__ == '__main__':
+ a = RandomAugment()
+ img = np.random.randn(32, 32, 3)
+ a(img)
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/node_sampler.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/node_sampler.py
new file mode 100644
index 0000000000000000000000000000000000000000..3add003697f772e814f972c344a5708afb3a3612
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/node_sampler.py
@@ -0,0 +1,1542 @@
+from pprint import pformat
+import random
+import numpy as np
+import time
+import os
+from utils.tsv_io import TSVDataset
+from utils.tsv_io import load_list_file
+from utils.tsv_io import get_tsv_lineidx, get_tsv_lineidx_8b
+from utils.tsv_io import TSVFile
+from utils.common import exclusive_open_to_read
+import os.path as op
+import logging
+import torch.multiprocessing as mp
+import math
+from utils.common import list_to_dict
+import torch
+import torch.distributed as dist
+from torch.utils.data.sampler import Sampler
+from utils.common import get_mpi_rank, get_mpi_size, get_mpi_local_size, get_mpi_local_rank
+from utils.common import print_frame_info
+from azfuse import File as QDFile
+
+
+def find_start_tsv_idx(num_each_tsv_file, node_offset):
+ x = node_offset
+ start_tsv_idx = None
+ for tsv_idx, tsv_size in enumerate(num_each_tsv_file):
+ x -= tsv_size
+ if x < 0:
+ start_tsv_idx = tsv_idx
+ break
+ assert start_tsv_idx is not None, (node_offset, sum(num_each_tsv_file))
+ return start_tsv_idx
+
+def construct_groups_by_chunk(num_each_tsv_file, offset, num, chunk_size):
+ s = 0
+ end_idx_each_tsv_file = []
+ for x in num_each_tsv_file:
+ end_idx_each_tsv_file.append(x + s)
+ s += x
+ curr_idx = offset
+ num = min(num, end_idx_each_tsv_file[-1] - offset)
+ tsv_groups = []
+ while curr_idx < offset + num:
+ curr_end_idx = curr_idx + chunk_size
+ curr_end_idx = min(curr_end_idx, offset + num)
+ g = {'start_idx': curr_idx, 'end_idx': curr_end_idx}
+ tsv_idx1 = find_start_tsv_idx(num_each_tsv_file, curr_idx)
+ tsv_idx2 = find_start_tsv_idx(num_each_tsv_file, curr_end_idx - 1)
+ g['all_tsv_idx'] = list(range(tsv_idx1, tsv_idx2 + 1))
+ tsv_groups.append(g)
+ curr_idx = curr_end_idx
+ return tsv_groups
+
+def construct_tsv_groups(node_offset, num_on_node, start_tsv_idx,
+ num_each_tsv_file):
+ tsv_groups = []
+ start_idx = node_offset
+ tsv_idx = start_tsv_idx
+ end_idx_each_tsv_file = []
+ s = 0
+ for x in num_each_tsv_file:
+ end_idx_each_tsv_file.append(x + s)
+ s += x
+ while True:
+ g = {'start_idx': start_idx, 'tsv_idx': tsv_idx}
+ #if tsv_idx == len(end_idx_each_tsv_file):
+ #assert tsv_groups[-1]['end_idx'] == num_on_node + node_offset
+ #break
+ if end_idx_each_tsv_file[tsv_idx] < num_on_node + node_offset:
+ g['end_idx'] = end_idx_each_tsv_file[tsv_idx]
+ tsv_groups.append(g)
+ tsv_idx += 1
+ start_idx = g['end_idx']
+ else:
+ g['end_idx'] = num_on_node + node_offset
+ tsv_groups.append(g)
+ break
+ return tsv_groups
+
+class ScaleNodeSplitBySplitSampler(Sampler):
+ def __init__(self, dataset, shuffle=False, random_seed=6, skip=0,
+ prepare_t_versions=[],
+ overwrite_dataset_len=None,
+ disable_prepare=False,
+ start_offset=0,
+ prepare_queue_len=0,
+ queue=None,
+ ):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_mpi_size()
+ self.local_size = get_mpi_local_size()
+ self.node_size = self.world_size // self.local_size
+ self.rank = get_mpi_rank()
+ self.node_idx = self.rank // self.local_size
+ self.local_rank = get_mpi_local_rank()
+ #self.next_epoch_skip_shuffle = first_epoch_skip_shuffle
+ self.overwrite_dataset_len = overwrite_dataset_len
+ self.prepare_queue_len = prepare_queue_len
+
+ # only be used when shuffle = True and first_epoch_skip_shuffle = True
+ self.prepare = None
+ self.prepare_t_versions = prepare_t_versions
+ self.enable_prepare = not disable_prepare
+ self.skip = skip
+ self.start_offset = start_offset
+ self.queue = queue
+ assert not (start_offset > 0 and overwrite_dataset_len is not None)
+
+ def __iter__(self):
+ if self.skip > 0:
+ logging.info('we will skip {}'.format(self.skip))
+ if self.overwrite_dataset_len:
+ # in vl-l sampler, we need to sample only the vl part, which is the
+ # first part
+ dataset_len = self.overwrite_dataset_len
+ else:
+ dataset_len = len(self.dataset)
+ num = dataset_len - self.start_offset
+ logging.info('num sample = {}'.format(num))
+ num_on_node = (num + self.node_size - 1) // self.node_size
+ node_offset = num_on_node * self.node_idx + self.start_offset
+ num_on_node = min(num_on_node, dataset_len - node_offset)
+ # each entry is the number of samples in one tsv, which means the
+ # dataset should not be randomly and should be ordered in one tsv by
+ # one tsv
+ num_each_tsv_file = self.dataset.get_num_each_tsv()
+
+ # find the tsv idx for the sample idx of node_offset
+ start_tsv_idx = find_start_tsv_idx(num_each_tsv_file, node_offset)
+ # construct tsv_groups
+ tsv_groups = construct_tsv_groups(node_offset, num_on_node, start_tsv_idx,
+ num_each_tsv_file)
+
+ if get_mpi_local_rank() == 0 and self.enable_prepare and self.prepare is None:
+ self.prepare = PrepareData(self.dataset,
+ prepare_t_versions=self.prepare_t_versions,
+ #prepare_queue_len=self.prepare_queue_len,
+ queue=self.queue,
+ )
+
+ local_random = random.Random()
+ local_random.seed(self.random_seed)
+ # prepare 3 tsv_split
+ num_tsv_cache = 8
+ local_rank_offset = self.local_rank
+ while True:
+ for idx_group, group in enumerate(tsv_groups):
+ start_idx = group['start_idx']
+ end_idx = group['end_idx']
+ curr_idx = range(start_idx, end_idx)
+ if self.shuffle:
+ curr_idx = list(curr_idx)
+ local_random.shuffle(curr_idx)
+ if self.prepare and self.skip <= 0:
+ for i in range(num_tsv_cache):
+ g = tsv_groups[(idx_group + 1 + i) % len(tsv_groups)]
+ self.prepare.prepare(g['tsv_idx'])
+ while local_rank_offset < len(curr_idx):
+ if self.skip <= 0:
+ yield curr_idx[local_rank_offset]
+ else:
+ self.skip -= 1
+ local_rank_offset += self.local_size
+ local_rank_offset -= len(curr_idx)
+
+ #def __len__(self):
+ # raise ValueError('should not be called')
+
+class ScaleNodeSplitSampler(Sampler):
+ def __init__(self, dataset, shuffle=False, random_seed=6, skip=0,
+ prepare_t_versions=[],
+ overwrite_dataset_len=None,
+ start_offset=0,
+ prepare_queue_len=0,
+ queue=None,
+ ):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_mpi_size()
+ self.local_size = get_mpi_local_size()
+ self.node_size = self.world_size // self.local_size
+ self.rank = get_mpi_rank()
+ self.node_idx = self.rank // self.local_size
+ self.local_rank = get_mpi_local_rank()
+ #self.next_epoch_skip_shuffle = first_epoch_skip_shuffle
+ self.overwrite_dataset_len = overwrite_dataset_len
+
+ # only be used when shuffle = True and first_epoch_skip_shuffle = True
+ self.prepare = None
+ self.prepare_t_versions = prepare_t_versions
+ self.enable_prepare = True
+ self.skip = skip
+ self.queue = queue
+ self.start_offset = start_offset
+ self.prepare_queue_len = prepare_queue_len
+
+ def get_shufle_idx(self, n):
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(n, generator=g)
+ self.random_seed += 99
+ return random_idx
+
+ def __iter__(self):
+ if self.skip > 0:
+ logging.info('we will skip {}'.format(self.skip))
+ idx_end_at = 0
+ if self.overwrite_dataset_len:
+ # in vl-l sampler, we need to sample only the vl part, which is the
+ # first part
+ num = self.overwrite_dataset_len
+ idx_end_at = num
+ assert self.start_offset == 0
+ else:
+ idx_end_at = len(self.dataset)
+ num = idx_end_at - self.start_offset
+ logging.info('num sample = {}'.format(num))
+ num_on_node = (num + self.node_size - 1) // self.node_size
+ node_offset = num_on_node * self.node_idx + self.start_offset
+ chunk_size = 1048576
+ chunk_size = chunk_size // self.local_size * self.local_size
+ num_each_tsv_file = self.dataset.get_num_each_tsv()
+ tsv_groups = construct_groups_by_chunk(num_each_tsv_file, node_offset, num_on_node, chunk_size)
+ for t in tsv_groups[:-1]:
+ assert t['start_idx'] < idx_end_at
+ assert t['end_idx'] < idx_end_at
+ t = tsv_groups[-1]
+ assert t['start_idx'] < idx_end_at
+ t['end_idx'] = min(idx_end_at, t['end_idx'])
+ if get_mpi_local_rank() == 0 and self.prepare is None:
+ self.prepare = PrepareData(self.dataset,
+ prepare_t_versions=self.prepare_t_versions,
+ #prepare_queue_len=self.prepare_queue_len,
+ queue=self.queue,
+ )
+ num_cache_group = 8
+ warmed_up = False
+ while True:
+ for idx_chunk, tsv_group in enumerate(tsv_groups):
+ chunk_start = tsv_group['start_idx']
+ chunk_end = tsv_group['end_idx']
+
+ chunk_idxs = list(range(chunk_start + self.local_rank, chunk_end, self.local_size))
+ all_sub_idx = self.get_shufle_idx(len(chunk_idxs)) if self.shuffle else range(len(chunk_idxs))
+
+ prepare_idx = int(random.random() * len(all_sub_idx))
+ prepare_idx = min(len(all_sub_idx) - 1, prepare_idx)
+ logging.info(f'will prepare at {prepare_idx}/{len(all_sub_idx)}')
+
+ for _idx, j in enumerate(all_sub_idx):
+ if self.prepare and self.skip <= 0 and (not warmed_up or _idx == prepare_idx) and self.enable_prepare:
+ if not warmed_up:
+ for cache_idx in range(num_cache_group):
+ self.prepare.prepare(tsv_groups[(idx_chunk + cache_idx)%len(tsv_groups)]['all_tsv_idx'])
+ warmed_up = True
+ else:
+ cache_idx = num_cache_group - 1
+ self.prepare.prepare(tsv_groups[(idx_chunk + cache_idx)%len(tsv_groups)]['all_tsv_idx'])
+ i = chunk_idxs[j]
+ if self.skip <= 0:
+ yield i
+ else:
+ self.skip -= 1
+
+ #def __len__(self):
+ # raise ValueError('should not be called')
+
+class NodeSplitSampler(Sampler):
+ def __init__(self, dataset, shuffle, random_seed, first_epoch_skip_shuffle=False,
+ prepare_t_versions=[],
+ skip=0,
+ ):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_mpi_size()
+ self.local_size = get_mpi_local_size()
+ self.node_size = self.world_size // self.local_size
+ self.rank = get_mpi_rank()
+ self.node_idx = self.rank // self.local_size
+ self.local_rank = get_mpi_local_rank()
+ self.next_epoch_skip_shuffle = first_epoch_skip_shuffle
+
+ # only be used when shuffle = True and first_epoch_skip_shuffle = True
+ self.prepare = None
+ self.prepare_t_versions = prepare_t_versions
+ self.skip = skip
+
+ def get_index_on_node(self):
+ # there is no need to cache source_list as we only call this function
+ # once in the whole training life-time
+ idx_split = self.dataset.get_composite_source_idx()
+ idx_split = list(enumerate(idx_split))
+ idx_split = torch.tensor(idx_split)
+ if self.shuffle:
+ random_idx = self.get_shufle_idx(len(idx_split))
+ idx_split = idx_split[random_idx]
+ max_split = idx_split[:, 1].max() + 1
+ priority = self.get_shufle_idx(max_split)
+ sort_idx = torch.argsort(priority[idx_split[:, 1]])
+ idx_split = idx_split[sort_idx]
+ num_idx_on_node = (len(idx_split) + self.node_size - 1) // self.node_size
+ offset = num_idx_on_node * self.node_idx
+ offset_end = offset + num_idx_on_node
+ offset_end = min(offset_end, len(idx_split))
+ if self.shuffle and self.next_epoch_skip_shuffle:
+ unique_split_index = ordered_unique(idx_split[offset:offset_end, 1].tolist())
+ logging.info(unique_split_index)
+ if get_mpi_local_rank() == 0:
+ self.prepare = PrepareData(self.dataset,
+ prepare_t_versions=self.prepare_t_versions,
+ )
+ self.prepare.prepare(list(unique_split_index))
+ return idx_split[offset:offset_end, 0]
+
+ def get_shufle_idx(self, n):
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(n, generator=g)
+ self.random_seed += 99
+ return random_idx
+
+ def get_index_on_rank(self, idx_on_node):
+ if self.shuffle:
+ if not self.next_epoch_skip_shuffle:
+ curr_idx_on_node = idx_on_node[self.get_shufle_idx(len(idx_on_node))]
+ else:
+ curr_idx_on_node = idx_on_node
+ self.next_epoch_skip_shuffle = False
+ else:
+ curr_idx_on_node = idx_on_node
+ idx_rank_size = (len(curr_idx_on_node) + self.local_size - 1) // self.local_size
+ offset = idx_rank_size * self.local_rank
+ offset_end = offset + idx_rank_size
+ offset_end = min(offset_end, len(curr_idx_on_node))
+ curr_idx_on_node = curr_idx_on_node.tolist()
+ for i in range(offset, offset_end):
+ yield curr_idx_on_node[i]
+
+ def __iter__(self):
+ self.curr_idx = 0
+ idx_on_node = self.get_index_on_node()
+ if self.skip > 0:
+ logging.info('we will skip {}'.format(self.skip))
+ while True:
+ for i in self.get_index_on_rank(idx_on_node):
+ if self.skip <= 0:
+ yield i
+ else:
+ self.skip -= 1
+
+ def __len__(self):
+ return 100000
+ #def __len__(self):
+ # raise ValueError('should not be called')
+
+class RankSplitSampler(Sampler):
+ def __init__(self, dataset, shuffle, random_seed):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_mpi_size()
+ self.rank = get_mpi_rank()
+
+ def get_index(self):
+ source_list = self.dataset.get_composite_source_idx()
+ idx_split = list(enumerate(source_list))
+ idx_split = torch.tensor(idx_split)
+ if self.shuffle:
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(len(idx_split), generator=g)
+ idx_split = idx_split[random_idx]
+ sort_idx = torch.argsort(idx_split[:, 1])
+ idx_split = idx_split[sort_idx]
+ rank_size = (len(idx_split) + self.world_size - 1) // self.world_size
+ offset = rank_size * self.rank
+ offset_end = offset + rank_size
+ offset_end = min(offset_end, len(idx_split))
+ return idx_split[offset:offset_end, 0].tolist()
+
+ def __iter__(self):
+ self.curr_idx = 0
+ all_idx = self.get_index()
+ while True:
+ if self.curr_idx >= len(all_idx):
+ self.curr_idx -= len(all_idx)
+ yield all_idx[self.curr_idx]
+ self.curr_idx += 1
+
+ #def __len__(self):
+ # raise ValueError('should not be called')
+
+
+class PrepareDataFileQueue(object):
+ def __init__(self, folder):
+ self.folder = folder
+ from utils.common import ensure_remove_dir, ensure_directory
+ logging.info('cleaning the folder of {}'.format(folder))
+ ensure_remove_dir(folder)
+ ensure_directory(folder)
+ self.iter = 0
+ self.curr_num_fnames = []
+
+ def put(self, ls):
+ fname = op.join(self.folder, str(self.iter))
+ self.iter += 1
+ if isinstance(ls, str):
+ ls = [ls]
+ from utils.tsv_io import write_to_file
+ write_to_file('\n'.join(ls), fname)
+
+ def get(self):
+ # get should not rely on the variable from put() as this function may be executed in anohter process
+ import glob
+ while True:
+ if len(self.curr_num_fnames) == 0:
+ fnames = glob.glob(op.join(self.folder, '*'))
+ if len(fnames) == 0:
+ time.sleep(10)
+ continue
+ basenames = [op.basename(f) for f in fnames]
+ num_fnames = [(int(b), f) for b, f in zip(basenames, fnames) if 'tmp' not in b]
+ #num_fnames = [(int(op.basename(f)), f) for f in fnames]
+ num_fnames = sorted(num_fnames, key=lambda x: x[0])
+ self.curr_num_fnames.extend(num_fnames)
+ fn = self.curr_num_fnames[0][1]
+ ls = load_list_file(fn)
+ from utils.common import ensure_remove_file
+ ensure_remove_file(fn)
+ del self.curr_num_fnames[0]
+ return ls
+
+def create_prepare_tsv_file_process(max_len=0):
+ use_thread = True
+ if use_thread:
+ import threading
+ import queue
+ prepare_queue = queue.Queue()
+ p = threading.Thread(
+ target=prepare_tsv_file_process, args=(prepare_queue, max_len),
+ daemon=True,
+ )
+ p.start()
+ else:
+ prepare_queue = mp.Queue()
+ p = mp.Process(
+ target=prepare_tsv_file_process, args=(prepare_queue, max_len),
+ daemon=True,
+ )
+ p.start()
+ return p, prepare_queue
+
+def prepare_tsv_file_process(queue, max_len=0):
+ if os.environ.get('QD_TSV_USE_FUSE'):
+ if int(os.environ['QD_TSV_USE_FUSE']):
+ ftype = 'fuser'
+ else:
+ ftype = 'blobfuse'
+ else:
+ ftype = 'blobfuse'
+
+ if ftype == 'fuser':
+ from utils.cloud_storage import create_cloud_fuse
+ fuser = create_cloud_fuse()
+ logging.info('ftype = {}'.format(ftype))
+
+ prepared = []
+
+ while True:
+ start = time.time()
+ fnames = queue.get()
+ end = time.time()
+ if (end - start) > 5:
+ logging.info('waiting {} to get a new tsv to prepare'.format(
+ end - start))
+ curr_fs = []
+ for fname in fnames:
+ curr_fs.append(fname)
+ if fname.endswith('.tsv'):
+ lineidx8b = get_tsv_lineidx_8b(fname)
+ curr_fs.append(lineidx8b)
+
+ def unprepare(info):
+ logging.info('unprepare {}'.format(info['fnames']))
+ if ftype == 'blobfuse':
+ for f in info['fps']:
+ f.close()
+ logging.info('unprepared {}'.format(info['fnames']))
+ else:
+ to_remove = []
+ for f in info['fnames']:
+ if all(f not in fs['fnames'] for fs in prepared):
+ to_remove.append(f)
+ fuser.ensure_del_cache(f)
+ logging.info('unprepared {}'.format(to_remove))
+
+ sames = [i for i, p in enumerate(prepared)
+ if all(f in p['fnames'] for f in curr_fs)]
+ if len(sames) > 0 and ftype == 'blobfuse':
+ # if it is cloud-fuse, we will check if the file exists in disk
+ i = sames[0]
+ p = prepared[i]
+ del prepared[i]
+ prepared.append(p)
+ logging.info('no need to prepare {} as it prepared'.format(
+ curr_fs
+ ))
+ continue
+
+ while max_len > 0 and len(prepared) >= max_len:
+ unprepare(prepared.pop(0))
+
+ logging.info('prepare {}'.format(curr_fs))
+ start = time.time()
+ if ftype == 'blobfuse':
+ info = {
+ 'fnames': curr_fs,
+ 'fps': [exclusive_open_to_read(x) for x in curr_fs]
+ }
+ prepared.append(info)
+ else:
+ info = {
+ 'fnames': curr_fs
+ }
+ if len(info['fnames']) > 0:
+ prepared.append(info)
+ fuser.ensure_cache(curr_fs, touch_cache_if_exist=True)
+ logging.info('use {}s, prepared {}; max len = {}; curr len = {}; all prepared = {}'.format(
+ time.time() - start,
+ curr_fs,
+ max_len,
+ len(prepared),
+ ';'.join([','.join(p['fnames']) for p in prepared]),
+ ))
+ time.sleep(random.random() * 5)
+
+def ordered_unique(sequence):
+ seen = set()
+ return [x for x in sequence if not (x in seen or seen.add(x))]
+
+class PrepareData(object):
+ fuser = None
+ def __init__(self, dataset, prepare_t_versions=[],
+ fixed_samples_in_node=False,
+ disable_prepare=None,
+ disable_garbage_collection=False,
+ prepare_queue_len=0,
+ queue=None,
+ ):
+ self.prepare_files = None
+ #self.prepare_process = None
+ self.dataset = dataset
+ self.prepare_t_versions = prepare_t_versions
+ #self.fixed_samples_in_node = fixed_samples_in_node
+ self.disable_prepare = disable_prepare or (queue is None)
+ #self.prepare_queue_len = prepare_queue_len
+ self.queue = queue
+ #assert queue is not None or disable_prepare
+
+ def get_composite_source_files(self):
+ data = self.dataset.dataset.data
+ split = self.dataset.dataset.split
+ dataset = TSVDataset(data)
+ result = []
+ for t, version in self.prepare_t_versions:
+ tsv = dataset.get_data(split, t, version)
+ if QDFile.isfile(tsv):
+ result.append([(tsv,0)])
+ else:
+ x_tsv = dataset.get_data(split + 'X', t, version)
+ assert op.isfile(x_tsv)
+ result.append(TSVFile(x_tsv))
+ return result
+
+ def prepare(self, split):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ if isinstance(split, (list, tuple)):
+ tsv_files = [ps[s][0] for s in split for ps in self.prepare_files]
+ else:
+ tsv_files = [ps[split][0] for ps in self.prepare_files]
+ logging.info('send to prepare: {}'.format(','.join(tsv_files)))
+ q.put(tsv_files)
+
+ def prepare_all(self, tsv_idx_start=0):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ tsv_files = []
+ for ps in self.prepare_files:
+ for i in range(tsv_idx_start, len(ps)):
+ tsv_files.append(ps[i][0])
+ assert len(tsv_files) > 0, 'maybe bug?'
+ q.put(tsv_files)
+
+ def ensure_init_prepare(self):
+ if self.prepare_files is None:
+ self.prepare_files = self.get_composite_source_files()
+ assert self.queue is not None
+ self.prepare_queue = self.queue
+
+class PrepareData_old(object):
+ fuser = None
+ def __init__(self, dataset, prepare_t_versions=[],
+ fixed_samples_in_node=False,
+ disable_prepare=None,
+ disable_garbage_collection=False,
+ prepare_queue_len=0,
+ queue=None,
+ ):
+ self.prepare_files = None
+ #self.prepare_process = None
+ self.dataset = dataset
+ self.prepare_t_versions = prepare_t_versions
+ #self.fixed_samples_in_node = fixed_samples_in_node
+ self.disable_prepare = disable_prepare or (queue is None)
+ #self.prepare_queue_len = prepare_queue_len
+ self.queue = queue
+ #assert queue is not None or disable_prepare
+
+ def get_composite_source_files(self):
+ data = self.dataset.dataset.data
+ split = self.dataset.dataset.split
+ dataset = TSVDataset(data)
+ result = []
+ for t, version in self.prepare_t_versions:
+ tsv = dataset.get_data(split, t, version)
+ if QDFile.isfile(tsv):
+ result.append([tsv])
+ else:
+ x_tsv = dataset.get_data(split + 'X', t, version)
+ assert op.isfile(x_tsv)
+ result.append(load_list_file(x_tsv))
+ return result
+
+ def prepare(self, split):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ #size = q.qsize()
+ #if size > 100:
+ #logging.info('prepare queue is too long {}'.format(size))
+ if isinstance(split, (list, tuple)):
+ tsv_files = [ps[s] for s in split for ps in self.prepare_files]
+ else:
+ tsv_files = [ps[split] for ps in self.prepare_files]
+ logging.info('send to prepare: {}'.format(','.join(tsv_files)))
+ q.put(tsv_files)
+
+ def prepare_all(self, tsv_idx_start=0):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ tsv_files = []
+ for ps in self.prepare_files:
+ tsv_files.extend(ps[tsv_idx_start:])
+ assert len(tsv_files) > 0, 'maybe bug?'
+ q.put(tsv_files)
+
+ def ensure_init_prepare(self):
+ if self.prepare_files is None:
+ self.prepare_files = self.get_composite_source_files()
+ assert self.queue is not None
+ self.prepare_queue = self.queue
+ #if self.prepare_process is None:
+ #if self.fixed_samples_in_node:
+ #max_len = 0
+ #else:
+ #max_len = self.prepare_queue_len
+ #logging.info('creating prepare thread from PrepareData')
+ #p, prepare_queue = create_prepare_tsv_file_process(
+ #max_len=max_len,
+ #)
+ #self.prepare_process = p
+ #self.prepare_queue = prepare_queue
+
+def create_download_worker(queue, max_len=0):
+ p = mp.Process(
+ target=prepare_tsv_file_process, args=(queue, max_len),
+ daemon=True,
+ )
+ p.start()
+ return p
+
+class SplitBySplitSampler(Sampler):
+ def __init__(self, dataset, group_size=1, shuffle=True,
+ fixed_samples_in_node=False,
+ random_seed=9,
+ skip=0,
+ prepare_t_versions=[],
+ disable_prepare=None,
+ ):
+ print_frame_info()
+ self.dataset = dataset
+ self.group_size = group_size
+ self.random_seed = random_seed
+ self.shuffle = shuffle
+
+ self.rank = get_mpi_rank()
+ self.local_rank = get_mpi_local_rank()
+ self.world_size = get_mpi_size()
+ self.local_size = get_mpi_local_size()
+
+ self.node_size = self.world_size // self.local_size
+ self.node_idx = self.rank // self.local_size
+
+ self.shuffle_group_process = None
+
+ self.prepare_process = None
+ self.prepare_queue = None
+ self.prepare_files = None
+ # currently, we only support to prepare one kind of files, but it could
+ # be extendeed to multiple files if we need
+ self.prepare_t_versions = prepare_t_versions
+ self.sub_process_create_shuffle = False
+ self._idx_split = None
+ self.iter_shuffle_group = None
+
+ self.curr_group_buffers = None
+ self.next_group_index = 0
+ self.cache_group_index_on_node = None
+
+ self.disable_prepare = disable_prepare
+ self.get_group_process = None
+ self.fixed_samples_in_node = fixed_samples_in_node
+ self.skip = skip
+
+ def get_composite_source_idx(self):
+ return self.dataset.get_composite_source_idx()
+
+ def get_composite_source_files(self):
+ data = self.dataset.dataset.data
+ split = self.dataset.dataset.split
+ dataset = TSVDataset(data)
+ result = []
+ for t, version in self.prepare_t_versions:
+ tsv = dataset.get_data(split, t, version)
+ if op.isfile(tsv):
+ result.append([tsv])
+ else:
+ x_tsv = dataset.get_data(split + 'X', t, version)
+ assert op.isfile(x_tsv)
+ result.append(load_list_file(x_tsv))
+ return result
+
+ def load_idx_split(self):
+ logging.info('loading source list')
+ source_list = self.get_composite_source_idx()
+ logging.info('loaded source list')
+ idx_split = list(enumerate(source_list))
+ idx_split = torch.tensor(idx_split)
+ return idx_split
+
+ @property
+ def idx_split(self):
+ if self._idx_split is None:
+ self._idx_split = self.load_idx_split()
+ #self._idx_split.share_memory_()
+ return self._idx_split
+
+ def get_shufle_idx(self, n):
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(n, generator=g)
+ self.random_seed += 99
+ return random_idx
+
+ def get_group_index_on_node_random(self):
+ idx_split = self.idx_split
+
+ max_split = idx_split[:, 1].max() + 1
+ priority = self.get_shufle_idx(max_split)
+
+ random_idx = self.get_shufle_idx(len(idx_split))
+ idx_split = idx_split[random_idx]
+
+ idx_split = torch.cat([idx_split[idx_split[:, 1] == p] for p in priority])
+
+ num_idx_on_node = (len(idx_split) + self.node_size - 1) // self.node_size
+ offset = num_idx_on_node * self.node_idx
+ offset_end = offset + num_idx_on_node
+ offset_end = min(offset_end, len(idx_split))
+ idx_split = idx_split[offset:offset_end]
+
+ unique_split_index = ordered_unique(idx_split[:, 1].tolist())
+ logging.info(unique_split_index)
+ result = [
+ {
+ 'idx_in_group': idx_split[idx_split[:, 1] == s][:, 0].tolist(),
+ 'split_in_group': s,
+ }
+ for s in unique_split_index
+ ]
+ return result
+
+ def get_group_index_on_node(self):
+ if self.shuffle and not self.fixed_samples_in_node:
+ return self.get_group_index_on_node_random()
+ elif self.shuffle and self.fixed_samples_in_node:
+ if self.cache_group_index_on_node is None:
+ self.cache_group_index_on_node = self.get_group_index_on_node_random()
+ idx = self.get_shufle_idx(len(self.cache_group_index_on_node))
+ group_in_node = [self.cache_group_index_on_node[i] for i in idx]
+ for g in group_in_node:
+ idx = self.get_shufle_idx(len(g['idx_in_group']))
+ g['idx_in_group'] = [g['idx_in_group'][i] for i in idx]
+ return group_in_node
+ else:
+ if self.cache_group_index_on_node is None:
+ self.cache_group_index_on_node = self.get_group_index_on_node_random()
+ return self.cache_group_index_on_node
+
+ def get_next_group_index_on_node(self):
+ if self.curr_group_buffers is None:
+ self.curr_group_buffers = self.get_group_index_on_node()
+ self.next_group_index = 0
+ if self.next_group_index >= len(self.curr_group_buffers):
+ self.curr_group_buffers = self.get_group_index_on_node()
+ self.next_group_index = 0
+ g = self.curr_group_buffers[self.next_group_index]
+ self.next_group_index += 1
+ return g
+
+ def get_group_thread(self, q):
+ while True:
+ if q.qsize() < 8:
+ g = self.get_next_group_index_on_node()
+ q.put(g)
+ else:
+ time.sleep(1)
+
+ def __iter__(self):
+ use_thread_to_get_group = True
+ if not use_thread_to_get_group:
+ assert self.skip == 0, 'not supported'
+ group_buffers = [self.get_next_group_index_on_node()
+ for _ in range(4)]
+ if self.local_rank == 0:
+ for g in group_buffers:
+ self.prepare(g['split_in_group'])
+ assert len(group_buffers) > 0
+ idx = self.local_rank
+ while True:
+ while idx >= len(group_buffers[0]['idx_in_group']):
+ idx -= len(group_buffers[0]['idx_in_group'])
+ group_buffers.pop(0)
+ new_g = self.get_next_group_index_on_node()
+ if self.local_rank == 0:
+ self.prepare(new_g['split_in_group'])
+ group_buffers.append(new_g)
+ r = group_buffers[0]['idx_in_group'][idx]
+ yield r
+ idx += self.local_size
+ else:
+ self.ensure_init_get_group_thread()
+ group_buffers = [self.get_group_queue.get()
+ for _ in range(4)]
+ if self.local_rank == 0:
+ for g in group_buffers:
+ if self.skip <= 0:
+ self.prepare(g['split_in_group'])
+ assert len(group_buffers) > 0
+ idx = self.local_rank
+ while True:
+ while idx >= len(group_buffers[0]['idx_in_group']):
+ idx -= len(group_buffers[0]['idx_in_group'])
+ group_buffers.pop(0)
+ start = time.time()
+ new_g = self.get_group_queue.get()
+ cost = time.time() - start
+ logging.info('time to get group index on node: {}'.format(cost))
+ if self.local_rank == 0 and self.skip <= 0:
+ self.prepare(new_g['split_in_group'])
+ group_buffers.append(new_g)
+ r = group_buffers[0]['idx_in_group'][idx]
+ if self.skip <= 0:
+ yield r
+ else:
+ self.skip -= 1
+ idx += self.local_size
+
+ def ensure_init_get_group_thread(self):
+ if self.get_group_process is None:
+ import threading
+ import queue
+ q = queue.Queue()
+ t = threading.Thread(
+ target=self.get_group_thread, args=(q,),
+ daemon=True,
+ )
+ t.start()
+ self.get_group_process = t
+ self.get_group_queue = q
+
+ def ensure_init_prepare(self):
+ if self.prepare_files is None:
+ self.prepare_files = self.get_composite_source_files()
+ if self.prepare_process is None:
+ max_len = 8 if not self.fixed_samples_in_node else 0
+ p, prepare_queue = create_prepare_tsv_file_process(
+ max_len=max_len)
+ self.prepare_process = p
+ self.prepare_queue = prepare_queue
+
+ def prepare(self, split):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ size = q.qsize()
+ if size > 100:
+ logging.info('prepare queue is too long {}'.format(size))
+ q.put([ps[split] for ps in self.prepare_files])
+
+ #def __len__(self):
+ # raise ValueError('should not be called')
+
+class AttachIterationNumberBatchSampler(object):
+ def __init__(self, batch_sampler, start_iter, num_iters,
+ gradient_accumulate=1):
+ self.batch_sampler = batch_sampler
+ self.curr_iter = start_iter
+ self.max_iter = num_iters
+ self.gradient_accumulate = gradient_accumulate
+
+ def __getattr__(self, att):
+ return getattr(self.batch_sampler, att)
+
+ def __iter__(self):
+ #if hasattr(self.batch_sampler, 'skip') and self.curr_iter > 0:
+ #logging.info('we will skip {} batches'.format(self.curr_iter))
+ #self.batch_sampler.skip(self.curr_iter)
+ for idx_batch, batch in enumerate(self.batch_sampler):
+ batch = [{'iteration': self.curr_iter,
+ 'idx': i,
+ 'max_iter': self.max_iter} for i in batch]
+ yield batch
+ if (idx_batch + 1) % self.gradient_accumulate == 0:
+ self.curr_iter += 1
+
+ def __len__(self):
+ return len(self.batch_sampler)
+
+class OrderedSplitSampler(Sampler):
+ def __init__(self, data_length):
+ curr_rank = get_mpi_rank()
+ world_size = get_mpi_size()
+ rank_size = (data_length + world_size - 1) // world_size
+ start = rank_size * curr_rank
+ end = start + rank_size
+ assert start >= 0 and start <= data_length
+ if curr_rank < world_size - 1:
+ assert end >= 0 and end <= data_length
+ end = min(end, data_length)
+ self.start = start
+ self.end = end
+
+ def __iter__(self):
+ return iter(range(self.start, self.end))
+
+ def __len__(self):
+ return self.end - self.start
+
+class BatchSampler(Sampler):
+ r"""Wraps another sampler to yield a mini-batch of indices.
+
+ Args:
+ sampler (Sampler): Base sampler.
+ batch_size (int): Size of mini-batch.
+ drop_last (bool): If ``True``, the sampler will drop the last batch if
+ its size would be less than ``batch_size``
+
+ Example:
+ >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
+ >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
+ """
+
+ def __init__(self, sampler, batch_size, drop_last):
+ if not isinstance(sampler, Sampler):
+ raise ValueError("sampler should be an instance of "
+ "torch.utils.data.Sampler, but got sampler={}"
+ .format(sampler))
+ if not isinstance(drop_last, bool):
+ raise ValueError("drop_last should be a boolean value, but got "
+ "drop_last={}".format(drop_last))
+ self.sampler = sampler
+ self.batch_size = batch_size
+ self.drop_last = drop_last
+
+ def __iter__(self):
+ batch = []
+ for idx in self.sampler:
+ batch.append(idx)
+ if len(batch) == self.batch_size:
+ yield batch
+ batch = []
+ if len(batch) > 0 and not self.drop_last:
+ yield batch
+
+ def __len__(self):
+ if self.drop_last:
+ return len(self.sampler) // self.batch_size
+ else:
+ return (len(self.sampler) + self.batch_size - 1) // self.batch_size
+
+class IterationBasedBatchSampler(BatchSampler):
+ """
+ Wraps a BatchSampler, resampling from it until
+ a specified number of iterations have been sampled
+ """
+
+ def __init__(self, batch_sampler, num_iterations, start_iter=0,
+ ):
+ self.batch_sampler = batch_sampler
+ self.num_iterations = num_iterations
+ self.start_iter = start_iter
+
+ if hasattr(batch_sampler, 'batch_size'):
+ self.batch_size = batch_sampler.batch_size
+
+ if hasattr(batch_sampler, 'drop_last'):
+ self.drop_last = batch_sampler.drop_last
+
+ def __iter__(self):
+ iteration = self.start_iter
+ while iteration <= self.num_iterations:
+ # if the underlying sampler has a set_epoch method, like
+ # DistributedSampler, used for making each process see
+ # a different split of the dataset, then set it
+ if hasattr(self.batch_sampler.sampler, "set_epoch"):
+ self.batch_sampler.sampler.set_epoch(iteration)
+ for batch in self.batch_sampler:
+ iteration += 1
+ if iteration > self.num_iterations:
+ break
+ yield batch
+
+ def __len__(self):
+ return self.num_iterations
+
+
+class DynamicBatchSampler(BatchSampler):
+ def __init__(self, sampler, get_batch_size, start_iter=0):
+ self.sampler = sampler
+ self.get_batch_size = get_batch_size
+ self.start_iter = start_iter
+
+ def __iter__(self):
+ batch = []
+ batch_size = None
+ curr_iter = self.start_iter
+ for idx in self.sampler:
+ batch.append(idx)
+ if batch_size is None:
+ batch_size = self.get_batch_size(curr_iter)
+ if len(batch) == batch_size:
+ yield batch
+ batch_size = None
+ curr_iter += 1
+ batch = []
+
+class InfinityDistributedSampler(Sampler):
+ def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True,
+ skip=0,
+ start_offset=0,
+ prepare_t_versions=[],
+ queue=None,
+ ):
+ if num_replicas is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ from utils.common import get_mpi_size
+ num_replicas = get_mpi_size()
+ if rank is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ from utils.common import get_mpi_rank
+ rank = get_mpi_rank()
+ self.dataset = dataset
+ self.num_replicas = num_replicas
+ self.rank = rank
+ self.epoch = 0
+ self.start_offset = start_offset
+ self.num_samples = int(math.ceil(self.get_effective_dataset_len() * 1.0 / self.num_replicas))
+ length_divisible = num_replicas
+ if length_divisible > 1:
+ import logging
+ logging.info('before making divisible = {}'.format(self.num_samples))
+ self.num_samples = ((self.num_samples + length_divisible - 1) //
+ length_divisible) * length_divisible
+ logging.info('adjust to = {}'.format(self.num_samples))
+ self.total_size = self.num_samples * self.num_replicas
+ self.shuffle = shuffle
+ self.skip = skip
+ self.num_passed = 0
+ # used in vl-l samplers
+ self.queue = queue
+ self.prepare = None
+ self.prepare_t_versions = prepare_t_versions
+
+ def get_effective_dataset_len(self):
+ return len(self.dataset) - self.start_offset
+
+ def state_dict(self):
+ return {'num_passed': self.num_passed}
+
+ def load_state_dict(self, info):
+ if info is not None:
+ self.skip = info['num_passed']
+
+ def __iter__(self):
+ self.num_passed = 0
+ if get_mpi_local_rank() == 0 and self.prepare is None:
+ self.prepare = PrepareData(self.dataset,
+ prepare_t_versions=self.prepare_t_versions,
+ queue=self.queue,
+ )
+ if self.start_offset == 0:
+ self.prepare.prepare_all()
+ else:
+ num_each_tsv_file = self.dataset.get_num_each_tsv()
+ start_tsv_idx = find_start_tsv_idx(num_each_tsv_file, self.start_offset)
+ self.prepare.prepare_all(start_tsv_idx)
+ while True:
+ if self.shuffle:
+ # deterministically shuffle based on epoch
+ g = torch.Generator()
+ g.manual_seed(self.epoch)
+ self.epoch += 1
+ indices = torch.randperm(self.get_effective_dataset_len(), generator=g).tolist()
+ else:
+ indices = torch.arange(self.get_effective_dataset_len()).tolist()
+
+ while len(indices) < self.total_size:
+ if 2 * len(indices) < self.total_size:
+ indices += indices
+ else:
+ indices += indices[: (self.total_size - len(indices))]
+ assert len(indices) == self.total_size
+
+ # subsample
+ offset = self.num_samples * self.rank
+ indices = indices[offset : offset + self.num_samples]
+ assert len(indices) == self.num_samples
+ for i in indices:
+ if self.skip > 0:
+ self.skip -= 1
+ else:
+ yield i + self.start_offset
+ self.num_passed += 1
+
+ def __len__(self):
+ raise ValueError('invalid')
+
+
+class DistributedSampler(Sampler):
+ # should only be used during testing
+ def __init__(self, dataset, num_replicas=None, rank=None, shuffle=True):
+ if num_replicas is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ from utils.common import get_mpi_size
+ num_replicas = get_mpi_size()
+ if rank is None:
+ if not dist.is_available():
+ raise RuntimeError("Requires distributed package to be available")
+ from utils.common import get_mpi_rank
+ rank = get_mpi_rank()
+ self.dataset = dataset
+ self.num_replicas = num_replicas
+ self.rank = rank
+ self.epoch = 0
+ self.num_samples = int(math.ceil(len(self.dataset) * 1.0 / self.num_replicas))
+ length_divisible = num_replicas
+ if length_divisible > 1:
+ logging.info('before making divisible = {}'.format(self.num_samples))
+ self.num_samples = ((self.num_samples + length_divisible - 1) //
+ length_divisible) * length_divisible
+ logging.info('adjust to = {}'.format(self.num_samples))
+ self.total_size = self.num_samples * self.num_replicas
+ self.shuffle = shuffle
+ logging.info('force shuffle = False')
+ self.shuffle = False
+
+ def __iter__(self):
+ if self.shuffle:
+ # deterministically shuffle based on epoch
+ g = torch.Generator()
+ g.manual_seed(self.epoch)
+ indices = torch.randperm(len(self.dataset), generator=g).tolist()
+ else:
+ indices = torch.arange(len(self.dataset)).tolist()
+
+ # add extra samples to make it evenly divisible
+ while len(indices) < self.total_size:
+ if 2 * len(indices) <= self.total_size:
+ indices += indices
+ else:
+ indices += indices[: (self.total_size - len(indices))]
+ indices += indices[: (self.total_size - len(indices))]
+ assert len(indices) == self.total_size
+
+ # subsample
+ offset = self.num_samples * self.rank
+ indices = indices[offset : offset + self.num_samples]
+ assert len(indices) == self.num_samples
+
+ return iter(indices)
+
+ def __len__(self):
+ return self.num_samples
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
+
+class ScaleNodeSplitVLPlusScaleNodeSplitLBatchSampler(Sampler):
+ def __init__(self,
+ dataset,
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ gradient_accumulate,
+ max_iter,
+ train_shuffle,
+ vl_data_rate,
+ prepare_t_versions=[],
+ vl_queue=None,
+ l_queue=None,
+ skip=0,
+ ):
+ print_frame_info()
+ self.dataset = dataset
+ self.one_fwd_batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ ]
+ self.gradient_accumulate = gradient_accumulate
+ self.max_iter = max_iter
+ self.train_shuffle = train_shuffle
+ self.rank = get_mpi_rank()
+ self.world_size = get_mpi_size()
+ self.batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu * gradient_accumulate,
+ one_fwd_batch_size_per_gpu_text_only * gradient_accumulate,
+ ]
+ self.prepare_t_versions = prepare_t_versions
+
+ self.vl_data_rate = vl_data_rate
+ self.vl_queue = vl_queue
+ self.l_queue = l_queue
+
+ self.skip_iter = skip
+ self.passed_iter = skip
+
+ def state_dict(self):
+ return {'passed_iter': self.passed_iter}
+
+ def load_state_dict(self, info):
+ self.skip_iter = info['passed_iter']
+
+ def __iter__(self):
+ logging.info('we will skip {}'.format(self.skip_iter))
+ vl_l_info = self.dataset.get_vl_l_info_from_cache()
+ vl_sampler = ScaleNodeSplitSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ prepare_t_versions=self.prepare_t_versions,
+ overwrite_dataset_len=vl_l_info['num_valid_vl_pair'],
+ queue=self.vl_queue,
+ )
+ l_sampler = ScaleNodeSplitSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ start_offset=vl_l_info['num_valid_vl_pair'],
+ prepare_t_versions=[('caption', None)],
+ queue=self.l_queue,
+ )
+ samplers = [vl_sampler, l_sampler]
+ samplers = [iter(s) for s in samplers]
+
+ if self.vl_data_rate is None:
+ self.vl_data_rate = vl_l_info['num_valid_vl_pair'] / vl_l_info['num_total']
+ logging.info(f'{self.vl_data_rate}')
+
+ if self.skip_iter > 0:
+ vl_sampler.enable_prepare = False
+ l_sampler.enable_prepare = False
+
+ passed_data = [0, 0]
+ for iteration in range(self.max_iter):
+ random.seed(self.passed_iter)
+ r = random.random()
+ source_idx = 0 if r <= self.vl_data_rate else 1
+ passed_data[source_idx] += 1
+ if (iteration % 100) == 0:
+ logging.info(f'vl iter = {passed_data[0]}; l iter={passed_data[1]}')
+
+ batch_size_per_gpu = self.batch_size_per_gpu[source_idx]
+ one_fwd_batch_size_per_gpu = self.one_fwd_batch_size_per_gpu[source_idx]
+ # we should run next(sampler) before skipping logic
+ ret = [next(samplers[source_idx]) for _ in range(batch_size_per_gpu)]
+
+ if self.skip_iter > 0:
+ self.skip_iter -= 1
+ else:
+ if not vl_sampler.enable_prepare:
+ vl_sampler.enable_prepare = True
+ if not l_sampler.enable_prepare:
+ l_sampler.enable_prepare = True
+ for i in range(self.gradient_accumulate):
+ yield [{
+ 'idx': j,
+ 'iteration': self.passed_iter,
+ } for j in ret[
+ i * one_fwd_batch_size_per_gpu:
+ (i + 1) * one_fwd_batch_size_per_gpu
+ ]]
+ self.passed_iter += 1
+
+ def __len__(self):
+ return self.max_iter * self.gradient_accumulate
+
+class ScaleNodeSplitVLPlusRandomLBatchSampler(Sampler):
+ def __init__(self,
+ dataset,
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ gradient_accumulate,
+ max_iter,
+ train_shuffle,
+ vl_data_rate,
+ prepare_t_versions=[],
+ vl_queue=None,
+ l_queue=None,
+ skip=0,
+ ):
+ print_frame_info()
+ self.dataset = dataset
+ self.one_fwd_batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ ]
+ self.gradient_accumulate = gradient_accumulate
+ self.max_iter = max_iter
+ self.train_shuffle = train_shuffle
+ self.rank = get_mpi_rank()
+ self.world_size = get_mpi_size()
+ self.batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu * gradient_accumulate,
+ one_fwd_batch_size_per_gpu_text_only * gradient_accumulate,
+ ]
+ self.prepare_t_versions = prepare_t_versions
+
+ self.vl_data_rate = vl_data_rate
+ self.vl_queue = vl_queue
+ self.l_queue = l_queue
+
+ self.skip_iter = skip
+ self.passed_iter = skip
+
+ def state_dict(self):
+ return {'passed_iter': self.passed_iter}
+
+ def load_state_dict(self, info):
+ self.skip_iter = info['passed_iter']
+
+ def __iter__(self):
+ logging.info('we will skip {}'.format(self.skip_iter))
+ vl_l_info = self.dataset.get_vl_l_info_from_cache()
+ vl_sampler = ScaleNodeSplitSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ prepare_t_versions=self.prepare_t_versions,
+ overwrite_dataset_len=vl_l_info['num_valid_vl_pair'],
+ queue=self.vl_queue,
+ )
+ l_sampler = InfinityDistributedSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ start_offset=vl_l_info['num_valid_vl_pair'],
+ prepare_t_versions=[('caption', None)],
+ queue=self.l_queue,
+ )
+ samplers = [vl_sampler, l_sampler]
+ samplers = [iter(s) for s in samplers]
+
+ if self.vl_data_rate is None:
+ self.vl_data_rate = vl_l_info['num_valid_vl_pair'] / vl_l_info['num_total']
+ logging.info(f'{self.vl_data_rate}')
+
+ passed_data = [0, 0]
+ if self.skip_iter > 0:
+ vl_sampler.enable_prepare = False
+ for iteration in range(self.max_iter):
+ random.seed(self.passed_iter)
+ r = random.random()
+ source_idx = 0 if r <= self.vl_data_rate else 1
+ passed_data[source_idx] += 1
+ if (iteration % 100) == 0 and self.skip_iter <= 0:
+ logging.info(f'vl iter = {passed_data[0]}; l iter={passed_data[1]}')
+
+ batch_size_per_gpu = self.batch_size_per_gpu[source_idx]
+ one_fwd_batch_size_per_gpu = self.one_fwd_batch_size_per_gpu[source_idx]
+ # we should run next(sampler) before skipping logic
+ ret = [next(samplers[source_idx]) for _ in range(batch_size_per_gpu)]
+
+ if self.skip_iter > 0:
+ self.skip_iter -= 1
+ else:
+ if not vl_sampler.enable_prepare:
+ vl_sampler.enable_prepare = True
+ for i in range(self.gradient_accumulate):
+ yield [{
+ 'idx': j,
+ 'iteration': self.passed_iter,
+ } for j in ret[
+ i * one_fwd_batch_size_per_gpu:
+ (i + 1) * one_fwd_batch_size_per_gpu
+ ]]
+ self.passed_iter += 1
+
+ def __len__(self):
+ return self.max_iter * self.gradient_accumulate
+
+class S3VLPlusS3LBatchSampler(Sampler):
+ def __init__(self,
+ dataset,
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ gradient_accumulate,
+ max_iter,
+ train_shuffle,
+ vl_data_rate,
+ prepare_t_versions=[],
+ disable_prepare=False,
+ vl_queue=None,
+ l_queue=None,
+ ):
+ print_frame_info()
+ self.dataset = dataset
+ self.one_fwd_batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu,
+ one_fwd_batch_size_per_gpu_text_only,
+ ]
+ self.gradient_accumulate = gradient_accumulate
+ self.max_iter = max_iter
+ self.train_shuffle = train_shuffle
+ self.rank = get_mpi_rank()
+ self.world_size = get_mpi_size()
+ self.batch_size_per_gpu = [
+ one_fwd_batch_size_per_gpu * gradient_accumulate,
+ one_fwd_batch_size_per_gpu_text_only * gradient_accumulate,
+ ]
+ self.prepare_t_versions = prepare_t_versions
+
+ self.vl_data_rate = vl_data_rate
+ self.disable_prepare = disable_prepare
+ self.vl_queue = vl_queue
+ self.l_queue = l_queue
+
+ self.skip_iter = 0
+ self.passed_iter = 0
+
+ def state_dict(self):
+ return {'passed_iter': self.passed_iter}
+
+ def load_state_dict(self, info):
+ self.skip_iter = info['passed_iter']
+
+ def __iter__(self):
+ logging.info('we will skip {}'.format(self.skip_iter))
+ vl_l_info = self.dataset.get_vl_l_info_from_cache()
+ vl_sampler = ScaleNodeSplitBySplitSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ prepare_t_versions=self.prepare_t_versions,
+ overwrite_dataset_len=vl_l_info['num_valid_vl_pair'],
+ disable_prepare=self.disable_prepare,
+ queue=self.vl_queue,
+ )
+ l_sampler = ScaleNodeSplitBySplitSampler(
+ self.dataset,
+ shuffle=self.train_shuffle,
+ prepare_t_versions=[('caption', None)],
+ start_offset=vl_l_info['num_valid_vl_pair'],
+ prepare_queue_len=0,
+ disable_prepare=self.disable_prepare,
+ queue=self.l_queue,
+ )
+ samplers = [vl_sampler, l_sampler]
+ samplers = [iter(s) for s in samplers]
+
+ if self.vl_data_rate is None:
+ self.vl_data_rate = vl_l_info['num_valid_vl_pair'] / vl_l_info['num_total']
+ logging.info(f'{self.vl_data_rate}')
+
+ passed_data = [0, 0]
+ for iteration in range(self.max_iter):
+ random.seed(self.passed_iter)
+ r = random.random()
+ source_idx = 0 if r <= self.vl_data_rate else 1
+ passed_data[source_idx] += 1
+ if (iteration % 10) == 0:
+ logging.info(f'vl iter = {passed_data[0]}; l iter={passed_data[1]}')
+
+ batch_size_per_gpu = self.batch_size_per_gpu[source_idx]
+ one_fwd_batch_size_per_gpu = self.one_fwd_batch_size_per_gpu[source_idx]
+ # we should run next(sampler) before skipping logic
+ ret = [next(samplers[source_idx]) for _ in range(batch_size_per_gpu)]
+
+ if self.skip_iter > 0:
+ self.skip_iter -= 1
+ else:
+ for i in range(self.gradient_accumulate):
+ yield [{
+ 'idx': j,
+ 'iteration': self.passed_iter,
+ } for j in ret[
+ i * one_fwd_batch_size_per_gpu:
+ (i + 1) * one_fwd_batch_size_per_gpu
+ ]]
+ self.passed_iter += 1
+
+ def __len__(self):
+ return self.max_iter * self.gradient_accumulate
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/sampler_utils.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/sampler_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cf7d0f2322700993df518954297cd7d814b2938
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/sampler_utils.py
@@ -0,0 +1,699 @@
+import time
+from utils.tsv_io import TSVDataset
+from utils.tsv_file import load_list_file
+from utils.tsv_io import get_tsv_lineidx, get_tsv_lineidx_8b
+from utils.common import exclusive_open_to_read
+import os.path as op
+import logging
+import math
+import random
+import torch
+import torch.distributed as dist
+from torch.utils.data.sampler import Sampler
+import os
+import torch.multiprocessing as mp
+from utils.dist import (
+ get_local_rank, get_local_size, get_rank, get_world_size)
+
+
+class RankSplitSampler(Sampler):
+ def __init__(self, dataset, shuffle, random_seed):
+ self.dataset = dataset
+ self.shuffle = shuffle
+ self.random_seed = random_seed
+
+ self.world_size = get_world_size()
+ self.rank = get_rank()
+
+ def get_index(self):
+ source_list = self.dataset.get_composite_source_idx()
+ idx_split = list(enumerate(source_list))
+ idx_split = torch.tensor(idx_split)
+ if self.shuffle:
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(len(idx_split), generator=g)
+ idx_split = idx_split[random_idx]
+ sort_idx = torch.argsort(idx_split[:, 1])
+ idx_split = idx_split[sort_idx]
+ rank_size = (len(idx_split) + self.world_size - 1) // self.world_size
+ offset = rank_size * self.rank
+ offset_end = offset + rank_size
+ offset_end = min(offset_end, len(idx_split))
+ return idx_split[offset:offset_end, 0].tolist()
+
+ def __iter__(self):
+ self.curr_idx = 0
+ all_idx = self.get_index()
+ while True:
+ if self.curr_idx >= len(all_idx):
+ self.curr_idx -= len(all_idx)
+ yield all_idx[self.curr_idx]
+ self.curr_idx += 1
+
+ def __len__(self):
+ raise ValueError('should not be called')
+
+
+def create_prepare_tsv_file_process(max_len=0):
+ use_thread = True
+ if use_thread:
+ import threading
+ import queue
+ prepare_queue = queue.Queue()
+ p = threading.Thread(
+ target=prepare_tsv_file_process, args=(prepare_queue, max_len),
+ daemon=True,
+ )
+ p.start()
+ else:
+ prepare_queue = mp.Queue()
+ p = mp.Process(
+ target=prepare_tsv_file_process, args=(prepare_queue, max_len),
+ daemon=True,
+ )
+ p.start()
+ return p, prepare_queue
+
+
+def prepare_tsv_file_process(queue, max_len=0):
+ if os.environ.get('QD_TSV_USE_FUSE'):
+ if int(os.environ['QD_TSV_USE_FUSE']):
+ ftype = 'fuser'
+ else:
+ ftype = 'blobfuse'
+ else:
+ ftype = 'blobfuse'
+
+ if ftype == 'fuser':
+ from utils.cloud_storage import create_cloud_fuse
+ fuser = create_cloud_fuse()
+ logging.info('ftype = {}'.format(ftype))
+
+ prepared = []
+
+ while True:
+ start = time.time()
+ fnames = queue.get()
+ end = time.time()
+ if (end - start) > 5:
+ logging.info('waiting {} to get a new tsv to prepare'.format(
+ end - start))
+ curr_fs = []
+ for fname in fnames:
+ curr_fs.append(fname)
+ if fname.endswith('.tsv'):
+ lineidx8b = get_tsv_lineidx_8b(fname)
+ curr_fs.append(lineidx8b)
+
+ def unprepare(info):
+ logging.info('unprepare {}'.format(info['fnames']))
+ if ftype == 'blobfuse':
+ for f in info['fps']:
+ f.close()
+ logging.info('unprepared {}'.format(info['fnames']))
+ # else:
+ # to_remove = []
+ # for f in info['fnames']:
+ # if all(f not in fs['fnames'] for fs in prepared):
+ # to_remove.append(f)
+ # fuser.ensure_del_cache(f)
+ # logging.info('unprepared {}'.format(to_remove))
+
+ sames = [i for i, p in enumerate(prepared)
+ if all(f in p['fnames'] for f in curr_fs)]
+ if len(sames) > 0 and ftype == 'blobfuse':
+ # if it is cloud-fuse, we will check if the file exists in disk
+ i = sames[0]
+ p = prepared[i]
+ del prepared[i]
+ prepared.append(p)
+ logging.info('no need to prepare {} as it prepared'.format(
+ curr_fs
+ ))
+ continue
+
+ while max_len > 0 and len(prepared) >= max_len:
+ unprepare(prepared.pop(0))
+
+ logging.info('prepare {}'.format(curr_fs))
+ start = time.time()
+ if ftype == 'blobfuse':
+ info = {
+ 'fnames': curr_fs,
+ 'fps': [exclusive_open_to_read(x) for x in curr_fs]
+ }
+ prepared.append(info)
+ else:
+ info = {
+ 'fnames': curr_fs
+ }
+ if len(info['fnames']) > 0:
+ prepared.append(info)
+ fuser.ensure_cache(curr_fs, touch_cache_if_exist=True)
+ logging.info('use {}s, prepared {}; max len = {}; curr len = {}; all prepared = {}'.format(
+ time.time() - start,
+ curr_fs,
+ max_len,
+ len(prepared),
+ ';'.join([','.join(p['fnames']) for p in prepared]),
+ ))
+ time.sleep(random.random() * 5)
+
+
+def ordered_unique(sequence):
+ seen = set()
+ return [x for x in sequence if not (x in seen or seen.add(x))]
+
+
+class PrepareData(object):
+ def __init__(self, dataset, prepare_t_versions=[],
+ fixed_samples_in_node=False,
+ disable_prepare=None,
+ ):
+ self.prepare_files = None
+ self.prepare_process = None
+ self.dataset = dataset
+ self.prepare_t_versions = prepare_t_versions
+ self.fixed_samples_in_node = fixed_samples_in_node
+ self.disable_prepare = disable_prepare
+
+ def get_composite_source_files(self):
+ root = self.dataset.root
+ assert self.dataset.is_composite
+ result = []
+ for t in ['visual_tsv', 'label_tsv', 'cap_tsv']:
+ tsv = getattr(self.dataset, t, None)
+ # tsv.ensure_initialized()
+ if tsv is not None:
+ result.append(
+ [f if op.exists(f) else op.join(root, f)
+ for f in tsv.file_list])
+
+ # data = self.dataset.dataset.data
+ # split = self.dataset.dataset.split
+ # dataset = TSVDataset(data)
+ # result = []
+ # for t, version in self.prepare_t_versions:
+ # tsv = dataset.get_data(split, t, version)
+ # if op.isfile(tsv):
+ # result.append([tsv])
+ # else:
+ # x_tsv = dataset.get_data(split + 'X', t, version)
+ # assert op.isfile(x_tsv)
+ # result.append(load_list_file(x_tsv))
+ return result
+
+ def prepare(self, split):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ size = q.qsize()
+ if size > 100:
+ logging.info('prepare queue is too long {}'.format(size))
+ q.put([ps[split] for ps in self.prepare_files])
+
+ def ensure_init_prepare(self):
+ if self.prepare_files is None:
+ self.prepare_files = self.get_composite_source_files()
+ if self.prepare_process is None:
+ max_len = 8 if not self.fixed_samples_in_node else 0
+ p, prepare_queue = create_prepare_tsv_file_process(
+ max_len=max_len)
+ self.prepare_process = p
+ self.prepare_queue = prepare_queue
+
+ if os.environ.get('QD_TSV_USE_FUSE') and \
+ int(os.environ['QD_TSV_USE_FUSE']) and \
+ not self.fixed_samples_in_node:
+ from utils.cloud_storage import create_cloud_fuse
+ fuser = create_cloud_fuse()
+ fuser.ensure_invoke_garbage_collect()
+ self.fuser = fuser
+
+
+class SplitBySplitSampler(Sampler):
+ # only used in training mode.
+ # prefer to use PrepareData(), but this class has already been used for a
+ # while and is working great. New approaches can leverage PrepareData, but
+ # at this moment, it is ok not to re-factor it
+ def __init__(self, dataset, group_size=1, shuffle=True,
+ fixed_samples_in_node=False,
+ random_seed=9,
+ prepare_t_versions=[],
+ disable_prepare=None,
+ ):
+ from utils.common import print_frame_info
+ print_frame_info()
+ self.dataset = dataset
+ self.group_size = group_size
+ self.random_seed = random_seed
+ self.shuffle = shuffle
+
+ self.rank = get_rank()
+ self.local_rank = get_local_rank()
+ self.world_size = get_world_size()
+ self.local_size = get_local_size()
+
+ self.node_size = self.world_size // self.local_size
+ self.node_idx = self.rank // self.local_size
+
+ self.shuffle_group_process = None
+
+ self.prepare_process = None
+ self.prepare_queue = None
+ self.prepare_files = None
+ # currently, we only support to prepare one kind of files, but it could
+ # be extendeed to multiple files if we need
+ self.prepare_t_versions = prepare_t_versions
+ self.sub_process_create_shuffle = False
+ self._idx_split = None
+ self.iter_shuffle_group = None
+
+ self.curr_group_buffers = None
+ self.next_group_index = 0
+ self.cache_group_index_on_node = None
+
+ self.disable_prepare = disable_prepare
+ self.get_group_process = None
+ self.fixed_samples_in_node = fixed_samples_in_node
+
+ def get_composite_source_idx(self):
+ return self.dataset.get_composite_source_idx()
+
+ def get_composite_source_files(self):
+ data = self.dataset.dataset.data
+ split = self.dataset.dataset.split
+ dataset = TSVDataset(data)
+ result = []
+ for t, version in self.prepare_t_versions:
+ tsv = dataset.get_data(split, t, version)
+ if op.isfile(tsv):
+ result.append([tsv])
+ else:
+ x_tsv = dataset.get_data(split + 'X', t, version)
+ assert op.isfile(x_tsv)
+ result.append(load_list_file(x_tsv))
+ return result
+
+ def load_idx_split(self):
+ logging.info('loading source list')
+ source_list = self.get_composite_source_idx()
+ logging.info('loaded source list')
+ idx_split = list(enumerate(source_list))
+ idx_split = torch.tensor(idx_split)
+ return idx_split
+
+ @property
+ def idx_split(self):
+ if self._idx_split is None:
+ self._idx_split = self.load_idx_split()
+ self._idx_split.share_memory_()
+ return self._idx_split
+
+ def get_shufle_idx(self, n):
+ g = torch.Generator()
+ g.manual_seed(self.random_seed)
+ random_idx = torch.randperm(n, generator=g)
+ self.random_seed += 99
+ return random_idx
+
+ def get_group_index_on_node_random(self):
+ idx_split = self.idx_split
+
+ max_split = idx_split[:, 1].max() + 1
+ priority = self.get_shufle_idx(max_split)
+
+ random_idx = self.get_shufle_idx(len(idx_split))
+ idx_split = idx_split[random_idx]
+
+ idx_split = torch.cat(
+ [idx_split[idx_split[:, 1] == p] for p in priority])
+
+ num_idx_on_node = (
+ len(idx_split) + self.node_size - 1) // self.node_size
+ offset = num_idx_on_node * self.node_idx
+ offset_end = offset + num_idx_on_node
+ offset_end = min(offset_end, len(idx_split))
+ idx_split = idx_split[offset:offset_end]
+
+ unique_split_index = ordered_unique(idx_split[:, 1].tolist())
+ logging.info(unique_split_index)
+ result = [
+ {
+ 'idx_in_group': idx_split[idx_split[:, 1] == s][:, 0].tolist(),
+ 'split_in_group': s,
+ }
+ for s in unique_split_index
+ ]
+ return result
+
+ def get_group_index_on_node(self):
+ if self.shuffle and not self.fixed_samples_in_node:
+ return self.get_group_index_on_node_random()
+ elif self.shuffle and self.fixed_samples_in_node:
+ if self.cache_group_index_on_node is None:
+ self.cache_group_index_on_node = self.get_group_index_on_node_random()
+ idx = self.get_shufle_idx(len(self.cache_group_index_on_node))
+ group_in_node = [self.cache_group_index_on_node[i] for i in idx]
+ for g in group_in_node:
+ idx = self.get_shufle_idx(len(g['idx_in_group']))
+ g['idx_in_group'] = [g['idx_in_group'][i] for i in idx]
+ return group_in_node
+ else:
+ if self.cache_group_index_on_node is None:
+ self.cache_group_index_on_node = self.get_group_index_on_node_random()
+ return self.cache_group_index_on_node
+
+ def get_next_group_index_on_node(self):
+ if self.curr_group_buffers is None:
+ self.curr_group_buffers = self.get_group_index_on_node()
+ self.next_group_index = 0
+ if self.next_group_index >= len(self.curr_group_buffers):
+ self.curr_group_buffers = self.get_group_index_on_node()
+ self.next_group_index = 0
+ g = self.curr_group_buffers[self.next_group_index]
+ self.next_group_index += 1
+ return g
+
+ def get_group_thread(self, q):
+ while True:
+ if q.qsize() < 8:
+ g = self.get_next_group_index_on_node()
+ q.put(g)
+ else:
+ time.sleep(1)
+
+ def __iter__(self):
+ use_thread_to_get_group = True
+ if not use_thread_to_get_group:
+ group_buffers = [self.get_next_group_index_on_node()
+ for _ in range(4)]
+ if self.local_rank == 0:
+ for g in group_buffers:
+ self.prepare(g['split_in_group'])
+ assert len(group_buffers) > 0
+ idx = self.local_rank
+ while True:
+ while idx >= len(group_buffers[0]['idx_in_group']):
+ idx -= len(group_buffers[0]['idx_in_group'])
+ group_buffers.pop(0)
+ new_g = self.get_next_group_index_on_node()
+ if self.local_rank == 0:
+ self.prepare(new_g['split_in_group'])
+ group_buffers.append(new_g)
+ r = group_buffers[0]['idx_in_group'][idx]
+ yield r
+ idx += self.local_size
+ else:
+ self.ensure_init_get_group_thread()
+ group_buffers = [self.get_group_queue.get()
+ for _ in range(4)]
+ if self.local_rank == 0:
+ for g in group_buffers:
+ self.prepare(g['split_in_group'])
+ assert len(group_buffers) > 0
+ idx = self.local_rank
+ while True:
+ while idx >= len(group_buffers[0]['idx_in_group']):
+ idx -= len(group_buffers[0]['idx_in_group'])
+ group_buffers.pop(0)
+ start = time.time()
+ new_g = self.get_group_queue.get()
+ cost = time.time() - start
+ logging.info(
+ 'time to get group index on node: {}'.format(cost))
+ if self.local_rank == 0:
+ self.prepare(new_g['split_in_group'])
+ group_buffers.append(new_g)
+ r = group_buffers[0]['idx_in_group'][idx]
+ yield r
+ idx += self.local_size
+
+ def ensure_init_get_group_thread(self):
+ if self.get_group_process is None:
+ import threading
+ import queue
+ q = queue.Queue()
+ t = threading.Thread(
+ target=self.get_group_thread, args=(q,),
+ daemon=True,
+ )
+ t.start()
+ self.get_group_process = t
+ self.get_group_queue = q
+
+ def ensure_init_prepare(self):
+ if self.prepare_files is None:
+ self.prepare_files = self.get_composite_source_files()
+ if self.prepare_process is None:
+ max_len = 8 if not self.fixed_samples_in_node else 0
+ p, prepare_queue = create_prepare_tsv_file_process(
+ max_len=max_len)
+ self.prepare_process = p
+ self.prepare_queue = prepare_queue
+
+ # if os.environ.get('QD_TSV_USE_FUSE') and \
+ # int(os.environ['QD_TSV_USE_FUSE']) and \
+ # not self.fixed_samples_in_node:
+ # from src.utils.cloud_storage import create_cloud_fuse
+ # fuser = create_cloud_fuse()
+ # fuser.ensure_invoke_garbage_collect()
+ # self.fuser = fuser
+
+ def prepare(self, split):
+ if self.disable_prepare:
+ return
+ self.ensure_init_prepare()
+ q = self.prepare_queue
+ size = q.qsize()
+ if size > 100:
+ logging.info('prepare queue is too long {}'.format(size))
+ q.put([ps[split] for ps in self.prepare_files])
+
+ def __len__(self):
+ raise ValueError('should not be called')
+
+
+class AttachIterationNumberBatchSampler(object):
+ def __init__(self, batch_sampler, start_iter, num_iters,
+ gradient_accumulate=1):
+ self.batch_sampler = batch_sampler
+ self.curr_iter = start_iter
+ self.max_iter = num_iters
+ self.gradient_accumulate = gradient_accumulate
+
+ def __getattr__(self, att):
+ return getattr(self.batch_sampler, att)
+
+ def __iter__(self):
+ # if hasattr(self.batch_sampler, 'skip') and self.curr_iter > 0:
+ # logging.info('we will skip {} batches'.format(self.curr_iter))
+ # self.batch_sampler.skip(self.curr_iter)
+ for idx_batch, batch in enumerate(self.batch_sampler):
+ batch = [{'iteration': self.curr_iter,
+ 'idx': i,
+ 'max_iter': self.max_iter} for i in batch]
+ yield batch
+ if (idx_batch + 1) % self.gradient_accumulate == 0:
+ self.curr_iter += 1
+
+ def __len__(self):
+ return len(self.batch_sampler)
+
+
+class OrderedSplitSampler(Sampler):
+ def __init__(self, data_length):
+ curr_rank = get_rank()
+ world_size = get_world_size()
+ rank_size = (data_length + world_size - 1) // world_size
+ start = rank_size * curr_rank
+ end = start + rank_size
+ assert start >= 0 and start <= data_length
+ if curr_rank < world_size - 1:
+ assert end >= 0 and end <= data_length
+ end = min(end, data_length)
+ self.start = start
+ self.end = end
+
+ def __iter__(self):
+ return iter(range(self.start, self.end))
+
+ def __len__(self):
+ return self.end - self.start
+
+
+class BatchSampler(Sampler):
+ r"""Wraps another sampler to yield a mini-batch of indices.
+
+ Args:
+ sampler (Sampler): Base sampler.
+ batch_size (int): Size of mini-batch.
+ drop_last (bool): If ``True``, the sampler will drop the last batch if
+ its size would be less than ``batch_size``
+
+ Example:
+ >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
+ >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
+ [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
+ """
+
+ def __init__(self, sampler, batch_size, drop_last):
+ if not isinstance(sampler, Sampler):
+ raise ValueError("sampler should be an instance of "
+ "torch.utils.data.Sampler, but got sampler={}"
+ .format(sampler))
+ if not isinstance(drop_last, bool):
+ raise ValueError("drop_last should be a boolean value, but got "
+ "drop_last={}".format(drop_last))
+ self.sampler = sampler
+ self.batch_size = batch_size
+ self.drop_last = drop_last
+
+ def __iter__(self):
+ batch = []
+ for idx in self.sampler:
+ batch.append(idx)
+ if len(batch) == self.batch_size:
+ yield batch
+ batch = []
+ if len(batch) > 0 and not self.drop_last:
+ yield batch
+
+ def __len__(self):
+ if self.drop_last:
+ return len(self.sampler) // self.batch_size
+ else:
+ return (len(self.sampler) + self.batch_size - 1) // self.batch_size
+
+
+class IterationBasedBatchSampler(BatchSampler):
+ """
+ Wraps a BatchSampler, resampling from it until
+ a specified number of iterations have been sampled
+ """
+
+ def __init__(self, batch_sampler, num_iterations, start_iter=0,
+ ):
+ self.batch_sampler = batch_sampler
+ self.num_iterations = num_iterations
+ self.start_iter = start_iter
+
+ if hasattr(batch_sampler, 'batch_size'):
+ self.batch_size = batch_sampler.batch_size
+
+ if hasattr(batch_sampler, 'drop_last'):
+ self.drop_last = batch_sampler.drop_last
+
+ def __iter__(self):
+ iteration = self.start_iter
+ while iteration <= self.num_iterations:
+ # if the underlying sampler has a set_epoch method, like
+ # DistributedSampler, used for making each process see
+ # a different split of the dataset, then set it
+ if hasattr(self.batch_sampler.sampler, "set_epoch"):
+ self.batch_sampler.sampler.set_epoch(iteration)
+ for batch in self.batch_sampler:
+ iteration += 1
+ if iteration > self.num_iterations:
+ break
+ yield batch
+
+ def __len__(self):
+ return self.num_iterations
+
+
+class DynamicBatchSampler(BatchSampler):
+ def __init__(self, sampler, get_batch_size, start_iter=0):
+ self.sampler = sampler
+ self.get_batch_size = get_batch_size
+ self.start_iter = start_iter
+
+ def __iter__(self):
+ batch = []
+ batch_size = None
+ curr_iter = self.start_iter
+ for idx in self.sampler:
+ batch.append(idx)
+ if batch_size is None:
+ batch_size = self.get_batch_size(curr_iter)
+ if len(batch) == batch_size:
+ yield batch
+ batch_size = None
+ curr_iter += 1
+ batch = []
+
+
+class DistributedSampler(Sampler):
+ """Sampler that restricts data loading to a subset of the dataset.
+ It is especially useful in conjunction with
+ :class:`torch.nn.parallel.DistributedDataParallel`. In such case, each
+ process can pass a DistributedSampler instance as a DataLoader sampler,
+ and load a subset of the original dataset that is exclusive to it.
+ .. note::
+ Dataset is assumed to be of constant size.
+ Arguments:
+ dataset: Dataset used for sampling.
+ num_replicas (optional): Number of processes participating in
+ distributed training.
+ rank (optional): Rank of the current process within num_replicas.
+ """
+
+ def __init__(
+ self, dataset, num_replicas=None, rank=None, shuffle=True,
+ length_divisible=1):
+ if num_replicas is None:
+ if not dist.is_available():
+ raise RuntimeError(
+ "Requires distributed package to be available")
+ num_replicas = get_world_size()
+ if rank is None:
+ if not dist.is_available():
+ raise RuntimeError(
+ "Requires distributed package to be available")
+ rank = get_rank()
+ self.dataset = dataset
+ self.num_replicas = num_replicas
+ self.rank = rank
+ self.epoch = 0
+ self.num_samples = int(math.ceil(
+ len(self.dataset) * 1.0 / self.num_replicas))
+ if length_divisible > 1:
+ import logging
+ logging.info(
+ 'before making divisible = {}'.format(self.num_samples))
+ self.num_samples = (
+ (self.num_samples + length_divisible - 1) //
+ length_divisible) * length_divisible
+ logging.info('adjust to = {}'.format(self.num_samples))
+ self.total_size = self.num_samples * self.num_replicas
+ self.shuffle = shuffle
+
+ def __iter__(self):
+ if self.shuffle:
+ # deterministically shuffle based on epoch
+ g = torch.Generator()
+ g.manual_seed(self.epoch)
+ indices = torch.randperm(len(self.dataset), generator=g).tolist()
+ else:
+ indices = torch.arange(len(self.dataset)).tolist()
+
+ # add extra samples to make it evenly divisible
+ assert (self.total_size - len(indices)) <= len(indices), 'not implemented'
+ indices += indices[: (self.total_size - len(indices))]
+ assert len(indices) == self.total_size
+
+ # subsample
+ offset = self.num_samples * self.rank
+ indices = indices[offset: offset + self.num_samples]
+ assert len(indices) == self.num_samples
+
+ return iter(indices)
+
+ def __len__(self):
+ return self.num_samples
+
+ def set_epoch(self, epoch):
+ self.epoch = epoch
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_functional.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_functional.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4b10ffe0a2eeed92f04e275550a7cdb2d10dbb2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_functional.py
@@ -0,0 +1,116 @@
+import numbers
+import torch
+import cv2
+import numpy as np
+import PIL
+from PIL import Image
+
+def _is_tensor_clip(clip):
+ return torch.is_tensor(clip) and clip.ndimension() == 4
+
+
+def crop_clip(clip, min_h, min_w, h, w):
+ if isinstance(clip[0], np.ndarray):
+ cropped = [img[min_h:min_h + h, min_w:min_w + w, :] for img in clip]
+
+ elif isinstance(clip[0], PIL.Image.Image):
+ cropped = [
+ img.crop((min_w, min_h, min_w + w, min_h + h)) for img in clip
+ ]
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ 'but got list of {0}'.format(type(clip[0])))
+ return cropped
+
+
+def to_grayscale(img, num_output_channels=1):
+ """Convert image to grayscale version of image.
+
+ Args:
+ img (PIL Image): Image to be converted to grayscale.
+
+ Returns:
+ PIL Image: Grayscale version of the image.
+ if num_output_channels = 1 : returned image is single channel
+
+ if num_output_channels = 3 : returned image is 3 channel with r = g = b
+ """
+ if not isinstance(img,PIL.Image.Image):
+ raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
+
+ if num_output_channels == 1:
+ img = img.convert('L')
+ elif num_output_channels == 3:
+ img = img.convert('L')
+ np_img = np.array(img, dtype=np.uint8)
+ np_img = np.dstack([np_img, np_img, np_img])
+ img = Image.fromarray(np_img, 'RGB')
+ else:
+ raise ValueError('num_output_channels should be either 1 or 3')
+
+ return img
+
+def resize_clip(clip, size, interpolation='bilinear'):
+ if isinstance(clip[0], np.ndarray):
+ if isinstance(size, numbers.Number):
+ im_h, im_w, im_c = clip[0].shape
+ # Min spatial dim already matches minimal size
+ if (im_w <= im_h and im_w == size) or (im_h <= im_w
+ and im_h == size):
+ return clip
+ new_h, new_w = get_resize_sizes(im_h, im_w, size)
+ size = (new_w, new_h)
+ else:
+ size = size[1], size[0]
+ if interpolation == 'bilinear':
+ np_inter = cv2.INTER_LINEAR
+ else:
+ np_inter = cv2.INTER_NEAREST
+ scaled = [
+ cv2.resize(img, size, interpolation=np_inter) for img in clip
+ ]
+ elif isinstance(clip[0], PIL.Image.Image):
+ if isinstance(size, numbers.Number):
+ im_w, im_h = clip[0].size
+ # Min spatial dim already matches minimal size
+ if (im_w <= im_h and im_w == size) or (im_h <= im_w
+ and im_h == size):
+ return clip
+ new_h, new_w = get_resize_sizes(im_h, im_w, size)
+ size = (new_w, new_h)
+ else:
+ size = size[1], size[0]
+ if interpolation == 'bilinear':
+ pil_inter = PIL.Image.NEAREST
+ else:
+ pil_inter = PIL.Image.BILINEAR
+ scaled = [img.resize(size, pil_inter) for img in clip]
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ 'but got list of {0}'.format(type(clip[0])))
+ return scaled
+
+
+def get_resize_sizes(im_h, im_w, size):
+ if im_w < im_h:
+ ow = size
+ oh = int(size * im_h / im_w)
+ else:
+ oh = size
+ ow = int(size * im_w / im_h)
+ return oh, ow
+
+
+def normalize(clip, mean, std, inplace=False):
+ if not _is_tensor_clip(clip):
+ raise TypeError('tensor is not a torch clip.')
+
+ if not inplace:
+ clip = clip.clone()
+
+ dtype = clip.dtype
+ mean = torch.as_tensor(mean, dtype=dtype, device=clip.device)
+ std = torch.as_tensor(std, dtype=dtype, device=clip.device)
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
+
+ return clip
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_transforms.py b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ec42830885bcbece2d6af9dcd7eb426f60fb89fa
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/data_utils/video_transforms.py
@@ -0,0 +1,596 @@
+import numbers
+import random
+import numpy as np
+import PIL
+import skimage.transform
+import torchvision
+import math
+import torch
+from PIL import Image
+
+from . import video_functional as F
+
+
+def my_convert_img(img):
+ """Converts (H, W, C) numpy.ndarray to (C, W, H) format
+ """
+ if len(img.shape) == 3:
+ img = img.transpose(2, 0, 1)
+ if len(img.shape) == 2:
+ img = np.expand_dims(img, 0)
+ return img
+
+
+class ClipToTensor(object):
+ """Convert a list of m (H x W x C) numpy.ndarrays in the range [0, 255]
+ to a torch.FloatTensor of shape (C x m x H x W) in the range [0, 1.0]
+ """
+
+ def __init__(self, channel_nb=3, div_255=True, numpy=False):
+ self.channel_nb = channel_nb
+ self.div_255 = div_255
+ self.numpy = numpy
+
+ def __call__(self, clip):
+ """
+ Args: clip (list of numpy.ndarray): clip (list of images)
+ to be converted to tensor.
+ """
+ # Retrieve shape
+ if isinstance(clip[0], np.ndarray):
+ h, w, ch = clip[0].shape
+ assert ch == self.channel_nb, 'Got {0} instead of 3 channels'.format(
+ ch)
+ elif isinstance(clip[0], Image.Image):
+ w, h = clip[0].size
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image\
+ but got list of {0}'.format(type(clip[0])))
+
+ np_clip = np.zeros([self.channel_nb, len(clip), int(h), int(w)])
+
+ # Convert
+ for img_idx, img in enumerate(clip):
+ if isinstance(img, np.ndarray):
+ pass
+ elif isinstance(img, Image.Image):
+ img = np.array(img, copy=False)
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image\
+ but got list of {0}'.format(type(clip[0])))
+ img = my_convert_img(img)
+ np_clip[:, img_idx, :, :] = img
+ if self.numpy:
+ if self.div_255:
+ np_clip = np_clip / 255
+ return np_clip
+
+ else:
+ tensor_clip = torch.from_numpy(np_clip)
+
+ if not isinstance(tensor_clip, torch.FloatTensor):
+ tensor_clip = tensor_clip.float()
+ if self.div_255:
+ tensor_clip = tensor_clip.div(255)
+ return tensor_clip
+
+
+class Compose(object):
+ """Composes several transforms
+
+ Args:
+ transforms (list of ``Transform`` objects): list of transforms
+ to compose
+ """
+
+ def __init__(self, transforms):
+ self.transforms = transforms
+
+ def __call__(self, clip):
+ for t in self.transforms:
+ clip = t(clip)
+ return clip
+
+
+class RandomHorizontalFlip(object):
+ """Horizontally flip the list of given images randomly with a given probability.
+
+ Args:
+ p (float): probability of the image being flipped. Default value is 0.5
+ """
+
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, clip):
+ """
+ Args:
+ img (PIL.Image or numpy.ndarray): List of images to be cropped
+ in format (h, w, c) in numpy.ndarray
+
+ Returns:
+ PIL.Image or numpy.ndarray: Randomly flipped clip
+ """
+ if random.random() < self.p:
+ if isinstance(clip[0], np.ndarray):
+ return [np.fliplr(img) for img in clip]
+ elif isinstance(clip[0], PIL.Image.Image):
+ return [
+ img.transpose(PIL.Image.FLIP_LEFT_RIGHT) for img in clip
+ ]
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ ' but got list of {0}'.format(type(clip[0])))
+ return clip
+
+ def __repr__(self):
+ return self.__class__.__name__ + '(p={})'.format(self.p)
+
+
+class RandomVerticalFlip(object):
+ """Vertically flip the list of given images randomly with a given probability.
+
+ Args:
+ p (float): probability of the image being flipped. Default value is 0.5
+ """
+
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, clip):
+ """
+
+ Args:
+ img (PIL.Image or numpy.ndarray): List of images to be flipped
+ in format (h, w, c) in numpy.ndarray
+
+ Returns:
+ PIL.Image or numpy.ndarray: Randomly flipped clip
+ """
+ if random.random() < self.p:
+ if isinstance(clip[0], np.ndarray):
+ return [np.flipud(img) for img in clip]
+ elif isinstance(clip[0], PIL.Image.Image):
+ return [
+ img.transpose(PIL.Image.FLIP_TOP_BOTTOM) for img in clip
+ ]
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ ' but got list of {0}'.format(type(clip[0])))
+ return clip
+
+ def __repr__(self):
+ return self.__class__.__name__ + '(p={})'.format(self.p)
+
+class RandomGrayscale(object):
+ """Randomly convert image to grayscale with a probability of p (default 0.1).
+ The image can be a PIL Image or a Tensor, in which case it is expected
+ to have [..., 3, H, W] shape, where ... means an arbitrary number of leading
+ dimensions
+ Args:
+ p (float): probability that image should be converted to grayscale.
+ Returns:
+ PIL Image or Tensor: Grayscale version of the input image with probability p and unchanged
+ with probability (1-p).
+ - If input image is 1 channel: grayscale version is 1 channel
+ - If input image is 3 channel: grayscale version is 3 channel with r == g == b
+ """
+ def __init__(self, p=0.1):
+ super().__init__()
+ self.p = p
+ def __call__(self,clip):
+ """
+ Args:
+ list of imgs (PIL Image or Tensor): Image to be converted to grayscale.
+ Returns:
+ PIL Image or Tensor: Randomly grayscaled image.
+ """
+ num_output_channels = 1 if clip[0].mode == 'L' else 3
+ if torch.rand(1) im_w or h > im_h:
+ error_msg = (
+ 'Initial image size should be larger then '
+ 'cropped size but got cropped sizes : ({w}, {h}) while '
+ 'initial image is ({im_w}, {im_h})'.format(
+ im_w=im_w, im_h=im_h, w=w, h=h))
+ raise ValueError(error_msg)
+
+ x1 = random.randint(0, im_w - w)
+ y1 = random.randint(0, im_h - h)
+ cropped = F.crop_clip(clip, y1, x1, h, w)
+
+ return cropped
+
+class RandomResizedCrop(object):
+ """Crop the given list of PIL Images to random size and aspect ratio.
+
+ A crop of random size (default: of 0.08 to 1.0) of the original size and a random
+ aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio is made. This crop
+ is finally resized to given size.
+ This is popularly used to train the Inception networks.
+
+ Args:
+ size: expected output size of each edge
+ scale: range of size of the origin size cropped
+ ratio: range of aspect ratio of the origin aspect ratio cropped
+ interpolation: Default: PIL.Image.BILINEAR
+ """
+
+ def __init__(self, size, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), interpolation='bilinear'):
+ if isinstance(size, (tuple, list)):
+ self.size = size
+ else:
+ self.size = (size, size)
+ if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
+ warnings.warn("range should be of kind (min, max)")
+
+ self.interpolation = interpolation
+ self.scale = scale
+ self.ratio = ratio
+
+ @staticmethod
+ def get_params(clip, scale, ratio):
+ """Get parameters for ``crop`` for a random sized crop.
+
+ Args:
+ img (list of PIL Image): Image to be cropped.
+ scale (tuple): range of size of the origin size cropped
+ ratio (tuple): range of aspect ratio of the origin aspect ratio cropped
+
+ Returns:
+ tuple: params (i, j, h, w) to be passed to ``crop`` for a random
+ sized crop.
+ """
+ if isinstance(clip[0], np.ndarray):
+ height, width, im_c = clip[0].shape
+ elif isinstance(clip[0], PIL.Image.Image):
+ width, height = clip[0].size
+ area = height * width
+
+ for _ in range(10):
+ target_area = random.uniform(*scale) * area
+ log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
+ aspect_ratio = math.exp(random.uniform(*log_ratio))
+
+ w = int(round(math.sqrt(target_area * aspect_ratio)))
+ h = int(round(math.sqrt(target_area / aspect_ratio)))
+
+ if 0 < w <= width and 0 < h <= height:
+ i = random.randint(0, height - h)
+ j = random.randint(0, width - w)
+ return i, j, h, w
+
+ # Fallback to central crop
+ in_ratio = float(width) / float(height)
+ if (in_ratio < min(ratio)):
+ w = width
+ h = int(round(w / min(ratio)))
+ elif (in_ratio > max(ratio)):
+ h = height
+ w = int(round(h * max(ratio)))
+ else: # whole image
+ w = width
+ h = height
+ i = (height - h) // 2
+ j = (width - w) // 2
+ return i, j, h, w
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip: list of img (PIL Image): Image to be cropped and resized.
+
+ Returns:
+ list of PIL Image: Randomly cropped and resized image.
+ """
+ i, j, h, w = self.get_params(clip, self.scale, self.ratio)
+ imgs = F.crop_clip(clip, i, j, h, w)
+ return F.resize_clip(clip, self.size, self.interpolation)
+ # return F.resized_crop(img, i, j, h, w, self.size, self.interpolation)
+
+ def __repr__(self):
+ interpolate_str = _pil_interpolation_to_str[self.interpolation]
+ format_string = self.__class__.__name__ + '(size={0}'.format(self.size)
+ format_string += ', scale={0}'.format(
+ tuple(round(s, 4) for s in self.scale))
+ format_string += ', ratio={0}'.format(
+ tuple(round(r, 4) for r in self.ratio))
+ format_string += ', interpolation={0})'.format(interpolate_str)
+ return format_string
+
+
+class RandomRotation(object):
+ """Rotate entire clip randomly by a random angle within
+ given bounds
+
+ Args:
+ degrees (sequence or int): Range of degrees to select from
+ If degrees is a number instead of sequence like (min, max),
+ the range of degrees, will be (-degrees, +degrees).
+
+ """
+
+ def __init__(self, degrees):
+ if isinstance(degrees, numbers.Number):
+ if degrees < 0:
+ raise ValueError('If degrees is a single number,'
+ 'must be positive')
+ degrees = (-degrees, degrees)
+ else:
+ if len(degrees) != 2:
+ raise ValueError('If degrees is a sequence,'
+ 'it must be of len 2.')
+
+ self.degrees = degrees
+
+ def __call__(self, clip):
+ """
+ Args:
+ img (PIL.Image or numpy.ndarray): List of images to be cropped
+ in format (h, w, c) in numpy.ndarray
+
+ Returns:
+ PIL.Image or numpy.ndarray: Cropped list of images
+ """
+ angle = random.uniform(self.degrees[0], self.degrees[1])
+ if isinstance(clip[0], np.ndarray):
+ rotated = [skimage.transform.rotate(img, angle) for img in clip]
+ elif isinstance(clip[0], PIL.Image.Image):
+ rotated = [img.rotate(angle) for img in clip]
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ 'but got list of {0}'.format(type(clip[0])))
+
+ return rotated
+
+
+class CenterCrop(object):
+ """Extract center crop at the same location for a list of images
+
+ Args:
+ size (sequence or int): Desired output size for the
+ crop in format (h, w)
+ """
+
+ def __init__(self, size):
+ if isinstance(size, numbers.Number):
+ size = (size, size)
+
+ self.size = size
+
+ def __call__(self, clip):
+ """
+ Args:
+ img (PIL.Image or numpy.ndarray): List of images to be cropped
+ in format (h, w, c) in numpy.ndarray
+
+ Returns:
+ PIL.Image or numpy.ndarray: Cropped list of images
+ """
+ h, w = self.size
+ if isinstance(clip[0], np.ndarray):
+ im_h, im_w, im_c = clip[0].shape
+ elif isinstance(clip[0], PIL.Image.Image):
+ im_w, im_h = clip[0].size
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ 'but got list of {0}'.format(type(clip[0])))
+ if w > im_w or h > im_h:
+ error_msg = (
+ 'Initial image size should be larger then '
+ 'cropped size but got cropped sizes : ({w}, {h}) while '
+ 'initial image is ({im_w}, {im_h})'.format(
+ im_w=im_w, im_h=im_h, w=w, h=h))
+ raise ValueError(error_msg)
+
+ x1 = int(round((im_w - w) / 2.))
+ y1 = int(round((im_h - h) / 2.))
+ cropped = F.crop_clip(clip, y1, x1, h, w)
+
+ return cropped
+
+
+class ColorJitter(object):
+ """Randomly change the brightness, contrast and saturation and hue of the clip
+
+ Args:
+ brightness (float): How much to jitter brightness. brightness_factor
+ is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
+ contrast (float): How much to jitter contrast. contrast_factor
+ is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
+ saturation (float): How much to jitter saturation. saturation_factor
+ is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
+ hue(float): How much to jitter hue. hue_factor is chosen uniformly from
+ [-hue, hue]. Should be >=0 and <= 0.5.
+ """
+
+ def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
+ self.brightness = brightness
+ self.contrast = contrast
+ self.saturation = saturation
+ self.hue = hue
+
+ def get_params(self, brightness, contrast, saturation, hue):
+ if brightness > 0:
+ brightness_factor = random.uniform(
+ max(0, 1 - brightness), 1 + brightness)
+ else:
+ brightness_factor = None
+
+ if contrast > 0:
+ contrast_factor = random.uniform(
+ max(0, 1 - contrast), 1 + contrast)
+ else:
+ contrast_factor = None
+
+ if saturation > 0:
+ saturation_factor = random.uniform(
+ max(0, 1 - saturation), 1 + saturation)
+ else:
+ saturation_factor = None
+
+ if hue > 0:
+ hue_factor = random.uniform(-hue, hue)
+ else:
+ hue_factor = None
+ return brightness_factor, contrast_factor, saturation_factor, hue_factor
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (list): list of PIL.Image
+
+ Returns:
+ list PIL.Image : list of transformed PIL.Image
+ """
+ if isinstance(clip[0], np.ndarray):
+ raise TypeError(
+ 'Color jitter not yet implemented for numpy arrays')
+ elif isinstance(clip[0], PIL.Image.Image):
+ brightness, contrast, saturation, hue = self.get_params(
+ self.brightness, self.contrast, self.saturation, self.hue)
+
+ # Create img transform function sequence
+ img_transforms = []
+ if brightness is not None:
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness))
+ if saturation is not None:
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation))
+ if hue is not None:
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue))
+ if contrast is not None:
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast))
+ random.shuffle(img_transforms)
+
+ # Apply to all images
+ jittered_clip = []
+ for img in clip:
+ for func in img_transforms:
+ jittered_img = func(img)
+ jittered_clip.append(jittered_img)
+
+ else:
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
+ 'but got list of {0}'.format(type(clip[0])))
+ return jittered_clip
+
+class Normalize(object):
+ """Normalize a clip with mean and standard deviation.
+ Given mean: ``(M1,...,Mn)`` and std: ``(S1,..,Sn)`` for ``n`` channels, this transform
+ will normalize each channel of the input ``torch.*Tensor`` i.e.
+ ``input[channel] = (input[channel] - mean[channel]) / std[channel]``
+
+ .. note::
+ This transform acts out of place, i.e., it does not mutates the input tensor.
+
+ Args:
+ mean (sequence): Sequence of means for each channel.
+ std (sequence): Sequence of standard deviations for each channel.
+ """
+
+ def __init__(self, mean, std):
+ self.mean = mean
+ self.std = std
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (Tensor): Tensor clip of size (T, C, H, W) to be normalized.
+
+ Returns:
+ Tensor: Normalized Tensor clip.
+ """
+ return F.normalize(clip, self.mean, self.std)
+
+
+ def __repr__(self):
+ return self.__class__.__name__ + '(mean={0}, std={1})'.format(self.mean, self.std)
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_imagefolder.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_imagefolder.py
new file mode 100644
index 0000000000000000000000000000000000000000..a5e2d666feae252844df1ffdc3e8fa03484b7e9f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_imagefolder.py
@@ -0,0 +1,175 @@
+from config import *
+import torch
+import os
+import numpy as np
+from PIL import Image
+from torch.utils.data import Dataset
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, imagefolder_path, imagefolder_mask_path, imagefolder_pose_path, split='val', preprocesser=None):
+ self.args = args
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.is_composite = False
+ self.basic_root_dir = BasicArgs.root_dir
+ self.preprocesser = preprocesser
+ self.split = split
+ if not hasattr(args, "ref_mode"):
+ args.ref_mode = "first"
+
+ self.data_dir = args.data_dir
+ self.transform = transforms.Compose([
+ # transforms.RandomResizedCrop(
+ # self.img_size,
+ # scale=(0.9, 1.0), ratio=(1., 1.),
+ # interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.Resize(self.img_size, interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ # transforms.RandomResizedCrop(
+ # (224, 224),
+ # scale=(0.9, 1.0), ratio=(1., 1.),
+ # interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ # transforms.RandomResizedCrop(
+ # (224, 224),
+ # scale=(0.9, 1.0), ratio=(1., 1.),
+ # interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.Resize((224, 224), interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.ToTensor(),
+ ])
+ self.cond_transform = transforms.Compose([
+ # transforms.RandomResizedCrop(
+ # self.img_size,
+ # scale=(0.9, 1.0), ratio=(1., 1.),
+ # interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.Resize(self.img_size, interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.imagefolder_path = imagefolder_path
+ self.imagefolder_mask_path = imagefolder_mask_path
+ self.imagefolder_pose_path = imagefolder_pose_path
+ self.folder_image_list = os.listdir(imagefolder_path)
+
+
+ def add_mask_to_img(self, img, mask, img_key): #pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(img_array * (1-mask_array)) # foreground, background
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def get_metadata(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, _) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(img_idx)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = is_video # True: video data, False: image data
+ meta_data['pose_img'] = self.get_cond(img_idx, 'poses')
+ if self.args.combine_use_mask:
+ meta_data['mask_img'] = self.get_cond(img_idx, 'masks')
+ ref_img_idx = self.get_reference_frame_idx(img_idx)
+ meta_data['ref_img_key'] = self.image_keys[ref_img_idx]
+ meta_data['reference_img'], _ = self.get_visual_data(ref_img_idx)
+ if self.args.combine_use_mask:
+ meta_data['mask_img_ref'] = self.get_cond(ref_img_idx, 'masks')
+ meta_data['img'] = frames
+ return meta_data
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(
+ f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ return len(self.folder_image_list)
+
+ def __getitem__(self, idx):
+ image_name = self.folder_image_list[idx]
+ image_path = os.path.join(self.imagefolder_path, image_name)
+ image_mask_path = os.path.join(self.imagefolder_mask_path, ''.join(image_name.split('.')[:-1])+'-person.png')
+ image_pose_path = os.path.join(self.imagefolder_pose_path, ''.join(image_name.split('.')[:-1])+'-pose.png')
+ image = Image.open(image_path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+
+ # add mask
+ try: # if the background image has human mask
+ image_mask = Image.open(image_mask_path)
+ if not image_mask.mode == "RGB":
+ image_mask = image_mask.convert("RGB")
+ state = torch.get_rng_state()
+
+ if self.args.eval_visu_changefore:
+ image_aug = self.augmentation(image, self.ref_transform, state)
+ image_mask_aug = self.augmentation(image_mask, self.ref_transform_mask, state)
+ image_mask_aug[image_mask_aug > 0] = 1.
+ image_foreground = image_aug * image_mask_aug
+ output = {'reference_img':image_foreground, 'background_mask':1-image_mask_aug}
+ else: # default to change the background
+ image_aug = self.augmentation(image, self.transform, state)
+ image_mask_aug = self.augmentation(image_mask, self.cond_transform, state)
+ image_mask_aug[image_mask_aug > 0] = 1.
+ image_background = image_aug * (1 - image_mask_aug)
+ output = {'reference_img_controlnet': image_background, 'background_mask':1-image_mask_aug}
+
+ except: # no mask provided, use ref mask in the following agent.py
+ state = torch.get_rng_state()
+ if self.args.eval_visu_changefore:
+ image_aug = self.augmentation(image, self.ref_transform, state) # full image
+ image_mask_aug = torch.zeros_like(image_aug)
+ output = {'reference_img':image_aug, 'background_mask':image_mask_aug}
+ else:
+ image_aug = self.augmentation(image, self.transform, state) # full image
+ image_mask_aug = torch.zeros_like(image_aug)
+ output = {'reference_img_controlnet': image_aug, 'background_mask':image_mask_aug}
+
+
+ if self.args.eval_visu_changepose:
+ try: # if the background image has human mask
+ image_pose = Image.open(image_pose_path)
+ if not image_pose.mode == "RGB":
+ image_pose = image_pose.convert("RGB")
+ skeleton_img = self.augmentation(image_pose, self.cond_transform, state)
+ except: #no pose, use the ref pose in the following agent.py
+ skeleton_img = torch.zeros_like(image_background)
+ output['cond_imgs'] = skeleton_img
+
+ return output
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_mask.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_mask.py
new file mode 100644
index 0000000000000000000000000000000000000000..b649d47a35ac2fa6234a3a929e1d7b4a76037830
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_mask.py
@@ -0,0 +1,398 @@
+from config import *
+import torch
+from torch.utils.data import Dataset
+from torchvision import transforms
+import torch.nn.functional as F
+
+import os, math, re, json
+import numpy as np
+from PIL import ImageFile, Image
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+import cv2
+
+training_templates_smallest = [
+ 'photo of a sks {}',
+]
+
+reg_templates_smallest = [
+ 'photo of a {}',
+]
+coco_joints_name = ['Nose', 'Left Eye', 'Right Eye', 'Left Ear', 'Right Ear', 'Left Shoulder', 'Right Shoulder', 'Left Elbow', 'Right Elbow', 'Left Wrist',
+ 'Right Wrist', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Left Ankle', 'Right Ankle', 'Pelvis', 'Neck']
+
+
+class RandomSquarePad():
+ def __init__(self, max_addition_perc=0.5):
+ self.max_addition_perc = max_addition_perc
+
+ def __call__(self, image):
+ width, height = image.size(-1), image.size(-2)
+ max_wh = max(width, height)
+ min_wh = min(width, height)
+ target_size = torch.randint(min_wh, int(max_wh * (1 + self.max_addition_perc)), (1,)).item()
+ # target_size = int(max_wh*(1+self.max_addition_perc))
+ vp = int((target_size - width) / 2)
+ hp = int((target_size - height) / 2)
+ padding = (vp, vp, hp, hp)
+ return F.pad(image, padding, mode='constant')
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.dataset = "tiktok"
+ self.args = args
+ self.split = split
+ self.is_train = split == "train"
+ self.is_composite = False
+ self.on_memory = getattr(args, 'on_memory', False)
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.yaml_file = yaml_file
+ self.stickwidth = 4
+ self.preprocesser = preprocesser
+ self.limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ self.colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(0.9, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(0.9, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+
+ if self.args.fg_variation > 0: # foreground variation
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ RandomSquarePad(max_addition_perc=self.args.fg_variation),
+ transforms.Resize(
+ (224, 224),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ RandomSquarePad(max_addition_perc=self.args.fg_variation),
+ transforms.Resize(
+ (224, 224),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ ])
+
+ else:
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(0.9, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(0.9, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+
+
+ self.total_num_videos = 340
+ self.anno_path = 'GIT/{:05d}/labels/{:04d}.txt'
+ self.image_path = '{:05d}/images/{:04d}.png'
+ self.anno_pose_path = '{:05d}/openpose_json/{:04d}.png.json'
+ self.ref_mask_path = '{:05d}/masks/{:04d}.png'
+
+ self.image_paths_list = []
+ self.ref_image_paths_list = []
+ self.anno_list = []
+ self.anno_pose_list = []
+ self.mask_list = []
+
+ if split == 'train':
+ video_idx_start = 1
+ video_idx_end = 335
+ else:
+ video_idx_start = 335
+ video_idx_end = self.total_num_videos
+
+ # To save time, try to directly load from the file
+ # assert os.path.exists(self.yaml_file), f'please check the annotation path: {self.yaml_file}'
+ # anno_input = torch.load(self.yaml_file)
+ # self.image_paths_list = anno_input['image_paths_list']
+ # self.ref_image_paths_list = anno_input['ref_image_paths_list']
+ # self.anno_pose_list = anno_input['anno_pose_list']
+ # self.anno_list = anno_input['anno_list']
+ # self.mask_list = anno_input['mask_list']
+
+ for vid in range(video_idx_start, video_idx_end):
+ folder_path = os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid)
+ # Get a list of all files in the folder
+ files = os.listdir(folder_path)
+ # Filter the list to only include image files
+ image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ num_frm = len(image_files)
+ # if num_frm > self.max_video_len:
+ # self.max_video_len = num_frm
+
+
+ # # Kevin Ver: always chooose the 1st frame as the referece image
+ # # TODO: WT Revision: if t = n, then reference frm could be between frame(0)~frame(n-1)
+ # for fid in range(1, num_frm):
+ # image_fname = self.image_path.format(vid, fid)
+ # ref_image_fname = self.image_path.format(vid, 1)
+ # anno_pose_fname = self.anno_pose_path.format(vid, fid)
+ # anno_fname = self.anno_path.format(vid, fid)
+ # self.image_paths_list.append(image_fname)
+ # self.ref_image_paths_list.append(ref_image_fname)
+ # self.anno_pose_list.append(anno_pose_fname)
+ # self.anno_list.append(anno_fname)
+ # # torch.save({'image_paths_list':self.image_paths_list, 'ref_image_paths_list':self.ref_image_paths_list, 'anno_pose_list':self.anno_pose_list, 'anno_list':self.anno_list}, '/datadrive_d/wangtan/neurips2023/neurips2023_msintern/discontrol_github/check_pretrain_controlnet/training_json/train_json_tiktok_1stframe_vid0_335.pt')
+
+ # WT Ver: any frame can be the reference
+ # fid_range = range(1, num_frm) if split == 'train' else range(1, num_frm)[::30] # for val, we sample once every 30 frames
+
+ ### # target img frame (1. train: 10fps [::3]; 2. val: all the frame) ####
+ fid_range = range(1, num_frm)[::3] if split == 'train' else range(1, num_frm)
+ for fid in fid_range:
+ image_fname = self.image_path.format(vid, fid) # generation target
+ anno_pose_fname = self.anno_pose_path.format(vid, fid)
+ anno_fname = self.anno_path.format(vid, fid)
+
+ # ref_fid_range = range(1, num_frm) if split == 'train' else range(1, num_frm)[::30] # for val, we sample once every 30 frames
+ # ref_fid_range = range(1, num_frm)[::30] # for both train and val, we sample once every 30 frames, 1fps
+
+ ### # ref img (1. train: 3fps [::10]; 2. val: 1st frame [0]) ####
+ # ref_fid_range = range(1, num_frm)[::10] if split == 'train' else range(1, 2)
+
+ ### # ref img (training: 3fps + first 3 frame)
+ ref_fid_range = range(1, num_frm)[::10][:3] if split == 'train' else range(1, 2)
+
+ for ref_fid in ref_fid_range: # not consider the repetition, easy implementation
+ ref_image_fname = self.image_path.format(vid, ref_fid)
+ ref_mask_fname = self.ref_mask_path.format(vid, ref_fid)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+ # torch.save({'image_paths_list':self.image_paths_list, 'mask_list':self.mask_list, 'ref_image_paths_list':self.ref_image_paths_list, 'anno_pose_list':self.anno_pose_list, 'anno_list':self.anno_list}, '/datadrive_d/wangtan/neurips2023/neurips2023_msintern/discontrol_github/check_pretrain_controlnet/training_json/train_json_tiktok_any2frame-ref3-targ10_vid0_335.pt')
+
+ self.num_images = len(self.image_paths_list)
+ self._length = self.num_images
+ print('number of samples:',self._length)
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, self._length)
+ else:
+ return self._length
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, self._length)
+ else:
+ return self._length
+
+ # draw the body keypoint and lims
+ def draw_bodypose(self, canvas, pose):
+ canvas = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
+ canvas = np.zeros_like(canvas)
+
+ for i in range(18):
+ x, y = pose[i][0:2]
+ if x>=0 and y>=0:
+ cv2.circle(canvas, (int(x), int(y)), 4, self.colors[i], thickness=-1)
+ # cv2.putText(canvas, '%d'%(i), (int(x), int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
+ for limb_idx in range(17):
+ cur_canvas = canvas.copy()
+ index_a = self.limbSeq[limb_idx][0]-1
+ index_b = self.limbSeq[limb_idx][1]-1
+
+ if pose[index_a][0]<0 or pose[index_b][0]<0 or pose[index_a][1]<0 or pose[index_b][1]<0:
+ continue
+
+ Y = [pose[index_a][0], pose[index_b][0]]
+ X = [pose[index_a][1], pose[index_b][1]]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), self.stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, self.colors[limb_idx])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # Convert color space from BGR to RGB
+ # canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
+ # Create PIL image object from numpy array
+ canvas = Image.fromarray(canvas)
+ return canvas
+
+
+ def coco2openpose(self, img, coco_keypoints):
+
+ # coco keypoints: [x1,y1,v1,...,xk,yk,vk] (k=17)
+ # ['Nose', Leye', 'Reye', 'Lear', 'Rear', 'Lsho', 'Rsho', 'Lelb',
+ # 'Relb', 'Lwri', 'Rwri', 'Lhip', 'Rhip', 'Lkne', 'Rkne', 'Lank', 'Rank']
+ # openpose keypoints: [y1,...,yk], [x1,...xk] (k=18, with Neck)
+ # ['Nose' (0), *'Neck'* (1), 'Rsho' (2), 'Relb' (3), 'Rwri' (4), 'Lsho' (5), 'Lelb' (6), 'Lwri' (7),'Rhip' (8),
+ # 'Rkne' (9), 'Rank' (10), 'Lhip' (11), 'Lkne' (12), 'Lank' (13), 'Reye' (14), 'Leye' (15), 'Rear' (16), 'Lear' (17)]
+
+ openpose_keypoints = [
+ coco_keypoints[0], # Nose (0)
+ list((np.asarray(coco_keypoints[5]) + np.asarray(coco_keypoints[6]))/2), # Neck (1)
+ coco_keypoints[6], # RShoulder (2)
+ coco_keypoints[8], # RElbow (3)
+ coco_keypoints[10], # RWrist (4)
+ coco_keypoints[5], # LShoulder (5)
+ coco_keypoints[7], # LElbow (6)
+ coco_keypoints[9], # LWrist (7)
+ coco_keypoints[12], # RHip (8)
+ coco_keypoints[14], # RKnee (9)
+ coco_keypoints[16], # RAnkle (10)
+ coco_keypoints[11], # LHip (11)
+ coco_keypoints[13], # LKnee (12)
+ coco_keypoints[15], # LAnkle (13)
+ coco_keypoints[2], # REye (14)
+ coco_keypoints[1], # LEye (15)
+ coco_keypoints[4], # REar (16)
+ coco_keypoints[3], # LEar (17)
+ ]
+ return self.draw_bodypose(img, openpose_keypoints)
+
+
+ def get_img_txt_pair(self, idx):
+ example = {}
+ img_path = os.path.join(self.args.tiktok_data_root, self.image_paths_list[idx % self.num_images])
+ ref_img_path = os.path.join(self.args.tiktok_data_root, self.ref_image_paths_list[idx % self.num_images])
+ sample = img_path.split('/')[-1]
+ anno_pose_path = os.path.join(self.args.tiktok_data_root, self.anno_pose_list[idx % self.num_images])
+ anno_path = os.path.join(self.args.tiktok_data_root, self.anno_list[idx % self.num_images])
+ ref_mask_path = os.path.join(self.args.tiktok_data_root, self.mask_list[idx % self.num_images])
+
+ image = Image.open(img_path)
+ ref_mask = Image.open(ref_mask_path).convert('RGB')
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+
+ ref_image = Image.open(ref_img_path)
+ if not ref_image.mode == "RGB":
+ ref_image = ref_image.convert("RGB")
+
+ ref_mask = ref_mask.resize(image.size) # resize the mask to img
+ anno = list(open(anno_path))
+ img_key = json.loads(anno[0].strip())['image_key']
+ """
+ example:
+ {"num_region": 6, "image_key": "TiktokDance_00001_0002.png", "image_split": "00001", "image_read_error": false}
+ {"box_id": 0, "class_name": "aerosol_can", "norm_bbox": [0.5, 0.5, 1.0, 1.0], "conf": 0.0, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 1, "class_name": "person", "norm_bbox": [0.46692365407943726, 0.4977584183216095, 0.9338473081588745, 0.995516836643219], "conf": 0.912740170955658, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 2, "class_name": "butterfly", "norm_bbox": [0.2368704378604889, 0.5088028907775879, 0.1444256454706192, 0.04199704900383949], "conf": 0.8738771677017212, "region_caption": "a brown butterfly sitting on an orange background.", "caption_conf": 0.9297735554473283}
+ {"box_id": 3, "class_name": "butterfly", "norm_bbox": [0.6688584089279175, 0.5137135982513428, 0.11311062425374985, 0.05455022677779198], "conf": 0.8287128806114197, "region_caption": "a brown butterfly sitting on an orange wall.", "caption_conf": 0.9264783379302365}
+ {"box_id": 4, "class_name": "blouse", "norm_bbox": [0.4692786931991577, 0.6465241312980652, 0.9283269643783569, 0.6027728319168091], "conf": 0.6851752400398254, "region_caption": "a woman wearing an orange shirt with butterflies on it.", "caption_conf": 0.9978814544264754}
+ {"box_id": 5, "class_name": "short_pants", "norm_bbox": [0.44008955359458923, 0.8769687414169312, 0.8799525499343872, 0.2431662678718567], "conf": 0.6741859316825867, "region_caption": "a person wearing an orange shirt and grey sweatpants.", "caption_conf": 0.9731313580907464}
+ """
+ # Now, we select detected box_id=0, which is the whole image.
+ image_anno = json.loads(anno[1].strip())
+ caption = image_anno['region_caption']
+
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path,'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d)>0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x,y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x,y])
+
+ # convert coordinates to skeleton image
+ skeleton_img = self.coco2openpose(image, pose_without_visibletag)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = False
+ meta_data['skeleton_img'] = skeleton_img
+ meta_data['reference_img'] = ref_image
+ meta_data['img'] = image
+ meta_data['ref_mask'] = ref_mask
+ return meta_data
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def __getitem__(self, idx):
+ try:
+ raw_data = self.get_img_txt_pair(idx)
+ except Exception as e:
+ print(e)
+ img = raw_data['img']
+ skeleton_img = raw_data['skeleton_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, self.ref_transform, state)
+
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['ref_mask']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ # ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(raw_data['reference_img'].size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, self.cond_transform, state) # controlnet path input
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
+
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg.py
new file mode 100644
index 0000000000000000000000000000000000000000..0934c40ab5f7a427785c3521f3242e6f8d9521f0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg.py
@@ -0,0 +1,392 @@
+from config import *
+import torch
+from torch.utils.data import Dataset
+from torchvision import transforms
+
+import os, math, re, json
+import numpy as np
+from tqdm import tqdm
+import random
+from PIL import ImageFile, Image
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+import cv2
+
+training_templates_smallest = [
+ 'photo of a sks {}',
+]
+
+reg_templates_smallest = [
+ 'photo of a {}',
+]
+coco_joints_name = ['Nose', 'Left Eye', 'Right Eye', 'Left Ear', 'Right Ear', 'Left Shoulder', 'Right Shoulder', 'Left Elbow', 'Right Elbow', 'Left Wrist',
+ 'Right Wrist', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Left Ankle', 'Right Ankle', 'Pelvis', 'Neck']
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.dataset = "tiktok"
+ self.args = args
+ self.split = split
+ self.is_train = split == "train"
+ self.is_composite = False
+ self.on_memory = getattr(args, 'on_memory', False)
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.yaml_file = yaml_file
+ self.stickwidth = 4
+ self.preprocesser = preprocesser
+ self.limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ self.colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ min_crop_scale = 0.5 if self.args.strong_aug_stage1 and split=='train' else 0.9 # for stronger augmentation (only use in train)
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.total_num_videos = 340
+ self.anno_path = 'GIT/{:05d}/labels/{:04d}.txt'
+ self.image_path = '{:05d}/images/{:04d}.png'
+ self.anno_pose_path = '{:05d}/openpose_json/{:04d}.png.json'
+ self.ref_mask_path = '{:05d}/masks/{:04d}.png'
+
+ self.image_paths_list = []
+ self.ref_image_paths_list = []
+ self.anno_list = []
+ self.anno_pose_list = []
+ self.mask_list = []
+
+ if split == 'train':
+ video_idx_start = 337 # only sample 1 image
+ video_idx_end = 338
+ else:
+ video_idx_start = 337
+ video_idx_end = 338
+
+ ### use specific image video frame to ft, sample in the fly
+ for vid in range(video_idx_start, video_idx_end):
+ folder_path = os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid)
+ # Get a list of all files in the folder
+ files = os.listdir(folder_path)
+ # Filter the list to only include image files
+ image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ num_frm = len(image_files)
+
+ ### if use specific number of frames as training sample
+ ft_img_num = getattr(self.args, 'ft_img_num', 0) # default value
+ ft_one_ref_image = getattr(self.args, 'ft_one_ref_image', True) # default value
+
+ if ft_img_num>0: # randomly sample n image as training sample
+ random.seed(self.args.seed)
+ frm_list = random.sample(list(range(1, num_frm)), ft_img_num)
+ frm_list.sort()
+ print('Random Sample Frames: {}'.format(frm_list))
+ else:
+ frm_list = list(range(1, num_frm))
+
+ # FT: [Kevin Ver] always chooose the 1st frame as the referece image
+ # TODO: WT Revision: if t = n, then reference frm could be between frame(0)~frame(n-1)
+ if ft_one_ref_image:
+ if split == 'train':
+ while len(frm_list) < 128:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ image_fname = self.image_path.format(vid, fid)
+ ref_image_fname = self.image_path.format(vid, frm_list[0])
+ ref_mask_fname = self.ref_mask_path.format(vid, frm_list[0]) # only choose 1st frame as ref frame
+ anno_pose_fname = self.anno_pose_path.format(vid, fid)
+ anno_fname = self.anno_path.format(vid, fid)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ else:
+ image_fname = self.image_path.format(vid, frm_list[0])
+ ref_image_fname = self.image_path.format(vid, frm_list[0])
+ ref_mask_fname = self.ref_mask_path.format(vid, frm_list[0]) # only choose 1st frame as ref frame
+
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid - 2))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ anno_pose_fname = self.anno_pose_path.format(vid - 2, fid % refpose_image_files_len) # change to the next frame's pose
+ anno_fname = self.anno_path.format(vid - 2, fid % refpose_image_files_len)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ else:
+ if split == 'train':
+ while len(frm_list) < 12:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ for ref_fid in frm_list:
+ image_fname = self.image_path.format(vid, fid)
+ ref_image_fname = self.image_path.format(vid, ref_fid)
+ anno_pose_fname = self.anno_pose_path.format(vid, fid)
+
+ anno_fname = self.anno_path.format(vid, fid)
+ ref_mask_fname = self.ref_mask_path.format(vid, ref_fid) # only choose 1st frame as ref frame
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+
+ else: # val
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid - 2))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ ref_fid = random.choice(frm_list)
+ image_fname = self.image_path.format(vid, ref_fid) # just use ref image as the gt
+ ref_image_fname = self.image_path.format(vid, ref_fid) # randomly choose a image as ref
+ ref_mask_fname = self.ref_mask_path.format(vid, ref_fid)
+ anno_pose_fname = self.anno_pose_path.format(vid - 2, fid % refpose_image_files_len) # change to the next frame's pose
+
+ anno_fname = self.anno_path.format(vid - 2, fid % refpose_image_files_len)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+
+ self.num_images = len(self.image_paths_list)
+ self._length = self.num_images
+ print('number of samples:',self._length)
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, self._length)
+ else:
+ return self._length
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, self._length)
+ else:
+ return self._length
+
+ # draw the body keypoint and lims
+ def draw_bodypose(self, canvas, pose):
+ canvas = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
+ canvas = np.zeros_like(canvas)
+
+ for i in range(18):
+ x, y = pose[i][0:2]
+ if x>=0 and y>=0:
+ cv2.circle(canvas, (int(x), int(y)), 4, self.colors[i], thickness=-1)
+ # cv2.putText(canvas, '%d'%(i), (int(x), int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
+ for limb_idx in range(17):
+ cur_canvas = canvas.copy()
+ index_a = self.limbSeq[limb_idx][0]-1
+ index_b = self.limbSeq[limb_idx][1]-1
+
+ if pose[index_a][0]<0 or pose[index_b][0]<0 or pose[index_a][1]<0 or pose[index_b][1]<0:
+ continue
+
+ Y = [pose[index_a][0], pose[index_b][0]]
+ X = [pose[index_a][1], pose[index_b][1]]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), self.stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, self.colors[limb_idx])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # Convert color space from BGR to RGB
+ # canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
+ # Create PIL image object from numpy array
+ canvas = Image.fromarray(canvas)
+ return canvas
+
+
+ def coco2openpose(self, img, coco_keypoints):
+
+ # coco keypoints: [x1,y1,v1,...,xk,yk,vk] (k=17)
+ # ['Nose', Leye', 'Reye', 'Lear', 'Rear', 'Lsho', 'Rsho', 'Lelb',
+ # 'Relb', 'Lwri', 'Rwri', 'Lhip', 'Rhip', 'Lkne', 'Rkne', 'Lank', 'Rank']
+ # openpose keypoints: [y1,...,yk], [x1,...xk] (k=18, with Neck)
+ # ['Nose' (0), *'Neck'* (1), 'Rsho' (2), 'Relb' (3), 'Rwri' (4), 'Lsho' (5), 'Lelb' (6), 'Lwri' (7),'Rhip' (8),
+ # 'Rkne' (9), 'Rank' (10), 'Lhip' (11), 'Lkne' (12), 'Lank' (13), 'Reye' (14), 'Leye' (15), 'Rear' (16), 'Lear' (17)]
+
+ openpose_keypoints = [
+ coco_keypoints[0], # Nose (0)
+ list((np.asarray(coco_keypoints[5]) + np.asarray(coco_keypoints[6]))/2), # Neck (1)
+ coco_keypoints[6], # RShoulder (2)
+ coco_keypoints[8], # RElbow (3)
+ coco_keypoints[10], # RWrist (4)
+ coco_keypoints[5], # LShoulder (5)
+ coco_keypoints[7], # LElbow (6)
+ coco_keypoints[9], # LWrist (7)
+ coco_keypoints[12], # RHip (8)
+ coco_keypoints[14], # RKnee (9)
+ coco_keypoints[16], # RAnkle (10)
+ coco_keypoints[11], # LHip (11)
+ coco_keypoints[13], # LKnee (12)
+ coco_keypoints[15], # LAnkle (13)
+ coco_keypoints[2], # REye (14)
+ coco_keypoints[1], # LEye (15)
+ coco_keypoints[4], # REar (16)
+ coco_keypoints[3], # LEar (17)
+ ]
+ return self.draw_bodypose(img, openpose_keypoints)
+
+
+ def get_img_txt_pair(self, idx):
+ example = {}
+ img_path = os.path.join(self.args.tiktok_data_root, self.image_paths_list[idx % self.num_images])
+ ref_img_path = os.path.join(self.args.tiktok_data_root, self.ref_image_paths_list[idx % self.num_images])
+ sample = img_path.split('/')[-1]
+ anno_pose_path = os.path.join(self.args.tiktok_data_root, self.anno_pose_list[idx % self.num_images])
+ anno_path = os.path.join(self.args.tiktok_data_root, self.anno_list[idx % self.num_images])
+ ref_mask_path = os.path.join(self.args.tiktok_data_root, self.mask_list[idx % self.num_images])
+
+ image = Image.open(img_path)
+ ref_mask = Image.open(ref_mask_path).convert('RGB')
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+
+ ref_image = Image.open(ref_img_path)
+ if not ref_image.mode == "RGB":
+ ref_image = ref_image.convert("RGB")
+
+ ref_mask = ref_mask.resize(image.size) # resize the mask to img
+ anno = list(open(anno_path))
+ img_key = json.loads(anno[0].strip())['image_key']
+ """
+ example:
+ {"num_region": 6, "image_key": "TiktokDance_00001_0002.png", "image_split": "00001", "image_read_error": false}
+ {"box_id": 0, "class_name": "aerosol_can", "norm_bbox": [0.5, 0.5, 1.0, 1.0], "conf": 0.0, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 1, "class_name": "person", "norm_bbox": [0.46692365407943726, 0.4977584183216095, 0.9338473081588745, 0.995516836643219], "conf": 0.912740170955658, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 2, "class_name": "butterfly", "norm_bbox": [0.2368704378604889, 0.5088028907775879, 0.1444256454706192, 0.04199704900383949], "conf": 0.8738771677017212, "region_caption": "a brown butterfly sitting on an orange background.", "caption_conf": 0.9297735554473283}
+ {"box_id": 3, "class_name": "butterfly", "norm_bbox": [0.6688584089279175, 0.5137135982513428, 0.11311062425374985, 0.05455022677779198], "conf": 0.8287128806114197, "region_caption": "a brown butterfly sitting on an orange wall.", "caption_conf": 0.9264783379302365}
+ {"box_id": 4, "class_name": "blouse", "norm_bbox": [0.4692786931991577, 0.6465241312980652, 0.9283269643783569, 0.6027728319168091], "conf": 0.6851752400398254, "region_caption": "a woman wearing an orange shirt with butterflies on it.", "caption_conf": 0.9978814544264754}
+ {"box_id": 5, "class_name": "short_pants", "norm_bbox": [0.44008955359458923, 0.8769687414169312, 0.8799525499343872, 0.2431662678718567], "conf": 0.6741859316825867, "region_caption": "a person wearing an orange shirt and grey sweatpants.", "caption_conf": 0.9731313580907464}
+ """
+ # Now, we select detected box_id=0, which is the whole image.
+ image_anno = json.loads(anno[1].strip())
+ caption = image_anno['region_caption']
+
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path,'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d)>0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x,y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x,y])
+
+ # convert coordinates to skeleton image
+ skeleton_img = self.coco2openpose(image, pose_without_visibletag)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = False
+ meta_data['skeleton_img'] = skeleton_img
+ meta_data['reference_img'] = ref_image
+ meta_data['img'] = image
+ meta_data['ref_mask'] = ref_mask
+ return meta_data
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def __getitem__(self, idx):
+ try:
+ raw_data = self.get_img_txt_pair(idx)
+ except Exception as e:
+ print(e)
+ img = raw_data['img']
+ skeleton_img = raw_data['skeleton_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, self.ref_transform, state)
+
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['ref_mask']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ # ### first resize mask to the img size
+ # mask_img_ref = mask_img_ref.resize(raw_data['reference_img'].size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, self.cond_transform, state) # controlnet path input
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
+
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web.py
new file mode 100644
index 0000000000000000000000000000000000000000..b22aaadbd492d16b4a496a72f53b7c715e58be66
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web.py
@@ -0,0 +1,613 @@
+from config import *
+import torch
+from torch.utils.data import Dataset
+from torchvision import transforms
+
+import os, math, re, json, copy
+import numpy as np
+from tqdm import tqdm
+import random
+from PIL import ImageFile, Image
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+import cv2
+import code
+
+training_templates_smallest = [
+ 'photo of a sks {}',
+]
+
+reg_templates_smallest = [
+ 'photo of a {}',
+]
+coco_joints_name = ['Nose', 'Left Eye', 'Right Eye', 'Left Ear', 'Right Ear', 'Left Shoulder', 'Right Shoulder', 'Left Elbow', 'Right Elbow', 'Left Wrist',
+ 'Right Wrist', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Left Ankle', 'Right Ankle', 'Pelvis', 'Neck']
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.dataset = "tiktok"
+ self.args = args
+ self.split = split
+ self.is_train = split == "train"
+ self.is_composite = False
+ self.on_memory = getattr(args, 'on_memory', False)
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.pose_normalize = getattr(args, 'pose_normalize', False)
+ self.normalize_by_1st_frm = getattr(args, 'normalize_by_1st_frm', False)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.yaml_file = yaml_file
+ self.stickwidth = 4
+ self.preprocesser = preprocesser
+ self.limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ self.colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ self.random_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int(torch.randint(0, img.height - img.width, (1,)).item()), left=0, height=img.width, width=img.width))
+ self.random_square_width = transforms.Lambda(lambda img: transforms.functional.crop(img, top=0, left=int(torch.randint(0, img.width - img.height, (1,)).item()), height=img.height, width=img.height))
+
+ self.fix_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int((img.height - img.width)/4), left=0, height=img.width, width=img.width))
+ min_crop_scale = 0.5 if self.args.strong_aug_stage1 and split=='train' else 1.0 # for stronger augmentation (only use in train)
+ # min_crop_scale = 0.5
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.total_num_videos = 340
+ self.anno_path = 'GIT/{:05d}/labels/{:04d}.txt'
+ self.image_path = '{:05d}/images/{:04d}.png'
+ self.anno_pose_path = '{:05d}/openpose_json/{:04d}.png.json'
+ self.ref_mask_path = '{:05d}/masks/{:04d}.png'
+
+ self.image_path_web = '{}/{}'
+ self.ref_image_path_web = '{}/{}'
+ self.anno_pose_path_web = '{}/openpose_json/{}.json'
+ self.ref_mask_path_web = '{}/groundsam/{}.mask.jpg'
+
+ self.image_paths_list = []
+ self.ref_image_paths_list = []
+ self.ref_pose_paths_list = []
+ self.anno_list = []
+ self.anno_pose_list = []
+ self.anno_init_pose_list = []
+ self.mask_list = []
+
+ ft_video_idx = getattr(args, 'ft_idx', '001_1.57_2.17_1x1') # default elon
+ if split == 'train': # for training video
+ # video_idx = ['001_1.57_2.17_1x1'] # elon mask 2
+ # video_idx = ['007_7.36_7.44_1x1'] # 007
+ video_idx = [ft_video_idx] # 007
+ dataset_prefix = self.args.web_data_root
+ else: # for pose video
+ video_idx = [335, 137]
+ # ref_video_idx = '001_1.57_2.17_1x1' # 007
+ # ref_video_idx = '007_7.36_7.44_1x1' # 007
+ ref_video_idx = ft_video_idx # 007
+ dataset_prefix = self.args.tiktok_data_root
+
+ ### use specific image video frame to ft, sample in the fly
+ for vid in video_idx:
+
+ if isinstance(vid, str): # web image data
+ assert split == 'train'
+ folder_path = os.path.join(args.web_data_root, '{}').format(vid)
+ image_files_idx = list(open(os.path.join(folder_path, 'image_list.txt')))
+ image_files_idx = [file.strip() for file in image_files_idx]
+
+ else:
+ assert split == 'val'
+ folder_path = os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid)
+ files = os.listdir(folder_path)
+ image_files_idx = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+
+ folder_path_ref = os.path.join(args.web_data_root, '{}').format(ref_video_idx)
+ image_files_idx_ref = list(open(os.path.join(folder_path_ref, 'image_list.txt')))
+ image_files_idx_ref = [file.strip() for file in image_files_idx_ref]
+
+ ### if use specific number of frames as training sample
+ ft_img_num = getattr(self.args, 'ft_img_num', 0) # default value
+ ft_one_ref_image = getattr(self.args, 'ft_one_ref_image', True) # default value
+
+ if ft_img_num>0: # randomly sample n image as training sample
+ random.seed(self.args.seed)
+ frm_list = random.sample(image_files_idx, ft_img_num)
+ frm_list.sort()
+ print('Random Sample Frames: {}'.format(frm_list))
+ else:
+ frm_list = image_files_idx
+
+ # FT: [Kevin Ver] always chooose the 1st frame as the referece image
+ # TODO: WT Revision: if t = n, then reference frm could be between frame(0)~frame(n-1)
+ if ft_one_ref_image: # only use 1st frame as the reference
+ if split == 'train':
+ while len(frm_list) < 128:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, fid))
+ ref_image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, frm_list[0]))
+ ref_mask_fname = os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, frm_list[0])) # only choose 1st frame as ref frame
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path_web.format(vid, fid))
+
+ # anno_fname = self.anno_path.format(vid, fid)
+ anno_fname = os.path.join(dataset_prefix, vid + '__' + fid)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ else: # use tiktok pose for dancing
+ ref_image_fname = os.path.join(self.args.web_data_root, self.image_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+ ref_mask_fname = os.path.join(self.args.web_data_root, self.ref_mask_path_web.format(ref_video_idx, image_files_idx_ref[0])) # only choose 1st frame as ref frame
+ ref_pose_fname = os.path.join(self.args.web_data_root, self.anno_pose_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ image_fname = os.path.join(dataset_prefix, self.image_path.format(vid, fid % refpose_image_files_len))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, fid % refpose_image_files_len)) # change to the next frame's pose
+ anno_fname = os.path.join(dataset_prefix, self.anno_path.format(vid, fid % refpose_image_files_len))
+ anno_init_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, 1))
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.ref_pose_paths_list.append(ref_pose_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.anno_init_pose_list.append(anno_init_pose_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ # random sort the input list for visualization
+ random_idx = list(range(len(self.image_paths_list)))
+ random.shuffle(random_idx)
+ self.image_paths_list = [self.image_paths_list[i] for i in random_idx]
+ self.ref_image_paths_list = [self.ref_image_paths_list[i] for i in random_idx]
+ self.ref_pose_paths_list = [self.ref_pose_paths_list[i] for i in random_idx]
+
+ self.anno_pose_list = [self.anno_pose_list[i] for i in random_idx]
+ self.anno_list = [self.anno_list[i] for i in random_idx]
+ self.mask_list = [self.mask_list[i] for i in random_idx]
+ self.anno_init_pose_list = [self.anno_init_pose_list[i] for i in random_idx]
+
+
+ else:
+ if split == 'train':
+ while len(frm_list) < 12:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ # ref image use random sample
+ ref_resample_flag = True
+ while ref_resample_flag:
+ ref_fid = random.choice(frm_list)
+ if os.path.exists(os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, ref_fid))):
+ ref_resample_flag = False
+
+ image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, fid))
+ ref_image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, ref_fid))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path_web.format(vid, fid))
+
+ # anno_fname = self.anno_path.format(vid, fid)
+ anno_fname = os.path.join(dataset_prefix, vid + '__' + fid)
+ ref_mask_fname = os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, ref_fid)) # only choose 1st frame as ref frame
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+
+ else: # use tiktok pose for dancing, still use the 1st frame
+ ref_image_fname = os.path.join(self.args.web_data_root, self.image_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+ ref_mask_fname = os.path.join(self.args.web_data_root, self.ref_mask_path_web.format(ref_video_idx, image_files_idx_ref[0])) # only choose 1st frame as ref frame
+ ref_pose_fname = os.path.join(self.args.web_data_root, self.anno_pose_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ image_fname = os.path.join(dataset_prefix, self.image_path.format(vid, fid % refpose_image_files_len))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, fid % refpose_image_files_len)) # change to the next frame's pose
+ anno_fname = os.path.join(dataset_prefix, self.anno_path.format(vid, fid % refpose_image_files_len))
+ anno_init_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path_web.format(vid, 1))
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.ref_pose_paths_list.append(ref_pose_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.anno_init_pose_list.append(anno_init_pose_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ # random sort the input list for visualization
+ random_idx = list(range(len(self.image_paths_list)))
+ random.shuffle(random_idx)
+ self.image_paths_list = [self.image_paths_list[i] for i in random_idx]
+ self.ref_image_paths_list = [self.ref_image_paths_list[i] for i in random_idx]
+ self.ref_pose_paths_list = [self.ref_pose_paths_list[i] for i in random_idx]
+
+ self.anno_pose_list = [self.anno_pose_list[i] for i in random_idx]
+ self.anno_list = [self.anno_list[i] for i in random_idx]
+ self.mask_list = [self.mask_list[i] for i in random_idx]
+ self.anno_init_pose_list = [self.anno_init_pose_list[i] for i in random_idx]
+
+
+ self.num_images = len(self.image_paths_list)
+ self._length = self.num_images
+ print('number of samples:',self._length)
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, self._length)
+ else:
+ return self._length
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, self._length)
+ else:
+ return self._length
+
+ # draw the body keypoint and lims
+ def draw_bodypose(self, canvas, pose):
+ canvas = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
+ canvas = np.zeros_like(canvas)
+
+ for i in range(18):
+ x, y = pose[i][0:2]
+ if x>=0 and y>=0:
+ cv2.circle(canvas, (int(x), int(y)), 4, self.colors[i], thickness=-1)
+ # cv2.putText(canvas, '%d'%(i), (int(x), int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
+ for limb_idx in range(17):
+ cur_canvas = canvas.copy()
+ index_a = self.limbSeq[limb_idx][0]-1
+ index_b = self.limbSeq[limb_idx][1]-1
+
+ if pose[index_a][0]<0 or pose[index_b][0]<0 or pose[index_a][1]<0 or pose[index_b][1]<0:
+ continue
+
+ Y = [pose[index_a][0], pose[index_b][0]]
+ X = [pose[index_a][1], pose[index_b][1]]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), self.stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, self.colors[limb_idx])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # Convert color space from BGR to RGB
+ # canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
+ # Create PIL image object from numpy array
+ canvas = Image.fromarray(canvas)
+ return canvas
+
+
+ def coco2openpose(self, img, coco_keypoints):
+
+ # coco keypoints: [x1,y1,v1,...,xk,yk,vk] (k=17)
+ # ['Nose', Leye', 'Reye', 'Lear', 'Rear', 'Lsho', 'Rsho', 'Lelb',
+ # 'Relb', 'Lwri', 'Rwri', 'Lhip', 'Rhip', 'Lkne', 'Rkne', 'Lank', 'Rank']
+ # openpose keypoints: [y1,...,yk], [x1,...xk] (k=18, with Neck)
+ # ['Nose' (0), *'Neck'* (1), 'Rsho' (2), 'Relb' (3), 'Rwri' (4), 'Lsho' (5), 'Lelb' (6), 'Lwri' (7),'Rhip' (8),
+ # 'Rkne' (9), 'Rank' (10), 'Lhip' (11), 'Lkne' (12), 'Lank' (13), 'Reye' (14), 'Leye' (15), 'Rear' (16), 'Lear' (17)]
+
+ openpose_keypoints = [
+ coco_keypoints[0], # Nose (0)
+ list((np.asarray(coco_keypoints[5]) + np.asarray(coco_keypoints[6]))/2), # Neck (1)
+ coco_keypoints[6], # RShoulder (2)
+ coco_keypoints[8], # RElbow (3)
+ coco_keypoints[10], # RWrist (4)
+ coco_keypoints[5], # LShoulder (5)
+ coco_keypoints[7], # LElbow (6)
+ coco_keypoints[9], # LWrist (7)
+ coco_keypoints[12], # RHip (8)
+ coco_keypoints[14], # RKnee (9)
+ coco_keypoints[16], # RAnkle (10)
+ coco_keypoints[11], # LHip (11)
+ coco_keypoints[13], # LKnee (12)
+ coco_keypoints[15], # LAnkle (13)
+ coco_keypoints[2], # REye (14)
+ coco_keypoints[1], # LEye (15)
+ coco_keypoints[4], # REar (16)
+ coco_keypoints[3], # LEar (17)
+ ]
+ return self.draw_bodypose(img, openpose_keypoints)
+
+
+ def load_image(self, path):
+ if os.path.exists(path):
+ image = Image.open(path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+ else:
+ image = None
+ return image
+
+ def load_mask(self, path):
+ try:
+ if os.path.exists(path):
+ img = self.load_image(path)
+ img = np.asarray(img)
+ bk = img[:, :, :] == [68, 0, 83]
+ fg = (bk == False)
+ fg = fg * 255.0
+ mask = fg.astype(np.uint8)
+ ipl_mask = Image.fromarray(mask)
+ else:
+ ipl_mask = None
+ except Exception as e:
+ print(e)
+ ipl_mask = None
+ return ipl_mask
+
+ def load_pose_ann(self, anno_pose_path):
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path, 'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d) > 0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x, y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x, y])
+ return pose_without_visibletag
+
+ def get_valid_jnt_index(self, image, pose):
+ img_width, img_height = image.size
+ valid_pose_index = np.asarray(
+ [item[0] > -1 and item[0] < img_width and item[1] > -1 and item[1] < img_height for item in pose])
+ # when compute affine transform, skip joints on the arms and legs
+ valid_pose_index[10] = False # RWrist
+ valid_pose_index[9] = False # LWrist
+ valid_pose_index[16] = False # RAnkle
+ valid_pose_index[15] = False # LAnkle
+ # add Neck to joint set
+ if valid_pose_index[5] == True and valid_pose_index[6] == True:
+ pose.append(list((np.asarray(pose[5]) + np.asarray(pose[6])) / 2))
+ valid_pose_index = np.append(valid_pose_index, True)
+ else:
+ pose.append([-1, -1])
+ valid_pose_index = np.append(valid_pose_index, False)
+ # add Pelvis to joint set
+ if valid_pose_index[11] == True and valid_pose_index[12] == True:
+ pose.append(list((np.asarray(pose[11]) + np.asarray(pose[12])) / 2))
+ valid_pose_index = np.append(valid_pose_index, True)
+ else:
+ pose.append([-1, -1])
+ valid_pose_index = np.append(valid_pose_index, False)
+ return valid_pose_index, pose
+
+ def pose_norm(self, image, input_ref_pose, input_init_pose, input_pose):
+ ref_pose = copy.deepcopy(input_ref_pose)
+ init_pose = copy.deepcopy(input_init_pose)
+ pose = copy.deepcopy(input_pose)
+ # compute transformation between ref_pose and init_pose, and apply transforms to pose
+ # get index for the valid joints
+ valid_ref_pose, ref_pose = self.get_valid_jnt_index(image, ref_pose) # reference pose is the pose of reference image
+ valid_init_pose, init_pose = self.get_valid_jnt_index(image, init_pose) # init pose is the initial target pose (1st frame)
+
+ # get common valid joints
+ common_valid_pose = valid_ref_pose * valid_init_pose
+ # if limited joints available, skip normalization
+ if np.sum(common_valid_pose * 1) < 5:
+ t_x, t_y = 0, 0
+ s_x, s_y = 1, 1
+ else:
+ np_ref_pose = np.asarray(ref_pose)
+ np_init_pose = np.asarray(init_pose)
+ np_ref_pose_set = np_ref_pose[common_valid_pose]
+ np_init_pose_set = np_init_pose[common_valid_pose]
+ # get affine trans matrix: transform from init pose to ref pose
+ affine_matrix, _ = cv2.estimateAffinePartial2D(np_init_pose_set, np_ref_pose_set)
+ t_x = affine_matrix[0, 2]
+ t_y = affine_matrix[1, 2]
+ s_x = np.sign(affine_matrix[0, 0]) * np.sqrt(
+ affine_matrix[0, 0] * affine_matrix[0, 0] + affine_matrix[0, 1] * affine_matrix[0, 1])
+ s_y = np.sign(affine_matrix[1, 1]) * np.sqrt(
+ affine_matrix[1, 0] * affine_matrix[1, 0] + affine_matrix[1, 1] * affine_matrix[1, 1])
+
+ # apply scale + translate to the given pose
+ for i in range(len(pose)):
+ if pose[i][0] >= 0 or pose[i][1] >= 0:
+ pose[i][0] = int(pose[i][0] * s_x + t_x)
+ pose[i][1] = int(pose[i][1] * s_y + t_y)
+ return pose
+
+ def normalize_mask(self, mask):
+ mask[mask>=0.001] = 1
+ mask[mask<0.001] = 0
+ return mask
+
+
+ def get_img_txt_pair(self, idx):
+
+ # img_path = os.path.join(self.args.tiktok_data_root, self.image_paths_list[idx % self.num_images])
+ # ref_img_path = os.path.join(self.args.tiktok_data_root, self.ref_image_paths_list[idx % self.num_images])
+ # anno_pose_path = os.path.join(self.args.tiktok_data_root, self.anno_pose_list[idx % self.num_images])
+ # anno_path = os.path.join(self.args.tiktok_data_root, self.anno_list[idx % self.num_images])
+ # ref_mask_path = os.path.join(self.args.tiktok_data_root, self.mask_list[idx % self.num_images])
+
+ img_path = self.image_paths_list[idx % self.num_images]
+ ref_img_path = self.ref_image_paths_list[idx % self.num_images]
+
+ anno_pose_path = self.anno_pose_list[idx % self.num_images]
+ anno_path = self.anno_list[idx % self.num_images]
+ ref_mask_path = self.mask_list[idx % self.num_images]
+
+ image = Image.open(img_path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+
+ if 'youtube' in ref_mask_path:
+ ref_mask = self.load_mask(ref_mask_path)
+ else:
+ ref_mask = Image.open(ref_mask_path).convert('RGB')
+
+ ref_image = Image.open(ref_img_path)
+ if not ref_image.mode == "RGB":
+ ref_image = ref_image.convert("RGB")
+
+ ref_original_width, ref_original_height = ref_image.size
+ ref_mask = ref_mask.resize(ref_image.size) # resize the mask to img
+ if self.pose_normalize and self.split is not 'train':
+ ref_image = ref_image.resize(image.size)
+ ref_new_width, ref_new_height = ref_image.size
+
+ if 'youtube' in anno_pose_path:
+ img_key = self.anno_list[idx % self.num_images]
+ else:
+ anno = list(open(anno_path))
+ img_key = json.loads(anno[0].strip())['image_key']
+ """
+ example:
+ {"num_region": 6, "image_key": "TiktokDance_00001_0002.png", "image_split": "00001", "image_read_error": false}
+ {"box_id": 0, "class_name": "aerosol_can", "norm_bbox": [0.5, 0.5, 1.0, 1.0], "conf": 0.0, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 1, "class_name": "person", "norm_bbox": [0.46692365407943726, 0.4977584183216095, 0.9338473081588745, 0.995516836643219], "conf": 0.912740170955658, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 2, "class_name": "butterfly", "norm_bbox": [0.2368704378604889, 0.5088028907775879, 0.1444256454706192, 0.04199704900383949], "conf": 0.8738771677017212, "region_caption": "a brown butterfly sitting on an orange background.", "caption_conf": 0.9297735554473283}
+ {"box_id": 3, "class_name": "butterfly", "norm_bbox": [0.6688584089279175, 0.5137135982513428, 0.11311062425374985, 0.05455022677779198], "conf": 0.8287128806114197, "region_caption": "a brown butterfly sitting on an orange wall.", "caption_conf": 0.9264783379302365}
+ {"box_id": 4, "class_name": "blouse", "norm_bbox": [0.4692786931991577, 0.6465241312980652, 0.9283269643783569, 0.6027728319168091], "conf": 0.6851752400398254, "region_caption": "a woman wearing an orange shirt with butterflies on it.", "caption_conf": 0.9978814544264754}
+ {"box_id": 5, "class_name": "short_pants", "norm_bbox": [0.44008955359458923, 0.8769687414169312, 0.8799525499343872, 0.2431662678718567], "conf": 0.6741859316825867, "region_caption": "a person wearing an orange shirt and grey sweatpants.", "caption_conf": 0.9731313580907464}
+ """
+
+ # Load detected openpose keypoint json file
+ pose_xy = self.load_pose_ann(anno_pose_path)
+ if self.pose_normalize and self.split is not 'train':
+ ref_pose_path = self.ref_pose_paths_list[idx]
+ anno_init_pose_path = self.anno_init_pose_list[idx]
+ ref_pose_xy = self.load_pose_ann(ref_pose_path)
+ for xy in ref_pose_xy:
+ if xy[0]!=-1 and xy[1]!=-1:
+ xy[0] = float(xy[0])/ref_original_width*ref_new_width
+ xy[1] = float(xy[1])/ref_original_height*ref_new_height
+
+
+ if self.normalize_by_1st_frm:
+ init_pose_xy = self.load_pose_ann(anno_init_pose_path)
+ pose_xy = self.pose_norm(image, ref_pose_xy, init_pose_xy, pose_xy)
+ else:
+ pose_xy = self.pose_norm(image, ref_pose_xy, pose_xy, pose_xy)
+
+
+ # convert coordinates to skeleton image
+ #skeleton_img = self.coco2openpose(image, pose_without_visibletag)
+ skeleton_img = self.coco2openpose(image, pose_xy)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = False
+ meta_data['skeleton_img'] = skeleton_img
+ meta_data['reference_img'] = ref_image
+ meta_data['img'] = image
+ meta_data['ref_mask'] = ref_mask
+ return meta_data
+
+ def augmentation(self, frame, transform1, transform2=None, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ frame_transform1 = transform1(frame) if transform1 is not None else frame
+ if transform2 is None:
+ return frame_transform1
+ else:
+ return transform2(frame_transform1)
+
+
+ def __getitem__(self, idx):
+ raw_data = self.get_img_txt_pair(idx)
+
+ img = raw_data['img']
+ skeleton_img = raw_data['skeleton_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+
+ # first check the size of the ref image
+ ref_img_size = raw_data['reference_img'].size
+ if self.args.strong_rand_stage2 and self.split == 'train':
+ if ref_img_size[0] > ref_img_size[1]: # width > height
+ transform1 = self.random_square_width
+ elif ref_img_size[0] < ref_img_size[1]:
+ transform1 = self.random_square_height
+ else:
+ transform1 = None
+ else:
+ transform1 = None
+
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, transform1, self.transform, state)
+
+ skeleton_img = self.augmentation(skeleton_img, transform1, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, transform1, self.transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, transform1, self.ref_transform, state)
+
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['ref_mask']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ # ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(ref_img_size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, transform1, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, transform1, self.cond_transform, state) # controlnet path input
+
+ # linshi wangtan
+ reference_img_mask = self.normalize_mask(reference_img_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+
+ outputs = {'img_key':img_key, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
+
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web_upsquare.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web_upsquare.py
new file mode 100644
index 0000000000000000000000000000000000000000..f31bde136f6e774469eb7b6a6f1c3d27713b637f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_specifcimg_web_upsquare.py
@@ -0,0 +1,628 @@
+from config import *
+import torch
+from torch.utils.data import Dataset
+from torchvision import transforms
+
+import os, math, re, json, copy
+import numpy as np
+from tqdm import tqdm
+import random
+from PIL import ImageFile, Image
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+import cv2
+import code
+
+training_templates_smallest = [
+ 'photo of a sks {}',
+]
+
+reg_templates_smallest = [
+ 'photo of a {}',
+]
+coco_joints_name = ['Nose', 'Left Eye', 'Right Eye', 'Left Ear', 'Right Ear', 'Left Shoulder', 'Right Shoulder', 'Left Elbow', 'Right Elbow', 'Left Wrist',
+ 'Right Wrist', 'Left Hip', 'Right Hip', 'Left Knee', 'Right Knee', 'Left Ankle', 'Right Ankle', 'Pelvis', 'Neck']
+
+
+class BaseDataset(Dataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.dataset = "tiktok"
+ self.args = args
+ self.split = split
+ self.is_train = split == "train"
+ self.is_composite = False
+ self.on_memory = getattr(args, 'on_memory', False)
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.pose_normalize = getattr(args, 'pose_normalize', False)
+ self.normalize_by_1st_frm = getattr(args, 'normalize_by_1st_frm', False)
+ self.max_video_len = 1 ## Todo, now it is image-based dataloader
+ self.size_frame = 1 ## Todo
+ self.yaml_file = yaml_file
+ self.stickwidth = 4
+ self.preprocesser = preprocesser
+ self.limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ self.colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ self.random_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int(torch.randint(0, img.height - img.width, (1,)).item()), left=0, height=img.width, width=img.width))
+ self.random_square_width = transforms.Lambda(lambda img: transforms.functional.crop(img, top=0, left=int(torch.randint(0, img.width - img.height, (1,)).item()), height=img.height, width=img.height))
+
+ self.fix_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int((img.height - img.width)/4), left=0, height=img.width, width=img.width))
+ min_crop_scale = 0.5 if self.args.strong_aug_stage1 and split=='train' else 1.0 # for stronger augmentation (only use in train)
+ # min_crop_scale = 0.5
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.total_num_videos = 340
+ self.anno_path = 'GIT/{:05d}/labels/{:04d}.txt'
+ self.image_path = '{:05d}/images/{:04d}.png'
+ self.anno_pose_path = '{:05d}/openpose_json/{:04d}.png.json'
+ self.ref_mask_path = '{:05d}/masks/{:04d}.png'
+
+ self.image_path_web = '{}/{}'
+ self.ref_image_path_web = '{}/{}'
+ self.anno_pose_path_web = '{}/openpose_json/{}.json'
+ self.ref_mask_path_web = '{}/groundsam/{}.mask.jpg'
+
+ self.image_paths_list = []
+ self.ref_image_paths_list = []
+ self.ref_pose_paths_list = []
+ self.anno_list = []
+ self.anno_pose_list = []
+ self.anno_init_pose_list = []
+ self.mask_list = []
+
+ ft_video_idx = getattr(args, 'ft_idx', '001_1.57_2.17_1x1') # default elon
+ if split == 'train': # for training video
+ # video_idx = ['001_1.57_2.17_1x1'] # elon mask 2
+ # video_idx = ['007_7.36_7.44_1x1'] # 007
+ # video_idx = ['001_1.57_2.17_9x16', '001_11.46_11.54_9x16', '001_5.37_5.44_9x16', '001_8.14_8.27_9x16'] # elon mask 1+2+3+4
+ video_idx = [ft_video_idx] # 007
+ dataset_prefix = self.args.web_data_root
+ else: # for pose video
+ video_idx = [335, 137]
+ # ref_video_idx = '001_1.57_2.17_1x1' # 007
+ # ref_video_idx = '007_7.36_7.44_1x1' # 007
+ ref_video_idx = ft_video_idx # 007
+ dataset_prefix = self.args.tiktok_data_root
+
+ ### use specific image video frame to ft, sample in the fly
+ for vid in video_idx:
+
+ if isinstance(vid, str): # web image data
+ assert split == 'train'
+ folder_path = os.path.join(args.web_data_root, '{}').format(vid)
+ if os.path.exists(os.path.join(folder_path, 'image_list.txt')):
+ image_files_idx = list(open(os.path.join(folder_path, 'image_list.txt')))
+ image_files_idx = [file.strip() for file in image_files_idx]
+ else:
+ image_files_idx = os.listdir(folder_path)
+ image_files_idx = [file for file in image_files_idx if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ else:
+ assert split == 'val'
+ folder_path = os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid)
+ files = os.listdir(folder_path)
+ image_files_idx = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+
+ folder_path_ref = os.path.join(args.web_data_root, '{}').format(ref_video_idx)
+ if os.path.exists(os.path.join(folder_path_ref, 'image_list.txt')):
+ image_files_idx_ref = list(open(os.path.join(folder_path_ref, 'image_list.txt')))
+ image_files_idx_ref = [file.strip() for file in image_files_idx_ref]
+ else:
+ image_files_idx_ref = os.listdir(folder_path_ref)
+ image_files_idx_ref = [file for file in image_files_idx_ref if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+
+ ### if use specific number of frames as training sample
+ ft_img_num = getattr(self.args, 'ft_img_num', 0) # default value
+ ft_one_ref_image = getattr(self.args, 'ft_one_ref_image', True) # default value
+
+ if ft_img_num>0: # randomly sample n image as training sample
+ random.seed(self.args.seed)
+ frm_list = random.sample(image_files_idx, ft_img_num)
+ frm_list.sort()
+ print('Random Sample Frames: {}'.format(frm_list))
+ else:
+ frm_list = image_files_idx
+
+ # FT: [Kevin Ver] always chooose the 1st frame as the referece image
+ # TODO: WT Revision: if t = n, then reference frm could be between frame(0)~frame(n-1)
+ if ft_one_ref_image: # only use 1st frame as the reference
+ if split == 'train':
+ while len(frm_list) < 128:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, fid))
+ ref_image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, frm_list[0]))
+ ref_mask_fname = os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, frm_list[0])) # only choose 1st frame as ref frame
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path_web.format(vid, fid))
+
+ # anno_fname = self.anno_path.format(vid, fid)
+ anno_fname = os.path.join(dataset_prefix, vid + '__' + fid)
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ else: # use tiktok pose for dancing
+ ref_image_fname = os.path.join(self.args.web_data_root, self.image_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+ ref_mask_fname = os.path.join(self.args.web_data_root, self.ref_mask_path_web.format(ref_video_idx, image_files_idx_ref[0])) # only choose 1st frame as ref frame
+ ref_pose_fname = os.path.join(self.args.web_data_root, self.anno_pose_path_web.format(ref_video_idx, image_files_idx_ref[0]))
+
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ image_fname = os.path.join(dataset_prefix, self.image_path.format(vid, fid % refpose_image_files_len))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, fid % refpose_image_files_len)) # change to the next frame's pose
+ anno_fname = os.path.join(dataset_prefix, self.anno_path.format(vid, fid % refpose_image_files_len))
+ anno_init_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, 1))
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.ref_pose_paths_list.append(ref_pose_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.anno_init_pose_list.append(anno_init_pose_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ # random sort the input list for visualization
+ random_idx = list(range(len(self.image_paths_list)))
+ random.shuffle(random_idx)
+ self.image_paths_list = [self.image_paths_list[i] for i in random_idx]
+ self.ref_image_paths_list = [self.ref_image_paths_list[i] for i in random_idx]
+ self.ref_pose_paths_list = [self.ref_pose_paths_list[i] for i in random_idx]
+
+ self.anno_pose_list = [self.anno_pose_list[i] for i in random_idx]
+ self.anno_list = [self.anno_list[i] for i in random_idx]
+ self.mask_list = [self.mask_list[i] for i in random_idx]
+ self.anno_init_pose_list = [self.anno_init_pose_list[i] for i in random_idx]
+
+
+ else:
+ if split == 'train':
+ while len(frm_list) < 12:
+ frm_list *= 2 # enlarge the dataset to fix the dataloader bug
+ for fid in frm_list:
+ # ref image use random sample
+ ref_resample_flag = True
+ while ref_resample_flag:
+ ref_fid = random.choice(frm_list)
+ if os.path.exists(os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, ref_fid))):
+ ref_resample_flag = False
+
+ image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, fid))
+ ref_image_fname = os.path.join(dataset_prefix, self.image_path_web.format(vid, ref_fid))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path_web.format(vid, fid))
+
+ # anno_fname = self.anno_path.format(vid, fid)
+ anno_fname = os.path.join(dataset_prefix, vid + '__' + fid)
+ ref_mask_fname = os.path.join(dataset_prefix, self.ref_mask_path_web.format(vid, ref_fid)) # only choose 1st frame as ref frame
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.mask_list.append(ref_mask_fname)
+
+
+ else: # use tiktok pose for dancing, randomly choose one frame as ref
+ # ref image use random sample
+ ref_resample_flag = True
+ while ref_resample_flag:
+ ref_fid = random.choice(image_files_idx_ref)
+ if os.path.exists(os.path.join(self.args.web_data_root, self.ref_mask_path_web.format(ref_video_idx, ref_fid))):
+ ref_resample_flag = False
+
+ ref_image_fname = os.path.join(self.args.web_data_root, self.image_path_web.format(ref_video_idx, ref_fid))
+ ref_mask_fname = os.path.join(self.args.web_data_root, self.ref_mask_path_web.format(ref_video_idx, ref_fid)) # only choose 1st frame as ref frame
+ ref_pose_fname = os.path.join(self.args.web_data_root, self.anno_pose_path_web.format(ref_video_idx, ref_fid))
+
+ refpose_files = os.listdir(os.path.join(args.tiktok_data_root, '{:05d}/images/').format(vid))
+ refpose_image_files = [file for file in refpose_files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ refpose_image_files_len = len(refpose_image_files)
+ for fid in range(1, refpose_image_files_len):
+ image_fname = os.path.join(dataset_prefix, self.image_path.format(vid, fid % refpose_image_files_len))
+ anno_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, fid % refpose_image_files_len)) # change to the next frame's pose
+ anno_fname = os.path.join(dataset_prefix, self.anno_path.format(vid, fid % refpose_image_files_len))
+ anno_init_pose_fname = os.path.join(dataset_prefix, self.anno_pose_path.format(vid, 1))
+ self.image_paths_list.append(image_fname)
+ self.ref_image_paths_list.append(ref_image_fname)
+ self.ref_pose_paths_list.append(ref_pose_fname)
+ self.anno_pose_list.append(anno_pose_fname)
+ self.anno_list.append(anno_fname)
+ self.anno_init_pose_list.append(anno_init_pose_fname)
+ self.mask_list.append(ref_mask_fname)
+
+ # random sort the input list for visualization
+ random_idx = list(range(len(self.image_paths_list)))
+ random.shuffle(random_idx)
+ self.image_paths_list = [self.image_paths_list[i] for i in random_idx]
+ self.ref_image_paths_list = [self.ref_image_paths_list[i] for i in random_idx]
+ self.ref_pose_paths_list = [self.ref_pose_paths_list[i] for i in random_idx]
+
+ self.anno_pose_list = [self.anno_pose_list[i] for i in random_idx]
+ self.anno_list = [self.anno_list[i] for i in random_idx]
+ self.mask_list = [self.mask_list[i] for i in random_idx]
+ self.anno_init_pose_list = [self.anno_init_pose_list[i] for i in random_idx]
+
+
+ self.num_images = len(self.image_paths_list)
+ self._length = self.num_images
+ print('number of samples:',self._length)
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, self._length)
+ else:
+ return self._length
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, self._length)
+ else:
+ return self._length
+
+ # draw the body keypoint and lims
+ def draw_bodypose(self, canvas, pose):
+ canvas = cv2.cvtColor(np.array(canvas), cv2.COLOR_RGB2BGR)
+ canvas = np.zeros_like(canvas)
+
+ for i in range(18):
+ x, y = pose[i][0:2]
+ if x>=0 and y>=0:
+ cv2.circle(canvas, (int(x), int(y)), 4, self.colors[i], thickness=-1)
+ # cv2.putText(canvas, '%d'%(i), (int(x), int(y)-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (36,255,12), 2)
+ for limb_idx in range(17):
+ cur_canvas = canvas.copy()
+ index_a = self.limbSeq[limb_idx][0]-1
+ index_b = self.limbSeq[limb_idx][1]-1
+
+ if pose[index_a][0]<0 or pose[index_b][0]<0 or pose[index_a][1]<0 or pose[index_b][1]<0:
+ continue
+
+ Y = [pose[index_a][0], pose[index_b][0]]
+ X = [pose[index_a][1], pose[index_b][1]]
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), self.stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(cur_canvas, polygon, self.colors[limb_idx])
+ canvas = cv2.addWeighted(canvas, 0.4, cur_canvas, 0.6, 0)
+ # Convert color space from BGR to RGB
+ # canvas = cv2.cvtColor(canvas, cv2.COLOR_BGR2RGB)
+ # Create PIL image object from numpy array
+ canvas = Image.fromarray(canvas)
+ return canvas
+
+
+ def coco2openpose(self, img, coco_keypoints):
+
+ # coco keypoints: [x1,y1,v1,...,xk,yk,vk] (k=17)
+ # ['Nose', Leye', 'Reye', 'Lear', 'Rear', 'Lsho', 'Rsho', 'Lelb',
+ # 'Relb', 'Lwri', 'Rwri', 'Lhip', 'Rhip', 'Lkne', 'Rkne', 'Lank', 'Rank']
+ # openpose keypoints: [y1,...,yk], [x1,...xk] (k=18, with Neck)
+ # ['Nose' (0), *'Neck'* (1), 'Rsho' (2), 'Relb' (3), 'Rwri' (4), 'Lsho' (5), 'Lelb' (6), 'Lwri' (7),'Rhip' (8),
+ # 'Rkne' (9), 'Rank' (10), 'Lhip' (11), 'Lkne' (12), 'Lank' (13), 'Reye' (14), 'Leye' (15), 'Rear' (16), 'Lear' (17)]
+
+ openpose_keypoints = [
+ coco_keypoints[0], # Nose (0)
+ list((np.asarray(coco_keypoints[5]) + np.asarray(coco_keypoints[6]))/2), # Neck (1)
+ coco_keypoints[6], # RShoulder (2)
+ coco_keypoints[8], # RElbow (3)
+ coco_keypoints[10], # RWrist (4)
+ coco_keypoints[5], # LShoulder (5)
+ coco_keypoints[7], # LElbow (6)
+ coco_keypoints[9], # LWrist (7)
+ coco_keypoints[12], # RHip (8)
+ coco_keypoints[14], # RKnee (9)
+ coco_keypoints[16], # RAnkle (10)
+ coco_keypoints[11], # LHip (11)
+ coco_keypoints[13], # LKnee (12)
+ coco_keypoints[15], # LAnkle (13)
+ coco_keypoints[2], # REye (14)
+ coco_keypoints[1], # LEye (15)
+ coco_keypoints[4], # REar (16)
+ coco_keypoints[3], # LEar (17)
+ ]
+ return self.draw_bodypose(img, openpose_keypoints)
+
+
+ def load_image(self, path):
+ if os.path.exists(path):
+ image = Image.open(path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+ else:
+ image = None
+ return image
+
+ def load_mask(self, path):
+ try:
+ if os.path.exists(path):
+ img = self.load_image(path)
+ img = np.asarray(img)
+ bk = img[:, :, :] == [68, 0, 83]
+ fg = (bk == False)
+ fg = fg * 255.0
+ mask = fg.astype(np.uint8)
+ ipl_mask = Image.fromarray(mask)
+ else:
+ ipl_mask = None
+ except Exception as e:
+ print(e)
+ ipl_mask = None
+ return ipl_mask
+
+ def load_pose_ann(self, anno_pose_path):
+ # Load detected openpose keypoint json file
+ pose_without_visibletag = []
+ f = open(anno_pose_path, 'r')
+ d = json.load(f)
+ # if there is a valid openpose skeleton, load it
+ if len(d) > 0:
+ for j in range(17):
+ x = d[0]['keypoints'][j][0]
+ y = d[0]['keypoints'][j][1]
+ pose_without_visibletag.append([x, y])
+ else: # if there is not valid openpose skeleton, add a dummy one
+ for j in range(17):
+ x = -1
+ y = -1
+ pose_without_visibletag.append([x, y])
+ return pose_without_visibletag
+
+ def get_valid_jnt_index(self, image, pose):
+ img_width, img_height = image.size
+ valid_pose_index = np.asarray(
+ [item[0] > -1 and item[0] < img_width and item[1] > -1 and item[1] < img_height for item in pose])
+ # when compute affine transform, skip joints on the arms and legs
+ valid_pose_index[10] = False # RWrist
+ valid_pose_index[9] = False # LWrist
+ valid_pose_index[16] = False # RAnkle
+ valid_pose_index[15] = False # LAnkle
+ # add Neck to joint set
+ if valid_pose_index[5] == True and valid_pose_index[6] == True:
+ pose.append(list((np.asarray(pose[5]) + np.asarray(pose[6])) / 2))
+ valid_pose_index = np.append(valid_pose_index, True)
+ else:
+ pose.append([-1, -1])
+ valid_pose_index = np.append(valid_pose_index, False)
+ # add Pelvis to joint set
+ if valid_pose_index[11] == True and valid_pose_index[12] == True:
+ pose.append(list((np.asarray(pose[11]) + np.asarray(pose[12])) / 2))
+ valid_pose_index = np.append(valid_pose_index, True)
+ else:
+ pose.append([-1, -1])
+ valid_pose_index = np.append(valid_pose_index, False)
+ return valid_pose_index, pose
+
+ def pose_norm(self, image, input_ref_pose, input_init_pose, input_pose):
+ ref_pose = copy.deepcopy(input_ref_pose)
+ init_pose = copy.deepcopy(input_init_pose)
+ pose = copy.deepcopy(input_pose)
+ # compute transformation between ref_pose and init_pose, and apply transforms to pose
+ # get index for the valid joints
+ valid_ref_pose, ref_pose = self.get_valid_jnt_index(image, ref_pose) # reference pose is the pose of reference image
+ valid_init_pose, init_pose = self.get_valid_jnt_index(image, init_pose) # init pose is the initial target pose (1st frame)
+
+ # get common valid joints
+ common_valid_pose = valid_ref_pose * valid_init_pose
+ # if limited joints available, skip normalization
+ if np.sum(common_valid_pose * 1) < 5:
+ t_x, t_y = 0, 0
+ s_x, s_y = 1, 1
+ else:
+ np_ref_pose = np.asarray(ref_pose)
+ np_init_pose = np.asarray(init_pose)
+ np_ref_pose_set = np_ref_pose[common_valid_pose]
+ np_init_pose_set = np_init_pose[common_valid_pose]
+ # get affine trans matrix: transform from init pose to ref pose
+ affine_matrix, _ = cv2.estimateAffinePartial2D(np_init_pose_set, np_ref_pose_set)
+ t_x = affine_matrix[0, 2]
+ t_y = affine_matrix[1, 2]
+ s_x = np.sign(affine_matrix[0, 0]) * np.sqrt(
+ affine_matrix[0, 0] * affine_matrix[0, 0] + affine_matrix[0, 1] * affine_matrix[0, 1])
+ s_y = np.sign(affine_matrix[1, 1]) * np.sqrt(
+ affine_matrix[1, 0] * affine_matrix[1, 0] + affine_matrix[1, 1] * affine_matrix[1, 1])
+
+ # apply scale + translate to the given pose
+ for i in range(len(pose)):
+ if pose[i][0] >= 0 or pose[i][1] >= 0:
+ pose[i][0] = int(pose[i][0] * s_x + t_x)
+ pose[i][1] = int(pose[i][1] * s_y + t_y)
+ return pose
+
+ def normalize_mask(self, mask):
+ mask[mask>=0.001] = 1
+ mask[mask<0.001] = 0
+ return mask
+
+
+ def get_img_txt_pair(self, idx):
+
+ # img_path = os.path.join(self.args.tiktok_data_root, self.image_paths_list[idx % self.num_images])
+ # ref_img_path = os.path.join(self.args.tiktok_data_root, self.ref_image_paths_list[idx % self.num_images])
+ # anno_pose_path = os.path.join(self.args.tiktok_data_root, self.anno_pose_list[idx % self.num_images])
+ # anno_path = os.path.join(self.args.tiktok_data_root, self.anno_list[idx % self.num_images])
+ # ref_mask_path = os.path.join(self.args.tiktok_data_root, self.mask_list[idx % self.num_images])
+
+ img_path = self.image_paths_list[idx % self.num_images]
+ ref_img_path = self.ref_image_paths_list[idx % self.num_images]
+
+ anno_pose_path = self.anno_pose_list[idx % self.num_images]
+ anno_path = self.anno_list[idx % self.num_images]
+ ref_mask_path = self.mask_list[idx % self.num_images]
+
+ image = Image.open(img_path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+
+ if 'youtube' in ref_mask_path:
+ ref_mask = self.load_mask(ref_mask_path)
+ else:
+ ref_mask = Image.open(ref_mask_path).convert('RGB')
+
+ ref_image = Image.open(ref_img_path)
+ if not ref_image.mode == "RGB":
+ ref_image = ref_image.convert("RGB")
+
+ ref_original_width, ref_original_height = ref_image.size
+ ref_mask = ref_mask.resize(ref_image.size) # resize the mask to img
+ if self.pose_normalize and self.split is not 'train':
+ ref_image = ref_image.resize(image.size)
+ ref_new_width, ref_new_height = ref_image.size
+
+ if 'youtube' in anno_pose_path:
+ img_key = self.anno_list[idx % self.num_images]
+ else:
+ anno = list(open(anno_path))
+ img_key = json.loads(anno[0].strip())['image_key']
+ """
+ example:
+ {"num_region": 6, "image_key": "TiktokDance_00001_0002.png", "image_split": "00001", "image_read_error": false}
+ {"box_id": 0, "class_name": "aerosol_can", "norm_bbox": [0.5, 0.5, 1.0, 1.0], "conf": 0.0, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 1, "class_name": "person", "norm_bbox": [0.46692365407943726, 0.4977584183216095, 0.9338473081588745, 0.995516836643219], "conf": 0.912740170955658, "region_caption": "a woman with an orange dress with butterflies on her shirt.", "caption_conf": 0.9404542168542169}
+ {"box_id": 2, "class_name": "butterfly", "norm_bbox": [0.2368704378604889, 0.5088028907775879, 0.1444256454706192, 0.04199704900383949], "conf": 0.8738771677017212, "region_caption": "a brown butterfly sitting on an orange background.", "caption_conf": 0.9297735554473283}
+ {"box_id": 3, "class_name": "butterfly", "norm_bbox": [0.6688584089279175, 0.5137135982513428, 0.11311062425374985, 0.05455022677779198], "conf": 0.8287128806114197, "region_caption": "a brown butterfly sitting on an orange wall.", "caption_conf": 0.9264783379302365}
+ {"box_id": 4, "class_name": "blouse", "norm_bbox": [0.4692786931991577, 0.6465241312980652, 0.9283269643783569, 0.6027728319168091], "conf": 0.6851752400398254, "region_caption": "a woman wearing an orange shirt with butterflies on it.", "caption_conf": 0.9978814544264754}
+ {"box_id": 5, "class_name": "short_pants", "norm_bbox": [0.44008955359458923, 0.8769687414169312, 0.8799525499343872, 0.2431662678718567], "conf": 0.6741859316825867, "region_caption": "a person wearing an orange shirt and grey sweatpants.", "caption_conf": 0.9731313580907464}
+ """
+
+ # Load detected openpose keypoint json file
+ pose_xy = self.load_pose_ann(anno_pose_path)
+ if self.pose_normalize and self.split is not 'train':
+ ref_pose_path = self.ref_pose_paths_list[idx]
+ anno_init_pose_path = self.anno_init_pose_list[idx]
+ ref_pose_xy = self.load_pose_ann(ref_pose_path)
+ for xy in ref_pose_xy:
+ if xy[0]!=-1 and xy[1]!=-1:
+ xy[0] = float(xy[0])/ref_original_width*ref_new_width
+ xy[1] = float(xy[1])/ref_original_height*ref_new_height
+
+
+ if self.normalize_by_1st_frm:
+ init_pose_xy = self.load_pose_ann(anno_init_pose_path)
+ pose_xy = self.pose_norm(image, ref_pose_xy, init_pose_xy, pose_xy)
+ else:
+ pose_xy = self.pose_norm(image, ref_pose_xy, pose_xy, pose_xy)
+
+
+ # convert coordinates to skeleton image
+ #skeleton_img = self.coco2openpose(image, pose_without_visibletag)
+ skeleton_img = self.coco2openpose(image, pose_xy)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = False
+ meta_data['skeleton_img'] = skeleton_img
+ meta_data['reference_img'] = ref_image
+ meta_data['img'] = image
+ meta_data['ref_mask'] = ref_mask
+ return meta_data
+
+ def augmentation(self, frame, transform1, transform2=None, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ frame_transform1 = transform1(frame) if transform1 is not None else frame
+ if transform2 is None:
+ return frame_transform1
+ else:
+ return transform2(frame_transform1)
+
+
+ def __getitem__(self, idx):
+ raw_data = self.get_img_txt_pair(idx)
+
+ img = raw_data['img']
+ skeleton_img = raw_data['skeleton_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+
+ # first check the size of the ref image
+ ref_img_size = raw_data['reference_img'].size
+ if self.args.strong_rand_stage2 and self.split == 'train':
+ if ref_img_size[0] > ref_img_size[1]: # width > height
+ transform1 = self.random_square_width
+ elif ref_img_size[0] < ref_img_size[1]:
+ transform1 = self.random_square_height
+ else:
+ transform1 = None
+ else:
+ transform1 = self.fix_square_height
+
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, transform1, self.transform, state)
+
+ skeleton_img = self.augmentation(skeleton_img, transform1, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, transform1, self.transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, transform1, self.ref_transform, state)
+
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['ref_mask']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ # ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(ref_img_size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, transform1, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, transform1, self.cond_transform, state) # controlnet path input
+
+ # linshi wangtan
+ reference_img_mask = self.normalize_mask(reference_img_mask)
+ reference_img_controlnet_mask = self.normalize_mask(reference_img_controlnet_mask)
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+
+ outputs = {'img_key':img_key, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
+
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..86c437088aa21b021af6dfb867d8dd71dec4932c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv.py
@@ -0,0 +1,190 @@
+from config import *
+import torch
+import numpy as np
+from PIL import Image
+from dataset.tsv_cond_dataset import TsvCondImgCompositeDataset
+
+
+class BaseDataset(TsvCondImgCompositeDataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.basic_root_dir = BasicArgs.root_dir
+ self.max_video_len = args.max_video_len
+ assert self.max_video_len == 1
+ self.fps = args.fps
+ self.dataset = "TiktokDance-Image"
+ self.preprocesser = preprocesser
+ if not hasattr(args, "ref_mode"):
+ args.ref_mode = "first"
+
+ super().__init__(
+ args, yaml_file, split=split,
+ size_frame=args.max_video_len, tokzr=None)
+ self.data_dir = args.data_dir
+ self.img_ratio = (1., 1.) if not hasattr(self.args, 'img_ratio') or self.args.img_ratio is None else self.args.img_ratio
+ self.img_scale = (1., 1.) if not split=='train' else getattr(self.args, 'img_scale', (0.9, 1.0)) # val set should keep scale=1.0 to avoid the random crop
+ print(f'Current Data: {split}; Use image scale: {self.img_scale}; Use image ratio: {self.img_ratio}')
+
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+ try:
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC, antialias=False),
+ transforms.ToTensor(),
+ ])
+ except:
+ print('### Current pt version not support antialias, thus remove it! ###')
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=self.img_scale, ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ def add_mask_to_img(self, img, mask, img_key): #pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(img_array * (1-mask_array)) # foreground, background
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def get_metadata(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, _) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(img_idx)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = is_video # True: video data, False: image data
+ meta_data['pose_img'] = self.get_cond(img_idx, 'poses')
+ if self.args.combine_use_mask:
+ meta_data['mask_img'] = self.get_cond(img_idx, 'masks')
+ ref_img_idx = self.get_reference_frame_idx(img_idx)
+ meta_data['ref_img_key'] = self.image_keys[ref_img_idx]
+ meta_data['reference_img'], _ = self.get_visual_data(ref_img_idx)
+ if self.args.combine_use_mask:
+ meta_data['mask_img_ref'] = self.get_cond(ref_img_idx, 'masks')
+ meta_data['img'] = frames
+ return meta_data
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(
+ f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, super().__len__())
+ else:
+ return super().__len__()
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, super().__len__())
+ else:
+ return super().__len__()
+
+ def __getitem__(self, idx):
+ # try:
+ raw_data = self.get_metadata(idx)
+ # except Exception as e:
+ # print(e, self.yaml_file)
+ img = raw_data['img']
+ skeleton_img = raw_data['pose_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+ ref_img_key = raw_data['ref_img_key']
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, self.transform, state) # controlnet path input
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, self.ref_transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['mask_img_ref']
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+
+ ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(raw_data['reference_img'].size)
+
+ reference_img_mask = self.augmentation(mask_img_ref, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, self.cond_transform, state) # controlnet path input
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv_strongaug.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv_strongaug.py
new file mode 100644
index 0000000000000000000000000000000000000000..47104e97d4d609b6f9f1fc158ff951c9b218a31c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_controlnet_t2i_imagevar_combine_tsv_strongaug.py
@@ -0,0 +1,192 @@
+from config import *
+import torch
+import numpy as np
+from PIL import Image
+from dataset.tsv_cond_dataset import TsvCondImgCompositeDataset
+
+
+class BaseDataset(TsvCondImgCompositeDataset):
+ def __init__(self, args, yaml_file, split='train', preprocesser=None):
+ self.img_size = getattr(args, 'img_full_size', args.img_size)
+ self.basic_root_dir = BasicArgs.root_dir
+ self.max_video_len = args.max_video_len
+ assert self.max_video_len == 1
+ self.fps = args.fps
+ self.dataset = "TiktokDance-Image"
+ self.preprocesser = preprocesser
+ if not hasattr(args, "ref_mode"):
+ args.ref_mode = "first"
+ self.split = split
+
+ super().__init__(
+ args, yaml_file, split=split,
+ size_frame=args.max_video_len, tokzr=None)
+ self.data_dir = args.data_dir
+
+ self.random_square_height = transforms.Lambda(lambda img: transforms.functional.crop(img, top=int(torch.randint(0, img.height - img.width, (1,)).item()), left=0, height=img.width, width=img.width))
+ self.random_square_width = transforms.Lambda(lambda img: transforms.functional.crop(img, top=0, left=int(torch.randint(0, img.width - img.height, (1,)).item()), height=img.height, width=img.height))
+
+ min_crop_scale = 0.5 if self.args.strong_aug_stage2 and split=='train' else 0.9 # for stronger augmentation (only use in train)
+ self.transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ])
+
+ self.cond_transform = transforms.Compose([
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BILINEAR),
+ transforms.ToTensor(),
+ ])
+
+ self.ref_transform = transforms.Compose([ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.Normalize([0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711]),
+ ])
+
+ self.ref_transform_mask = transforms.Compose([ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=(min_crop_scale, 1.0), ratio=(1., 1.),
+ interpolation=transforms.InterpolationMode.BICUBIC),
+ transforms.ToTensor(),
+ ])
+
+
+ def add_mask_to_img(self, img, mask, img_key): #pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(img_array * (1-mask_array)) # foreground, background
+
+ def augmentation(self, frame, transform1, transform2=None, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ frame_transform1 = transform1(frame) if transform1 is not None else frame
+ if transform2 is None:
+ return frame_transform1
+ else:
+ return transform2(frame_transform1)
+
+ def get_metadata(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, _) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(img_idx)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = is_video # True: video data, False: image data
+ meta_data['pose_img'] = self.get_cond(img_idx, 'poses')
+ if self.args.combine_use_mask:
+ meta_data['mask_img'] = self.get_cond(img_idx, 'masks')
+ ref_img_idx = self.get_reference_frame_idx(img_idx)
+ meta_data['ref_img_key'] = self.image_keys[ref_img_idx]
+ meta_data['reference_img'], _ = self.get_visual_data(ref_img_idx)
+ if self.args.combine_use_mask:
+ meta_data['mask_img_ref'] = self.get_cond(ref_img_idx, 'masks')
+ meta_data['img'] = frames
+ return meta_data
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(
+ f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ if self.split == 'train':
+ if getattr(self.args, 'max_train_samples', None):
+ return min(self.args.max_train_samples, super().__len__())
+ else:
+ return super().__len__()
+ else:
+ if getattr(self.args, 'max_eval_samples', None):
+ return min(self.args.max_eval_samples, super().__len__())
+ else:
+ return super().__len__()
+
+ def __getitem__(self, idx):
+ # try:
+ raw_data = self.get_metadata(idx)
+ # except Exception as e:
+ # print(e, self.yaml_file)
+ img = raw_data['img']
+ skeleton_img = raw_data['pose_img']
+ reference_img = raw_data['reference_img']
+ img_key = raw_data['img_key']
+ ref_img_key = raw_data['ref_img_key']
+
+ # first check the size of the ref image
+ ref_img_size = raw_data['reference_img'].size
+ if self.args.strong_rand_stage2 and self.split=='train':
+ if ref_img_size[0] > ref_img_size[1]: # width > height
+ transform1 = self.random_square_width
+ elif ref_img_size[0] < ref_img_size[1]:
+ transform1 = self.random_square_height
+ else:
+ transform1 = None
+ else:
+ transform1 = None
+
+ reference_img_controlnet = reference_img
+ state = torch.get_rng_state()
+ img = self.augmentation(img, transform1, self.transform, state)
+ skeleton_img = self.augmentation(skeleton_img, transform1, self.cond_transform, state)
+ reference_img_controlnet = self.augmentation(reference_img_controlnet, transform1, self.transform, state) # controlnet path input
+ if getattr(self.args, 'refer_clip_preprocess', None):
+ reference_img = self.preprocesser(reference_img).pixel_values[0] # use clip preprocess
+ else:
+ reference_img = self.augmentation(reference_img, transform1, self.ref_transform, state)
+
+ reference_img_vae = reference_img_controlnet
+ if self.args.combine_use_mask:
+ mask_img_ref = raw_data['mask_img_ref']
+ ### first resize mask to the img size
+ mask_img_ref = mask_img_ref.resize(ref_img_size)
+
+ assert not getattr(self.args, 'refer_clip_preprocess', None) # mask not support the CLIP process
+ reference_img_mask = self.augmentation(mask_img_ref, transform1, self.ref_transform_mask, state)
+ reference_img_controlnet_mask = self.augmentation(mask_img_ref, transform1, self.cond_transform, state) # controlnet path input
+
+ # apply the mask
+ reference_img = reference_img * reference_img_mask# foreground
+ reference_img_vae = reference_img_vae * reference_img_controlnet_mask # foreground, but for vae
+ reference_img_controlnet = reference_img_controlnet * (1 - reference_img_controlnet_mask)# background
+
+ caption = raw_data['caption']
+ outputs = {'img_key':img_key, 'input_text': caption, 'label_imgs': img, 'cond_imgs': skeleton_img, 'reference_img': reference_img, 'reference_img_controlnet':reference_img_controlnet, 'reference_img_vae':reference_img_vae}
+ if self.args.combine_use_mask:
+ outputs['background_mask'] = (1 - reference_img_mask)
+ outputs['background_mask_controlnet'] = (1 - reference_img_controlnet_mask)
+
+ return outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_video_dataset.py b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_video_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..9982b0ae097417aedb66de51024ff0dcb908e180
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tiktok_video_dataset.py
@@ -0,0 +1,354 @@
+import re
+
+import numpy as np
+import torch
+from PIL import Image
+
+from config import *
+from dataset.tsv_cond_dataset import TsvCondImgCompositeDataset
+
+
+class BaseDataset(TsvCondImgCompositeDataset):
+ def __init__(self, args, yaml_file, split="train", preprocesser=None):
+ self.img_size = getattr(args, "img_full_size", args.img_size)
+ self.basic_root_dir = BasicArgs.root_dir
+ self.max_video_len = args.max_video_len
+ assert self.max_video_len == 1
+ self.fps = args.fps
+ self.dataset = "TiktokDance-Image"
+ self.preprocesser = preprocesser
+ if not hasattr(args, "ref_mode"):
+ args.ref_mode = "first"
+
+ super().__init__(
+ args, yaml_file, split=split, size_frame=args.max_video_len, tokzr=None
+ )
+ self.eval_sample_interval = args.eval_sample_interval
+ self.train_sample_interval = args.train_sample_interval
+ self.img_key_dict = {key: i for i, key in enumerate(self.image_keys)}
+ self.data_dir = args.data_dir
+ self.img_ratio = (
+ (1.0, 1.0)
+ if not hasattr(self.args, "img_ratio") or self.args.img_ratio is None
+ else self.args.img_ratio
+ )
+ self.img_scale = (
+ (1.0, 1.0)
+ if not split == "train"
+ else getattr(self.args, "img_scale", (0.9, 1.0))
+ ) # val set should keep scale=1.0 to avoid the random crop
+ print(
+ f"Current Data: {split}; Use image scale: {self.img_scale}; Use image ratio: {self.img_ratio}"
+ )
+
+ self.transform = transforms.Compose(
+ [
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BILINEAR,
+ ),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5], [0.5]),
+ ]
+ )
+ try:
+ self.ref_transform = transforms.Compose(
+ [ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC,
+ antialias=False,
+ ),
+ transforms.Normalize(
+ [0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711],
+ ),
+ ]
+ )
+ self.ref_transform_mask = transforms.Compose(
+ [ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC,
+ antialias=False,
+ ),
+ transforms.ToTensor(),
+ ]
+ )
+ except:
+ print("### Current pt version not support antialias, thus remove it! ###")
+ self.ref_transform = transforms.Compose(
+ [ # follow CLIP transform
+ transforms.ToTensor(),
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC,
+ ),
+ transforms.Normalize(
+ [0.48145466, 0.4578275, 0.40821073],
+ [0.26862954, 0.26130258, 0.27577711],
+ ),
+ ]
+ )
+ self.ref_transform_mask = transforms.Compose(
+ [ # follow CLIP transform
+ transforms.RandomResizedCrop(
+ (224, 224),
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BICUBIC,
+ ),
+ transforms.ToTensor(),
+ ]
+ )
+ self.cond_transform = transforms.Compose(
+ [
+ transforms.RandomResizedCrop(
+ self.img_size,
+ scale=self.img_scale,
+ ratio=self.img_ratio,
+ interpolation=transforms.InterpolationMode.BILINEAR,
+ ),
+ transforms.ToTensor(),
+ ]
+ )
+
+ def add_mask_to_img(self, img, mask, img_key): # pil, pil
+ if not img.size == mask.size:
+ # import pdb; pdb.set_trace()
+ # print(f'Reference image ({img_key}) size ({img.size}) is different from the mask size ({mask.size}), therefore try to resize the mask')
+ mask = mask.resize(img.size) # resize the mask
+ mask_array = np.array(mask)
+ img_array = np.array(img)
+ mask_array[mask_array < 127.5] = 0
+ mask_array[mask_array > 127.5] = 1
+ return Image.fromarray(img_array * mask_array), Image.fromarray(
+ img_array * (1 - mask_array)
+ ) # foreground, background
+
+ def augmentation(self, frame, transform, state=None):
+ if state is not None:
+ torch.set_rng_state(state)
+ return transform(frame)
+
+ def _get_frame_idx_seq(self, start_img_key, nframes: int, frame_interval: int):
+ format1 = r"^(.*TiktokDance_\d+_)(\d+)(\.\w+)$"
+ format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\.\w+)$"
+ format3 = r"^(.*_TiktokDance_[a-z0-9]+_\d+_)(\d+)(\.\w+)$"
+ format4 = r"^(?!.*TiktokDance)([^_]+_)(\d+)$" # NTU dataset
+ match1 = re.match(format1, start_img_key)
+ match2 = re.match(format2, start_img_key)
+ match3 = re.match(format3, start_img_key)
+ match4 = re.match(format4, start_img_key)
+ if match1:
+ prefix, start_frame_idx, suffix = match1.groups()
+ elif match2:
+ prefix, start_frame_idx, suffix = match2.groups()
+ elif match3:
+ prefix, start_frame_idx, suffix = match3.groups()
+ elif match4:
+ prefix, start_frame_idx = match4.groups()
+ suffix = ""
+ else:
+ raise IndexError(f"failed to parse {start_img_key}")
+
+ start_frame_idx_int = int(start_frame_idx)
+ img_idx_seq = []
+ for i in range(nframes):
+ frame_idx = str(start_frame_idx_int + i * frame_interval).zfill(
+ len(start_frame_idx)
+ )
+ img_key = prefix + frame_idx + suffix
+ if img_key not in self.img_key_dict:
+ return False, None
+ img_idx_seq.append(self.img_key_dict[img_key])
+ return True, img_idx_seq
+
+ def get_metadata(self, idx):
+ while True:
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ status, frame_idx_seq = self._get_frame_idx_seq(
+ self.image_keys[img_idx], self.args.nframes, self.args.frame_interval
+ )
+ if status:
+ break
+ idx -= 1
+
+ frame_seq = []
+ img_key_seq = []
+ for frame_idx in frame_idx_seq:
+ img_key = self.image_keys[frame_idx]
+ frame, _ = self.get_visual_data(frame_idx)
+ frame_seq.append(frame)
+ img_key_seq.append(img_key)
+
+ pose_img_seq = []
+ for frame_idx in frame_idx_seq:
+ pose_img = self.get_cond(frame_idx, "poses")
+ pose_img_seq.append(pose_img)
+
+ # preparing outputs
+ meta_data = {}
+ meta_data["img_seq"] = frame_seq
+ meta_data["img_key_seq"] = img_key_seq
+ meta_data["pose_img_seq"] = pose_img_seq
+
+ ref_img_idx = self.get_reference_frame_idx(img_idx)
+ meta_data["ref_img_key"] = self.image_keys[ref_img_idx]
+ meta_data["ref_img"], _ = self.get_visual_data(ref_img_idx)
+ meta_data["ref_mask"] = self.get_cond(ref_img_idx, "masks")
+ meta_data["bg_ref_img_key"] = meta_data["ref_img_key"]
+ meta_data["bg_ref_img"] = meta_data["ref_img"]
+ meta_data["bg_ref_mask"] = meta_data["ref_mask"]
+
+ return meta_data
+
+ def get_reference_frame_idx(self, img_idx):
+ def _get_first_frame_img_key(prefix, frame_idx, suffix):
+ new_frame_idx = str(1).zfill(len(frame_idx))
+ result = prefix + new_frame_idx + suffix
+ if result in self.img_key_dict.keys():
+ return result
+ else:
+ keys = [key for key in self.img_key_dict.keys() if prefix in key]
+ keys = sorted(keys)
+ return keys[0]
+
+ img_key = self.image_keys[img_idx]
+ format1 = r"^(.*TiktokDance_\d+_)(\d+)(\.\w+)$"
+ format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\.\w+)$"
+ format3 = r"^(.*_TiktokDance_[a-z0-9]+_\d+_)(\d+)(\.\w+)$"
+ format4 = r"^(?!.*TiktokDance)([^_]+_)(\d+)$" # NTU dataset
+ match1 = re.match(format1, img_key)
+ match2 = re.match(format2, img_key)
+ match3 = re.match(format3, img_key)
+ match4 = re.match(format4, img_key)
+ if match1:
+ prefix, frame_idx, suffix = match1.groups()
+ # print(f"{img_key} matched to match1, {prefix}, {frame_idx}, {suffix}")
+ elif match2:
+ prefix, frame_idx, suffix = match2.groups()
+ # print(f"{img_key} matched to match2, {prefix}, {frame_idx}, {suffix}")
+ elif match3:
+ prefix, frame_idx, suffix = match3.groups()
+ # print(f"{img_key} matched to match3, {prefix}, {frame_idx}, {suffix}")
+ elif match4:
+ prefix, frame_idx = match4.groups()
+ suffix = ""
+ # print(f"{img_key} matched to match4, {prefix}, {frame_idx}")
+ else:
+ print("failed to match the image key: ", img_key)
+ return super().get_reference_frame_idx(img_idx)
+
+ try:
+ if self.args.ref_mode == "first" or self.split != "train":
+ new_img_key = _get_first_frame_img_key(prefix, frame_idx, suffix)
+ else:
+ valid_img_keys = [x for x in self.img_key_dict.keys() if prefix in x]
+ if self.args.ref_mode == "random":
+ new_img_key = random.choice(valid_img_keys)
+ elif self.args.ref_mode == "random_sparse":
+ new_img_key = random.choice(valid_img_keys[::30])
+ elif self.args.ref_mode == "random_sparse_part":
+ if random.random() < 0.2:
+ new_img_key = random.choice(valid_img_keys[::30])
+ else:
+ new_img_key = _get_first_frame_img_key(
+ prefix, frame_idx, suffix
+ )
+ except:
+ new_img_key = _get_first_frame_img_key(prefix, frame_idx, suffix)
+ return self.img_key_dict[new_img_key]
+
+ def get_visual_data(self, img_idx):
+ try:
+ row = self.get_row_from_tsv(self.visual_tsv, img_idx)
+ return self.str2img(row[-1]), False
+ except Exception as e:
+ raise ValueError(f"{e}, in get_visual_data()")
+
+ def __len__(self):
+ if self.split == "train":
+ if getattr(self.args, "max_train_samples", None):
+ return min(self.args.max_train_samples, super().__len__())
+ else:
+ return int(super().__len__() // self.train_sample_interval)
+ else:
+ if getattr(self.args, "max_eval_samples", None):
+ return min(self.args.max_eval_samples, super().__len__())
+ else:
+ return int(super().__len__() // self.eval_sample_interval)
+
+ def __getitem__(self, idx):
+ if self.split == "train":
+ idx = int(idx * self.train_sample_interval)
+ idx = idx + random.randint(0, self.train_sample_interval - 1)
+ idx = min(idx, len(self) - 1)
+ elif self.split == "eval":
+ idx = int(idx * self.eval_sample_interval)
+
+ raw_data = self.get_metadata(idx)
+ img_seq = raw_data["img_seq"]
+ pose_img_seq = raw_data["pose_img_seq"]
+ fg_img = raw_data["ref_img"]
+ bg_img = raw_data["bg_ref_img"]
+
+ state = torch.get_rng_state()
+ fg_state = state
+ aug_img_seq = []
+ for img in img_seq:
+ img = self.augmentation(img, self.transform, state)
+ aug_img_seq.append(img)
+ aug_img_seq = torch.stack(aug_img_seq, dim=1)
+ aug_pose_img_seq = []
+ for pose_img in pose_img_seq:
+ pose_img = self.augmentation(pose_img, self.cond_transform, state)
+ aug_pose_img_seq.append(pose_img)
+ aug_pose_img_seq = torch.stack(aug_pose_img_seq, dim=1)
+ if getattr(self.args, "refer_clip_preprocess", None):
+ raise NotImplementedError
+ fg_img = self.preprocesser(fg_img).pixel_values[0] # use clip preprocess
+ else:
+ fg_img = self.augmentation(fg_img, self.ref_transform, fg_state)
+ bg_img = self.augmentation(bg_img, self.transform, state)
+
+ if self.args.combine_use_mask: # True
+ ref_mask = raw_data["ref_mask"]
+ bg_ref_mask = raw_data["bg_ref_mask"]
+ assert not getattr(
+ self.args, "refer_clip_preprocess", None
+ ) # mask not support the CLIP process
+
+ ### first resize mask to the img size
+ ref_mask = ref_mask.resize(raw_data["ref_img"].size)
+ bg_ref_mask = bg_ref_mask.resize(raw_data["bg_ref_img"].size)
+
+ ref_mask = self.augmentation(ref_mask, self.ref_transform_mask, fg_state)
+ bg_ref_mask = self.augmentation(
+ bg_ref_mask, self.cond_transform, state
+ ) # controlnet path input
+
+ # apply the mask
+ fg_img = fg_img * ref_mask # foreground
+ bg_img = bg_img * (1 - bg_ref_mask) # background
+
+ # caption = raw_data["caption"]
+ outputs = {
+ "img_key_seq": ";".join(raw_data["img_key_seq"]),
+ # "input_text": caption,
+ "label_img_seq": aug_img_seq, # ground truth
+ "cond_img_seq": aug_pose_img_seq, # pose
+ "reference_img": fg_img, # foreground
+ "reference_img_controlnet": bg_img, # background
+ }
+
+ return outputs
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tsv_cond_dataset.py b/One-to-All-Animation/benchmark/DisCo/dataset/tsv_cond_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cf97ef5a3e8bafb7f51388a53a7c04a83ac062c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tsv_cond_dataset.py
@@ -0,0 +1,71 @@
+from .tsv_dataset import TsvCompositeDataset
+import json
+import random
+
+
+class TsvCondImgCompositeDataset(TsvCompositeDataset):
+ def __init__(self, args, yaml_file,
+ split="train", size_frame=1, tokzr=None):
+ super().__init__(args, yaml_file, split, size_frame, tokzr)
+
+ # by defualt we store a vid2line file
+ self.vid2line_file = self.cfg.get('vid2line', None) # get_row_from_tsv
+ self.vid2line_tsv = self.get_tsv_file(self.vid2line_file)
+ for cond in self.args.conds:
+ # poses
+ setattr(self, f"{cond}_file", self.cfg.get(cond, None))
+ setattr(self, f"{cond}_tsv", self.get_tsv_file(getattr(self,f"{cond}_file")))
+
+ def get_current_video_start_end(self, img_idx):
+ row = self.get_row_from_tsv(self.vid2line_tsv, img_idx)
+ image_key = row[0]
+ if self.is_composite:
+ assert image_key in self.image_keys[img_idx] # keli: ugly fix
+ else:
+ assert image_key == self.image_keys[img_idx]
+ start_end = json.loads(row[1])
+ return start_end
+
+ def get_reference_frame_idx(self, img_idx):
+ start_end = self.get_current_video_start_end(img_idx)
+ start_end = [item+img_idx for item in start_end]
+ try:
+ if self.args.ref_mode == "first" or self.split != 'train':
+ # if self.args.ref_mode == "first":
+ return start_end[0]
+ elif self.args.ref_mode == "random":
+ return random.randint(start_end[0], start_end[1])
+ elif self.args.ref_mode == "random_sparse":
+ return random.randrange(start_end[0], start_end[1], 30)
+ elif self.args.ref_mode == "random_sparse_part": # 20% random
+ if random.random() < 0.2:
+ return random.randrange(start_end[0], start_end[1], 30)
+ else:
+ return start_end[0]
+ # elif self.args.ref_mode == "random_sparse_filter":
+ # resample_flag = True
+ # ref_img_idx = random.randrange(start_end[0], start_end[1], 30)
+ # while resample_flag:
+ # ref_skeleton = self.get_cond(img_idx, 'poses')
+ # if len(ref_skeleton) > 10:
+ # resample_flag = False
+ # else:
+ # ref_img_idx = random.randrange(start_end[0], start_end[1], 30)
+ else:
+ raise NotImplementedError(f"Unknown ref_mode {self.args.ref_mode}")
+ except:
+ return start_end[0]
+
+ def get_cond(self, img_idx, cond):
+ cond_tsv = getattr(self,f"{cond}_tsv")
+ row = self.get_row_from_tsv(cond_tsv, img_idx)
+ if len(row) == 3:
+ image_key, buf, valid = row
+ # assert image_key == self.image_keys[img_idx]
+ if not valid:
+ return None
+ else:
+ return self.str2img(buf)
+ else:
+ return self.str2img(row[1])
+
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/dataset/tsv_dataset.py b/One-to-All-Animation/benchmark/DisCo/dataset/tsv_dataset.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cd0fbb006aa555a35c81a1176a2acad544a0ea5
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/dataset/tsv_dataset.py
@@ -0,0 +1,865 @@
+from utils.lib import *
+from .data_utils.video_transforms import (
+ Normalize, Resize, CenterCrop, ClipToTensor,
+ RandomCrop, Compose)
+from .data_utils.albef_randaug import RandomAugment
+# from utils.tsv_file import TSVFile, CompositeTSVFile
+from utils.tsv_io import tsv_reader
+from utils.tsv_io import (
+ TSVFile, load_list_file, load_from_yaml_file)
+from utils.load_files import (
+ find_file_path_in_yaml, load_box_linelist_file)
+from utils.logger import LOGGER
+from utils.dist import get_world_size, get_rank
+from .data_sampler import (
+ DistributedSamplerLimited, NodeSplitSampler, IterationBasedBatchSampler)
+from .data_utils.node_sampler import ScaleNodeSplitSampler
+try:
+ from azfuse import File
+except ImportError:
+ print("azfuse is not installed")
+
+
+class Dataset_Base(T.utils.data.Dataset):
+ def __init__(self, args, split="train", size_frame=4, tokzr=None):
+ super().__init__()
+ self.args = args
+ self.size_frame = size_frame
+ self.split = split
+
+ self.tokzr = tokzr
+ # if tokzr is not None:
+ # self.tokzr = tokzr
+ # else:
+ # self.tokzr = transformers.AutoTokenizer.from_pretrained(
+ # self.args.tokenizer)
+ if self.tokzr is not None:
+ (self.cls_token_id, self.sep_token_id,
+ self.pad_token_id, self.mask_token_id,
+ self.unk_token_id) = self.tokzr.convert_tokens_to_ids(
+ [self.tokzr.cls_token,
+ self.tokzr.sep_token, self.tokzr.pad_token,
+ self.tokzr.mask_token,
+ self.tokzr.unk_token])
+ self.true_token_id = self.tokzr.convert_tokens_to_ids(
+ ["true"])[0]
+ self.false_token_id = self.tokzr.convert_tokens_to_ids(
+ ["false"])[0]
+
+ def read_tsv(self, worker_id):
+ assert hasattr(self, 'img_tsv_path')
+ self.img = open(self.img_tsv_path, 'r')
+
+ def seek_img_tsv(self, pos):
+ self.img.seek(pos)
+ return [s.strip() for s in self.img.readline().split('\t')]
+
+ def get_partial_data(self):
+ if self.split != 'train' or self.args.data_ratio == 1:
+ return
+ assert self.args.data_ratio > 0
+ self.video2txt = defaultdict(list)
+ for item in self.txt:
+ self.video2txt[item["video"]].append(item)
+ vids = list(self.video2txt.keys())
+ random.shuffle(vids)
+ if self.args.data_ratio < 1:
+ n_partial_vids = math.ceil(len(vids)*self.args.data_ratio)
+ else:
+ n_partial_vids = min(
+ int(self.args.data_ratio), len(vids))
+ partial_vids = vids[:n_partial_vids]
+ partial_txt = []
+ for vid in partial_vids:
+ partial_txt.extend(self.video2txt[vid])
+ self.txt = partial_txt
+
+ def concat_txt(self, txt_a, txt_b):
+ self.sep_token = self.tokzr.sep_token
+ return txt_a + f" {self.sep_token} " + txt_b
+
+ def pad_resize(self, img):
+ w, h = img.size
+ img = TV.transforms.Compose([
+ TV.transforms.Pad([0, (w-h)//2] if w > h else [(h-w)//2, 0]),
+ TV.transforms.Resize(
+ [self.args.size_img, self.args.size_img]),
+ TV.transforms.ToTensor(),
+ TV.transforms.Normalize(
+ [0.485, 0.456, 0.406],
+ [0.229, 0.224, 0.225])
+ ])(img)
+ return img
+
+ def img_center_crop(self, img):
+ img = TV.transforms.Compose([
+ TV.transforms.Resize(self.args.size_img),
+ TV.transforms.CenterCrop(
+ (self.args.size_img, self.args.size_img)),
+ TV.transforms.ToTensor(),
+ TV.transforms.Normalize(
+ [0.485, 0.456, 0.406],
+ [0.229, 0.224, 0.225])
+ ])(img)
+ return img
+
+ def vid_center_crop(self, img):
+ img = Compose([
+ Resize(self.args.size_img),
+ CenterCrop(
+ (self.args.size_img, self.args.size_img)),
+ ClipToTensor(channel_nb=3),
+ Normalize(
+ [0.485, 0.456, 0.406],
+ [0.229, 0.224, 0.225])
+ ])(img)
+ img = img.permute(1, 0, 2, 3)
+ return img
+
+ def vid_rand_crop(self, img):
+ assert self.split == "train"
+ img = Compose([
+ Resize(self.args.size_img),
+ RandomCrop(
+ (self.args.size_img, self.args.size_img)),
+ ClipToTensor(channel_nb=3),
+ Normalize(
+ [0.485, 0.456, 0.406],
+ [0.229, 0.224, 0.225])
+ ])(img)
+ # adapt from torch_videovision:
+ # https://github.com/hassony2/torch_videovision
+ # after augmentation, output tensor (C x T x H x W)
+ # in the range [0, 1.0]
+ # (C x T x H x W) --> (T x C x H x W)
+ img = img.permute(1, 0, 2, 3)
+ return img
+
+ def img_rand_crop(self, img):
+ assert self.split == "train"
+ img = TV.transforms.Compose([
+ TV.transforms.Resize(self.args.size_img),
+ TV.transforms.RandomCrop(
+ (self.args.size_img, self.args.size_img)),
+ RandomAugment(
+ 2, 5, isPIL=True, augs=[
+ 'Identity', 'AutoContrast', 'Equalize',
+ 'Brightness', 'Sharpness', 'ShearX',
+ 'ShearY', 'TranslateX', 'TranslateY', 'Rotate']),
+ TV.transforms.ToTensor(),
+ TV.transforms.Normalize(
+ [0.485, 0.456, 0.406],
+ [0.229, 0.224, 0.225])
+ ])(img)
+ return img
+
+ def str2img(self, b):
+ try:
+ img = Image.fromarray(
+ cv2.imdecode(
+ np.frombuffer(base64.b64decode(b), np.uint8),
+ cv2.IMREAD_COLOR)[:, :, ::-1]
+ ).convert('RGB')
+ except Exception:
+ img = Image.open(io.BytesIO(base64.b64decode(b))).convert('RGB')
+ return img
+
+ def sampling(self, start, end, n):
+ if n == 1:
+ return [int(round((start+end)/2.))]
+ if n < 1:
+ raise Exception("behaviour not defined for n<2")
+ step = (end-start)/float(n-1)
+ return [int(round(start+x*step)) for x in range(n)]
+
+ def temporal_sample(self, list_of_b, random_sample=False):
+ max_size_frame = len(list_of_b)
+ if max_size_frame == 1 or self.size_frame == max_size_frame:
+ return list_of_b
+ if max_size_frame < self.size_frame:
+ print(f"Error in size_frame",
+ f"\tasked for {size_frame} from {max_size_frame} frames")
+
+ size_frame = min(self.size_frame, max_size_frame)
+ size_clips = int(math.ceil(max_size_frame / size_frame))
+ if random_sample:
+ sampled_start = random.choice(range(size_clips))
+ sampled_end = min(
+ sampled_start + (size_frame - 1) * size_clips,
+ max_size_frame - 1)
+ else:
+ sampled_start = 0
+ sampled_end = max_size_frame - 1
+ sampled_index = self.sampling(sampled_start, sampled_end, size_frame)
+ sampled_video = [list_of_b[i] for i in sampled_index]
+ return sampled_video
+
+ def get_img_or_video_w_transform(self, list_of_b):
+ bufs = self.temporal_sample(
+ list_of_b, random_sample=(self.split == 'train'))
+ img = []
+ for b in bufs:
+ single_img = self.str2img(b)
+ if self.split == "train":
+ vis_transform = random.choice(self.args.img_transform)
+ if vis_transform == "vid_rand_crop":
+ img.append(single_img)
+ else:
+ if vis_transform == "pad_resize":
+ single_img = self.pad_resize(single_img)
+ elif vis_transform == "img_center_crop":
+ single_img = self.img_center_crop(single_img)
+ else:
+ single_img = self.img_rand_crop(single_img)
+ img.append(single_img.unsqueeze(0))
+ else:
+ if self.args.img_transform == ["vid_rand_crop"]:
+ vis_transform = "vid_center_crop"
+ img.append(single_img)
+ else:
+ if self.args.img_transform == ["pad_resize"]:
+ vis_transform = "pad_resize"
+ single_img = self.pad_resize(single_img)
+ else:
+ vis_transform = "img_center_crop"
+ single_img = self.img_center_crop(single_img)
+ img.append(single_img.unsqueeze(0))
+
+ if vis_transform == "vid_rand_crop":
+ img = self.vid_rand_crop(img)
+ elif vis_transform == "vid_center_crop":
+ img = self.vid_center_crop(img)
+ else:
+ img = T.cat(img, dim=0)
+
+ return img
+
+ def str2txt(self, s):
+ # if version.parse(transformers.__version__) >= version.parse("4.16.1"):
+ # txt = self.tokzr.encode(s)
+ # old_len = len(txt)
+ # txt = txt[:self.args.size_txt-1]
+ # new_len = len(txt)
+ # if new_len < old_len:
+ # txt = txt + [self.sep_token_id]
+ # padding_len = self.args.size_txt-len(txt)
+ # txt = txt + [self.pad_token_id]*(padding_len)
+ # else:
+ assert self.tokzr is not None
+ txt = self.tokzr.encode(
+ s, padding='max_length', max_length=self.args.size_txt,
+ truncation=True)
+ mask = [1 if w != self.pad_token_id else 0 for w in txt]
+ mask = T.LongTensor(mask)
+ txt = T.LongTensor(txt)
+ assert len(txt[txt == self.sep_token_id]) == 1, f'{txt}'
+ return txt, mask
+
+
+def get_dl(ds, args, worker_init_fn=None, collate_fn=None):
+ if args.distributed:
+ sp = T.utils.data.distributed.DistributedSampler(
+ ds, shuffle=(ds.split == 'train'))
+ else:
+ if ds.split == 'train':
+ sp = T.utils.data.RandomSampler(ds)
+ else:
+ sp = T.utils.data.SequentialSampler(ds)
+ # if ds.split=='train':
+ # sp.set_epoch(ep)
+ dl = T.utils.data.DataLoader(
+ ds, batch_size=args.size_batch, num_workers=args.n_workers,
+ pin_memory=True, sampler=sp, worker_init_fn=worker_init_fn,
+ collate_fn=collate_fn)
+ return dl
+
+
+def get_tsv_dls(args, DataCls, tokzr=None):
+ if tokzr is None:
+ tokzr = transformers.AutoTokenizer.from_pretrained(
+ args.tokenizer)
+ img_path = f'{args.data_dir}/img_{args.dataset}.tsv'
+ LOGGER.info(f"rank {get_rank()}: loading video frames from {img_path}")
+ lineidx_data = pickle.load(open(
+ f'{args.data_dir}/img_{args.dataset}.id2lineidx.pkl', 'rb'))
+ txt_path = f'{args.data_dir}/txt_{args.task}.json'
+ LOGGER.info(f"rank {get_rank()}: loading text from {txt_path}")
+ txt_data = json.load(open(txt_path, 'r'))
+ splits = ['train', 'val']
+ if 'test' in txt_data:
+ splits.append('test')
+
+ ds_all = {
+ split: DataCls(
+ args, img_path, txt_data, lineidx_data, split,
+ tokzr=tokzr)
+ for split in splits}
+ log_data_len = f"data_ratio: {args.data_ratio}"
+ for split in splits:
+ log_data_len += f", {split}: {len(ds_all[split])}"
+ LOGGER.info(log_data_len)
+
+ dl_all = {
+ split:
+ get_dl(
+ ds, args,
+ worker_init_fn=ds.read_tsv if hasattr(ds, 'read_tsv') else None,
+ collate_fn=ds.collate_batch if hasattr(ds, 'collate_batch') else None)
+ for split, ds in ds_all.items()}
+ dl_tr, dl_vl = [
+ dl_all[split] for split in ["train", "val"]]
+ dl_ts = dl_all["test"] if "test" in dl_all else None
+ return dl_tr, dl_vl, dl_ts
+
+
+def move_to_cuda(batch):
+ if isinstance(batch, T.Tensor):
+ return batch.cuda(non_blocking=True)
+ elif isinstance(batch, list):
+ new_batch = [move_to_cuda(t) for t in batch]
+ elif isinstance(batch, tuple):
+ new_batch = tuple(move_to_cuda(t) for t in batch)
+ elif isinstance(batch, dict):
+ new_batch = {n: move_to_cuda(t) for n, t in batch.items()}
+ else:
+ return batch
+ return new_batch
+
+
+class CompositeTSVFile(object):
+ def __init__(self, list_file, seq_file, cache_policy=False,
+ hold_buffer=0, data_dir=None,
+ ):
+ # list_file can be a loaded or constructed pair of index, rather than a
+ # filename to load. In this case, seq_file will be a list of dataset,
+ # which should implement len() and __getitem__() so that we can
+ # reference it.
+ self.seq_file = seq_file
+ # self.file_list = list_file
+ if isinstance(list_file, str):
+ self.file_list = load_list_file(list_file)
+ else:
+ assert isinstance(list_file, list)
+ self.file_list = list_file
+ self.cache_policy = cache_policy
+ self.seq = None
+ self.tsvs = []
+ # please do ont call ensure_initialized here. we wil always do it
+ # lazily. we may load a huge amount of seq, which could be super slow
+ # when spawning multiple processes.
+
+ # this means, how many tsv fp pointer we will hold. If it is 0 or less
+ # than 0, we will hold all fp pointers we need. If it is larger than 0,
+ # we only hold some, which are kept in self.hold_sources
+ self.hold_buffer = hold_buffer
+ self.hold_sources = []
+ self.data_dir = data_dir
+
+ def __repr__(self):
+ return 'CompositeTSVFile(list_file={}, seq_file={})'.format(
+ self.seq_file,
+ self.file_list
+ )
+
+ def get_row_len(self, i):
+ self.ensure_initialized()
+ idx_source, idx_row, _ = map(int, self.seq[i])
+ result = self.tsvs[idx_source].get_row_len(idx_row)
+ return result
+
+ def get_key(self, index):
+ # added by Linjie
+ self.ensure_initialized()
+ idx_source, idx_row, _ = map(int, self.seq[index])
+ k = self.tsvs[idx_source].get_key(idx_row)
+ return '_'.join([self.file_list[idx_source], k])
+
+ def __getitem__(self, index):
+ self.ensure_initialized()
+ idx_source, idx_row, _ = map(int, self.seq[index])
+ start = time.time()
+ result = self.tsvs[idx_source].seek(idx_row)
+ end = time.time()
+ if end - start > 10:
+ import logging
+ logging.warning('too long to load fname = {}, source={}, row={}, time={}'.format(
+ self.tsvs[idx_source],
+ idx_source,
+ idx_row,
+ end - start
+ ))
+ if self.hold_buffer > 0 and idx_source not in self.hold_sources:
+ if len(self.hold_sources) >= self.hold_buffer:
+ close_idx_source = self.hold_sources.pop(0)
+ self.tsvs[close_idx_source].close_fp()
+ self.hold_sources.append(idx_source)
+ return result
+
+ def __len__(self):
+ self.ensure_initialized()
+ return len(self.seq)
+
+ def num_rows(self):
+ # added by Linjie
+ self.ensure_initialized()
+ return len(self.seq)
+
+ def __iter__(self):
+ self.ensure_initialized()
+ self.next_row = 0
+ for idx_source, idx_row in self.seq:
+ idx_source, idx_row = int(idx_source), int(idx_row)
+ yield self.tsvs[idx_source][idx_row]
+
+ def release(self):
+ # this is to ensure we released all the resources
+ self.seq = None
+ for t in self.tsvs:
+ t.close()
+
+ def close(self):
+ self.release()
+
+ def seek_first_column(self, index):
+ self.ensure_initialized()
+ idx_source, idx_row, _ = map(int, self.seq[index])
+ return self.tsvs[idx_source].seek_first_column(idx_row)
+
+ def get_composite_source_idx(self):
+ return [int(i) for i, _, _ in self.seq]
+
+ def is_from_valid_file(self, idx=None):
+ self.ensure_initialized()
+ if idx is None:
+ return [self.tsvs[int(idx_source)] is not None for idx_source, _, _ in tqdm(self.seq)]
+ else:
+ return self.tsvs[int(self.seq[idx][0])] is not None
+
+ def ensure_initialized(self):
+ if self.seq is None:
+ print("CompositeTSVFile: initializing")
+ # if isinstance(self.file_list, str) and \
+ # isinstance(self.seq_file, str):
+ self.seq = TSVFile(self.seq_file)
+ tsv_path = [f if op.exists(f) else op.join(self.data_dir, f) for f in self.file_list]
+ print(f"CompositeTSVFile: {tsv_path}")
+ # if self.data_dir is not None:
+ self.tsvs = [TSVFile(f, self.cache_policy) if f != 'd' else None for f in tsv_path]
+ print("CompositeTSVFile: initialized")
+ # else:
+ # self.tsvs = [TSVFile(f, self.cache_policy) if f != 'd' else None for f in self.file_list]
+ # else:
+ # self.seq = self.file_list
+ # self.tsvs = self.seq_file
+
+
+class TsvCompositeDataset(Dataset_Base):
+ def __init__(self, args, yaml_file,
+ split="train", size_frame=4, tokzr=None):
+ super().__init__(args, split, size_frame, tokzr)
+ # yaml_file = op.join(args.data_dir, yaml_file)
+ # LOGGER.info(f'yaml_file:{yaml_file}')
+ if not op.isfile(yaml_file):
+ yaml_file = op.join(args.data_dir, yaml_file)
+ assert op.isfile(yaml_file), f"{yaml_file} does not exists"
+ try:
+ self.cfg = load_from_yaml_file(yaml_file)
+ except Exception as e:
+ print(f"{yaml_file} does not exists")
+
+ self.yaml_file = yaml_file
+ self.root = op.dirname(yaml_file)
+
+ self.is_composite = self.cfg.get('composite', False)
+ self.cap_linelist_file = find_file_path_in_yaml(
+ self.cfg.get('caption_linelist', None), self.root)
+ self.visual_file = self.cfg.get('img', None)
+ self.visual_tsv = self.get_tsv_file(self.visual_file)
+
+ self.label_file = self.cfg.get('label', None)
+ self.label_tsv = self.get_tsv_file(self.label_file)
+
+ self.cap_file = self.cfg.get('caption', None)
+ self.cap_tsv = self.get_tsv_file(self.cap_file)
+ if self.is_composite:
+ assert op.isfile(self.cap_linelist_file)
+ self.cap_line_list = [
+ int(row[2]) for row in tsv_reader(self.cap_linelist_file)]
+ self.img_line_list = [i for i in range(len(self.cap_line_list))]
+ elif self.cap_linelist_file:
+ line_list = load_box_linelist_file(self.cap_linelist_file)
+ self.img_line_list = line_list[0]
+ self.cap_line_list = line_list[1]
+ else:
+ # one caption per image/video
+ self.img_line_list = [i for i in range(self.cap_tsv.num_rows())]
+ self.cap_line_list = [0 for i in range(self.cap_tsv.num_rows())]
+ self.is_train = split == "train"
+ if self.is_train:
+ assert self.cap_tsv is not None
+ # assert self.tokzr is not None
+ self.image_keys = self.prepare_image_keys()
+ self.key2index = self.prepare_image_key_to_index()
+ # self.img_res = self.args.size_img
+ # self.patch_size = getattr(args, 'patch_size', 32)
+
+ self.use_asr = getattr(args, 'use_asr', False)
+ # for MERLOT/HT100M only
+ self.append_pred_mf_cap = getattr(args, 'append_pred_mf_cap', False)
+ self.pred_mf_cap_only = getattr(args, 'pred_mf_cap_only', False)
+ self.alternate_asr_pred_cap = getattr(
+ args, 'alternate_asr_pred_cap', False)
+ self.alternate_asr_pred_cap = (
+ self.alternate_asr_pred_cap and self.use_asr
+ and self.pred_mf_cap_only)
+ LOGGER.info(f'Use_asr: {self.use_asr}')
+ self.on_memory = getattr(args, 'on_memory', False)
+
+ def get_partial_data(self):
+ if self.split != 'train' or self.args.data_ratio == 1:
+ return
+ assert self.args.data_ratio > 0
+ list_of_idx = list(range(len(self.img_line_list)))
+ random.shuffle(list_of_idx)
+ if self.args.data_ratio < 1:
+ num_samples = math.ceil(len(list_of_idx) * self.args.data_ratio)
+ else:
+ num_samples = min(
+ int(self.args.data_ratio), len(list_of_idx))
+ sampled_idx = list_of_idx[:num_samples]
+ img_line_list = [self.img_line_list[idx] for idx in sampled_idx]
+ cap_line_list = [self.cap_line_list[idx] for idx in sampled_idx]
+ self.img_line_list = img_line_list
+ self.cap_line_list = cap_line_list
+ return
+
+ def __len__(self):
+ return len(self.img_line_list)
+
+ def __cap_len__(self):
+ return len(self.cap_line_list)
+
+ def get_composite_source_idx(self):
+ if self.is_composite:
+ # assert op.isfile(self.cap_linelist_file)
+ # self.composite_source_idx = [
+ # int(row[0]) for row in tsv_reader(self.cap_linelist_file)]
+ self.composite_source_idx = self.cap_tsv.get_composite_source_idx()
+ else:
+ # only a single tsv file is used as input
+ self.composite_source_idx = [
+ 0 for _ in range(len(self.cap_line_list))]
+ return self.composite_source_idx
+
+ def get_tsv_file(self, tsv_file):
+ if tsv_file:
+ if self.is_composite:
+ return CompositeTSVFile(
+ tsv_file, self.cap_linelist_file, data_dir=self.root)
+ tsv_path = find_file_path_in_yaml(tsv_file, self.root)
+ return TSVFile(tsv_path)
+
+ def load_caption_to_memory(self):
+ self.caption_on_memory = {}
+ for img_idx in set(self.img_line_list):
+ row = self.get_row_from_tsv(self.cap_tsv, img_idx)
+ for cap_idx, data in enumerate(json.loads(row[1])):
+ self.caption_on_memory[(img_idx, cap_idx)] = data['caption']
+
+ def get_valid_tsv(self):
+ if self.is_train:
+ return self.cap_tsv
+ # sorted by file size
+ if self.cap_tsv:
+ return self.cap_tsv
+ if self.visual_tsv:
+ return self.visual_tsv
+
+ def prepare_image_keys(self):
+ tsv = self.get_valid_tsv()
+ return [tsv.get_key(i) for i in range(tsv.num_rows())]
+
+ def prepare_image_key_to_index(self):
+ tsv = self.get_valid_tsv()
+ return {tsv.get_key(i): i for i in range(tsv.num_rows())}
+
+ def get_image_cap_index(self, idx):
+ return self.img_line_list[idx], self.cap_line_list[idx]
+
+ def get_row_from_tsv(self, tsv, img_idx):
+ row = tsv[img_idx]
+ if self.is_composite:
+ # try:
+ assert self.image_keys[img_idx].endswith(row[0])
+ # except:
+ # print(img_idx)
+ # print(self.image_keys[img_idx])
+ # print(row[0])
+ else:
+ assert row[0] == self.image_keys[img_idx]
+ return row
+
+ def get_caption(self, img_idx, cap_idx):
+ if self.is_train:
+ if self.on_memory:
+ return self.caption_on_memory[(img_idx, cap_idx)]
+ row = self.get_row_from_tsv(self.cap_tsv, img_idx)
+ return json.loads(row[1])[cap_idx]['caption']
+ return ""
+
+ def get_merlot_caption_asr(self, data_sample):
+ try:
+ if self.pred_mf_cap_only:
+ caption = data_sample['pred_cap_mf15'][0]
+ else:
+ caption = data_sample['captions'][0]
+ if self.append_pred_mf_cap:
+ caption += ' [SEP] ' + data_sample['pred_cap_mf15'][0]
+ if 'noise_asr' in data_sample:
+ asr = data_sample['noise_asr'][0]
+ else:
+ asr = data_sample['captions'][0]
+ if self.alternate_asr_pred_cap:
+ p = random.random()
+ if p > 0.5:
+ return asr, caption, '', ''
+ return caption, asr, '', ''
+ except Exception:
+ # FIXME: quick hack for youtube-short-videos
+ return data_sample['caption'], '', '', ''
+
+ def get_caption_and_timeinfo(self, data, cap_idx):
+ caption, tag, start, end = '', ' ', None, None
+ data_sample = data[cap_idx]
+ if self.is_train:
+ caption = data_sample['caption']
+ if 'start' in data_sample:
+ start = data_sample['start']
+ if 'end' in data_sample:
+ end = data_sample['end']
+ if 'label' in data_sample and self.use_action_label:
+ tag += data_sample['label']
+ if 'asr' in data_sample and self.use_asr:
+ asr = data_sample['asr'] # .lower()
+ tag = asr
+ else:
+ if 'start' in data_sample:
+ start = data_sample['start']
+ if 'end' in data_sample:
+ end = data_sample['end']
+ if 'label' in data_sample and self.use_action_label:
+ tag += data_sample['label']
+ if 'asr' in data_sample and self.use_asr:
+ asr = data_sample['asr'] # .lower()
+ tag = asr
+ if 'caption' in data_sample:
+ caption = data_sample['caption']
+ return caption, tag, start, end
+
+ def get_caption_and_timeinfo_wrapper(self, img_idx, cap_idx):
+ row = self.get_row_from_tsv(self.cap_tsv, img_idx)
+ data_sample = json.loads(row[1])
+ is_merlot = False
+ if type(data_sample) is dict:
+ # for merlot tsv format
+ is_merlot = True
+ caption, asr_or_tag, start, end = self.get_merlot_caption_asr(
+ data_sample)
+ else:
+ # for other datasets (VATEX, MSRVTT, TVC, YouCook,
+ # COCO, GoogleCC+SBU+COCO)
+ caption, asr_or_tag, start, end = self.get_caption_and_timeinfo(
+ data_sample, cap_idx)
+ return caption, asr_or_tag, start, end, is_merlot
+
+ def get_caption_file_in_coco_format(self):
+ # for evaluation
+ cap_file_coco_format = find_file_path_in_yaml(
+ self.cfg.get('caption_coco_format', None), self.root)
+ if cap_file_coco_format:
+ return cap_file_coco_format
+ test_split = op.basename(self.yaml_file).split('.')[0]
+ return op.join(self.root, test_split + '_caption_coco_format.json')
+
+ def get_captions_by_key(self, key):
+ # get a list of captions for image (by key)
+ img_idx = self.key2index[key]
+ cap_info = json.loads(self.cap_tsv[img_idx][1])
+ return [c['caption'] for c in cap_info]
+
+ def get_video_key(self, idx):
+ return self.get_row_from_tsv(self.label_tsv, idx)[0]
+
+ def get_visual_data(self, idx, is_MERLOT=False):
+ row = self.get_row_from_tsv(self.visual_tsv, idx)
+ if row[0] == row[-1]:
+ # if the input is a video tsv, on the fly decoding
+ # return self.decode_and_get_frames(row[-1], start, end), True
+ raise NotImplementedError("On the fly decoding is not supported")
+ elif is_MERLOT or len(row) >= self.size_frame + 2:
+ # return self.get_frames_from_tsv(row[2:]), True
+ return self.get_img_or_video(row[2:]), True
+ else: # if the input is a image tsv, return image numpy array
+ return self.get_img_or_video([row[-1]]), False
+
+ def get_img_txt_pair(self, idx):
+ img_idx, cap_idx = self.get_image_cap_index(idx)
+ img_key = self.image_keys[img_idx]
+ (caption_sample, tag, start,
+ end, is_MERLOT) = self.get_caption_and_timeinfo_wrapper(
+ img_idx, cap_idx)
+ # get image or video frames
+ # frames: (T, C, H, W), is_video: binary tag
+ frames, is_video = self.get_visual_data(
+ img_idx, is_MERLOT)
+
+ if isinstance(caption_sample, dict):
+ caption = caption_sample["caption"]
+ else:
+ caption = caption_sample
+ caption_sample = None
+
+ # preparing outputs
+ meta_data = {}
+ meta_data['caption'] = caption # raw text data, not tokenized
+ meta_data['img_key'] = img_key
+ meta_data['is_video'] = (
+ is_video and len(frames) > 1
+ ) # True: video data, False: image data
+ meta_data['tag'] = tag
+ meta_data['img'] = frames
+ return meta_data
+
+
+def make_batch_data_sampler(
+ sampler, images_per_gpu, num_iters=None, start_iter=0):
+ batch_sampler = T.utils.data.sampler.BatchSampler(
+ sampler, images_per_gpu, drop_last=False
+ )
+ if num_iters is not None and num_iters >= 0:
+ batch_sampler = IterationBasedBatchSampler(
+ batch_sampler, num_iters, start_iter
+ )
+ return batch_sampler
+
+
+def make_data_sampler(
+ dataset, shuffle, distributed, random_seed, limited_samples=-1):
+ is_train = dataset.split == 'train'
+ if distributed:
+ enable_node_split_sampler = dataset.is_composite and getattr(dataset.args, "node_split_sampler", False)
+ enable_node_split_sampler = enable_node_split_sampler and is_train
+ if enable_node_split_sampler:
+ # first_epoch_skip_shuffle not working yet
+ print(
+ "Enable NodeSplitSampler with first_epoch_skip_shuffle=True")
+ return NodeSplitSampler(
+ dataset, shuffle=shuffle, random_seed=random_seed,
+ first_epoch_skip_shuffle=True)
+ elif limited_samples < 1:
+ return T.utils.data.distributed.DistributedSampler(
+ dataset, shuffle=shuffle)
+ else: # use limited distributed sampler
+ return DistributedSamplerLimited(
+ dataset, shuffle=shuffle, limited=limited_samples)
+ if shuffle:
+ sampler = T.utils.data.sampler.RandomSampler(dataset)
+ else:
+ sampler = T.utils.data.sampler.SequentialSampler(dataset)
+ return sampler
+
+
+def make_data_loader(
+ args, dataset, ep=0):
+ is_train = dataset.split == 'train'
+ collate_fn = dataset.collate_batch
+ is_distributed = args.distributed
+ num_gpus = args.num_gpus
+ if is_train:
+ shuffle = True
+ images_per_gpu = min(
+ args.size_batch * (args.size_frame // dataset.size_frame),
+ 128)
+ images_per_batch = images_per_gpu * get_world_size()
+ iter_per_ep = len(dataset) // images_per_batch
+ num_iters = iter_per_ep * args.size_epoch
+ # num_iters = iter_per_ep
+ start_iter = 0
+ else:
+ shuffle = False
+ images_per_gpu = args.size_batch * (
+ args.size_frame // dataset.size_frame)
+ images_per_batch = images_per_gpu * get_world_size()
+ iter_per_ep = None
+ num_iters = None
+ start_iter = 0
+
+ if hasattr(args, 'limited_samples'):
+ limited_samples = args.limited_samples // num_gpus
+ else:
+ limited_samples = -1
+ random_seed = args.seed
+ sampler = make_data_sampler(
+ dataset, shuffle, is_distributed, limited_samples=limited_samples,
+ random_seed=random_seed)
+ batch_sampler = make_batch_data_sampler(
+ sampler, images_per_gpu, num_iters, start_iter
+ )
+
+ # if is_train:
+ # batch_sampler.set_epoch(ep)
+ data_loader = T.utils.data.DataLoader(
+ dataset, num_workers=args.n_workers, batch_sampler=batch_sampler,
+ pin_memory=True, collate_fn=collate_fn
+ )
+ meta_info = (images_per_batch, iter_per_ep, num_iters)
+ return data_loader, meta_info
+
+
+class MetaLoader(object):
+ """ wraps multiple data loaders """
+ def __init__(self, loaders, accum_steps=1, distributed=False):
+ assert isinstance(loaders, dict)
+ self.name2loader = {}
+ self.name2iter = {}
+ self.sampling_pools = []
+ for n, l in loaders.items():
+ if isinstance(l, tuple):
+ l, r = l
+ elif isinstance(l, T.utils.data.DataLoader):
+ r = 1
+ else:
+ raise ValueError()
+ assert isinstance(r, int)
+ self.name2loader[n] = l
+ self.name2iter[n] = iter(l)
+ self.sampling_pools.extend([n]*r)
+
+ self.accum_steps = accum_steps
+ self.distributed = distributed
+ self.step = 0
+
+ def __iter__(self):
+ """ this iterator will run indefinitely """
+ task = self.sampling_pools[0]
+ while True:
+ if self.step % self.accum_steps == 0:
+ task = random.choice(self.sampling_pools)
+ if self.distributed:
+ # make sure all process is training same task
+ objects = [task]
+ DIST.broadcast_object_list(
+ objects, src=0)
+ task = objects[0]
+ # task = any_broadcast(task, 0)
+ self.step += 1
+ # print(f'calling iter for {task}')
+ iter_ = self.name2iter[task]
+ try:
+ batch = next(iter_)
+ except StopIteration:
+ iter_ = iter(self.name2loader[task])
+ batch = next(iter_)
+ self.name2iter[task] = iter_
+
+ yield task, batch
diff --git a/One-to-All-Animation/benchmark/DisCo/eval_animal.sh b/One-to-All-Animation/benchmark/DisCo/eval_animal.sh
new file mode 100644
index 0000000000000000000000000000000000000000..4e3554241b52455f0bbcba63c6b2f7c282cae7b9
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/eval_animal.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+# pip install pytorch_fid ffmpeg-python imageio
+# pip install scikit-image lpips
+# pip uninstall ffmpeg -y
+# pip install imageio-ffmpeg
+pip uninstall ffmpeg-python -y
+pip install ffmpeg-python
+# export CUDA_VISIBLE_DEVICES=0 #
+base_dir="../temp_eval_cartoon_frames"
+
+for dataset in "$base_dir"/*; do
+ # 只处理目录
+ if [ -d "$dataset" ]; then
+ folder_name=$(basename "$dataset")
+ update_name="${folder_name}"
+ update_path="${base_dir}/${update_name}"
+ metrics_file="${update_path}/metrics_fid-vid_fvd_dtssd_16frames.json"
+
+
+ echo "============== 开始处理任务: $folder_name =============="
+
+ update_folder="$update_path"
+ pred_folder="$update_folder/pred"
+ gt_folder="$update_folder/gt"
+
+
+ # Step 2: FID
+ for clip_id in $(ls "$pred_folder"); do
+ pred_path="$pred_folder/$clip_id"
+ gt_path="$gt_folder/$clip_id"
+
+ if [ -d "$pred_path" ] && [ -d "$gt_path" ]; then
+ fid_file="$update_folder/${clip_id}_pytorch_fid.txt"
+ python -m pytorch_fid "$pred_path" "$gt_path" --device cuda:0 > "$fid_file"
+ echo "[INFO] FID 保存到 $fid_file"
+ else
+ echo "[WARN] $clip_id 缺失 pred 或 gt 目录"
+ fi
+ done
+
+ # Step 3: L1/SSIM/LPIPS/PSNR
+ for clip_id in $(ls "$pred_folder"); do
+ pred_path="$pred_folder/$clip_id"
+ gt_path="$gt_folder/$clip_id"
+
+ if [ -d "$pred_path" ] && [ -d "$gt_path" ]; then
+ metrics_file="$update_folder/${clip_id}_metrics_l1_ssim_lpips_psnr.json"
+ python tool/metrics/metric_center.py \
+ --root_dir "$update_folder" \
+ --path_gen "$pred_path" \
+ --path_gt "$gt_path" \
+ --type l1 ssim lpips psnr \
+ --write_metric_to "$metrics_file"
+ echo "[INFO] 指标保存到 $metrics_file"
+ else
+ echo "[WARN] $clip_id 缺失 pred 或 gt 目录"
+ fi
+ done
+
+ # Step 4: 生成 MP4
+ python tool/video/yz_gen_gifs_for_fvd_subfolders.py -i "${pred_folder}" -o "${pred_folder}_16framemp4" --fps 3 --format mp4
+ python tool/video/yz_gen_gifs_for_fvd_subfolders.py -i "${gt_folder}" -o "${gt_folder}_16framemp4" --fps 3 --format mp4
+
+ # Step 5: FVD / FID-VID
+ python tool/metrics/metric_center.py \
+ --root_dir . \
+ --path_gen "${pred_folder}_16framemp4" \
+ --path_gt "${gt_folder}_16framemp4" \
+ --type fid-vid fvd \
+ --write_metric_to "${update_folder}/metrics_fid-vid_fvd_dtssd_16frames.json" \
+ --number_sample_frames 16 --sample_duration 16
+
+ echo "============== 完成任务: $folder_name =============="
+ fi
+done
diff --git a/One-to-All-Animation/benchmark/DisCo/eval_fvd/requirements.txt b/One-to-All-Animation/benchmark/DisCo/eval_fvd/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..23a675abf01ede9f68bc50405a2a28020f058ac2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/eval_fvd/requirements.txt
@@ -0,0 +1,5 @@
+https://huggingface.co/datasets/MochunniaN1/fvd/tree/main
+
+i3d_pretrained_400.pt
+resnet-50-kinetics.pth
+
diff --git a/One-to-All-Animation/benchmark/DisCo/eval_tiktok.sh b/One-to-All-Animation/benchmark/DisCo/eval_tiktok.sh
new file mode 100644
index 0000000000000000000000000000000000000000..900ba3e4e0b7cc5d96cfcb734e031f3a3ac7ba05
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/eval_tiktok.sh
@@ -0,0 +1,75 @@
+#!/bin/bash
+# pip install pytorch_fid ffmpeg-python imageio
+# pip install scikit-image lpips
+# pip uninstall ffmpeg -y
+# pip install imageio-ffmpeg
+pip uninstall ffmpeg-python -y
+pip install ffmpeg-python
+# export CUDA_VISIBLE_DEVICES=0 #
+base_dir="../temp_eval_tiktok_frames"
+
+for dataset in "$base_dir"/*; do
+ # 只处理目录
+ if [ -d "$dataset" ]; then
+ folder_name=$(basename "$dataset")
+ update_name="${folder_name}"
+ update_path="${base_dir}/${update_name}"
+ metrics_file="${update_path}/metrics_fid-vid_fvd_dtssd_16frames.json"
+
+
+ echo "============== 开始处理任务: $folder_name =============="
+
+ update_folder="$update_path"
+ pred_folder="$update_folder/pred"
+ gt_folder="$update_folder/gt"
+
+
+ # Step 2: FID
+ for clip_id in $(ls "$pred_folder"); do
+ pred_path="$pred_folder/$clip_id"
+ gt_path="$gt_folder/$clip_id"
+
+ if [ -d "$pred_path" ] && [ -d "$gt_path" ]; then
+ fid_file="$update_folder/${clip_id}_pytorch_fid.txt"
+ python -m pytorch_fid "$pred_path" "$gt_path" --device cuda:0 > "$fid_file"
+ echo "[INFO] FID 保存到 $fid_file"
+ else
+ echo "[WARN] $clip_id 缺失 pred 或 gt 目录"
+ fi
+ done
+
+ # Step 3: L1/SSIM/LPIPS/PSNR
+ for clip_id in $(ls "$pred_folder"); do
+ pred_path="$pred_folder/$clip_id"
+ gt_path="$gt_folder/$clip_id"
+
+ if [ -d "$pred_path" ] && [ -d "$gt_path" ]; then
+ metrics_file="$update_folder/${clip_id}_metrics_l1_ssim_lpips_psnr.json"
+ python tool/metrics/metric_center.py \
+ --root_dir "$update_folder" \
+ --path_gen "$pred_path" \
+ --path_gt "$gt_path" \
+ --type l1 ssim lpips psnr \
+ --write_metric_to "$metrics_file"
+ echo "[INFO] 指标保存到 $metrics_file"
+ else
+ echo "[WARN] $clip_id 缺失 pred 或 gt 目录"
+ fi
+ done
+
+ # Step 4: 生成 MP4
+ python tool/video/yz_gen_gifs_for_fvd_subfolders.py -i "${pred_folder}" -o "${pred_folder}_16framemp4" --fps 3 --format mp4
+ python tool/video/yz_gen_gifs_for_fvd_subfolders.py -i "${gt_folder}" -o "${gt_folder}_16framemp4" --fps 3 --format mp4
+
+ # Step 5: FVD / FID-VID
+ python tool/metrics/metric_center.py \
+ --root_dir . \
+ --path_gen "${pred_folder}_16framemp4" \
+ --path_gt "${gt_folder}_16framemp4" \
+ --type fid-vid fvd \
+ --write_metric_to "${update_folder}/metrics_fid-vid_fvd_dtssd_16frames.json" \
+ --number_sample_frames 16 --sample_duration 16
+
+ echo "============== 完成任务: $folder_name =============="
+ fi
+done
diff --git a/One-to-All-Animation/benchmark/DisCo/finetune_sdm_yaml.py b/One-to-All-Animation/benchmark/DisCo/finetune_sdm_yaml.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc5f25bf53834763cdc8517d1ecbb50697de7ca7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/finetune_sdm_yaml.py
@@ -0,0 +1,174 @@
+# --------------------------------------------------------
+# DisCo - Disentangled Control for Referring Human Dance Generation in Real World
+# Licensed under The Apache-2.0 license License [see LICENSE for details]
+# Tan Wang (TAN317@e.ntu.edu.sg)
+# Work done during internship at Microsoft
+# --------------------------------------------------------
+
+from utils.wutils_ldm import *
+from agent import Agent_LDM, WarmupLinearLR, WarmupLinearConstantLR
+import os
+import torch
+from utils.lib import *
+from utils.dist import dist_init
+from dataset.tsv_dataset import make_data_sampler, make_batch_data_sampler
+torch.multiprocessing.set_sharing_strategy('file_system')
+
+
+def get_loader_info(args, size_batch, dataset):
+ is_train = dataset.split == 'train'
+ if is_train:
+ images_per_gpu = min(
+ size_batch * max(1, (args.max_video_len // dataset.max_video_len)),
+ 128)
+ images_per_batch = images_per_gpu * args.world_size
+ iter_per_ep = len(dataset) // images_per_batch
+ if args.epochs == -1: # try to add iters into args
+ assert args.ft_iters > 0
+ num_iters = args.ft_iters
+ args.epochs = (num_iters * images_per_batch) // len(dataset) + 1
+ else:
+ num_iters = iter_per_ep * args.epochs
+ else:
+ images_per_gpu = size_batch * (
+ args.max_video_len // dataset.max_video_len)
+ images_per_batch = images_per_gpu * args.world_size
+ iter_per_ep = None
+ num_iters = None
+ loader_info = (images_per_gpu, images_per_batch, iter_per_ep, num_iters)
+ return loader_info
+
+
+def make_data_loader(
+ args, size_batch, dataset, start_iter=0, loader_info=None):
+ is_train = dataset.split == 'train'
+ collate_fn = None #dataset.collate_batch
+ is_distributed = args.distributed
+ if is_train:
+ shuffle = True
+ start_iter = start_iter
+ else:
+ shuffle = False
+ start_iter = 0
+ if loader_info is None:
+ loader_info = get_loader_info(args, size_batch, dataset)
+ images_per_gpu, images_per_batch, iter_per_ep, num_iters = loader_info
+
+ if hasattr(args, 'limited_samples'):
+ limited_samples = args.limited_samples // args.local_size
+ else:
+ limited_samples = -1
+ random_seed = args.seed
+ sampler = make_data_sampler(
+ dataset, shuffle, is_distributed, limited_samples=limited_samples,
+ random_seed=random_seed)
+ batch_sampler = make_batch_data_sampler(
+ sampler, images_per_gpu, num_iters, start_iter
+ )
+ data_loader = torch.utils.data.DataLoader(
+ dataset, num_workers=args.num_workers, batch_sampler=batch_sampler,
+ pin_memory=True, collate_fn=collate_fn
+ )
+ meta_info = (images_per_batch, iter_per_ep, num_iters)
+ return data_loader, meta_info
+
+
+def main_worker(args):
+ """
+
+ """
+ cf = import_filename(args.cf)
+ Net, inner_collect_fn = cf.Net, cf.inner_collect_fn
+
+ dataset_cf = import_filename(args.dataset_cf)
+ BaseDataset = dataset_cf.BaseDataset
+
+ print(f"Args: {edict(sorted(vars(args).items()))}")
+ # init models
+ logger.info('Building models...')
+ model = Net(args)
+ if args.do_train:
+ logger.warning("Do training...")
+ # Prepare Dataset.
+ if getattr(args, 'refer_clip_preprocess', None):
+ train_dataset = BaseDataset(args, args.train_yaml, split='train', preprocesser=model.feature_extractor)
+ eval_dataset = BaseDataset(args, args.val_yaml, split='val', preprocesser=model.feature_extractor)
+ else:
+ train_dataset = BaseDataset(args, args.train_yaml, split='train')
+ eval_dataset = BaseDataset(args, args.val_yaml, split='val')
+
+ train_info = get_loader_info(args, args.local_train_batch_size,
+ train_dataset)
+ _, images_per_batch, args.iter_per_ep, args.num_iters = train_info
+ if args.eval_step <= 5.0:
+ args.eval_step = args.eval_step * args.iter_per_ep
+ if args.save_step <= 5.0:
+ args.save_step = args.save_step * args.iter_per_ep
+
+ args.eval_step = int(max(10, args.eval_step))
+ args.save_step = int(max(10, args.save_step))
+
+ from torch.optim import AdamW
+ optimizer = AdamW(model.parameters(), lr=args.learning_rate, betas=(0.9, 0.98), weight_decay=args.decay)
+ optimizer = getattr(model, 'optimizer', optimizer)
+
+ if args.constant_lr:
+ scheduler = WarmupLinearConstantLR(
+ optimizer,
+ max_iter=(args.num_iters // args.gradient_accumulate_steps) + 1,
+ warmup_ratio=getattr(args, 'warmup_ratio', 0.05))
+ else:
+ scheduler = WarmupLinearLR(
+ optimizer,
+ max_iter=(
+ args.num_iters//args.gradient_accumulate_steps)+1,
+ warmup_ratio=getattr(args, 'warmup_ratio', 0.05))
+ scheduler = getattr(model, 'scheduler', scheduler)
+
+ trainer = Agent_LDM(args, model, optimizer, scheduler)
+ trainer.setup_model_for_training()
+
+ train_dataloader, train_info = make_data_loader(
+ args, args.local_train_batch_size,
+ train_dataset, start_iter=trainer.global_step+1, loader_info=train_info)
+ logger.info(
+ f"Video Length {train_dataset.size_frame}")
+ logger.info(
+ f"Total batch size {images_per_batch}")
+ logger.info(
+ f"Total training steps {args.num_iters}")
+ logger.info(f"Starting train iter: {trainer.global_step+1}")
+ logger.info(
+ f"Training steps per epoch (accumulated) {args.iter_per_ep}")
+ logger.info(
+ f"Training dataloader length {len(train_dataloader)}")
+ logger.info(
+ f"Evaluation happens every {args.eval_step} steps")
+ logger.info(
+ f"Checkpoint saves every {args.save_step} steps")
+
+ eval_dataloader, eval_info = make_data_loader(
+ args, args.local_eval_batch_size,
+ eval_dataset)
+
+ trainer.train_eval_by_iter(train_loader=train_dataloader, eval_loader=eval_dataloader, inner_collect_fn=inner_collect_fn)
+
+ if args.eval_visu:
+ logger.warning("Do eval_visu...")
+ if getattr(args, 'refer_clip_preprocess', None):
+ eval_dataset = BaseDataset(args, args.val_yaml, split='val', preprocesser=model.feature_extractor)
+ else:
+ eval_dataset = BaseDataset(args, args.val_yaml, split='val')
+ eval_dataloader, eval_info = make_data_loader(
+ args, args.local_eval_batch_size,
+ eval_dataset)
+
+
+ trainer = Agent_LDM(args=args, model=model)
+ trainer.eval(eval_dataloader, inner_collect_fn=inner_collect_fn,
+ enc_dec_only='enc_dec_only' in args.eval_save_filename)
+
+if __name__ == "__main__":
+ from utils.args import sharedArgs
+ parsed_args = sharedArgs.parse_args()
+ main_worker(parsed_args)
diff --git a/One-to-All-Animation/benchmark/DisCo/human_img_edit_gradio.ipynb b/One-to-All-Animation/benchmark/DisCo/human_img_edit_gradio.ipynb
new file mode 100644
index 0000000000000000000000000000000000000000..6070db988e5dffe1a20023cc0b530759b2625cb6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/human_img_edit_gradio.ipynb
@@ -0,0 +1,659 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "473523df",
+ "metadata": {},
+ "source": [
+ "### Example Jupyter Code for Generation Results with Gradio Demo\n",
+ "\n",
+ "```\n",
+ "--------------------------------------------------------\n",
+ "DisCo - Disentangled Control for Referring Human Dance Generation in Real World\n",
+ "Licensed under The Apache-2.0 license License [see LICENSE for details]\n",
+ "Tan Wang (TAN317@e.ntu.edu.sg)\n",
+ "Work done during internship at Microsoft\n",
+ "--------------------------------------------------------\n",
+ "```\n",
+ "\n",
+ "Pls remember to change the path (model checkpoint, root dir, eval_save_filename, and so on) in the `manual_args`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 1,
+ "id": "fdbf0c37",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/home/wangtan/.local/lib/python3.8/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
+ " from .autonotebook import tqdm as notebook_tqdm\n",
+ "[2023-07-03 08:19:31 ] : Deep Learning Utils @ Chenfei Wu\u001b[0m\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "WANDB_ENABLE: 0\n",
+ "2023-07-03 08:19:31,989.989 262807:common.py:1785 setup_yaml(): python 3 env\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:32 ] : Deep Learning Utils @ Chenfei Wu\u001b[0m\n",
+ "[2023-07-03 08:19:32 ] : Deep Learning Utils @ Chenfei Wu\u001b[0m\n",
+ "[2023-07-03 08:19:32 <__init__.py:71> BasicArgs] Detected unknown Node MICL-ZhangHWSvr1.\u001b[0m\n",
+ "[2023-07-03 08:19:32 <__init__.py:71> BasicArgs] Detected unknown Node MICL-ZhangHWSvr1.\u001b[0m\n"
+ ]
+ }
+ ],
+ "source": [
+ "import os\n",
+ "os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
+ "os.environ[\"WANDB_ENABLE\"] = \"0\"\n",
+ "\n",
+ "from utils.wutils_ldm import *\n",
+ "from agent import Agent_LDM, WarmupLinearLR, WarmupLinearConstantLR\n",
+ "import torch\n",
+ "from config import BasicArgs\n",
+ "from utils.lib import *\n",
+ "# from utils.args import parse_with_cf\n",
+ "from utils.dist import dist_init\n",
+ "from dataset.tsv_dataset import make_data_sampler, make_batch_data_sampler\n",
+ "from finetune_sdm_yaml import get_loader_info, make_data_loader\n",
+ "torch.multiprocessing.set_sharing_strategy('file_system')"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "a8735d83",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 2,
+ "id": "f0fcd501",
+ "metadata": {
+ "scrolled": false
+ },
+ "outputs": [
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "2023-07-03 08:19:32,623.623 262807:__init__.py:51 _is_triton_available(): A matching Triton is not available, some optimizations will not be enabled.\n",
+ "Error caught was: No module named 'triton'\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:32 <507173574.py:71> ] Building models...\u001b[0m\n",
+ "[2023-07-03 08:19:32 <507173574.py:71> ] Building models...\u001b[0m\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "distributed training ... presumbly debug with 1 GPU\n",
+ "Using seed 42 for rank 0\n",
+ "Using seed 42 for torch.cuda\n",
+ "Loading pre-trained image_encoder from /home1/wangtan/code/ms_internship2/github_repo/run_test/diffusers/sd-image-variations-diffusers/image_encoder\n",
+ "Loading pre-trained vae from /home1/wangtan/code/ms_internship2/github_repo/run_test/diffusers/sd-image-variations-diffusers/vae\n",
+ "Loading pre-trained unet from /home1/wangtan/code/ms_internship2/github_repo/run_test/diffusers/sd-image-variations-diffusers/unet\n",
+ "use sd vae to init the controlnet condition embedding\n",
+ "Args: {'root_dir': '/home1/wangtan/code/ms_internship2/github_repo/run_test', 'cf': 'config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py', 'pretrained_model': '/home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt', 'pretrained_model_lora': None, 'pretrained_model_controlnet': None, 'debug': False, 'debug_seed': False, 'debug_dataloader': False, 'log_dir': '/home1/wangtan/code/ms_internship2/github_repo/run_test/exp/tiktok_ft', 'deepspeed': True, 'use_amp': False, 'seed': 42, 'fix_dist_seed': True, 'tiktok_data_root': 'keli/dataset/TikTok_dataset/', 'img_size': [256, 256], 'max_video_len': 1, 'debug_max_video_len': 1, 'conds': ['poses', 'masks'], 'gradient_checkpointing': True, 'find_unused_parameters': False, 'enable_xformers_memory_efficient_attention': True, 'trainable_modules': None, 'scale_factor': 0.18215, 'loss_target': 'noise', 'x0_steps': 200, 'pretrained_model_path': '/home1/wangtan/code/ms_internship2/github_repo/run_test/diffusers/sd-image-variations-diffusers', 'num_workers': 4, 'node_split_sampler': False, 'gradient_accumulate_steps': 1, 'max_grad_norm': -1, 'learning_rate': 0.0002, 'decay': 0.001, 'warmup_ratio': 0.1, 'max_train_samples': None, 'debug_max_train_samples': 100, 'drop_text': 1.0, 'local_train_batch_size': 32, 'epochs': 20, 'eval_step': 500.0, 'save_step': 500.0, 'do_train': False, 'train_yaml': './blob_dir/debug_output/video_sythesis/dataset/composite/train_webvid10m_a_54.yaml', 'resume': False, 'null_caption': False, 'refer_sdvae': True, 'controlnet_conditioning_scale_cond': 1.0, 'controlnet_conditioning_scale_ref': 1.0, 'unet_unfreeze_type': 'all', 'controlnet_attn': False, 'use_cfg': False, 'refer_clip_preprocess': False, 'refer_clip_proj': False, 'ref_null_caption': False, 'combine_clip_local': True, 'combine_use_mask': True, 'drop_ref': 0.0, 'my_adapter': False, 'pos_resize_img': False, 'fg_variation': 0.0, 'strong_aug_stage2': False, 'strong_rand_stage2': False, 'strong_aug_stage1': False, 'stage1_pretrain_path': None, 'stage2_only_pose': False, 'constant_lr': False, 'SD2_not_add_image_emb_noise': False, 'val_yaml': './blob_dir/debug_output/video_sythesis/dataset/composite/val_webvid10m_a.yaml', 'max_eval_samples': None, 'debug_max_eval_samples': 20, 'pose_normalize': False, 'normalize_by_1st_frm': False, 'local_eval_batch_size': 32, 'eval_visu': True, 'eval_visu_trainsample': False, 'eval_visu_imagefolder': False, 'eval_visu_changepose': False, 'eval_visu_changefore': False, 'eval_save_filename': 'try', 'eval_before_train': True, 'eval_scheduler': 'ddim', 'eval_enc_dec_only': False, 'num_inf_videos_per_prompt': 1, 'num_inference_steps': 50, 'guidance_scale': 3.0, 'stepwise_sample_depth': -1, 'interpolation': None, 'interpolate_mode': None, 'visu_save': False, 'freeze_pose': False, 'freeze_background': False, 'ft_img_num': 0, 'ft_one_ref_image': True, 'ft_iters': None, 's1': 1.0, 's2': 1.0, 'ft_idx': None, 'ref_mode': 'first', '__module__': 'mymodule', 'task_name': 'ref_attn_clip_combine_controlnet', 'method_name': 'app_demo_image_edit', 'dataset_cf': 'dataset/app_demo_human_image_edit_singleinput.py', 'img_full_size': [256, 256], 'fps': 5, 'data_dir': './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain', 'debug_train_yaml': './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/train_webvid2.5m_2.yaml', 'debug_val_yaml': './blob_dir/data/mtp_vlp_ray/debug/debug_pretrain/composite/val_webvid2.5m.yaml', 'web_data_root': '/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/dataset/Lindsey_0504_youtube/frames/single_person', 'sd15_path': '/home1/wangtan/code/ms_internship2/github_repo/run_test/diffusers/stable-diffusion-v1-5-2', 'freeze_unet': True, 'num_inf_images_per_prompt': 1, '__doc__': None, 'n_gpu': 1, 'local_size': 1, 'num_gpus': 1, 'distributed': True, 'num_nodes': 1, 'word_size': 1, 'local_rank': 0, 'rank': 0, 'node_id': 0, 'dist': True, 'nodes': 1, 'world_size': 1, 'train_batch_size': 32, 'eval_batch_size': 32}\n"
+ ]
+ }
+ ],
+ "source": [
+ "from utils.args import sharedArgs\n",
+ "manual_args = ['--cf', 'config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py', '--eval_visu', 'True', '--root_dir', '/home1/wangtan/code/ms_internship2/github_repo/run_test', '--local_train_batch_size', '32', '--local_eval_batch_size', '32', '--log_dir', 'exp/tiktok_ft', '--epochs', '20', '--deepspeed', '--eval_step', '500',\n",
+ " '--save_step', '500', '--gradient_accumulate_steps', '1', '--learning_rate', '2e-4', '--fix_dist_seed', 'True', '--loss_target',\n",
+ " 'noise', '--unet_unfreeze_type', 'all', '--guidance_scale', '3', '--refer_sdvae', 'True', '--ref_null_caption', 'False', '--combine_clip_local', 'True', '--combine_use_mask', 'True', '--conds', 'poses','masks', '--pretrained_model', '/home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt', '--eval_save_filename', 'try']\n",
+ "parsed_args = sharedArgs.parser.parse_args(args=manual_args)\n",
+ "# args = sharedArgs.parser.parse_args(args=['--cf', 'config/ref_attn_clip_combine_controlnet/app_demo_image_edit.py', '--eval_visu', 'True'])\n",
+ "# import pdb; pdb.set_trace()\n",
+ "\n",
+ "###### process the args #######\n",
+ "if parsed_args.root_dir:\n",
+ " BasicArgs.root_dir = parsed_args.root_dir\n",
+ "else:\n",
+ " parsed_args.root_dir = BasicArgs.root_dir\n",
+ "parsed_args.pretrained_model_path = os.path.join(parsed_args.root_dir, parsed_args.pretrained_model_path)\n",
+ "\n",
+ "def parse_with_cf(parsed_args):\n",
+ " \"\"\"This function will set args based on the input config file.\n",
+ " (1) it only overwrites unset parameters,\n",
+ " i.e., these parameters not set from user command line input\n",
+ " (2) it also sets configs in the config file but declared in the parser\n",
+ " \"\"\"\n",
+ " # convert to EasyDict object,\n",
+ " # enabling access from attributes even for nested config\n",
+ " # e.g., args.train_datasets[0].name\n",
+ " args = edict(vars(parsed_args))\n",
+ " if os.path.exists(parsed_args.cf):\n",
+ " cf = import_filename(parsed_args.cf)\n",
+ " config_args = edict(vars(cf.Args))\n",
+ " override_keys = {arg[2:].split(\"=\")[0] for arg in manual_args\n",
+ " if arg.startswith(\"--\")}\n",
+ " # import pdb;pdb.set_trace()\n",
+ " for k, v in config_args.items():\n",
+ " if k not in override_keys:\n",
+ " setattr(args, k, v)\n",
+ " else:\n",
+ " raise NotImplementedError('Config filename %s does not exist.' % args.cf)\n",
+ " return args\n",
+ "\n",
+ "args = parse_with_cf(parsed_args)\n",
+ " \n",
+ "args.n_gpu = T.cuda.device_count() # local size\n",
+ "args.local_size = args.n_gpu\n",
+ "if args.root_dir not in args.log_dir:\n",
+ " args.log_dir = os.path.join(args.root_dir, args.log_dir)\n",
+ "if args.stepwise_sample_depth == -1:\n",
+ " args.interpolation = None\n",
+ " args.interpolate_mode = None\n",
+ "if args.interpolation != \"interpolate\":\n",
+ " args.interpolate_mode = None\n",
+ "\n",
+ "assert args.eval_step > 0, \"eval_step must be positive\"\n",
+ "assert args.save_step > 0, \"save_step must be positive\"\n",
+ "\n",
+ "dist_init(args)\n",
+ "args.dist = args.distributed\n",
+ "args.nodes = args.num_nodes\n",
+ "args.world_size = args.num_gpus\n",
+ "args.train_batch_size = args.local_train_batch_size * args.world_size\n",
+ "args.eval_batch_size = args.local_eval_batch_size * args.world_size\n",
+ "#############################################\n",
+ "\n",
+ "cf = import_filename(args.cf)\n",
+ "Net, inner_collect_fn = cf.Net, cf.inner_collect_fn\n",
+ "\n",
+ "dataset_cf = import_filename(args.dataset_cf)\n",
+ "BaseDataset = dataset_cf.BaseDataset\n",
+ "\n",
+ "# args = update_args(parsed_args, args)\n",
+ "\n",
+ "# init models\n",
+ "logger.info('Building models...')\n",
+ "model = Net(args)\n",
+ "print(f\"Args: {edict(vars(args))}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "019e44c6",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "21a550cd",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "8f876d44",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 3,
+ "id": "d1666198",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "\u001b[33m[2023-07-03 08:19:47 <287074974.py:3> ] Do eval_visu...\u001b[0m\n",
+ "\u001b[33m[2023-07-03 08:19:47 <287074974.py:3> ] Do eval_visu...\u001b[0m\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "number of samples: 25\n",
+ "Specify the load model path, not use deepspeed but the pytorch original load func\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:51 file2data] Loaded data from /home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt\u001b[0m\n",
+ "[2023-07-03 08:19:51 file2data] Loaded data from /home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt\u001b[0m\n",
+ "\u001b[33m[2023-07-03 08:19:54 adaptively_load_state_dict] Strictly Loaded state_dict.\u001b[0m\n",
+ "\u001b[33m[2023-07-03 08:19:54 adaptively_load_state_dict] Strictly Loaded state_dict.\u001b[0m\n",
+ "\u001b[33m[2023-07-03 08:19:54 load_checkpoint_for_deepspeed_diff_gpu] Loaded checkpoint /home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt of global_step 7200\u001b[0m\n",
+ "\u001b[33m[2023-07-03 08:19:54 load_checkpoint_for_deepspeed_diff_gpu] Loaded checkpoint /home/wangtan/data/disco/ft_checkpoint/moretiktok_nocfg/mp_rank_00_model_states.pt of global_step 7200\u001b[0m\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:54,390] [INFO] [logging.py:69:log_dist] [Rank 0] DeepSpeed info: version=0.6.3, git-hash=unknown, git-branch=unknown\n",
+ "[2023-07-03 08:19:54,729] [INFO] [engine.py:278:__init__] DeepSpeed Flops Profiler Enabled: False\n",
+ "[2023-07-03 08:19:54,734] [INFO] [config.py:1059:print] DeepSpeedEngine configuration:\n",
+ "[2023-07-03 08:19:54,736] [INFO] [config.py:1063:print] activation_checkpointing_config {\n",
+ " \"partition_activations\": false, \n",
+ " \"contiguous_memory_optimization\": false, \n",
+ " \"cpu_checkpointing\": false, \n",
+ " \"number_checkpoints\": null, \n",
+ " \"synchronize_checkpoint_boundary\": false, \n",
+ " \"profile\": false\n",
+ "}\n",
+ "[2023-07-03 08:19:54,737] [INFO] [config.py:1063:print] aio_config ................... {'block_size': 1048576, 'queue_depth': 8, 'thread_count': 1, 'single_submit': False, 'overlap_events': True}\n",
+ "[2023-07-03 08:19:54,738] [INFO] [config.py:1063:print] amp_enabled .................. False\n",
+ "[2023-07-03 08:19:54,739] [INFO] [config.py:1063:print] amp_params ................... False\n",
+ "[2023-07-03 08:19:54,740] [INFO] [config.py:1063:print] autotuning_config ............ {\n",
+ " \"enabled\": false, \n",
+ " \"start_step\": null, \n",
+ " \"end_step\": null, \n",
+ " \"metric_path\": null, \n",
+ " \"arg_mappings\": null, \n",
+ " \"metric\": \"throughput\", \n",
+ " \"model_info\": null, \n",
+ " \"results_dir\": null, \n",
+ " \"exps_dir\": null, \n",
+ " \"overwrite\": true, \n",
+ " \"fast\": true, \n",
+ " \"start_profile_step\": 3, \n",
+ " \"end_profile_step\": 5, \n",
+ " \"tuner_type\": \"gridsearch\", \n",
+ " \"tuner_early_stopping\": 5, \n",
+ " \"tuner_num_trials\": 50, \n",
+ " \"model_info_path\": null, \n",
+ " \"mp_size\": 1, \n",
+ " \"max_train_batch_size\": null, \n",
+ " \"min_train_batch_size\": 1, \n",
+ " \"max_train_micro_batch_size_per_gpu\": 1.024000e+03, \n",
+ " \"min_train_micro_batch_size_per_gpu\": 1, \n",
+ " \"num_tuning_micro_batch_sizes\": 3\n",
+ "}\n",
+ "[2023-07-03 08:19:54,740] [INFO] [config.py:1063:print] bfloat16_enabled ............. False\n",
+ "[2023-07-03 08:19:54,741] [INFO] [config.py:1063:print] checkpoint_tag_validation_enabled True\n",
+ "[2023-07-03 08:19:54,742] [INFO] [config.py:1063:print] checkpoint_tag_validation_fail False\n",
+ "[2023-07-03 08:19:54,743] [INFO] [config.py:1063:print] communication_data_type ...... None\n",
+ "[2023-07-03 08:19:54,744] [INFO] [config.py:1063:print] curriculum_enabled ........... False\n",
+ "[2023-07-03 08:19:54,745] [INFO] [config.py:1063:print] curriculum_params ............ False\n",
+ "[2023-07-03 08:19:54,745] [INFO] [config.py:1063:print] dataloader_drop_last ......... False\n",
+ "[2023-07-03 08:19:54,746] [INFO] [config.py:1063:print] disable_allgather ............ False\n",
+ "[2023-07-03 08:19:54,747] [INFO] [config.py:1063:print] dump_state ................... False\n",
+ "[2023-07-03 08:19:54,748] [INFO] [config.py:1063:print] dynamic_loss_scale_args ...... None\n",
+ "[2023-07-03 08:19:54,748] [INFO] [config.py:1063:print] eigenvalue_enabled ........... False\n",
+ "[2023-07-03 08:19:54,749] [INFO] [config.py:1063:print] eigenvalue_gas_boundary_resolution 1\n",
+ "[2023-07-03 08:19:54,751] [INFO] [config.py:1063:print] eigenvalue_layer_name ........ bert.encoder.layer\n",
+ "[2023-07-03 08:19:54,752] [INFO] [config.py:1063:print] eigenvalue_layer_num ......... 0\n",
+ "[2023-07-03 08:19:54,753] [INFO] [config.py:1063:print] eigenvalue_max_iter .......... 100\n",
+ "[2023-07-03 08:19:54,753] [INFO] [config.py:1063:print] eigenvalue_stability ......... 1e-06\n",
+ "[2023-07-03 08:19:54,754] [INFO] [config.py:1063:print] eigenvalue_tol ............... 0.01\n",
+ "[2023-07-03 08:19:54,755] [INFO] [config.py:1063:print] eigenvalue_verbose ........... False\n",
+ "[2023-07-03 08:19:54,755] [INFO] [config.py:1063:print] elasticity_enabled ........... False\n",
+ "[2023-07-03 08:19:54,756] [INFO] [config.py:1063:print] flops_profiler_config ........ {\n",
+ " \"enabled\": false, \n",
+ " \"profile_step\": 1, \n",
+ " \"module_depth\": -1, \n",
+ " \"top_modules\": 3, \n",
+ " \"detailed\": true, \n",
+ " \"output_file\": null\n",
+ "}\n",
+ "[2023-07-03 08:19:54,757] [INFO] [config.py:1063:print] fp16_enabled ................. True\n",
+ "[2023-07-03 08:19:54,757] [INFO] [config.py:1063:print] fp16_master_weights_and_gradients False\n",
+ "[2023-07-03 08:19:54,758] [INFO] [config.py:1063:print] fp16_mixed_quantize .......... False\n",
+ "[2023-07-03 08:19:54,758] [INFO] [config.py:1063:print] global_rank .................. 0\n",
+ "[2023-07-03 08:19:54,759] [INFO] [config.py:1063:print] gradient_accumulation_steps .. 1\n",
+ "[2023-07-03 08:19:54,760] [INFO] [config.py:1063:print] gradient_clipping ............ 0.0\n",
+ "[2023-07-03 08:19:54,760] [INFO] [config.py:1063:print] gradient_predivide_factor .... 1.0\n",
+ "[2023-07-03 08:19:54,761] [INFO] [config.py:1063:print] initial_dynamic_scale ........ 4294967296\n",
+ "[2023-07-03 08:19:54,761] [INFO] [config.py:1063:print] loss_scale ................... 0\n",
+ "[2023-07-03 08:19:54,762] [INFO] [config.py:1063:print] memory_breakdown ............. False\n",
+ "[2023-07-03 08:19:54,763] [INFO] [config.py:1063:print] optimizer_legacy_fusion ...... False\n",
+ "[2023-07-03 08:19:54,763] [INFO] [config.py:1063:print] optimizer_name ............... None\n",
+ "[2023-07-03 08:19:54,764] [INFO] [config.py:1063:print] optimizer_params ............. None\n",
+ "[2023-07-03 08:19:54,764] [INFO] [config.py:1063:print] pipeline ..................... {'stages': 'auto', 'partition': 'best', 'seed_layers': False, 'activation_checkpoint_interval': 0}\n",
+ "[2023-07-03 08:19:54,765] [INFO] [config.py:1063:print] pld_enabled .................. False\n",
+ "[2023-07-03 08:19:54,765] [INFO] [config.py:1063:print] pld_params ................... False\n",
+ "[2023-07-03 08:19:54,766] [INFO] [config.py:1063:print] prescale_gradients ........... False\n",
+ "[2023-07-03 08:19:54,766] [INFO] [config.py:1063:print] quantize_change_rate ......... 0.001\n",
+ "[2023-07-03 08:19:54,767] [INFO] [config.py:1063:print] quantize_groups .............. 1\n",
+ "[2023-07-03 08:19:54,767] [INFO] [config.py:1063:print] quantize_offset .............. 1000\n",
+ "[2023-07-03 08:19:54,768] [INFO] [config.py:1063:print] quantize_period .............. 1000\n",
+ "[2023-07-03 08:19:54,768] [INFO] [config.py:1063:print] quantize_rounding ............ 0\n",
+ "[2023-07-03 08:19:54,769] [INFO] [config.py:1063:print] quantize_start_bits .......... 16\n",
+ "[2023-07-03 08:19:54,769] [INFO] [config.py:1063:print] quantize_target_bits ......... 8\n",
+ "[2023-07-03 08:19:54,770] [INFO] [config.py:1063:print] quantize_training_enabled .... False\n",
+ "[2023-07-03 08:19:54,770] [INFO] [config.py:1063:print] quantize_type ................ 0\n",
+ "[2023-07-03 08:19:54,771] [INFO] [config.py:1063:print] quantize_verbose ............. False\n",
+ "[2023-07-03 08:19:54,771] [INFO] [config.py:1063:print] scheduler_name ............... None\n",
+ "[2023-07-03 08:19:54,772] [INFO] [config.py:1063:print] scheduler_params ............. None\n",
+ "[2023-07-03 08:19:54,772] [INFO] [config.py:1063:print] sparse_attention ............. None\n",
+ "[2023-07-03 08:19:54,773] [INFO] [config.py:1063:print] sparse_gradients_enabled ..... False\n",
+ "[2023-07-03 08:19:54,773] [INFO] [config.py:1063:print] steps_per_print .............. 10\n",
+ "[2023-07-03 08:19:54,774] [INFO] [config.py:1063:print] tensorboard_enabled .......... True\n",
+ "[2023-07-03 08:19:54,774] [INFO] [config.py:1063:print] tensorboard_job_name ......... tensorboard_log\n",
+ "[2023-07-03 08:19:54,775] [INFO] [config.py:1063:print] tensorboard_output_path ...... /home1/wangtan/code/ms_internship2/github_repo/run_test/exp/tiktok_ft\n",
+ "[2023-07-03 08:19:54,775] [INFO] [config.py:1063:print] train_batch_size ............. 32\n",
+ "[2023-07-03 08:19:54,776] [INFO] [config.py:1063:print] train_micro_batch_size_per_gpu 32\n",
+ "[2023-07-03 08:19:54,776] [INFO] [config.py:1063:print] use_quantizer_kernel ......... False\n",
+ "[2023-07-03 08:19:54,776] [INFO] [config.py:1063:print] wall_clock_breakdown ......... False\n",
+ "[2023-07-03 08:19:54,777] [INFO] [config.py:1063:print] world_size ................... 1\n",
+ "[2023-07-03 08:19:54,777] [INFO] [config.py:1063:print] zero_allow_untested_optimizer False\n",
+ "[2023-07-03 08:19:54,778] [INFO] [config.py:1063:print] zero_config .................. {\n",
+ " \"stage\": 0, \n",
+ " \"contiguous_gradients\": true, \n",
+ " \"reduce_scatter\": true, \n",
+ " \"reduce_bucket_size\": 5.000000e+08, \n",
+ " \"allgather_partitions\": true, \n",
+ " \"allgather_bucket_size\": 5.000000e+08, \n",
+ " \"overlap_comm\": false, \n",
+ " \"load_from_fp32_weights\": true, \n",
+ " \"elastic_checkpoint\": false, \n",
+ " \"offload_param\": null, \n",
+ " \"offload_optimizer\": null, \n",
+ " \"sub_group_size\": 1.000000e+09, \n",
+ " \"prefetch_bucket_size\": 5.000000e+07, \n",
+ " \"param_persistence_threshold\": 1.000000e+05, \n",
+ " \"max_live_parameters\": 1.000000e+09, \n",
+ " \"max_reuse_distance\": 1.000000e+09, \n",
+ " \"gather_16bit_weights_on_model_save\": false, \n",
+ " \"ignore_unused_parameters\": true, \n",
+ " \"round_robin_gradients\": false, \n",
+ " \"legacy_stage1\": false\n",
+ "}\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:54,779] [INFO] [config.py:1063:print] zero_enabled ................. False\n",
+ "[2023-07-03 08:19:54,779] [INFO] [config.py:1063:print] zero_optimization_stage ...... 0\n",
+ "[2023-07-03 08:19:54,780] [INFO] [config.py:1065:print] json = {\n",
+ " \"train_micro_batch_size_per_gpu\": 32, \n",
+ " \"gradient_accumulation_steps\": 1, \n",
+ " \"fp16\": {\n",
+ " \"enabled\": true\n",
+ " }, \n",
+ " \"flops_profiler\": {\n",
+ " \"enabled\": false, \n",
+ " \"profile_step\": 1, \n",
+ " \"module_depth\": -1, \n",
+ " \"top_modules\": 3, \n",
+ " \"detailed\": true\n",
+ " }, \n",
+ " \"tensorboard\": {\n",
+ " \"enabled\": true, \n",
+ " \"output_path\": \"/home1/wangtan/code/ms_internship2/github_repo/run_test/exp/tiktok_ft\", \n",
+ " \"job_name\": \"tensorboard_log\"\n",
+ " }\n",
+ "}\n",
+ "Using /home/wangtan/.cache/torch_extensions/py38_cu113 as PyTorch extensions root...\n",
+ "Emitting ninja build file /home/wangtan/.cache/torch_extensions/py38_cu113/utils/build.ninja...\n",
+ "Building extension module utils...\n",
+ "Allowing ninja to set a default number of workers... (overridable by setting the environment variable MAX_JOBS=N)\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "[2023-07-03 08:19:56 prepare_dist_model] Successfully built models with {'trainable': 1581790996, 'frozen': 387620071, 'trainable_fp32': 0, 'trainalbe_fp16': 1581790996, 'frozen_fp32': 303966208, 'frozen_fp16': 83653863} parameters\u001b[0m\n",
+ "[2023-07-03 08:19:56 prepare_dist_model] Successfully built models with {'trainable': 1581790996, 'frozen': 387620071, 'trainable_fp32': 0, 'trainalbe_fp16': 1581790996, 'frozen_fp32': 303966208, 'frozen_fp16': 83653863} parameters\u001b[0m\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "ninja: no work to do.\n",
+ "Loading extension module utils...\n",
+ "Time to load utils op: 0.8241767883300781 seconds\n",
+ "Mode [all]: There are 686 modules in unet to be set as requires_grad=True.\n"
+ ]
+ }
+ ],
+ "source": [
+ "### prepare the eval\n",
+ "\n",
+ "logger.warning(\"Do eval_visu...\")\n",
+ "if getattr(args, 'refer_clip_preprocess', None):\n",
+ " eval_dataset = BaseDataset(args, args.val_yaml, split='val', preprocesser=model.feature_extractor)\n",
+ "else:\n",
+ " eval_dataset = BaseDataset(args, args.val_yaml, split='val')\n",
+ "eval_dataloader, eval_info = make_data_loader(\n",
+ " args, args.local_eval_batch_size, \n",
+ " eval_dataset)\n",
+ "\n",
+ "\n",
+ "trainer = Agent_LDM(args=args, model=model)\n",
+ "trainer.eval_demo_pre()"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 4,
+ "id": "4377766c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def load_image(image):\n",
+ " if not image.mode == \"RGB\":\n",
+ " image = image.convert(\"RGB\")\n",
+ "\n",
+ " return image\n",
+ "\n",
+ "\n",
+ "\n",
+ "@torch.no_grad()\n",
+ "def inference(reference_fg, fg_mask, ref_bg_image, bg_mask, skeleton_img, *args, **kwargs):\n",
+ " reference_fg = load_image(reference_fg)\n",
+ " fg_mask = load_image(fg_mask)\n",
+ " ref_bg_image = load_image(ref_bg_image)\n",
+ " bg_mask = load_image(bg_mask)\n",
+ " skeleton_img = load_image(skeleton_img)\n",
+ " \n",
+ " input_data = [reference_fg, fg_mask, ref_bg_image, bg_mask, skeleton_img]\n",
+ " output_image = trainer.eval_demo_run(input_data, eval_dataset=eval_dataset)\n",
+ " return output_image\n",
+ "\n",
+ "@torch.no_grad()\n",
+ "def inference_masked(reference_fg, ref_bg_image, skeleton_img, *args, **kwargs):\n",
+ " reference_fg = load_image(reference_fg)\n",
+ " ref_bg_image = load_image(ref_bg_image)\n",
+ " skeleton_img = load_image(skeleton_img)\n",
+ " \n",
+ " input_data = [reference_fg, ref_bg_image, skeleton_img]\n",
+ " output_image = trainer.eval_demo_run_masked(input_data, eval_dataset=eval_dataset)\n",
+ " return output_image"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "0580155a",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "035a1454",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ },
+ {
+ "cell_type": "code",
+ "execution_count": 5,
+ "id": "d9c3b8ff",
+ "metadata": {},
+ "outputs": [
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "/home/wangtan/anaconda3/envs/disco/lib/python3.8/site-packages/gradio/layouts.py:80: UserWarning: The `style` method is deprecated. Please set these arguments in the constructor instead.\n",
+ " warnings.warn(\n",
+ "/home/wangtan/anaconda3/envs/disco/lib/python3.8/site-packages/gradio/blocks.py:261: UserWarning: api_name load_example already exists, using load_example_1\n",
+ " warnings.warn(f\"api_name {api_name} already exists, using {api_name_}\")\n",
+ "/home/wangtan/anaconda3/envs/disco/lib/python3.8/site-packages/gradio/blocks.py:261: UserWarning: api_name load_example already exists, using load_example_2\n",
+ " warnings.warn(f\"api_name {api_name} already exists, using {api_name_}\")\n"
+ ]
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Running on local URL: http://127.0.0.1:7861\n",
+ "Running on public URL: https://e4ec2a4f33f5ee858d.gradio.live\n",
+ "\n",
+ "This share link expires in 72 hours. For free permanent hosting and GPU upgrades, run `gradio deploy` from Terminal to deploy to Spaces (https://huggingface.co/spaces)\n"
+ ]
+ },
+ {
+ "data": {
+ "text/html": [
+ ""
+ ],
+ "text/plain": [
+ ""
+ ]
+ },
+ "metadata": {},
+ "output_type": "display_data"
+ },
+ {
+ "data": {
+ "text/plain": []
+ },
+ "execution_count": 5,
+ "metadata": {},
+ "output_type": "execute_result"
+ },
+ {
+ "name": "stdout",
+ "output_type": "stream",
+ "text": [
+ "Mode [all]: There are 686 modules in unet to be set as requires_grad=True.\n"
+ ]
+ },
+ {
+ "name": "stderr",
+ "output_type": "stream",
+ "text": [
+ "100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 50/50 [00:04<00:00, 12.48it/s]\n"
+ ]
+ }
+ ],
+ "source": [
+ "#### Launch the gradio demo\n",
+ "\n",
+ "import gradio as gr\n",
+ "'''\n",
+ "launch app\n",
+ "'''\n",
+ "title = \"DisCo Demo (Video Demo Comming Soon!)\"\n",
+ "description = \"\"\" Project Page | Paper | Github Repo | Video
\n",
+ "Skip the queue by duplicating this space and upgrading to GPU in settings
\n",
+ "
\n",
+ "\"\"\"\n",
+ "\n",
+ "\n",
+ "\n",
+ "with gr.Blocks() as demo:\n",
+ " gr.Markdown(\n",
+ " \"\"\"\n",
+ " # DisCo Demo (Video Demo Comming Soon!)\n",
+ " Start edit the human with provided human foreground, background, pose. \n",
+ " \n",
+ " Note that for self-uploaded images, TikTok-Style human images are preferred.\n",
+ " \n",
+ " [Project Page](https://disco-dance.github.io/) | [Github](https://github.com/Wangt-CN/DisCo)\n",
+ " \"\"\")\n",
+ " # gr.Markdown(\n",
+ "# \"\"\"\n",
+ "# ## DisCo Demo (Video Demo Comming Soon!)\n",
+ "# Project Page | Paper | Github Repo | Video
\n",
+ "# Skip the queue by duplicating this space and upgrading to GPU in settings
\n",
+ "#
\n",
+ "# \"\"\")\n",
+ " \n",
+ " with gr.Row().style(equal_height=False):\n",
+ " with gr.Column(min_width=400, scale=2):\n",
+ " input_fg = gr.Image(type='pil',label=\"Foreground Image\")\n",
+ " gr.Examples(examples=[\"./demo_data/fg/masked_images/00035.png\", \"./demo_data/fg/masked_images/00335.png\", \"./demo_data/fg/masked_images/00147.png\", \"./demo_data/fg/masked_images/00072.png\", \"./demo_data/fg/masked_images/00115.png\"], inputs=input_fg)\n",
+ "\n",
+ " input_bg = gr.Image(type='pil',label=\"Background Image\")\n",
+ " gr.Examples(examples=[\"./demo_data/bg/masked_images/00035.png\", \"./demo_data/bg/masked_images/00335.png\", \"./demo_data/bg/masked_images/00147.png\", \"./demo_data/bg/masked_images/00072.png\", \"./demo_data/bg/masked_images/00115.png\"], inputs=input_bg)\n",
+ "\n",
+ " input_pose = gr.Image(type='pil',label=\"Target Pose\",scale=1)\n",
+ " gr.Examples(examples=[\"./demo_data/pose_img/0049.png\",\"./demo_data/pose_img/0198.png\",\"./demo_data/pose_img/0213.png\",\"./demo_data/pose_img/0264.png\",\"./demo_data/pose_img/0144.png\",\"./demo_data/pose_img/0054.png\"], inputs=input_pose)\n",
+ "\n",
+ " btn = gr.Button(\"Generate\")\n",
+ " \n",
+ " \n",
+ " with gr.Column(min_width=150):\n",
+ " output_img = gr.Image(type='pil',label=\"Edited Human Image\")\n",
+ " \n",
+ " btn.click(inference_masked, inputs=[input_fg, input_bg, input_pose], outputs=[output_img])\n",
+ " \n",
+ "demo.queue(concurrency_count=2)\n",
+ "demo.launch(share=True)"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "141af2b1",
+ "metadata": {},
+ "outputs": [],
+ "source": []
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python [conda env:disco]",
+ "language": "python",
+ "name": "conda-env-disco-py"
+ },
+ "language_info": {
+ "codemirror_mode": {
+ "name": "ipython",
+ "version": 3
+ },
+ "file_extension": ".py",
+ "mimetype": "text/x-python",
+ "name": "python",
+ "nbconvert_exporter": "python",
+ "pygments_lexer": "ipython3",
+ "version": "3.8.13"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/One-to-All-Animation/benchmark/DisCo/requirements.txt b/One-to-All-Animation/benchmark/DisCo/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..94edfdc77261d31d57b8a17e04be3048a283733f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/requirements.txt
@@ -0,0 +1,39 @@
+wandb
+ffmpeg-python
+opencv-python
+timm
+ftfy==6.0.3
+tensorboardX==2.4.1
+# pycocotools==2.0.4
+# pycocoevalcap==1.2
+datasets
+rouge_score
+omegaconf
+diffusers[torch]==0.14.0
+decord==0.6.0
+invisible-watermark
+colorlog
+deepdish
+configobj
+json_lines
+albumentations==1.1.0
+opencv-python==4.2.0.34
+pudb==2019.2
+imageio==2.14.1
+imageio-ffmpeg==0.4.7
+pytorch-lightning==1.5.9
+omegaconf==2.1.1
+test-tube>=0.7.5
+streamlit>=0.73.1
+setuptools==59.5.0
+pillow==9.0.1
+einops==0.4.1
+torch-fidelity==0.3.0
+transformers==4.27.4
+torchmetrics==0.6.0
+kornia==0.6
+clean-fid
+h5py
+gradio
+pytorch-fid
+lpips
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/summary.py b/One-to-All-Animation/benchmark/DisCo/summary.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8fee70134a624228ab23b1b8ffde739cd819f4c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/summary.py
@@ -0,0 +1,97 @@
+import json
+from pathlib import Path
+import statistics
+from tabulate import tabulate # pip install tabulate
+
+def parse_metrics_dir(model_update_dir: Path):
+
+ l1_vals, ssim_vals, lpips_vals, psnr_vals, fid_vals = [], [], [], [], []
+ per_clip_records = []
+ fvd_3drn50, fvd_3dinception = None, None
+
+ for file in sorted(model_update_dir.iterdir()):
+ if file.name.endswith("_metrics_l1_ssim_lpips_psnr.json"):
+ clip_id = file.name.split("_metrics_l1_ssim_lpips_psnr.json")[0]
+ with open(file) as f:
+ data = json.load(f)
+
+ l1_vals.append(data.get("L1"))
+ ssim_vals.append(data.get("SSIM"))
+ lpips_vals.append(data.get("LPIPS"))
+ psnr_vals.append(data.get("PSNR"))
+
+ fid_file = model_update_dir / f"{clip_id}_pytorch_fid.txt"
+ fid_val = None
+ if fid_file.exists():
+ with open(fid_file) as ff:
+ content = ff.read().strip()
+ try:
+ fid_val = float(content.split()[-1])
+ fid_vals.append(fid_val)
+ except Exception:
+ pass
+
+ per_clip_records.append([
+ clip_id,
+ f"{data.get('L1'):.6f}",
+ f"{data.get('SSIM'):.6f}",
+ f"{data.get('LPIPS'):.6f}",
+ f"{data.get('PSNR'):.6f}",
+ f"{fid_val:.6f}" if fid_val is not None else "N/A"
+ ])
+
+ elif file.name == "metrics_fid-vid_fvd_dtssd_16frames.json":
+ with open(file) as f:
+ data = json.load(f)
+ fvd_3drn50 = data.get("FVD-3DRN50")
+ fvd_3dinception = data.get("FVD-3DInception")
+
+ metrics_summary = [
+ statistics.mean(l1_vals) if l1_vals else None,
+ statistics.mean(ssim_vals) if ssim_vals else None,
+ statistics.mean(lpips_vals) if lpips_vals else None,
+ statistics.mean(psnr_vals) if psnr_vals else None,
+ statistics.mean(fid_vals) if fid_vals else None,
+ fvd_3drn50,
+ fvd_3dinception
+ ]
+
+ return metrics_summary, per_clip_records
+
+def main():
+ base_dir = Path("../temp_eval_tiktok_frames")
+ # base_dir = Path("../temp_eval_cartoon_frames")
+ model_summary_all = []
+ clip_detail_all = []
+
+ for model_name in sorted(base_dir.iterdir()):
+ if model_name.is_dir():
+ metrics_summary, per_clip_records = parse_metrics_dir(model_name)
+
+ model_summary_all.append(
+ [model_name] + [f"{v:.6f}" if v is not None else "N/A" for v in metrics_summary]
+ )
+
+ for clip_row in per_clip_records:
+ clip_detail_all.append([model_name] + clip_row)
+
+ summary_header = ["Model", "L1_avg", "SSIM_avg", "LPIPS_avg", "PSNR_avg",
+ "FID_avg", "FVD-3DRN50", "FVD-3DInception"]
+ detail_header = ["Model", "VideoID", "L1", "SSIM", "LPIPS", "PSNR", "FID"]
+
+
+ summary_table = tabulate(model_summary_all, headers=summary_header, tablefmt="grid")
+ detail_table = tabulate(clip_detail_all, headers=detail_header, tablefmt="grid")
+
+
+ (base_dir / "model_summary.txt").write_text(summary_table)
+ (base_dir / "clip_details.txt").write_text(detail_table)
+
+ print("\n===== 模型总体指标 =====")
+ print(summary_table)
+ print("\n===== 每视频详细指标 =====")
+ print(detail_table)
+ print(f"\n[DONE] 已保存到: {base_dir}/model_summary.txt 和 clip_details.txt")
+
+if __name__ == "__main__":
+ main()
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/ClipScore.py b/One-to-All-Animation/benchmark/DisCo/tool/ClipScore.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cf7d7803b547ad3f9876ed05c8b39e7cb711d6a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/ClipScore.py
@@ -0,0 +1,95 @@
+import sys
+import os
+sys.path.append(os.path.dirname(__file__) + os.sep + '../')
+import clip
+from config import *
+
+
+class CLIPSimilarity(nn.Module):
+ def __init__(self, model_filename):
+ super(CLIPSimilarity, self).__init__()
+ self.model_filename = model_filename
+ self.model, self.p = clip.load(model_filename, device='cpu')
+ self.model = self.model.eval()
+
+ def forward(self, text, image, batch_size=None):
+ '''
+ text: [X]
+ for example, ['str_1', 'str_2', ..., 'str_X']
+ image: [Y, c, w, h]
+
+ return: [X, Y]
+ '''
+ device = image.device
+ img_input = F.interpolate(image, size=224)
+ image_mean = torch.tensor([0.48145466, 0.4578275, 0.40821073]).to(device)
+ image_std = torch.tensor([0.26862954, 0.26130258, 0.27577711]).to(device)
+ img_input = (img_input.clamp(min=-1.0, max=1.0) + 1.0) / 2.0
+ img_input -= image_mean[:, None, None]
+ img_input /= image_std[:, None, None]
+ text_input = clip.tokenize(text, truncate=True).to(device)
+ with torch.no_grad():
+ text_features = self.model.encode_text(text_input).float()
+ image_features = self.model.encode_image(img_input).float()
+
+ image_features /= image_features.norm(dim=-1, keepdim=True)
+ text_features /= text_features.norm(dim=-1, keepdim=True)
+
+ logit_scale = 1.0 # Default value is models.logit_scale.exp()
+ if batch_size:
+ text_features = rearrange(text_features, '(b x) d -> b x d', b=batch_size)
+ image_features = rearrange(image_features, '(b y) d -> b d y', b=batch_size)
+ else:
+ image_features = image_features.t()
+ logits_per_text = logit_scale * torch.matmul(text_features, image_features)
+ similarity = logits_per_text
+ return similarity
+
+
+class BaseDataset(Dataset):
+ def __init__(self, img_list, txt_list):
+
+ self.img_list = img_list
+ self.txt_list = txt_list
+
+ assert len(img_list) == len(txt_list), 'len_img must equal len_txt!'
+
+ self.transform = transforms.Compose([
+ transforms.Resize((224, 224)),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
+ ])
+
+ def __len__(self):
+ return len(self.img_list)
+
+ def __getitem__(self, i):
+ img_path = self.img_list[i]
+ caption = self.txt_list[i]
+ img = Image.open(img_path).convert('RGB')
+ image = self.transform(img)
+
+ sample = {"label_imgs": image, 'input_text': caption}
+ return sample
+
+
+def compute_clip_score(model_pth, img_list, txt_list, batch_size=32, cuda_device=0):
+
+ device = torch.device(f'cuda:{cuda_device}')
+ model = CLIPSimilarity(model_pth).to(device)
+
+ data = BaseDataset(img_list, txt_list)
+ loader = DataLoader(data, batch_size=batch_size, shuffle=False, num_workers=32)
+
+ clip_sim_total = 0
+ num = 0
+ for sample in tqdm(loader):
+ imgs = sample['label_imgs'].to(device)
+ caps = sample['input_text']
+
+ clip_sim = model(caps, imgs, batch_size=len(caps))
+
+ clip_sim_total += clip_sim.mean().item()
+ num += 1
+
+ return clip_sim_total/num
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/__init__.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/downloads_helper.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/downloads_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..443c2f9c4ebbeb5bead5b1f4481e58798332d2f0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/downloads_helper.py
@@ -0,0 +1,67 @@
+import os
+import urllib.request
+import requests
+import shutil
+
+
+inception_url = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metrics/inception-2015-12-05.pt"
+
+
+"""
+Download the pretrined inception weights if it does not exists
+ARGS:
+ fpath - output folder path
+"""
+def check_download_inception(fpath="./"):
+ inception_path = os.path.join(fpath, "inception-2015-12-05.pt")
+ if not os.path.exists(inception_path):
+ # download the file
+ with urllib.request.urlopen(inception_url) as response, open(inception_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+ return inception_path
+
+
+"""
+Download any url if it does not exist
+ARGS:
+ local_folder - output folder path
+ url - the weburl to download
+"""
+def check_download_url(local_folder, url):
+ name = os.path.basename(url)
+ local_path = os.path.join(local_folder, name)
+ if not os.path.exists(local_path):
+ os.makedirs(local_folder, exist_ok=True)
+ print(f"downloading statistics to {local_path}")
+ with urllib.request.urlopen(url) as response, open(local_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+ return local_path
+
+
+"""
+Download a file from google drive
+ARGS:
+ file_id - id of the google drive file
+ out_path - output folder path
+"""
+def download_google_drive(file_id, out_path):
+ def get_confirm_token(response):
+ for key, value in response.cookies.items():
+ if key.startswith('download_warning'):
+ return value
+ return None
+
+ URL = "https://drive.google.com/uc?export=download"
+ session = requests.Session()
+ response = session.get(URL, params={'id': file_id}, stream=True)
+ token = get_confirm_token(response)
+
+ if token:
+ params = {'id': file_id, 'confirm': token}
+ response = session.get(URL, params=params, stream=True)
+
+ CHUNK_SIZE = 32768
+ with open(out_path, "wb") as f:
+ for chunk in response.iter_content(CHUNK_SIZE):
+ if chunk:
+ f.write(chunk)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/features.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/features.py
new file mode 100644
index 0000000000000000000000000000000000000000..74ce4ddb76b316db7f482aa05a3b0d9a82b546f0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/features.py
@@ -0,0 +1,69 @@
+"""
+helpers for extracting features from image
+"""
+import os
+import platform
+import numpy as np
+import torch
+import tool.cleanfid
+from tool.cleanfid.downloads_helper import check_download_url
+from tool.cleanfid.inception_pytorch import InceptionV3
+from tool.cleanfid.inception_torchscript import InceptionV3W
+
+
+"""
+returns a functions that takes an image in range [0,255]
+and outputs a feature embedding vector
+"""
+def feature_extractor(name="torchscript_inception", device=torch.device("cuda"), resize_inside=False):
+ if name == "torchscript_inception":
+ path = "./" if platform.system() == "Windows" else "/tmp"
+ model = InceptionV3W(path, download=True, resize_inside=resize_inside).to(device)
+ model.eval()
+ def model_fn(x): return model(x)
+ elif name == "pytorch_inception":
+ model = InceptionV3(output_blocks=[3], resize_input=False).to(device)
+ model.eval()
+ def model_fn(x): return model(x/255)[0].squeeze(-1).squeeze(-1)
+ else:
+ raise ValueError(f"{name} feature extractor not implemented")
+ return model_fn
+
+
+"""
+Build a feature extractor for each of the modes
+"""
+def build_feature_extractor(mode, device=torch.device("cuda")):
+ if mode == "legacy_pytorch":
+ feat_model = feature_extractor(name="pytorch_inception", resize_inside=False, device=device)
+ elif mode == "legacy_tensorflow":
+ feat_model = feature_extractor(name="torchscript_inception", resize_inside=True, device=device)
+ elif mode == "clean":
+ feat_model = feature_extractor(name="torchscript_inception", resize_inside=False, device=device)
+ return feat_model
+
+
+"""
+Load precomputed reference statistics for commonly used datasets
+"""
+def get_reference_statistics(name, res, mode="clean", seed=0, split="test", metric="FID"):
+ base_url = "https://www.cs.cmu.edu/~clean-fid/stats/"
+ if split == "custom":
+ res = "na"
+ if metric == "FID":
+ rel_path = (f"{name}_{mode}_{split}_{res}.npz").lower()
+ url = f"{base_url}/{rel_path}"
+ mod_path = os.path.dirname(cleanfid.__file__)
+ stats_folder = os.path.join(mod_path, "stats")
+ fpath = check_download_url(local_folder=stats_folder, url=url)
+ stats = np.load(fpath)
+ mu, sigma = stats["mu"], stats["sigma"]
+ return mu, sigma
+ elif metric == "KID":
+ rel_path = (f"{name}_{mode}_{split}_{res}_kid.npz").lower()
+ url = f"{base_url}/{rel_path}"
+ mod_path = os.path.dirname(cleanfid.__file__)
+ stats_folder = os.path.join(mod_path, "stats")
+ fpath = check_download_url(local_folder=stats_folder, url=url)
+ stats = np.load(fpath)
+ return stats["feats"]
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/fid.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/fid.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6a816ecfe9d8f510b820f5a07987133de168c7e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/fid.py
@@ -0,0 +1,458 @@
+import os
+import random
+from tqdm import tqdm
+from glob import glob
+import torch
+import numpy as np
+from scipy import linalg
+import zipfile
+import tool.cleanfid
+from tool.cleanfid.utils import *
+from tool.cleanfid.features import build_feature_extractor, get_reference_statistics
+from tool.cleanfid.resize import *
+
+
+"""
+Numpy implementation of the Frechet Distance.
+The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
+and X_2 ~ N(mu_2, C_2) is
+ d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
+Stable version by Danica J. Sutherland.
+Params:
+ mu1 : Numpy array containing the activations of a layer of the
+ inception net (like returned by the function 'get_predictions')
+ for generated samples.
+ mu2 : The sample mean over activations, precalculated on an
+ representative data set.
+ sigma1: The covariance matrix over activations for generated samples.
+ sigma2: The covariance matrix over activations, precalculated on an
+ representative data set.
+"""
+def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
+ mu1 = np.atleast_1d(mu1)
+ mu2 = np.atleast_1d(mu2)
+ sigma1 = np.atleast_2d(sigma1)
+ sigma2 = np.atleast_2d(sigma2)
+
+ assert mu1.shape == mu2.shape, \
+ 'Training and test mean vectors have different lengths'
+ assert sigma1.shape == sigma2.shape, \
+ 'Training and test covariances have different dimensions'
+
+ diff = mu1 - mu2
+
+ # Product might be almost singular
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
+ if not np.isfinite(covmean).all():
+ msg = ('fid calculation produces singular product; '
+ 'adding %s to diagonal of cov estimates') % eps
+ print(msg)
+ offset = np.eye(sigma1.shape[0]) * eps
+ covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
+
+ # Numerical error might give slight imaginary component
+ if np.iscomplexobj(covmean):
+ if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
+ m = np.max(np.abs(covmean.imag))
+ raise ValueError('Imaginary component {}'.format(m))
+ covmean = covmean.real
+
+ tr_covmean = np.trace(covmean)
+
+ return (diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean)
+
+
+"""
+Compute the KID score given the sets of features
+"""
+def kernel_distance(feats1, feats2, num_subsets=100, max_subset_size=1000):
+ n = feats1.shape[1]
+ m = min(min(feats1.shape[0], feats2.shape[0]), max_subset_size)
+ t = 0
+ for _subset_idx in range(num_subsets):
+ x = feats2[np.random.choice(feats2.shape[0], m, replace=False)]
+ y = feats1[np.random.choice(feats1.shape[0], m, replace=False)]
+ a = (x @ x.T / n + 1) ** 3 + (y @ y.T / n + 1) ** 3
+ b = (x @ y.T / n + 1) ** 3
+ t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m
+ kid = t / num_subsets / m
+ return float(kid)
+
+
+"""
+Compute the inception features for a batch of images
+"""
+def get_batch_features(batch, model, device):
+ with torch.no_grad():
+ feat = model(batch.to(device))
+ return feat.detach().cpu().numpy()
+
+
+"""
+Compute the inception features for a list of files
+"""
+def get_files_features(l_files, model=None, num_workers=12,
+ batch_size=128, device=torch.device("cuda"),
+ mode="clean", custom_fn_resize=None,
+ description="", verbose=True,
+ custom_image_tranform=None):
+ # define the models if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+
+ # wrap the images in a dataloader for parallelizing the resize operation
+ dataset = ResizeDataset(l_files, mode=mode)
+ if custom_image_tranform is not None:
+ dataset.custom_image_tranform=custom_image_tranform
+ if custom_fn_resize is not None:
+ dataset.fn_resize = custom_fn_resize
+
+ dataloader = torch.utils.data.DataLoader(dataset,
+ batch_size=batch_size, shuffle=False,
+ drop_last=False, num_workers=num_workers)
+
+ # collect all inception features
+ l_feats = []
+ if verbose:
+ pbar = tqdm(dataloader, desc=description)
+ else:
+ pbar = dataloader
+
+ for batch in pbar:
+ l_feats.append(get_batch_features(batch, model, device))
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+"""
+Compute the inception features for a folder of image files
+"""
+def get_folder_features(fdir, model=None, num_workers=12, num=None,
+ shuffle=False, seed=0, batch_size=128, device=torch.device("cuda"),
+ mode="clean", custom_fn_resize=None, description="", verbose=True,
+ custom_image_tranform=None):
+ # get all relevant files in the dataset
+ if ".zip" in fdir:
+ files = list(set(zipfile.ZipFile(fdir).namelist()))
+ # remove the non-image files inside the zip
+ files = [x for x in files if os.path.splitext(x)[1].lower()[1:] in EXTENSIONS]
+ if '.json' in fdir:
+ pass
+ else:
+ files = sorted([file for ext in EXTENSIONS
+ for file in glob(os.path.join(fdir, f"**/*.{ext}"), recursive=True)])
+ # filter
+
+
+ if verbose:
+ print(f"Found {len(files)} images in the folder {fdir}")
+ # use a subset number of files if needed
+ if num is not None:
+ if shuffle:
+ random.seed(seed)
+ random.shuffle(files)
+ files = files[:num]
+ np_feats = get_files_features(files, model, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ custom_fn_resize=custom_fn_resize,
+ custom_image_tranform=custom_image_tranform,
+ description=description, verbose=verbose)
+ return np_feats
+
+
+"""
+Compute the FID score given the inception features stack
+"""
+def fid_from_feats(feats1, feats2):
+ mu1, sig1 = np.mean(feats1, axis=0), np.cov(feats1, rowvar=False)
+ mu2, sig2 = np.mean(feats2, axis=0), np.cov(feats2, rowvar=False)
+ return frechet_distance(mu1, sig1, mu2, sig2)
+
+
+"""
+Computes the FID score for a folder of images for a specific dataset
+and a specific resolution
+"""
+def fid_folder(fdir, dataset_name, dataset_res, dataset_split,
+ model=None, mode="clean", num_workers=12,
+ batch_size=128, device=torch.device("cuda"), verbose=True):
+ # define the models if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split)
+ fbname = os.path.basename(fdir)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir, model, num_workers=num_workers,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"FID {fbname} : ", verbose=verbose)
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+
+"""
+Compute the FID stats from a generator models
+"""
+def get_model_features(G, model, mode="clean", z_dim=512,
+ num_gen=50_000, batch_size=128,
+ device=torch.device("cuda"), desc="FID models: ", verbose=True, return_z=False):
+ fn_resize = build_resizer(mode)
+ # Generate test features
+ num_iters = int(np.ceil(num_gen / batch_size))
+ l_feats = []
+ latents = []
+ if verbose:
+ pbar = tqdm(range(num_iters), desc=desc)
+ else:
+ pbar = range(num_iters)
+ for idx in pbar:
+ with torch.no_grad():
+ z_batch = torch.randn((batch_size, z_dim)).to(device)
+ if return_z:
+ latents.append(z_batch)
+ # generated image is in range [0,255]
+ img_batch = G(z_batch)
+ # split into individual batches for resizing if needed
+ if mode != "legacy_tensorflow":
+ resized_batch = torch.zeros(batch_size, 3, 299, 299)
+ for idx in range(batch_size):
+ curr_img = img_batch[idx]
+ img_np = curr_img.cpu().numpy().transpose((1, 2, 0))
+ img_resize = fn_resize(img_np)
+ resized_batch[idx] = torch.tensor(img_resize.transpose((2, 0, 1)))
+ else:
+ resized_batch = img_batch
+ feat = get_batch_features(resized_batch, model, device)
+ l_feats.append(feat)
+ np_feats = np.concatenate(l_feats)
+ if return_z:
+ latents = torch.cat(latents, 0)
+ return np_feats, latents
+ return np_feats
+
+
+"""
+Computes the FID score for a generator models for a specific dataset
+and a specific resolution
+"""
+def fid_model(G, dataset_name, dataset_res, dataset_split,
+ model=None, z_dim=512, num_gen=50_000,
+ mode="clean", num_workers=0, batch_size=128,
+ device=torch.device("cuda"), verbose=True):
+ # define the models if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split,)
+
+ # Generate test features
+ np_feats = get_model_features(G, model, mode=mode,
+ z_dim=z_dim, num_gen=num_gen,
+ batch_size=batch_size, device=device, verbose=verbose)
+
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+
+"""
+Computes the FID score between the two given folders
+"""
+def compare_folders(fdir1, fdir2, feat_model, mode, num_workers=0,
+ batch_size=8, device=torch.device("cuda"), verbose=True,
+ custom_image_tranform=None):
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, feat_model, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"FID {fbname1} : ", verbose=verbose,
+ custom_image_tranform=custom_image_tranform)
+ mu1 = np.mean(np_feats1, axis=0)
+ sigma1 = np.cov(np_feats1, rowvar=False)
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, feat_model, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"FID {fbname2} : ", verbose=verbose,
+ custom_image_tranform=custom_image_tranform)
+ mu2 = np.mean(np_feats2, axis=0)
+ sigma2 = np.cov(np_feats2, rowvar=False)
+ fid = frechet_distance(mu1, sigma1, mu2, sigma2)
+ return fid
+
+
+"""
+Test if a custom statistic exists
+"""
+def test_stats_exists(name, mode, metric="FID"):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ split, res = "custom", "na"
+ if metric == "FID":
+ fname = f"{name}_{mode}_{split}_{res}.npz"
+ elif metric == "KID":
+ fname = f"{name}_{mode}_{split}_{res}_kid.npz"
+ fpath = os.path.join(stats_folder, fname)
+ return os.path.exists(fpath)
+
+
+"""
+Remove the custom FID features from the stats folder
+"""
+def remove_custom_stats(name, mode="clean"):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ # remove the FID stats
+ split, res = "custom", "na"
+ outname = f"{name}_{mode}_{split}_{res}.npz"
+ outf = os.path.join(stats_folder, outname)
+ if not os.path.exists(outf):
+ msg = f"The stats file {name} does not exist."
+ raise Exception(msg)
+ os.remove(outf)
+ # remove the KID stats
+ outf = os.path.join(stats_folder, f"{name}_{mode}_{split}_{res}_kid.npz")
+ if not os.path.exists(outf):
+ msg = f"The stats file {name} does not exist."
+ raise Exception(msg)
+ os.remove(outf)
+
+
+"""
+Cache a custom dataset statistics file
+"""
+def make_custom_stats(name, fdir, num=None, mode="clean",
+ num_workers=0, batch_size=64, device=torch.device("cuda")):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ os.makedirs(stats_folder, exist_ok=True)
+ split, res = "custom", "na"
+ outname = f"{name}_{mode}_{split}_{res}.npz"
+ outf = os.path.join(stats_folder, outname)
+ # if the custom stat file already exists
+ if os.path.exists(outf):
+ msg = f"The statistics file {name} already exists. "
+ msg += "Use remove_custom_stats function to delete it first."
+ raise Exception(msg)
+
+ feat_model = build_feature_extractor(mode, device)
+ fbname = os.path.basename(fdir)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir, feat_model, num_workers=num_workers, num=num,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"custom stats: {fbname} : ")
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ print(f"saving custom FID stats to {outf}")
+ np.savez_compressed(outf, mu=mu, sigma=sigma)
+ # KID stats
+ outf = os.path.join(stats_folder, f"{name}_{mode}_{split}_{res}_kid.npz")
+ print(f"saving custom KID stats to {outf}")
+ np.savez_compressed(outf, feats=np_feats)
+
+
+def compute_kid(fdir1=None, fdir2=None, gen=None,
+ mode="clean", num_workers=12, batch_size=32,
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512):
+ # build the feature extractor based on the mode
+ feat_model = build_feature_extractor(mode, device)
+
+ # if both dirs are specified, compute KID between folders
+ if fdir1 is not None and fdir2 is not None:
+ print("compute KID between two folders")
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, None, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"KID {fbname1} : ")
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, None, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"KID {fbname2} : ")
+ score = kernel_distance(np_feats1, np_feats2)
+ return score
+
+ # compute kid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ print(f"compute KID of a folder with {dataset_name} statistics")
+ # define the models if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ fbname = os.path.basename(fdir1)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir1, model, num_workers=num_workers,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"KID {fbname} : ")
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ print(f"compute KID of a models with {dataset_name}-{dataset_res} statistics")
+ # define the models if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ # Generate test features
+ np_feats = get_model_features(gen, model, mode=mode,
+ z_dim=z_dim, num_gen=num_gen, desc="KID models: ",
+ batch_size=batch_size, device=device)
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ else:
+ raise ValueError("invalid combination of directories and models entered")
+
+"""
+custom_image_tranform:
+ function that takes an np_array image as input [0,255] and
+ applies a custom transform such as cropping
+"""
+def compute_fid(fdir1=None, fdir2=None, gen=None,
+ mode="clean", num_workers=12, batch_size=32,
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512,
+ custom_feat_mode=None, verbose=True, custom_image_tranform=None):
+ # build the feature extractor based on the mode
+ if custom_feat_mode is None:
+ feat_model = build_feature_extractor(mode, device)
+ else:
+ feat_model = custom_feat_mode
+
+ # if both dirs are specified, compute FID between folders
+ if fdir1 is not None and fdir2 is not None:
+ if not verbose:
+ print("compute FID between two folders")
+ score = compare_folders(fdir1, fdir2, feat_model,
+ mode=mode, batch_size=batch_size,
+ num_workers=num_workers, device=device,
+ custom_image_tranform=custom_image_tranform,
+ verbose=verbose)
+ return score
+
+ # compute fid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ if not verbose:
+ print(f"compute FID of a folder with {dataset_name} statistics")
+ score = fid_folder(fdir1, dataset_name, dataset_res, dataset_split,
+ model=feat_model, mode=mode, num_workers=num_workers,
+ batch_size=batch_size, device=device, verbose=verbose)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ if not verbose:
+ print(f"compute FID of a models with {dataset_name}-{dataset_res} statistics")
+ score = fid_model(gen, dataset_name, dataset_res, dataset_split,
+ model=feat_model, z_dim=z_dim, num_gen=num_gen,
+ mode=mode, num_workers=num_workers, batch_size=batch_size,
+ device=device, verbose=verbose)
+ return score
+
+ else:
+ raise ValueError("invalid combination of directories and models entered")
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_pytorch.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..a10124c6d06980a280c9d749d803cb8264d68057
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_pytorch.py
@@ -0,0 +1,328 @@
+"""
+File from: https://github.com/mseitzer/pytorch-fid
+"""
+
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torchvision
+
+try:
+ from torchvision.models.utils import load_state_dict_from_url
+except ImportError:
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
+
+# Inception weights ported to Pytorch from
+# http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
+FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' # noqa: E501
+
+
+class InceptionV3(nn.Module):
+ """Pretrained InceptionV3 network returning feature maps"""
+
+ # Index of default block of inception to return,
+ # corresponds to output of final average pooling
+ DEFAULT_BLOCK_INDEX = 3
+
+ # Maps feature dimensionality to their output blocks indices
+ BLOCK_INDEX_BY_DIM = {
+ 64: 0, # First max pooling features
+ 192: 1, # Second max pooling featurs
+ 768: 2, # Pre-aux classifier features
+ 2048: 3 # Final average pooling features
+ }
+
+ def __init__(self,
+ output_blocks=(DEFAULT_BLOCK_INDEX,),
+ resize_input=True,
+ normalize_input=True,
+ requires_grad=False,
+ use_fid_inception=True):
+ """Build pretrained InceptionV3
+ Parameters
+ ----------
+ output_blocks : list of int
+ Indices of blocks to return features of. Possible values are:
+ - 0: corresponds to output of first max pooling
+ - 1: corresponds to output of second max pooling
+ - 2: corresponds to output which is fed to aux classifier
+ - 3: corresponds to output of final average pooling
+ resize_input : bool
+ If true, bilinearly resizes input to width and height 299 before
+ feeding input to models. As the network without fully connected
+ layers is fully convolutional, it should be able to handle inputs
+ of arbitrary size, so resizing might not be strictly needed
+ normalize_input : bool
+ If true, scales the input from range (0, 1) to the range the
+ pretrained Inception network expects, namely (-1, 1)
+ requires_grad : bool
+ If true, parameters of the models require gradients. Possibly useful
+ for finetuning the network
+ use_fid_inception : bool
+ If true, uses the pretrained Inception models used in Tensorflow's
+ FID implementation. If false, uses the pretrained Inception models
+ available in torchvision. The FID Inception models has different
+ weights and a slightly different structure from torchvision's
+ Inception models. If you want to compute FID scores, you are
+ strongly advised to set this parameter to true to get comparable
+ results.
+ """
+ super(InceptionV3, self).__init__()
+
+ self.resize_input = resize_input
+ self.normalize_input = normalize_input
+ self.output_blocks = sorted(output_blocks)
+ self.last_needed_block = max(output_blocks)
+
+ assert self.last_needed_block <= 3, \
+ 'Last possible output block index is 3'
+
+ self.blocks = nn.ModuleList()
+
+ if use_fid_inception:
+ inception = fid_inception_v3()
+ else:
+ inception = _inception_v3(pretrained=True)
+
+ # Block 0: input to maxpool1
+ block0 = [
+ inception.Conv2d_1a_3x3,
+ inception.Conv2d_2a_3x3,
+ inception.Conv2d_2b_3x3,
+ nn.MaxPool2d(kernel_size=3, stride=2)
+ ]
+ self.blocks.append(nn.Sequential(*block0))
+
+ # Block 1: maxpool1 to maxpool2
+ if self.last_needed_block >= 1:
+ block1 = [
+ inception.Conv2d_3b_1x1,
+ inception.Conv2d_4a_3x3,
+ nn.MaxPool2d(kernel_size=3, stride=2)
+ ]
+ self.blocks.append(nn.Sequential(*block1))
+
+ # Block 2: maxpool2 to aux classifier
+ if self.last_needed_block >= 2:
+ block2 = [
+ inception.Mixed_5b,
+ inception.Mixed_5c,
+ inception.Mixed_5d,
+ inception.Mixed_6a,
+ inception.Mixed_6b,
+ inception.Mixed_6c,
+ inception.Mixed_6d,
+ inception.Mixed_6e,
+ ]
+ self.blocks.append(nn.Sequential(*block2))
+
+ # Block 3: aux classifier to final avgpool
+ if self.last_needed_block >= 3:
+ block3 = [
+ inception.Mixed_7a,
+ inception.Mixed_7b,
+ inception.Mixed_7c,
+ nn.AdaptiveAvgPool2d(output_size=(1, 1))
+ ]
+ self.blocks.append(nn.Sequential(*block3))
+
+ for param in self.parameters():
+ param.requires_grad = requires_grad
+
+ def forward(self, inp):
+ """Get Inception feature maps
+ Parameters
+ ----------
+ inp : torch.autograd.Variable
+ Input tensor of shape Bx3xHxW. Values are expected to be in
+ range (0, 1)
+ Returns
+ -------
+ List of torch.autograd.Variable, corresponding to the selected output
+ block, sorted ascending by index
+ """
+ outp = []
+ x = inp
+
+ if self.resize_input:
+ raise ValueError("should not resize here")
+ x = F.interpolate(x,
+ size=(299, 299),
+ mode='bilinear',
+ align_corners=False)
+
+ if self.normalize_input:
+ x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)
+
+ for idx, block in enumerate(self.blocks):
+ x = block(x)
+ if idx in self.output_blocks:
+ outp.append(x)
+
+ if idx == self.last_needed_block:
+ break
+
+ return outp
+
+
+def _inception_v3(*args, **kwargs):
+ """Wraps `torchvision.models.inception_v3`
+ Skips default weight inititialization if supported by torchvision version.
+ See https://github.com/mseitzer/pytorch-fid/issues/28.
+ """
+ try:
+ version = tuple(map(int, torchvision.__version__.split('.')[:2]))
+ except ValueError:
+ # Just a caution against weird version strings
+ version = (0,)
+
+ if version >= (0, 6):
+ kwargs['init_weights'] = False
+
+ return torchvision.models.inception_v3(*args, **kwargs)
+
+
+def fid_inception_v3():
+ """Build pretrained Inception models for FID computation
+ The Inception models for FID computation uses a different set of weights
+ and has a slightly different structure than torchvision's Inception.
+ This method first constructs torchvision's Inception and then patches the
+ necessary parts that are different in the FID Inception models.
+ """
+ inception = _inception_v3(num_classes=1008,
+ aux_logits=False,
+ pretrained=False)
+ inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
+ inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
+ inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
+ inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128)
+ inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160)
+ inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160)
+ inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192)
+ inception.Mixed_7b = FIDInceptionE_1(1280)
+ inception.Mixed_7c = FIDInceptionE_2(2048)
+
+ state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=False)
+ inception.load_state_dict(state_dict)
+ return inception
+
+
+class FIDInceptionA(torchvision.models.inception.InceptionA):
+ """InceptionA block patched for FID computation"""
+ def __init__(self, in_channels, pool_features):
+ super(FIDInceptionA, self).__init__(in_channels, pool_features)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch5x5 = self.branch5x5_1(x)
+ branch5x5 = self.branch5x5_2(branch5x5)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionC(torchvision.models.inception.InceptionC):
+ """InceptionC block patched for FID computation"""
+ def __init__(self, in_channels, channels_7x7):
+ super(FIDInceptionC, self).__init__(in_channels, channels_7x7)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch7x7 = self.branch7x7_1(x)
+ branch7x7 = self.branch7x7_2(branch7x7)
+ branch7x7 = self.branch7x7_3(branch7x7)
+
+ branch7x7dbl = self.branch7x7dbl_1(x)
+ branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionE_1(torchvision.models.inception.InceptionE):
+ """First InceptionE block patched for FID computation"""
+ def __init__(self, in_channels):
+ super(FIDInceptionE_1, self).__init__(in_channels)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch3x3 = self.branch3x3_1(x)
+ branch3x3 = [
+ self.branch3x3_2a(branch3x3),
+ self.branch3x3_2b(branch3x3),
+ ]
+ branch3x3 = torch.cat(branch3x3, 1)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = [
+ self.branch3x3dbl_3a(branch3x3dbl),
+ self.branch3x3dbl_3b(branch3x3dbl),
+ ]
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionE_2(torchvision.models.inception.InceptionE):
+ """Second InceptionE block patched for FID computation"""
+ def __init__(self, in_channels):
+ super(FIDInceptionE_2, self).__init__(in_channels)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch3x3 = self.branch3x3_1(x)
+ branch3x3 = [
+ self.branch3x3_2a(branch3x3),
+ self.branch3x3_2b(branch3x3),
+ ]
+ branch3x3 = torch.cat(branch3x3, 1)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = [
+ self.branch3x3dbl_3a(branch3x3dbl),
+ self.branch3x3dbl_3b(branch3x3dbl),
+ ]
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
+
+ # Patch: The FID Inception models uses max pooling instead of average
+ # pooling. This is likely an error in this specific Inception
+ # implementation, as other Inception models use average pooling here
+ # (which matches the description in the paper).
+ branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_torchscript.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_torchscript.py
new file mode 100644
index 0000000000000000000000000000000000000000..b371778a281389acd2b66e9107698a0dfe134b65
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/inception_torchscript.py
@@ -0,0 +1,55 @@
+import os
+import torch
+import torch.nn as nn
+from tool.cleanfid.downloads_helper import *
+import contextlib
+
+
+@contextlib.contextmanager
+def disable_gpu_fuser_on_pt19():
+ # On PyTorch 1.9 a CUDA fuser bug prevents the Inception JIT models to run. See
+ # https://github.com/GaParmar/clean-fid/issues/5
+ # https://github.com/pytorch/pytorch/issues/64062
+ if torch.__version__.startswith('1.9.'):
+ old_val = torch._C._jit_can_fuse_on_gpu()
+ torch._C._jit_override_can_fuse_on_gpu(False)
+ yield
+ if torch.__version__.startswith('1.9.'):
+ torch._C._jit_override_can_fuse_on_gpu(old_val)
+
+
+class InceptionV3W(nn.Module):
+ """
+ Wrapper around Inception V3 torchscript models provided here
+ https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metrics/inception-2015-12-05.pt
+
+ path: locally saved inception weights
+ """
+ def __init__(self, path, download=True, resize_inside=False):
+ super(InceptionV3W, self).__init__()
+ # download the network if it is not present at the given directory
+ # use the current directory by default
+ if download:
+ check_download_inception(fpath=path)
+ path = os.path.join(path, "inception-2015-12-05.pt")
+ self.base = torch.jit.load(path).eval()
+ self.layers = self.base.layers
+ self.resize_inside = resize_inside
+
+ """
+ Get the inception features without resizing
+ x: Image with values in range [0,255]
+ """
+ def forward(self, x):
+ with disable_gpu_fuser_on_pt19():
+ bs = x.shape[0]
+ if self.resize_inside:
+ features = self.base(x, return_features=True).view((bs, 2048))
+ else:
+ # make sure it is resized already
+ assert (x.shape[2] == 299) and (x.shape[3] == 299)
+ # apply normalization
+ x1 = x - 128
+ x2 = x1 / 128
+ features = self.layers.forward(x2, ).view((bs, 2048))
+ return features
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/leaderboard.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/leaderboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..165b529ce24018fdba3122652990bb6601dea862
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/leaderboard.py
@@ -0,0 +1,43 @@
+import os
+import csv
+import shutil
+import urllib.request
+
+
+def get_score(model_name=None, dataset_name=None,
+ dataset_res=None, dataset_split=None, task_name=None):
+ # download the csv file from server
+ url = "https://www.cs.cmu.edu/~clean-fid/files/leaderboard.csv"
+ local_path = "/tmp/leaderboard.csv"
+ with urllib.request.urlopen(url) as response, open(local_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+
+ d_field2idx = {}
+ l_matches = []
+ with open(local_path, 'r') as f:
+ csvreader = csv.reader(f)
+ l_fields = next(csvreader)
+ for idx, val in enumerate(l_fields):
+ d_field2idx[val.strip()] = idx
+ # iterate through all rows
+ for row in csvreader:
+ # skip empty rows
+ if len(row) == 0:
+ continue
+ # skip if the filter doesn't match
+ if model_name is not None and (row[d_field2idx["model_name"]].strip() != model_name):
+ continue
+ if dataset_name is not None and (row[d_field2idx["dataset_name"]].strip() != dataset_name):
+ continue
+ if dataset_res is not None and (row[d_field2idx["dataset_res"]].strip() != dataset_res):
+ continue
+ if dataset_split is not None and (row[d_field2idx["dataset_split"]].strip() != dataset_split):
+ continue
+ if task_name is not None and (row[d_field2idx["task_name"]].strip() != task_name):
+ continue
+ curr = {}
+ for f in l_fields:
+ curr[f.strip()] = row[d_field2idx[f.strip()]].strip()
+ l_matches.append(curr)
+ os.remove(local_path)
+ return l_matches
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/resize.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/resize.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4fbebe96455ca5011d209589bffdd0472a13b6d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/resize.py
@@ -0,0 +1,125 @@
+"""
+Helpers for resizing with multiple CPU cores
+"""
+import os
+import numpy as np
+import torch
+from PIL import Image
+import torch.nn.functional as F
+
+
+def build_resizer(mode):
+ if mode == "clean":
+ return make_resizer("PIL", False, "bicubic", (299,299))
+ # if using legacy tensorflow, do not manually resize outside the network
+ elif mode == "legacy_tensorflow":
+ return lambda x: x
+ elif mode == "legacy_pytorch":
+ return make_resizer("PyTorch", False, "bilinear", (299, 299))
+ else:
+ raise ValueError(f"Invalid mode {mode} specified")
+
+
+"""
+Construct a function that resizes a numpy image based on the
+flags passed in.
+"""
+def make_resizer(library, quantize_after, filter, output_size):
+ if library == "PIL" and quantize_after:
+ name_to_filter = {
+ "bicubic": Image.BICUBIC,
+ "bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "lanczos": Image.LANCZOS,
+ "box": Image.BOX
+ }
+ def func(x):
+ x = Image.fromarray(x)
+ x = x.resize(output_size, resample=name_to_filter[filter])
+ x = np.asarray(x).clip(0, 255).astype(np.uint8)
+ return x
+ elif library == "PIL" and not quantize_after:
+ name_to_filter = {
+ "bicubic": Image.BICUBIC,
+ "bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "lanczos": Image.LANCZOS,
+ "box": Image.BOX
+ }
+ s1, s2 = output_size
+ def resize_single_channel(x_np):
+ img = Image.fromarray(x_np.astype(np.float32), mode='F')
+ img = img.resize(output_size, resample=name_to_filter[filter])
+ return np.asarray(img).clip(0, 255).reshape(s1, s2, 1)
+ def func(x):
+ x = [resize_single_channel(x[:, :, idx]) for idx in range(3)]
+ x = np.concatenate(x, axis=2).astype(np.float32)
+ return x
+ elif library == "PyTorch":
+ import warnings
+ # ignore the numpy warnings
+ warnings.filterwarnings("ignore")
+ def func(x):
+ x = torch.Tensor(x.transpose((2, 0, 1)))[None, ...]
+ x = F.interpolate(x, size=output_size, mode=filter, align_corners=False)
+ x = x[0, ...].cpu().data.numpy().transpose((1, 2, 0)).clip(0, 255)
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+ elif library == "TensorFlow":
+ import warnings
+ # ignore the numpy warnings
+ warnings.filterwarnings("ignore")
+ import tensorflow as tf
+ def func(x):
+ x = tf.constant(x)[tf.newaxis, ...]
+ x = tf.image.resize(x, output_size, method=filter)
+ x = x[0, ...].numpy().clip(0, 255)
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+ elif library == "OpenCV":
+ import cv2
+ name_to_filter = {
+ "bilinear": cv2.INTER_LINEAR,
+ "bicubic": cv2.INTER_CUBIC,
+ "lanczos": cv2.INTER_LANCZOS4,
+ "nearest": cv2.INTER_NEAREST,
+ "area": cv2.INTER_AREA
+ }
+ def func(x):
+ x = cv2.resize(x, output_size, interpolation=name_to_filter[filter])
+ x = x.clip(0, 255)
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+ else:
+ raise NotImplementedError('library [%s] is not include' % library)
+ return func
+
+
+class FolderResizer(torch.utils.data.Dataset):
+ def __init__(self, files, outpath, fn_resize, output_ext=".png"):
+ self.files = files
+ self.outpath = outpath
+ self.output_ext = output_ext
+ self.fn_resize = fn_resize
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ path = str(self.files[i])
+ img_np = np.asarray(Image.open(path))
+ img_resize_np = self.fn_resize(img_np)
+ # swap the output extension
+ basename = os.path.basename(path).split(".")[0] + self.output_ext
+ outname = os.path.join(self.outpath, basename)
+ if self.output_ext == ".npy":
+ np.save(outname, img_resize_np)
+ elif self.output_ext == ".png":
+ img_resized_pil = Image.fromarray(img_resize_np)
+ img_resized_pil.save(outname)
+ else:
+ raise ValueError("invalid output extension")
+ return 0
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/utils.py b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e2eba6fac87e7609b4ca1b684aa0505243a139e
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/cleanfid/utils.py
@@ -0,0 +1,58 @@
+import random
+
+import numpy as np
+import torch
+import torchvision
+from PIL import Image
+from tool.cleanfid.resize import build_resizer
+import zipfile
+
+
+class ResizeDataset(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, mode, size=(299, 299), fdir=None):
+ self.files = files
+ self.fdir = fdir
+ self.transforms = torchvision.transforms.ToTensor()
+ self.size = size
+ self.fn_resize = build_resizer(mode)
+ self.custom_image_tranform = lambda x: x
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ try:
+ path = str(self.files[i])
+ if self.fdir is not None and '.zip' in self.fdir:
+ with zipfile.ZipFile(self.fdir).open(path, 'r') as f:
+ img_np = np.array(Image.open(f).convert('RGB'))
+ if ".npy" in path:
+ img_np = np.load(path)
+ else:
+ img_pil = Image.open(path).convert('RGB')
+ img_np = np.array(img_pil)
+ # apply a custom image transform before resizing the image to 299x299
+ img_np = self.custom_image_tranform(img_np)
+ # fn_resize expects a np array and returns a np array
+ img_resized = self.fn_resize(img_np)
+
+ # ToTensor() converts to [0,1] only if input in uint8
+ if img_resized.dtype == "uint8":
+ img_t = self.transforms(np.array(img_resized))*255
+ elif img_resized.dtype == "float32":
+ img_t = self.transforms(img_resized)
+ return img_t
+ except:
+ return self.__getitem__(np.random.randint(0, self.__len__() - 1))
+
+
+EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
+ 'tif', 'tiff', 'webp', 'npy'}
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/inception_score.py b/One-to-All-Animation/benchmark/DisCo/tool/inception_score.py
new file mode 100644
index 0000000000000000000000000000000000000000..57a3fe61a08cd0a1fdc88d4a225dde4d55e034b6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/inception_score.py
@@ -0,0 +1,98 @@
+import os
+import torch
+from torch import nn
+from torch.autograd import Variable
+from torch.nn import functional as F
+import torch.utils.data
+from torchvision import transforms
+from torch.utils.data import Dataset, SequentialSampler, DataLoader, RandomSampler
+from torchvision.models.inception import inception_v3
+import numpy as np
+from scipy.stats import entropy
+from PIL import Image
+from tqdm import tqdm
+
+def inception_score(imgs, cuda=True, batch_size=32, splits=10):
+ N = len(imgs)
+ print(f'detect images {N}')
+ assert batch_size > 0
+ assert N > batch_size
+
+ # Set up dtype
+ if cuda:
+ dtype = torch.cuda.FloatTensor
+ else:
+ if torch.cuda.is_available():
+ print("WARNING: You have a CUDA device, so you should probably set cuda=True")
+ dtype = torch.FloatTensor
+
+ # Set up dataloader
+ dataloader = torch.utils.data.DataLoader(imgs, batch_size=batch_size, shuffle=False,
+ drop_last=False, num_workers=16)
+
+
+ # Load inception models
+ inception_model = inception_v3(pretrained=True, transform_input=False).type(dtype)
+ inception_model.eval()
+ def get_pred(x):
+ x = inception_model(x)
+ return F.softmax(x).data.cpu().numpy()
+
+ # Get predictions
+ preds = np.zeros((N, 1000))
+
+ for i, batch in tqdm(enumerate(dataloader, 0)):
+ batch = batch.type(dtype)
+ batchv = Variable(batch)
+ batch_size_i = batch.size()[0]
+
+ preds[i*batch_size:i*batch_size + batch_size_i] = get_pred(batchv)
+
+ # Now compute the mean kl-div
+ split_scores = []
+
+ for k in range(splits):
+ part = preds[k * (N // splits): (k+1) * (N // splits), :]
+ py = np.mean(part, axis=0)
+ scores = []
+ for i in range(part.shape[0]):
+ pyx = part[i, :]
+ scores.append(entropy(pyx, py))
+ split_scores.append(np.exp(np.mean(scores)))
+
+ return np.mean(split_scores), np.std(split_scores)
+
+
+class ISDataset(Dataset):
+ def __init__(self, dir):
+ self.args = dir
+ self.fileroot = dir
+ self.filelist = os.listdir(self.fileroot)
+
+ self.transform = transforms.Compose([
+ lambda x: Image.open(x).convert('RGB'),
+ transforms.Resize((299, 299)),
+ transforms.ToTensor(),
+ transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
+ ])
+
+ def __len__(self):
+ return len(self.filelist)
+
+ def __getitem__(self, i):
+ try:
+ img_name = self.filelist[i]
+ img_path = os.path.join(self.fileroot, img_name)
+ image = self.transform(img_path)
+ return image
+ except Exception as e:
+ print('Bad idx %s skipped because of %s' % (self.filelist[i], e))
+ return self.__getitem__(np.random.randint(0, self.__len__() - 1))
+
+
+def calculate_is(img_dir, batch_size=32, splits=10):
+ data = ISDataset(img_dir)
+ mean, std = inception_score(data, cuda=True, batch_size=batch_size, splits=splits)
+ return mean, std
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/merge_subfolder.py b/One-to-All-Animation/benchmark/DisCo/tool/merge_subfolder.py
new file mode 100644
index 0000000000000000000000000000000000000000..4faf8d52354bc21b86a65a9bcbcf21a5e7928090
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/merge_subfolder.py
@@ -0,0 +1,86 @@
+import argparse
+import shutil
+from pathlib import Path
+
+from tqdm import tqdm
+
+
+def copy_files(input_folder, output_folder, use_symlink=False, selected_frame_idx: int = 0):
+ print("Copying files from {} to {}".format(input_folder, output_folder))
+ input_folder = Path(input_folder)
+ output_folder = Path(output_folder)
+
+ # Ensure output directory exists
+ output_folder.mkdir(parents=True, exist_ok=True)
+ # try:
+ # print(f"Copying files from {input_folder.absolute()} to {output_folder.absolute()}")
+ # except Exception as e:
+ # print(e)
+
+ # Collect all subfolders
+ subfolders = list(input_folder.iterdir())
+
+ # Collect and copy or link files from each subfolder
+ for subfolder in tqdm(subfolders, desc="Copying files", unit="subfolder"):
+ if subfolder.is_dir():
+ file_list = sorted(list(subfolder.iterdir()))
+ if selected_frame_idx != -1: # -1 means use all frames
+ selected_frame_idx = max(min(selected_frame_idx, len(file_list) - 1), 0)
+
+ for idx, file in enumerate(file_list):
+ if idx != selected_frame_idx:
+ continue
+
+ # Skip files of 0 size
+ if file.stat().st_size > 0:
+ if selected_frame_idx == -1: # -1 means use all frames
+ output_file_path = output_folder / (subfolder.name + "-" + file.name)
+ else:
+ output_file_path = output_folder / file.name
+
+ if use_symlink:
+ if not output_file_path.exists(): # Check if file doesn't exist
+ output_file_path.symlink_to(file.resolve()) # Using absolute path here
+ else:
+ shutil.copy2(file, output_folder)
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "-i",
+ "--input_folder",
+ type=str,
+ required=True,
+ help="Input folder path containing subfolders with files",
+ )
+ parser.add_argument(
+ "-o",
+ "--output_folder",
+ type=str,
+ default="",
+ help="Output folder path where files will be copied or linked",
+ )
+ parser.add_argument(
+ "--soft",
+ action="store_true",
+ default=False,
+ help="If set, creates symbolic links instead of copying files",
+ )
+ parser.add_argument(
+ "--frame_idx",
+ type=int,
+ default=0,
+ help="The frame index to be copied from each subfolder",
+ )
+
+ args = parser.parse_args()
+
+ # Remove trailing slash from input_folder if it exists
+ args.input_folder = args.input_folder.rstrip("/")
+
+ # Set default output folder if not provided
+ if args.output_folder == "":
+ args.output_folder = args.input_folder + f"_{args.frame_idx}nd_frames"
+
+ copy_files(args.input_folder, args.output_folder, args.soft, args.frame_idx)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/__init__.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/downloads_helper.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/downloads_helper.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c00f4c5511f11eb1c6f1b2855c066d44c32d548
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/downloads_helper.py
@@ -0,0 +1,69 @@
+import os
+import sys
+from argparse import ArgumentParser
+import urllib.request
+import requests
+import shutil
+
+
+inception_url = "https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metrics/inception-2015-12-05.pt"
+
+
+"""
+Download the pretrined inception weights if it does not exists
+ARGS:
+ fpath - output folder path
+"""
+def check_download_inception(fpath="./"):
+ inception_path = os.path.join(fpath, "inception-2015-12-05.pt")
+ if not os.path.exists(inception_path):
+ # download the file
+ with urllib.request.urlopen(inception_url) as response, open(inception_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+ return inception_path
+
+
+"""
+Download any url if it does not exist
+ARGS:
+ local_folder - output folder path
+ url - the weburl to download
+"""
+def check_download_url(local_folder, url):
+ name = os.path.basename(url)
+ local_path = os.path.join(local_folder, name)
+ if not os.path.exists(local_path):
+ os.makedirs(local_folder, exist_ok=True)
+ print(f"downloading statistics to {local_path}")
+ with urllib.request.urlopen(url) as response, open(local_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+ return local_path
+
+
+"""
+Download a file from google drive
+ARGS:
+ file_id - id of the google drive file
+ out_path - output folder path
+"""
+def download_google_drive(file_id, out_path):
+ def get_confirm_token(response):
+ for key, value in response.cookies.items():
+ if key.startswith('download_warning'):
+ return value
+ return None
+
+ URL = "https://drive.google.com/uc?export=download"
+ session = requests.Session()
+ response = session.get(URL, params={'id': file_id}, stream=True)
+ token = get_confirm_token(response)
+
+ if token:
+ params = {'id': file_id, 'confirm': token}
+ response = session.get(URL, params=params, stream=True)
+
+ CHUNK_SIZE = 32768
+ with open(out_path, "wb") as f:
+ for chunk in response.iter_content(CHUNK_SIZE):
+ if chunk:
+ f.write(chunk)
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/features.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/features.py
new file mode 100644
index 0000000000000000000000000000000000000000..68dc9b602d5f1743576776e951a23a6ee771445d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/features.py
@@ -0,0 +1,75 @@
+"""
+helpers for extractign features from image
+"""
+import os
+from random import sample
+import numpy as np
+import torch
+import torch.nn as nn
+from tool.metrics.downloads_helper import check_download_url
+from tool.metrics.inception_pytorch import InceptionV3
+from tool.metrics.inception_torchscript import InceptionV3W
+import torchvision.models as models
+import tool.metrics.resnet3d as resnet3d
+from tool.metrics.inception3d import InceptionI3d
+
+"""
+Build a feature extractor for each of the modes
+"""
+
+
+def build_feature_extractor(mode, root_dir, device=torch.device("cuda"), sample_duration=16):
+
+ if mode == "clean":
+ feat_model = InceptionV3W("/tmp", download=True, resize_inside=False).to(device)
+ feat_model = feat_model.eval()
+
+ elif mode == "clean_InceptionScore":
+ # we need the softmax function after the calcualtion
+ feat_model = models.inception_v3(pretrained=True, progress=True)
+ feat_model = feat_model.to(device).eval()
+ elif mode == "FVD-3DRN50":
+ feat_model = resnet3d.resnet50(num_classes=400, shortcut_type="B", sample_size=112, sample_duration=sample_duration, last_fc=False)
+ model_data = torch.load(os.path.join(root_dir, "eval_fvd/resnet-50-kinetics.pth"), map_location='cpu')
+ model_state_new = {}
+ for key, value in model_data['state_dict'].items():
+ key_new = key.replace('module.', '')
+ model_state_new[key_new] = value
+
+ feat_model.load_state_dict(model_state_new)
+ feat_model = feat_model.to(device).eval()
+ elif mode == "FVD-3DInception": # based on logits to calcuate, which can be found the description from latent vision transformer
+ feat_model = InceptionI3d(400, in_channels=3)
+ feat_model.load_state_dict(torch.load(os.path.join(root_dir, "eval_fvd/i3d_pretrained_400.pt")))
+ feat_model = feat_model.to(device).eval()
+ else:
+ raise NotImplementedError
+ return feat_model
+
+
+"""
+Load precomputed reference statistics for commonly used datasets
+"""
+
+
+def get_reference_statistics(name, res, mode="clean", seed=0, split="test", metric="FID"):
+ base_url = "https://www.cs.cmu.edu/~clean-fid/stats/"
+ if split == "custom":
+ res = "na"
+ if metric == "FID":
+ rel_path = (f"{name}_{mode}_{split}_{res}.npz").lower()
+ url = f"{base_url}/{rel_path}"
+ mod_path = os.path.dirname(metrics.__file__)
+ stats_folder = os.path.join(mod_path, "stats")
+ fpath = check_download_url(local_folder=stats_folder, url=url)
+ stats = np.load(fpath)
+ mu, sigma = stats["mu"], stats["sigma"]
+ return mu, sigma
+ elif metric == "KID":
+ rel_path = (f"{name}_{mode}_{split}_{res}_kid.npz").lower()
+ url = f"{base_url}/{rel_path}"
+ mod_path = os.path.dirname(metrics.__file__)
+ stats_folder = os.path.join(mod_path, "stats")
+ fpath = check_download_url(local_folder=stats_folder, url=url)
+ stats = np.load(fpath)
+ return stats["feats"]
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/fid.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/fid.py
new file mode 100644
index 0000000000000000000000000000000000000000..d38f0ac1be0934506049738866b1df5c5326fae3
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/fid.py
@@ -0,0 +1,411 @@
+import os
+import random
+from tqdm import tqdm
+from glob import glob
+import torch
+import numpy as np
+from scipy import linalg
+from utils import *
+from tool.metrics.features import *
+from tool.metrics.resize import *
+from PIL import Image
+from tool.metrics.utils import ResizeDataset
+
+
+"""
+Compute the FID score given the mu, sigma of two sets
+"""
+def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
+ """Numpy implementation of the Frechet Distance.
+ The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
+ and X_2 ~ N(mu_2, C_2) is
+ d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
+ Stable version by Danica J. Sutherland.
+ Params:
+ -- mu1 : Numpy array containing the activations of a layer of the
+ inception net (like returned by the function 'get_predictions')
+ for generated samples.
+ -- mu2 : The sample mean over activations, precalculated on an
+ representative data set.
+ -- sigma1: The covariance matrix over activations for generated samples.
+ -- sigma2: The covariance matrix over activations, precalculated on an
+ representative data set.
+ Returns:
+ -- : The Frechet Distance.
+ """
+ mu1 = np.atleast_1d(mu1)
+ mu2 = np.atleast_1d(mu2)
+ sigma1 = np.atleast_2d(sigma1)
+ sigma2 = np.atleast_2d(sigma2)
+
+ assert mu1.shape == mu2.shape, \
+ 'Training and test mean vectors have different lengths'
+ assert sigma1.shape == sigma2.shape, \
+ 'Training and test covariances have different dimensions'
+
+ diff = mu1 - mu2
+
+ # Product might be almost singular
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
+ if not np.isfinite(covmean).all():
+ msg = ('fid calculation produces singular product; '
+ 'adding %s to diagonal of cov estimates') % eps
+ print(msg)
+ offset = np.eye(sigma1.shape[0]) * eps
+ covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
+
+ # Numerical error might give slight imaginary component
+ if np.iscomplexobj(covmean):
+ if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
+ m = np.max(np.abs(covmean.imag))
+ raise ValueError('Imaginary component {}'.format(m))
+ covmean = covmean.real
+
+ tr_covmean = np.trace(covmean)
+
+ return (diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean)
+
+
+"""
+Compute the KID score given the sets of features
+"""
+def kernel_distance(feats1, feats2, num_subsets=100, max_subset_size=1000):
+ n = feats1.shape[1]
+ m = min(min(feats1.shape[0], feats2.shape[0]), max_subset_size)
+ t = 0
+ for _subset_idx in range(num_subsets):
+ x = feats2[np.random.choice(feats2.shape[0], m, replace=False)]
+ y = feats1[np.random.choice(feats1.shape[0], m, replace=False)]
+ a = (x @ x.T / n + 1) ** 3 + (y @ y.T / n + 1) ** 3
+ b = (x @ y.T / n + 1) ** 3
+ t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m
+ kid = t / num_subsets / m
+ return float(kid)
+
+
+"""
+Compute the inception features for a batch of images
+"""
+def get_batch_features(batch, model, device):
+ with torch.no_grad():
+ feat = model(batch.to(device))
+ return feat.detach().cpu().numpy()
+
+"""
+Compute the inception features for a list of files
+"""
+def get_files_features(l_files, model=None, num_workers=12,
+ batch_size=128, device=torch.device("cuda"),
+ mode="clean", custom_fn_resize=None,
+ description=""):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+
+ # build resizing function based on options
+ if custom_fn_resize is not None:
+ fn_resize = custom_fn_resize
+ else:
+ fn_resize = build_resizer(mode)
+
+ # wrap the images in a dataloader for parallelizing the resize operation
+ dataset = ResizeDataset(l_files, fn_resize=fn_resize)
+ dataloader = torch.utils.data.DataLoader(dataset,
+ batch_size=batch_size, shuffle=False,
+ drop_last=False, num_workers=num_workers)
+
+ # collect all inception features
+ l_feats = []
+ for batch in tqdm(dataloader, desc=description):
+ l_feats.append(get_batch_features(batch, model, device))
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+"""
+Compute the inception features for a folder of features
+"""
+def get_folder_features(fdir, model=None, num_workers=12, num=None,
+ shuffle=False, seed=0, batch_size=128, device=torch.device("cuda"),
+ mode="clean", custom_fn_resize=None, description=""):
+ # get all relevant files in the dataset
+ # = sorted([file for ext in EXTENSIONS for file in glob(os.path.join(fdir, f"**/*.{ext}"), recursive=True)])
+ files = []
+ for ext in EXTENSIONS:
+ for file in glob(os.path.join(fdir, f"**/*.{ext}"), recursive=True):
+ try:
+ image = Image.open(str(file))
+ image.verify()
+ image.close()
+ files.append(file)
+ except:
+ print('{} can not open'.format(file))
+ continue
+ files = sorted(files)
+
+ print(f"Found {len(files)} images in the folder {fdir}")
+ # use a subset number of files if needed
+ if num is not None:
+ if shuffle:
+ random.seed(seed)
+ random.shuffle(files)
+ files = files[:num]
+ np_feats = get_files_features(files, model, num_workers=num_workers,
+ batch_size=batch_size, device=device,
+ mode=mode,
+ custom_fn_resize=custom_fn_resize,
+ description=description)
+ return np_feats
+
+"""
+Compute the FID score given the inception features stack
+"""
+def fid_from_feats(feats1, feats2):
+ mu1, sig1 = np.mean(feats1, axis=0), np.cov(feats1, rowvar=False)
+ mu2, sig2 = np.mean(feats2, axis=0), np.cov(feats2, rowvar=False)
+ return frechet_distance(mu1, sig1, mu2, sig2)
+
+"""
+Computes the FID score for a folder of images for a specific dataset
+and a specific resolution
+"""
+def fid_folder(fdir, dataset_name, dataset_res, dataset_split,
+ model=None, mode="clean", num_workers=12,
+ batch_size=128, device=torch.device("cuda")):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split)
+ fbname = os.path.basename(fdir)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir, model, num_workers=num_workers,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"FID {fbname} : ")
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+"""
+Compute the FID stats from a generator model
+"""
+def get_model_features(G, model, mode="clean", z_dim=512,
+ num_gen=50_000, batch_size=128,
+ device=torch.device("cuda"), desc="FID model: "):
+ fn_resize = build_resizer(mode)
+ # Generate test features
+ num_iters = int(np.ceil(num_gen / batch_size))
+ l_feats = []
+ for idx in tqdm(range(num_iters), desc=desc):
+ with torch.no_grad():
+ z_batch = torch.randn((batch_size, z_dim)).to(device)
+ # generated image is in range [0,255]
+ img_batch = G(z_batch)
+ # split into individual batches for resizing if needed
+ if mode != "legacy_tensorflow":
+ resized_batch = torch.zeros(batch_size, 3, 299, 299)
+ for idx in range(batch_size):
+ curr_img = img_batch[idx]
+ img_np = curr_img.cpu().numpy().transpose((1, 2, 0))
+ img_resize = fn_resize(img_np)
+ resized_batch[idx] = torch.tensor(img_resize.transpose((2, 0, 1)))
+ else:
+ resized_batch = img_batch
+ feat = get_batch_features(resized_batch, model, device)
+ l_feats.append(feat)
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+"""
+Computes the FID score for a generator model for a specific dataset
+and a specific resolution
+"""
+def fid_model(G, dataset_name, dataset_res, dataset_split,
+ model=None, z_dim=512, num_gen=50_000,
+ mode="clean", num_workers=0, batch_size=128,
+ device=torch.device("cuda")):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split)
+ # build resizing function based on options
+ fn_resize = build_resizer(mode)
+
+ # Generate test features
+ np_feats = get_model_features(G, model, mode=mode,
+ z_dim=z_dim, num_gen=num_gen,
+ batch_size=batch_size, device=device)
+
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+
+"""
+Computes the FID score between the two given folders
+"""
+def compare_folders(fdir1, fdir2, feat_model, mode, num_workers=0,
+ batch_size=8, device=torch.device("cuda")):
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, feat_model, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"FID {fbname1} : ")
+ mu1 = np.mean(np_feats1, axis=0)
+ sigma1 = np.cov(np_feats1, rowvar=False)
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, feat_model, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"FID {fbname2} : ")
+ mu2 = np.mean(np_feats2, axis=0)
+ sigma2 = np.cov(np_feats2, rowvar=False)
+ fid = frechet_distance(mu1, sigma1, mu2, sigma2)
+ return fid
+
+
+"""
+Test if a custom statistic exists
+"""
+def test_stats_exists(name, mode):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ split, res="custom", "na"
+ fname = f"{name}_{mode}_{split}_{res}.npz"
+ fpath = os.path.join(stats_folder, fname)
+ return os.path.exists(fpath)
+
+def remove_custom_stats(name, mode="clean"):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ split, res="custom", "na"
+ outname = f"{name}_{mode}_{split}_{res}.npz"
+ outf = os.path.join(stats_folder, outname)
+ if not os.path.exists(outf):
+ msg = f"The stats file {name} does not exist."
+ raise Exception(msg)
+ os.remove(outf)
+
+
+"""
+Cache a custom dataset statistics file
+"""
+def make_custom_stats(name, fdir, num=None, mode="clean",
+ num_workers=0, batch_size=64, device=torch.device("cuda")):
+ stats_folder = os.path.join(os.path.dirname(cleanfid.__file__), "stats")
+ split, res = "custom", "na"
+ outname = f"{name}_{mode}_{split}_{res}.npz"
+ outf = os.path.join(stats_folder, outname)
+ # if the custom stat file already exists
+ if os.path.exists(outf):
+ msg = f"The statistics file {name} already exists. "
+ msg += f"Use remove_custom_stats function to delete it first."
+ raise Exception(msg)
+
+ feat_model = build_feature_extractor(mode, device)
+ fbname = os.path.basename(fdir)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir, feat_model, num_workers=num_workers, num=num,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"FID {fbname} : ")
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ print(f"saving custom stats to {outf}")
+ np.savez_compressed(outf, mu=mu, sigma=sigma)
+
+
+def compute_kid(fdir1=None, fdir2=None, gen=None,
+ mode="clean", num_workers=12, batch_size=32,
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512):
+ # build the feature extractor based on the mode
+ feat_model = build_feature_extractor(mode, device)
+
+ # if both dirs are specified, compute KID between folders
+ if fdir1 is not None and fdir2 is not None:
+ print("compute KID between two folders")
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, None, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"KID {fbname1} : ")
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, None, num_workers=num_workers,
+ batch_size=batch_size, device=device, mode=mode,
+ description=f"KID {fbname2} : ")
+ score = kernel_distance(np_feats1, np_feats2)
+ return score
+
+ # compute kid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ print(f"compute KID of a folder with {dataset_name} statistics")
+ # define the model if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ fbname = os.path.basename(fdir1)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir1, model, num_workers=num_workers,
+ batch_size=batch_size, device=device,
+ mode=mode, description=f"KID {fbname} : ")
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ print(f"compute KID of a model with {dataset_name}-{dataset_res} statistics")
+ # define the model if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ # build resizing function based on options
+ fn_resize = build_resizer(mode)
+ # Generate test features
+ np_feats = get_model_features(gen, model, mode=mode,
+ z_dim=z_dim, num_gen=num_gen, desc="KID model: ",
+ batch_size=batch_size, device=device)
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ else:
+ raise ValueError(f"invalid combination of directories and models entered")
+
+
+def compute_fid(fdir1=None, fdir2=None, gen=None,
+ mode="clean", num_workers=12, batch_size=32,
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512):
+ # build the feature extractor based on the mode
+ feat_model = build_feature_extractor(mode, device)
+
+ # if both dirs are specified, compute FID between folders
+ if fdir1 is not None and fdir2 is not None:
+ print("compute FID between two folders")
+ score = compare_folders(fdir1, fdir2, feat_model,
+ mode=mode, batch_size=batch_size,
+ num_workers=num_workers, device=device)
+ return score
+
+ # compute fid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ print(f"compute FID of a folder with {dataset_name} statistics")
+ score = fid_folder(fdir1, dataset_name, dataset_res, dataset_split,
+ model=feat_model, mode=mode, num_workers=num_workers,
+ batch_size=batch_size, device=device)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ print(f"compute FID of a model with {dataset_name}-{dataset_res} statistics")
+ score = fid_model(gen, dataset_name, dataset_res, dataset_split,
+ model=feat_model, z_dim=z_dim, num_gen=num_gen,
+ mode=mode, num_workers=num_workers, batch_size=batch_size,
+ device=device)
+ return score
+
+ else:
+ raise ValueError(f"invalid combination of directories and models entered")
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception3d.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..3062d3967c4053143f1177eb8f24eeb98c0822ab
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception3d.py
@@ -0,0 +1,360 @@
+# -*- encoding: utf-8 -*-
+'''
+@Time :2021/10/13 19:50:21
+@Author :Yongfei Liu
+@Email :liuyf3@shanghaitech.edu.cn
+'''
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd import Variable
+import numpy as np
+import os
+import sys
+from collections import OrderedDict
+
+
+class MaxPool3dSamePadding(nn.MaxPool3d):
+
+ def compute_pad(self, dim, s):
+ if s % self.stride[dim] == 0:
+ return max(self.kernel_size[dim] - self.stride[dim], 0)
+ else:
+ return max(self.kernel_size[dim] - (s % self.stride[dim]), 0)
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ # # print t,h,w
+ # out_t = np.ceil(float(t) / float(self.stride[0]))
+ # out_h = np.ceil(float(h) / float(self.stride[1]))
+ # out_w = np.ceil(float(w) / float(self.stride[2]))
+ # # print out_t, out_h, out_w
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+ return super(MaxPool3dSamePadding, self).forward(x)
+
+
+class Unit3D(nn.Module):
+
+ def __init__(self, in_channels,
+ output_channels,
+ kernel_shape=(1, 1, 1),
+ stride=(1, 1, 1),
+ padding=0,
+ activation_fn=F.relu,
+ use_batch_norm=True,
+ use_bias=False,
+ name='unit_3d'):
+ """Initializes Unit3D module."""
+ super(Unit3D, self).__init__()
+
+ self._output_channels = output_channels
+ self._kernel_shape = kernel_shape
+ self._stride = stride
+ self._use_batch_norm = use_batch_norm
+ self._activation_fn = activation_fn
+ self._use_bias = use_bias
+ self.name = name
+ self.padding = padding
+
+ self.conv3d = nn.Conv3d(in_channels=in_channels,
+ out_channels=self._output_channels,
+ kernel_size=self._kernel_shape,
+ stride=self._stride,
+ padding=0, # we always want padding to be 0 here. We will dynamically pad based on input size in forward function
+ bias=self._use_bias)
+
+ if self._use_batch_norm:
+ self.bn = nn.BatchNorm3d(
+ self._output_channels, eps=0.001, momentum=0.01)
+
+ def compute_pad(self, dim, s):
+ if s % self._stride[dim] == 0:
+ return max(self._kernel_shape[dim] - self._stride[dim], 0)
+ else:
+ return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0)
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ # #print t,h,w
+ # out_t = np.ceil(float(t) / float(self._stride[0]))
+ # out_h = np.ceil(float(h) / float(self._stride[1]))
+ # out_w = np.ceil(float(w) / float(self._stride[2]))
+ # #print out_t, out_h, out_w
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+ # print pad_t, pad_h, pad_w
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+
+ x = self.conv3d(x)
+ if self._use_batch_norm:
+ x = self.bn(x)
+ if self._activation_fn is not None:
+ x = self._activation_fn(x)
+ return x
+
+
+class InceptionModule(nn.Module):
+ def __init__(self, in_channels, out_channels, name):
+ super(InceptionModule, self).__init__()
+
+ self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[
+ 1, 1, 1], padding=0, name=name+'/Branch_0/Conv3d_0a_1x1')
+ self.b1a = Unit3D(in_channels=in_channels, output_channels=out_channels[1], kernel_shape=[
+ 1, 1, 1], padding=0, name=name+'/Branch_1/Conv3d_0a_1x1')
+ self.b1b = Unit3D(in_channels=out_channels[1], output_channels=out_channels[2], kernel_shape=[
+ 3, 3, 3], name=name+'/Branch_1/Conv3d_0b_3x3')
+ self.b2a = Unit3D(in_channels=in_channels, output_channels=out_channels[3], kernel_shape=[
+ 1, 1, 1], padding=0, name=name+'/Branch_2/Conv3d_0a_1x1')
+ self.b2b = Unit3D(in_channels=out_channels[3], output_channels=out_channels[4], kernel_shape=[
+ 3, 3, 3], name=name+'/Branch_2/Conv3d_0b_3x3')
+ self.b3a = MaxPool3dSamePadding(
+ kernel_size=[3, 3, 3], stride=(1, 1, 1), padding=0)
+ self.b3b = Unit3D(in_channels=in_channels, output_channels=out_channels[5], kernel_shape=[
+ 1, 1, 1], padding=0, name=name+'/Branch_3/Conv3d_0b_1x1')
+ self.name = name
+
+ def forward(self, x):
+ b0 = self.b0(x)
+ b1 = self.b1b(self.b1a(x))
+ b2 = self.b2b(self.b2a(x))
+ b3 = self.b3b(self.b3a(x))
+ return torch.cat([b0, b1, b2, b3], dim=1)
+
+
+class InceptionI3d(nn.Module):
+ """Inception-v1 I3D architecture.
+ The model is introduced in:
+ Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
+ Joao Carreira, Andrew Zisserman
+ https://arxiv.org/pdf/1705.07750v1.pdf.
+ See also the Inception architecture, introduced in:
+ Going deeper with convolutions
+ Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,
+ Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.
+ http://arxiv.org/pdf/1409.4842v1.pdf.
+ """
+
+ # Endpoints of the model in order. During construction, all the endpoints up
+ # to a designated `final_endpoint` are returned in a dictionary as the
+ # second return value.
+ VALID_ENDPOINTS = (
+ 'Conv3d_1a_7x7',
+ 'MaxPool3d_2a_3x3',
+ 'Conv3d_2b_1x1',
+ 'Conv3d_2c_3x3',
+ 'MaxPool3d_3a_3x3',
+ 'Mixed_3b',
+ 'Mixed_3c',
+ 'MaxPool3d_4a_3x3',
+ 'Mixed_4b',
+ 'Mixed_4c',
+ 'Mixed_4d',
+ 'Mixed_4e',
+ 'Mixed_4f',
+ 'MaxPool3d_5a_2x2',
+ 'Mixed_5b',
+ 'Mixed_5c',
+ 'Logits',
+ 'Predictions',
+ )
+
+ def __init__(self, num_classes=400, spatial_squeeze=True,
+ final_endpoint='Logits', name='inception_i3d', in_channels=3, dropout_keep_prob=0.5):
+ """Initializes I3D model instance.
+ Args:
+ num_classes: The number of outputs in the logit layer (default 400, which
+ matches the Kinetics dataset).
+ spatial_squeeze: Whether to squeeze the spatial dimensions for the logits
+ before returning (default True).
+ final_endpoint: The model contains many possible endpoints.
+ `final_endpoint` specifies the last endpoint for the model to be built
+ up to. In addition to the output at `final_endpoint`, all the outputs
+ at endpoints up to `final_endpoint` will also be returned, in a
+ dictionary. `final_endpoint` must be one of
+ InceptionI3d.VALID_ENDPOINTS (default 'Logits').
+ name: A string (optional). The name of this module.
+ Raises:
+ ValueError: if `final_endpoint` is not recognized.
+ """
+
+ if final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' % final_endpoint)
+
+ super(InceptionI3d, self).__init__()
+ self._num_classes = num_classes
+ self._spatial_squeeze = spatial_squeeze
+ self._final_endpoint = final_endpoint
+ self.logits = None
+
+ if self._final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' %
+ self._final_endpoint)
+
+ self.end_points = {}
+ end_point = 'Conv3d_1a_7x7'
+ self.end_points[end_point] = Unit3D(in_channels=in_channels, output_channels=64, kernel_shape=[7, 7, 7],
+ stride=(2, 2, 2), padding=(3, 3, 3), name=name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'MaxPool3d_2a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(
+ kernel_size=[1, 3, 3], stride=(1, 2, 2), padding=0)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Conv3d_2b_1x1'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=64, kernel_shape=[
+ 1, 1, 1], padding=0, name=name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Conv3d_2c_3x3'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=192, kernel_shape=[
+ 3, 3, 3], padding=1, name=name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'MaxPool3d_3a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(
+ kernel_size=[1, 3, 3], stride=(1, 2, 2), padding=0)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_3b'
+ self.end_points[end_point] = InceptionModule(
+ 192, [64, 96, 128, 16, 32, 32], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_3c'
+ self.end_points[end_point] = InceptionModule(
+ 256, [128, 128, 192, 32, 96, 64], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'MaxPool3d_4a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(
+ kernel_size=[3, 3, 3], stride=(2, 2, 2), padding=0)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_4b'
+ self.end_points[end_point] = InceptionModule(
+ 128+192+96+64, [192, 96, 208, 16, 48, 64], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_4c'
+ self.end_points[end_point] = InceptionModule(
+ 192+208+48+64, [160, 112, 224, 24, 64, 64], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_4d'
+ self.end_points[end_point] = InceptionModule(
+ 160+224+64+64, [128, 128, 256, 24, 64, 64], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_4e'
+ self.end_points[end_point] = InceptionModule(
+ 128+256+64+64, [112, 144, 288, 32, 64, 64], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_4f'
+ self.end_points[end_point] = InceptionModule(
+ 112+288+64+64, [256, 160, 320, 32, 128, 128], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'MaxPool3d_5a_2x2'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[2, 2, 2], stride=(2, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_5b'
+ self.end_points[end_point] = InceptionModule(
+ 256+320+128+128, [256, 160, 320, 32, 128, 128], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Mixed_5c'
+ self.end_points[end_point] = InceptionModule(
+ 256+320+128+128, [384, 192, 384, 48, 128, 128], name+end_point)
+ if self._final_endpoint == end_point:
+ return
+
+ end_point = 'Logits'
+ self.avg_pool = nn.AvgPool3d(kernel_size=[1, 7, 7],
+ stride=(1, 1, 1))
+ self.dropout = nn.Dropout(dropout_keep_prob)
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+ self.build()
+
+ def replace_logits(self, num_classes):
+ self._num_classes = num_classes
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+ def build(self):
+ for k in self.end_points.keys():
+ self.add_module(k, self.end_points[k])
+
+ def forward(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ # use _modules to work with dataparallel
+ x = self._modules[end_point](x)
+
+ x = self.logits(self.dropout(self.avg_pool(x)))
+ if self._spatial_squeeze:
+ logits = x.squeeze(3).squeeze(3)
+ logits = logits.mean(2)
+
+ # logits is batch X time X classes, which is what we want to work with
+ return logits
+
+ def extract_features(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ x = self._modules[end_point](x)
+ return self.avg_pool(x)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_pytorch.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_pytorch.py
new file mode 100644
index 0000000000000000000000000000000000000000..131b5533d661bf4cdf96e9b887dec4285fae7e93
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_pytorch.py
@@ -0,0 +1,325 @@
+"""
+File from: https://github.com/mseitzer/pytorch-fid
+"""
+
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import torchvision
+
+try:
+ from torchvision.models.utils import load_state_dict_from_url
+except ImportError:
+ from torch.utils.model_zoo import load_url as load_state_dict_from_url
+
+# Inception weights ported to Pytorch from
+# http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz
+FID_WEIGHTS_URL = 'https://github.com/mseitzer/pytorch-fid/releases/download/fid_weights/pt_inception-2015-12-05-6726825d.pth' # noqa: E501
+
+
+class InceptionV3(nn.Module):
+ """Pretrained InceptionV3 network returning feature maps"""
+
+ # Index of default block of inception to return,
+ # corresponds to output of final average pooling
+ DEFAULT_BLOCK_INDEX = 3
+
+ # Maps feature dimensionality to their output blocks indices
+ BLOCK_INDEX_BY_DIM = {
+ 64: 0, # First max pooling features
+ 192: 1, # Second max pooling featurs
+ 768: 2, # Pre-aux classifier features
+ 2048: 3 # Final average pooling features
+ }
+
+ def __init__(self,
+ output_blocks=(DEFAULT_BLOCK_INDEX,),
+ resize_input=True,
+ normalize_input=True,
+ requires_grad=False,
+ use_fid_inception=True):
+ """Build pretrained InceptionV3
+ Parameters
+ ----------
+ output_blocks : list of int
+ Indices of blocks to return features of. Possible values are:
+ - 0: corresponds to output of first max pooling
+ - 1: corresponds to output of second max pooling
+ - 2: corresponds to output which is fed to aux classifier
+ - 3: corresponds to output of final average pooling
+ resize_input : bool
+ If true, bilinearly resizes input to width and height 299 before
+ feeding input to model. As the network without fully connected
+ layers is fully convolutional, it should be able to handle inputs
+ of arbitrary size, so resizing might not be strictly needed
+ normalize_input : bool
+ If true, scales the input from range (0, 1) to the range the
+ pretrained Inception network expects, namely (-1, 1)
+ requires_grad : bool
+ If true, parameters of the model require gradients. Possibly useful
+ for finetuning the network
+ use_fid_inception : bool
+ If true, uses the pretrained Inception model used in Tensorflow's
+ FID implementation. If false, uses the pretrained Inception model
+ available in torchvision. The FID Inception model has different
+ weights and a slightly different structure from torchvision's
+ Inception model. If you want to compute FID scores, you are
+ strongly advised to set this parameter to true to get comparable
+ results.
+ """
+ super(InceptionV3, self).__init__()
+
+ self.resize_input = resize_input
+ self.normalize_input = normalize_input
+ self.output_blocks = sorted(output_blocks)
+ self.last_needed_block = max(output_blocks)
+
+ assert self.last_needed_block <= 3, \
+ 'Last possible output block index is 3'
+
+ self.blocks = nn.ModuleList()
+
+ if use_fid_inception:
+ inception = fid_inception_v3()
+ else:
+ inception = _inception_v3(pretrained=True)
+
+ # Block 0: input to maxpool1
+ block0 = [
+ inception.Conv2d_1a_3x3,
+ inception.Conv2d_2a_3x3,
+ inception.Conv2d_2b_3x3,
+ nn.MaxPool2d(kernel_size=3, stride=2)
+ ]
+ self.blocks.append(nn.Sequential(*block0))
+
+ # Block 1: maxpool1 to maxpool2
+ if self.last_needed_block >= 1:
+ block1 = [
+ inception.Conv2d_3b_1x1,
+ inception.Conv2d_4a_3x3,
+ nn.MaxPool2d(kernel_size=3, stride=2)
+ ]
+ self.blocks.append(nn.Sequential(*block1))
+
+ # Block 2: maxpool2 to aux classifier
+ if self.last_needed_block >= 2:
+ block2 = [
+ inception.Mixed_5b,
+ inception.Mixed_5c,
+ inception.Mixed_5d,
+ inception.Mixed_6a,
+ inception.Mixed_6b,
+ inception.Mixed_6c,
+ inception.Mixed_6d,
+ inception.Mixed_6e,
+ ]
+ self.blocks.append(nn.Sequential(*block2))
+
+ # Block 3: aux classifier to final avgpool
+ if self.last_needed_block >= 3:
+ block3 = [
+ inception.Mixed_7a,
+ inception.Mixed_7b,
+ inception.Mixed_7c,
+ nn.AdaptiveAvgPool2d(output_size=(1, 1))
+ ]
+ self.blocks.append(nn.Sequential(*block3))
+
+ for param in self.parameters():
+ param.requires_grad = requires_grad
+
+ def forward(self, inp):
+ """Get Inception feature maps
+ Parameters
+ ----------
+ inp : torch.autograd.Variable
+ Input tensor of shape Bx3xHxW. Values are expected to be in
+ range (0, 1)
+ Returns
+ -------
+ List of torch.autograd.Variable, corresponding to the selected output
+ block, sorted ascending by index
+ """
+ outp = []
+ x = inp
+
+ if self.resize_input:
+ raise ValueError("should not resize here")
+ x = F.interpolate(x, size=(299, 299), mode='bilinear', align_corners=False)
+
+ if self.normalize_input:
+ x = 2 * x - 1 # Scale from range (0, 1) to range (-1, 1)
+
+ for idx, block in enumerate(self.blocks):
+ x = block(x)
+ if idx in self.output_blocks:
+ outp.append(x)
+
+ if idx == self.last_needed_block:
+ break
+
+ return outp
+
+
+def _inception_v3(*args, **kwargs):
+ """Wraps `torchvision.models.inception_v3`
+ Skips default weight inititialization if supported by torchvision version.
+ See https://github.com/mseitzer/pytorch-fid/issues/28.
+ """
+ try:
+ version = tuple(map(int, torchvision.__version__.split('.')[:2]))
+ except ValueError:
+ # Just a caution against weird version strings
+ version = (0,)
+
+ if version >= (0, 6):
+ kwargs['init_weights'] = False
+
+ return torchvision.models.inception_v3(*args, **kwargs)
+
+
+def fid_inception_v3():
+ """Build pretrained Inception model for FID computation
+ The Inception model for FID computation uses a different set of weights
+ and has a slightly different structure than torchvision's Inception.
+ This method first constructs torchvision's Inception and then patches the
+ necessary parts that are different in the FID Inception model.
+ """
+ inception = _inception_v3(num_classes=1008,
+ aux_logits=False,
+ pretrained=False)
+ inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
+ inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
+ inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
+ inception.Mixed_6b = FIDInceptionC(768, channels_7x7=128)
+ inception.Mixed_6c = FIDInceptionC(768, channels_7x7=160)
+ inception.Mixed_6d = FIDInceptionC(768, channels_7x7=160)
+ inception.Mixed_6e = FIDInceptionC(768, channels_7x7=192)
+ inception.Mixed_7b = FIDInceptionE_1(1280)
+ inception.Mixed_7c = FIDInceptionE_2(2048)
+
+ state_dict = load_state_dict_from_url(FID_WEIGHTS_URL, progress=True)
+ inception.load_state_dict(state_dict)
+ return inception
+
+
+class FIDInceptionA(torchvision.models.inception.InceptionA):
+ """InceptionA block patched for FID computation"""
+ def __init__(self, in_channels, pool_features):
+ super(FIDInceptionA, self).__init__(in_channels, pool_features)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch5x5 = self.branch5x5_1(x)
+ branch5x5 = self.branch5x5_2(branch5x5)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = self.branch3x3dbl_3(branch3x3dbl)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch5x5, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionC(torchvision.models.inception.InceptionC):
+ """InceptionC block patched for FID computation"""
+ def __init__(self, in_channels, channels_7x7):
+ super(FIDInceptionC, self).__init__(in_channels, channels_7x7)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch7x7 = self.branch7x7_1(x)
+ branch7x7 = self.branch7x7_2(branch7x7)
+ branch7x7 = self.branch7x7_3(branch7x7)
+
+ branch7x7dbl = self.branch7x7dbl_1(x)
+ branch7x7dbl = self.branch7x7dbl_2(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_3(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_4(branch7x7dbl)
+ branch7x7dbl = self.branch7x7dbl_5(branch7x7dbl)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch7x7, branch7x7dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionE_1(torchvision.models.inception.InceptionE):
+ """First InceptionE block patched for FID computation"""
+ def __init__(self, in_channels):
+ super(FIDInceptionE_1, self).__init__(in_channels)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch3x3 = self.branch3x3_1(x)
+ branch3x3 = [
+ self.branch3x3_2a(branch3x3),
+ self.branch3x3_2b(branch3x3),
+ ]
+ branch3x3 = torch.cat(branch3x3, 1)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = [
+ self.branch3x3dbl_3a(branch3x3dbl),
+ self.branch3x3dbl_3b(branch3x3dbl),
+ ]
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
+
+ # Patch: Tensorflow's average pool does not use the padded zero's in
+ # its average calculation
+ branch_pool = F.avg_pool2d(x, kernel_size=3, stride=1, padding=1,
+ count_include_pad=False)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
+
+
+class FIDInceptionE_2(torchvision.models.inception.InceptionE):
+ """Second InceptionE block patched for FID computation"""
+ def __init__(self, in_channels):
+ super(FIDInceptionE_2, self).__init__(in_channels)
+
+ def forward(self, x):
+ branch1x1 = self.branch1x1(x)
+
+ branch3x3 = self.branch3x3_1(x)
+ branch3x3 = [
+ self.branch3x3_2a(branch3x3),
+ self.branch3x3_2b(branch3x3),
+ ]
+ branch3x3 = torch.cat(branch3x3, 1)
+
+ branch3x3dbl = self.branch3x3dbl_1(x)
+ branch3x3dbl = self.branch3x3dbl_2(branch3x3dbl)
+ branch3x3dbl = [
+ self.branch3x3dbl_3a(branch3x3dbl),
+ self.branch3x3dbl_3b(branch3x3dbl),
+ ]
+ branch3x3dbl = torch.cat(branch3x3dbl, 1)
+
+ # Patch: The FID Inception model uses max pooling instead of average
+ # pooling. This is likely an error in this specific Inception
+ # implementation, as other Inception models use average pooling here
+ # (which matches the description in the paper).
+ branch_pool = F.max_pool2d(x, kernel_size=3, stride=1, padding=1)
+ branch_pool = self.branch_pool(branch_pool)
+
+ outputs = [branch1x1, branch3x3, branch3x3dbl, branch_pool]
+ return torch.cat(outputs, 1)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_torchscript.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_torchscript.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb9645dd6236d88d69132e88c2b45620f3b93f03
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/inception_torchscript.py
@@ -0,0 +1,41 @@
+import os
+import torch
+import torch.nn as nn
+from tool.metrics.downloads_helper import check_download_inception
+
+
+class InceptionV3W(nn.Module):
+ """
+ Wrapper around Inception V3 torchscript model provided here
+ https://nvlabs-fi-cdn.nvidia.com/stylegan2-ada-pytorch/pretrained/metrics/inception-2015-12-05.pt
+ path: locally saved inception weights
+ """
+
+ def __init__(self, path, download=True, resize_inside=False):
+ super(InceptionV3W, self).__init__()
+ # download the network if it is not present at the given directory
+ # use the current directory by default
+ if download:
+ check_download_inception(fpath=path)
+ path = os.path.join(path, "inception-2015-12-05.pt")
+ self.base = torch.jit.load(path).eval()
+ self.layers = self.base.layers
+ self.resize_inside = resize_inside
+
+
+ """
+ Get the inception features without resizing
+ x: Image with values in range [0,255]
+ """
+ def forward(self, x):
+ bs = x.shape[0]
+ if self.resize_inside:
+ features = self.base(x, return_features=True).view((bs, 2048))
+ else:
+ # make sure it is resized already
+ assert (x.shape[2] == 299) and (x.shape[3] == 299)
+ # apply normalization
+ x1 = x - 128
+ x2 = x1 / 128
+ features = self.layers.forward(x2, ).view((bs, 2048))
+ return features
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/leaderboard.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/leaderboard.py
new file mode 100644
index 0000000000000000000000000000000000000000..5db5b87eb78d97904b3e00e8b61d2190c9cb673d
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/leaderboard.py
@@ -0,0 +1,41 @@
+import os
+import csv
+import shutil
+import urllib.request
+
+def get_score(model_name=None, dataset_name=None,
+ dataset_res=None, dataset_split=None, task_name=None):
+ # download the csv file from server
+ url = "https://www.cs.cmu.edu/~clean-fid/files/leaderboard.csv"
+ local_path = "/tmp/leaderboard.csv"
+ with urllib.request.urlopen(url) as response, open(local_path, 'wb') as f:
+ shutil.copyfileobj(response, f)
+
+ d_field2idx = {}
+ l_matches = []
+ with open(local_path, 'r') as f:
+ csvreader = csv.reader(f)
+ l_fields = next(csvreader)
+ for idx, val in enumerate(l_fields):
+ d_field2idx[val.strip()]=idx
+ # iterate through all rows
+ for row in csvreader:
+ # skip empty rows
+ if len(row)==0: continue
+ # skip if the filter doesn't match
+ if model_name is not None and (row[d_field2idx["model_name"]].strip() != model_name):
+ continue
+ if dataset_name is not None and (row[d_field2idx["dataset_name"]].strip() != dataset_name):
+ continue
+ if dataset_res is not None and (row[d_field2idx["dataset_res"]].strip() != dataset_res):
+ continue
+ if dataset_split is not None and (row[d_field2idx["dataset_split"]].strip() != dataset_split):
+ continue
+ if task_name is not None and (row[d_field2idx["task_name"]].strip() != task_name):
+ continue
+ curr = {}
+ for f in l_fields:
+ curr[f.strip()] = row[d_field2idx[f.strip()]].strip()
+ l_matches.append(curr)
+ os.remove(local_path)
+ return l_matches
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/metric_center.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/metric_center.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cac00d95f9115750f709809ae20c1ae1e217deb
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/metric_center.py
@@ -0,0 +1,914 @@
+# -*- encoding: utf-8 -*-
+'''
+@Time :2021/10/13 15:32:28
+@Author :Yongfei Liu
+@Email :liuyf3@shanghaitech.edu.cn
+
+
+## support FID-K(Gassian Blur), IS, FID-Img(from video to image), FID-ViD(3DRN50), FVD(Inception3D)
+'''
+import sys
+from pathlib import Path
+
+import os
+import random
+from tqdm import tqdm
+from glob import glob
+import torch
+import numpy as np
+from scipy import linalg
+from PIL import Image
+import os.path as osp
+import torch.nn.functional as F
+import glob
+import json
+import os
+import sys
+pythonpath = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+print(pythonpath)
+sys.path.insert(0, pythonpath)
+from tool.metrics.utils import ResizeDataset, EXTENSIONS, ResizeDatasetBlur, ResizeDatasetInceptionScoreBlur, ResizeDatasetFIDVideoBlur
+from tool.metrics.utils import DatasetFVDVideoResize, DatasetFVDVideoFromFramesResize
+from tool.metrics.features import build_feature_extractor, get_reference_statistics
+from tool.metrics.resize import build_resizer
+from tool.metrics.ssim_l1_lpips_psnr import compute_ssim_l1_psnr, compute_lpips
+import json
+
+"""
+Compute the FID score given the mu, sigma of two sets
+"""
+
+
+def frechet_distance(mu1, sigma1, mu2, sigma2, eps=1e-6):
+ """Numpy implementation of the Frechet Distance.
+ The Frechet distance between two multivariate Gaussians X_1 ~ N(mu_1, C_1)
+ and X_2 ~ N(mu_2, C_2) is
+ d^2 = ||mu_1 - mu_2||^2 + Tr(C_1 + C_2 - 2*sqrt(C_1*C_2)).
+ Stable version by Danica J. Sutherland.
+ Params:
+ -- mu1 : Numpy array containing the activations of a layer of the
+ inception net (like returned by the function 'get_predictions')
+ for generated samples.
+ -- mu2 : The sample mean over activations, precalculated on an
+ representative data set.
+ -- sigma1: The covariance matrix over activations for generated samples.
+ -- sigma2: The covariance matrix over activations, precalculated on an
+ representative data set.
+ Returns:
+ -- : The Frechet Distance.
+ """
+ mu1 = np.atleast_1d(mu1)
+ mu2 = np.atleast_1d(mu2)
+ sigma1 = np.atleast_2d(sigma1)
+ sigma2 = np.atleast_2d(sigma2)
+
+ assert mu1.shape == mu2.shape, 'Training and test mean vectors have different lengths'
+ assert sigma1.shape == sigma2.shape, 'Training and test covariances have different dimensions'
+
+ diff = mu1 - mu2
+
+ # Product might be almost singular
+ covmean, _ = linalg.sqrtm(sigma1.dot(sigma2), disp=False)
+ if not np.isfinite(covmean).all():
+ msg = ('fid calculation produces singular product; adding %s to diagonal of cov estimates') % eps
+ print(msg)
+ offset = np.eye(sigma1.shape[0]) * eps
+ covmean = linalg.sqrtm((sigma1 + offset).dot(sigma2 + offset))
+
+ # Numerical error might give slight imaginary component
+ if np.iscomplexobj(covmean):
+ if not np.allclose(np.diagonal(covmean).imag, 0, atol=1e-3):
+ m = np.max(np.abs(covmean.imag))
+ raise ValueError('Imaginary component {}'.format(m))
+ covmean = covmean.real
+
+ tr_covmean = np.trace(covmean)
+ return (diff.dot(diff) + np.trace(sigma1) + np.trace(sigma2) - 2 * tr_covmean)
+
+
+"""
+Compute the KID score given the sets of features
+"""
+
+
+def kernel_distance(feats1, feats2, num_subsets=100, max_subset_size=1000):
+ n = feats1.shape[1]
+ m = min(min(feats1.shape[0], feats2.shape[0]), max_subset_size)
+ t = 0
+ for _subset_idx in range(num_subsets):
+ x = feats2[np.random.choice(feats2.shape[0], m, replace=False)]
+ y = feats1[np.random.choice(feats1.shape[0], m, replace=False)]
+ a = (x @ x.T / n + 1) ** 3 + (y @ y.T / n + 1) ** 3
+ b = (x @ y.T / n + 1) ** 3
+ t += (a.sum() - np.diag(a).sum()) / (m - 1) - b.sum() * 2 / m
+ kid = t / num_subsets / m
+ return float(kid)
+
+
+"""
+Compute the inception features for a batch of images
+"""
+
+
+def get_batch_features(batch, model, device):
+ if model is None:
+ return batch.numpy()
+ with torch.no_grad():
+ feat = model(batch.to(device))
+ return feat.detach().cpu().numpy()
+
+
+"""
+Compute the inception features for a list of files
+"""
+
+
+def get_files_features(l_files, batch_size, num_workers, model=None, device=torch.device("cuda"), mode="clean", custom_fn_resize=None, description=""):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+
+ # build resizing function based on options
+ if custom_fn_resize is not None:
+ fn_resize = custom_fn_resize
+ else:
+ fn_resize = build_resizer(mode)
+
+ # wrap the images in a dataloader for parallelizing the resize operation
+ dataset = ResizeDataset(l_files, fn_resize=fn_resize)
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=False)
+
+ # collect all inception features
+ l_feats = []
+ for batch in tqdm(dataloader, desc=description):
+ l_feats.append(get_batch_features(batch, model, device))
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+"""
+Compute the inception features for a folder of features
+"""
+
+
+def get_folder_features(fdir, batch_size, num_workers, model=None, num=None,
+ shuffle=False, seed=0, device=torch.device("cuda"),
+ mode="clean", custom_fn_resize=None, description=""):
+ # get all relevant files in the dataset
+ # = sorted([file for ext in EXTENSIONS for file in glob(os.path.join(fdir, f"**/*.{ext}"), recursive=True)])
+ files = []
+ for ext in EXTENSIONS:
+ for file in glob(os.path.join(fdir, f"**/*.{ext}"), recursive=True):
+ try:
+ image = Image.open(str(file))
+ image.verify()
+ image.close()
+ files.append(file)
+ except:
+ print('{} can not open'.format(file))
+ continue
+ files = sorted(files)
+
+ print(f"Found {len(files)} images in the folder {fdir}")
+ # use a subset number of files if needed
+ if num is not None:
+ if shuffle:
+ random.seed(seed)
+ random.shuffle(files)
+ files = files[:num]
+ np_feats = get_files_features(files, model, batch_size=batch_size, num_workers=num_workers, device=device,
+ mode=mode,
+ custom_fn_resize=custom_fn_resize,
+ description=description)
+ return np_feats
+
+
+"""
+Compute the FID score given the inception features stack
+"""
+
+
+def fid_from_feats(feats1, feats2):
+ mu1, sig1 = np.mean(feats1, axis=0), np.cov(feats1, rowvar=False)
+ mu2, sig2 = np.mean(feats2, axis=0), np.cov(feats2, rowvar=False)
+ return frechet_distance(mu1, sig1, mu2, sig2)
+
+
+"""
+Computes the FID score for a folder of images for a specific dataset
+and a specific resolution
+"""
+
+
+def fid_folder(fdir, dataset_name, dataset_res, dataset_split, batch_size, num_workers, model=None, mode="clean",
+ device=torch.device("cuda")):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split)
+ fbname = os.path.basename(fdir)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir, model, batch_size=batch_size, num_workers=num_workers,
+ device=device,
+ mode=mode, description=f"FID {fbname} : ")
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+
+"""
+Compute the FID stats from a generator model
+"""
+
+
+def get_model_features(G, model, batch_size, mode="clean", z_dim=512,
+ num_gen=50_000,
+ device=torch.device("cuda"), desc="FID model: "):
+ fn_resize = build_resizer(mode)
+ # Generate test features
+ num_iters = int(np.ceil(num_gen / batch_size))
+ l_feats = []
+ for idx in tqdm(range(num_iters), desc=desc):
+ with torch.no_grad():
+ z_batch = torch.randn((batch_size, z_dim)).to(device)
+ # generated image is in range [0,255]
+ img_batch = G(z_batch)
+ # split into individual batches for resizing if needed
+ if mode != "legacy_tensorflow":
+ resized_batch = torch.zeros(batch_size, 3, 299, 299)
+ for idx in range(batch_size):
+ curr_img = img_batch[idx]
+ img_np = curr_img.cpu().numpy().transpose((1, 2, 0))
+ img_resize = fn_resize(img_np)
+ resized_batch[idx] = torch.tensor(
+ img_resize.transpose((2, 0, 1)))
+ else:
+ resized_batch = img_batch
+ feat = get_batch_features(resized_batch, model, device)
+ l_feats.append(feat)
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+"""
+Computes the FID score for a generator model for a specific dataset
+and a specific resolution
+"""
+
+
+def fid_model(G, dataset_name, dataset_res, dataset_split, batch_size, num_workers,
+ model=None, z_dim=512, num_gen=50_000,
+ mode="clean",
+ device=torch.device("cuda")):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+ # Load reference FID statistics (download if needed)
+ ref_mu, ref_sigma = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split)
+ # build resizing function based on options
+ fn_resize = build_resizer(mode)
+
+ # Generate test features
+ np_feats = get_model_features(G, model, batch_size=batch_size, mode=mode,
+ z_dim=z_dim, num_gen=num_gen,
+ device=device)
+
+ mu = np.mean(np_feats, axis=0)
+ sigma = np.cov(np_feats, rowvar=False)
+ fid = frechet_distance(mu, sigma, ref_mu, ref_sigma)
+ return fid
+
+
+"""
+Computes the FID score between the two given folders
+"""
+
+
+def compare_folders(fdir1, fdir2, feat_model, mode, batch_size, num_workers,
+ device=torch.device("cuda")):
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, feat_model, batch_size=batch_size, num_workers=num_workers,
+ device=device, mode=mode,
+ description=f"FID {fbname1} : ")
+ mu1 = np.mean(np_feats1, axis=0)
+ sigma1 = np.cov(np_feats1, rowvar=False)
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, feat_model, batch_size=batch_size, num_workers=num_workers,
+ device=device, mode=mode,
+ description=f"FID {fbname2} : ")
+ mu2 = np.mean(np_feats2, axis=0)
+ sigma2 = np.cov(np_feats2, rowvar=False)
+ fid = frechet_distance(mu1, sigma1, mu2, sigma2)
+ return fid
+
+
+def compute_kid(batch_size, num_workers, fdir1=None, fdir2=None, gen=None,
+ mode="clean",
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512):
+ # build the feature extractor based on the mode
+ feat_model = build_feature_extractor(mode, device)
+
+ # if both dirs are specified, compute KID between folders
+ if fdir1 is not None and fdir2 is not None:
+ print("compute KID between two folders")
+ # get all inception features for the first folder
+ fbname1 = os.path.basename(fdir1)
+ np_feats1 = get_folder_features(fdir1, None, batch_size=batch_size, num_workers=num_workers,
+ device=device, mode=mode,
+ description=f"KID {fbname1} : ")
+ # get all inception features for the second folder
+ fbname2 = os.path.basename(fdir2)
+ np_feats2 = get_folder_features(fdir2, None, batch_size=batch_size, num_workers=num_workers,
+ device=device, mode=mode,
+ description=f"KID {fbname2} : ")
+ score = kernel_distance(np_feats1, np_feats2)
+ return score
+
+ # compute kid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ print(f"compute KID of a folder with {dataset_name} statistics")
+ # define the model if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ fbname = os.path.basename(fdir1)
+ # get all inception features for folder images
+ np_feats = get_folder_features(fdir1, model, batch_size=batch_size, num_workers=num_workers,
+ device=device,
+ mode=mode, description=f"KID {fbname} : ")
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ print(
+ f"compute KID of a model with {dataset_name}-{dataset_res} statistics")
+ # define the model if it is not specified
+ model = build_feature_extractor(mode, device)
+ ref_feats = get_reference_statistics(dataset_name, dataset_res,
+ mode=mode, seed=0, split=dataset_split, metric="KID")
+ # build resizing function based on options
+ fn_resize = build_resizer(mode)
+ # Generate test features
+ np_feats = get_model_features(gen, model, batch_size=batch_size, mode=mode,
+ z_dim=z_dim, num_gen=num_gen, desc="KID model: ",
+ device=device)
+ score = kernel_distance(ref_feats, np_feats)
+ return score
+
+ else:
+ raise ValueError(f"invalid combination of directories and models entered")
+
+
+def compute_fid(batch_size, num_workers, fdir1=None, fdir2=None, gen=None,
+ mode="clean",
+ device=torch.device("cuda"), dataset_name="FFHQ",
+ dataset_res=1024, dataset_split="train", num_gen=50_000, z_dim=512):
+ # build the feature extractor based on the mode
+ feat_model = build_feature_extractor(mode, device)
+
+ # if both dirs are specified, compute FID between folders
+ if fdir1 is not None and fdir2 is not None:
+ print("compute FID between two folders")
+ score = compare_folders(fdir1, fdir2, feat_model, batch_size=batch_size, num_workers=num_workers,
+ mode=mode,
+ device=device)
+ return score
+
+ # compute fid of a folder
+ elif fdir1 is not None and fdir2 is None:
+ print(f"compute FID of a folder with {dataset_name} statistics")
+ score = fid_folder(fdir1, dataset_name, dataset_res, dataset_split, batch_size=batch_size, num_workers=num_workers,
+ model=feat_model, mode=mode,
+ device=device)
+ return score
+
+ # compute fid for a generator
+ elif gen is not None:
+ print(f"compute FID of a model with {dataset_name}-{dataset_res} statistics")
+ score = fid_model(gen, dataset_name, dataset_res, dataset_split, batch_size=batch_size, num_workers=num_workers,
+ model=feat_model, z_dim=z_dim, num_gen=num_gen,
+ mode=mode,
+ device=device)
+ return score
+
+ else:
+ raise ValueError("invalid combination of directories and models entered")
+
+
+def get_files_features_blur(l_files, batch_size, num_workers, model=None, device=torch.device("cuda"), mode="clean", custom_fn_resize=None, description=""):
+ # define the model if it is not specified
+ if model is None:
+ model = build_feature_extractor(mode, device)
+
+ # build resizing function based on options
+ if custom_fn_resize is not None:
+ fn_resize = custom_fn_resize
+ else:
+ fn_resize = build_resizer(mode)
+
+ # wrap the images in a dataloader for parallelizing the resize operation
+ dataset = ResizeDataset(l_files, fn_resize=fn_resize)
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=False)
+
+ # collect all inception features
+ l_feats = []
+ for batch in tqdm(dataloader, desc=description):
+ l_feats.append(get_batch_features(batch, model, device))
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+def compute_net_prediction(dataset, feat_model, batch_size, num_workers):
+
+ # fn_resize = build_resizer(mode='clean')
+
+ # wrap the images in a dataloader for parallelizing the resize operation
+ # dataset = ResizeDatasetBlur(inst_name_full, fn_resize=fn_resize, )
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=False)
+
+ # collect all inception features
+ l_feats = []
+ for batch in tqdm(dataloader, desc='start load the feature'):
+ l_feats.append(get_batch_features(batch, feat_model, torch.device('cuda')))
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+def compute_net_vid_prediction(dataset, feat_model, batch_size, num_workers):
+
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=False)
+
+ # collect all inception features
+ l_feats = []
+ num_frame = 0
+ batch_assemble = []
+ for batch in tqdm(dataloader, desc='start load the feature'):
+ batch = batch.squeeze(0)
+ num_frame += batch.shape[0]
+ batch_assemble.append(batch)
+ if num_frame >= batch_size:
+ batch_s = torch.cat(batch_assemble, dim=0)
+ l_feats.append(get_batch_features(batch_s, feat_model, torch.device('cuda')))
+ batch_assemble = []
+ num_frame = 0
+ else:
+ batch_assemble.append(batch)
+
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+def compute_3d_video_prediction(dataset, feat_model, batch_size, num_workers):
+
+ dataloader = torch.utils.data.DataLoader(dataset, batch_size=batch_size, num_workers=num_workers, shuffle=False, drop_last=False)
+ assert batch_size == 1
+ # collect all inception features
+ l_feats = []
+
+ for batch in tqdm(dataloader, desc='start load the feature'):
+
+ batch = batch.squeeze(0)
+ l_feats.append(get_batch_features(batch, feat_model, torch.device('cuda')).mean(0, keepdims=True)) # one video is split into multiple segment, we need average every segments
+
+ np_feats = np.concatenate(l_feats)
+ return np_feats
+
+
+def compute_fid_folder_scores(gen_inst_name_full, gt_inst_name_full, feat_model, is_blur_img, gaussian_blur_kernel, batch_size, num_workers):
+
+ fn_resize = build_resizer(mode='clean')
+
+ dataset_gen = ResizeDatasetBlur(gen_inst_name_full, fn_resize=fn_resize, is_blur=is_blur_img, gaussian_kernel=gaussian_blur_kernel)
+ np_feats_gen = compute_net_prediction(dataset_gen, feat_model, batch_size=batch_size, num_workers=num_workers)
+
+ dataset_gt = ResizeDatasetBlur(gt_inst_name_full, fn_resize=fn_resize, is_blur=is_blur_img, gaussian_kernel=gaussian_blur_kernel)
+ np_feats_gt = compute_net_prediction(dataset_gt, feat_model, batch_size=batch_size, num_workers=num_workers)
+
+ fid_score = fid_from_feats(feats1=np_feats_gen, feats2=np_feats_gt)
+
+ return fid_score
+
+
+def compute_video_fid_folder_scores(gen_inst_name_full, gt_inst_name_full, feat_model, is_blur_img, gaussian_blur_kernel, sample_frames, is_sample_frames, batch_size, num_workers):
+
+ fn_resize = build_resizer(mode='clean')
+
+ dataset_gen = ResizeDatasetFIDVideoBlur(gen_inst_name_full, fn_resize=fn_resize, is_blur=is_blur_img, gaussian_kernel=gaussian_blur_kernel,
+ is_sample_frames=is_sample_frames, sample_frames=sample_frames)
+ np_feats_gen = compute_net_vid_prediction(dataset_gen, feat_model, batch_size=batch_size, num_workers = num_workers)
+
+ dataset_gt = ResizeDatasetFIDVideoBlur(gt_inst_name_full, fn_resize=fn_resize, is_blur=is_blur_img, gaussian_kernel=gaussian_blur_kernel,
+ is_sample_frames=is_sample_frames, sample_frames=sample_frames)
+ np_feats_gt = compute_net_vid_prediction(dataset_gt, feat_model, batch_size=batch_size, num_workers = num_workers)
+ fid_score = fid_from_feats(feats1=np_feats_gen, feats2=np_feats_gt)
+
+ return fid_score
+
+
+def compute_inception_scores(gen_inst_name_full, feat_model, is_blur_img, gaussian_blur_kernel, batch_size, num_workers, num_splits=1):
+
+ fn_resize = build_resizer(mode='clean')
+
+ dataset_gen = ResizeDatasetInceptionScoreBlur(gen_inst_name_full, fn_resize=fn_resize, is_blur=is_blur_img, gaussian_kernel=gaussian_blur_kernel)
+ np_pred_logit_gen = compute_net_prediction(dataset_gen, feat_model, batch_size=batch_size, num_workers=num_workers)
+
+ preds = F.softmax(torch.as_tensor(np_pred_logit_gen), dim=1)
+ N = preds.shape[0]
+ split_scores = []
+ for k in range(num_splits):
+ part = preds[k * (N // num_splits): (k+1) * (N // num_splits), :]
+ pmean = part.mean(0, keepdim=True)
+ scores = (part * (part.log() - pmean.log())).sum(1).numpy()
+ split_scores.append(np.exp(np.mean(scores)))
+ # part = part.numpy()
+ # pmean = pmean.numpy()
+ # kl = part * (np.log(part) - np.log(pmean))
+ # kl = np.mean(np.sum(kl, 1))
+ # split_scores.append(np.exp(kl))
+
+ return np.mean(split_scores), np.std(split_scores)
+
+
+def compute_fid_video_scores(gen_inst_name_full, gt_inst_name_full, feat_model, mode, sample_duration, batch_size, num_workers):
+
+ if mode == "FVD-3DRN50":
+ sample_size = 112
+ elif mode == "FVD-3DInception":
+ sample_size = 224
+ elif mode == 'MAE':
+ sample_size = 224
+ else:
+ raise NotImplementedError
+
+ if Path(gen_inst_name_full[0]).suffix in [".mp4", ".gif"]:
+ print("Using raw video gen dataset for FVD computation, first file suffix: ", Path(gen_inst_name_full[0]).suffix)
+ dataset_gen = DatasetFVDVideoResize(gen_inst_name_full, sample_duration, mode, sample_size)
+ else:
+ print("Using frame gen dataset for FVD computation, first file suffix: ", Path(gen_inst_name_full[0]).suffix)
+ dataset_gen = DatasetFVDVideoFromFramesResize(gen_inst_name_full, sample_duration, mode, sample_size)
+
+ np_feats_gen = compute_3d_video_prediction(dataset_gen, feat_model, batch_size=batch_size, num_workers=num_workers)
+
+ if Path(gt_inst_name_full[0]).suffix in [".mp4", ".gif"]:
+ print("Using raw video gt dataset for FVD computation, first file suffix: ", Path(gt_inst_name_full[0]).suffix)
+ dataset_gt = DatasetFVDVideoResize(gt_inst_name_full, sample_duration, mode, sample_size)
+ else:
+ print("Using frame gt dataset for FVD computation, first file suffix: ", Path(gt_inst_name_full[0]).suffix)
+ dataset_gt = DatasetFVDVideoFromFramesResize(gt_inst_name_full, sample_duration, mode, sample_size)
+
+ np_feats_gt = compute_3d_video_prediction(dataset_gt, feat_model, batch_size=batch_size, num_workers=num_workers)
+ if mode == 'MAE':
+ fid_score = np.abs((np_feats_gen - np_feats_gt)).mean()
+ else:
+ fid_score = fid_from_feats(feats1=np_feats_gen, feats2=np_feats_gt)
+
+ return fid_score
+
+
+def compute_dtssd_video_scores(gen_inst_name_full, gt_inst_name_full, sample_duration):
+ sample_size = 256
+
+ if Path(gen_inst_name_full[0]).suffix in [".jpg", ".png"]:
+ print("Using frame gen dataset for dtssd computation, first file suffix: ", Path(gen_inst_name_full[0]).suffix)
+ dataset_gen = DatasetFVDVideoFromFramesResize(gen_inst_name_full, 2, None, sample_size, return_name=True)
+ else:
+ print("Using raw video gen dataset for dtssd computation, first file suffix: ", Path(gen_inst_name_full[0]).suffix)
+ dataset_gen = DatasetFVDVideoResize(gen_inst_name_full, sample_duration, None, sample_size, return_name=True)
+
+ if Path(gt_inst_name_full[0]).suffix in [".jpg", ".png"]:
+ print("Using frame gt dataset for dtssd computation, first file suffix: ", Path(gt_inst_name_full[0]).suffix)
+ dataset_gt = DatasetFVDVideoFromFramesResize(gt_inst_name_full, 2, None, sample_size, return_name=True)
+ else:
+ print("Using raw video gt dataset for dtssd computation, first file suffix: ", Path(gt_inst_name_full[0]).suffix)
+ dataset_gt = DatasetFVDVideoResize(gt_inst_name_full, sample_duration, None, sample_size, return_name=True)
+
+ dtssd_list = []
+ cnt = 0
+ print("length of dataset_gen: ", len(dataset_gen), "length of dataset_gt: ", len(dataset_gt))
+ pbar = tqdm(zip(dataset_gen, dataset_gt), desc="computing dtssd", total=len(dataset_gen))
+ for (gen_video_tuple, gt_video_tuple) in pbar:
+ gen_video, gen_name = gen_video_tuple
+ gt_video, gt_name = gt_video_tuple
+ if gen_name != gt_name:
+ print(f"gen_name: {gen_name}, gt_name: {gt_name} failed to compute dtssd")
+ break
+ else:
+ pbar.set_description(f"computing dtssd for {gen_name} and {gt_name}")
+
+ gen_diff = gen_video[1] - gen_video[0]
+ gt_diff = gt_video[1] - gt_video[0]
+
+ dtssd = ((gen_diff - gt_diff) ** 2).mean()
+ dtssd_list.append(dtssd.item())
+ cnt += 1
+
+ print("compute dtssd over {} videos".format(cnt))
+ dtssd = np.mean(np.array(dtssd_list))
+ return dtssd
+
+
+def evaluation_visual_creation(
+ gen_inst_names_full, batch_size, num_workers,
+ root_dir, gt_inst_names_full=None, metric="FID",
+ gaussian_blur_kernel=0, num_splits=1, is_sample_frame=False,
+ number_sample_frames=1, sample_duration=16):
+ """
+ gen_inst_path: the generated image/video path, "/dataspace/MSCOCO/train2014"
+ gen_inst_names: list of image/video name ['xxx.jpg', 'xxx.jpg']
+ gt_inst_path: the groundtruth image path
+ gt_inst_names: the groundtruth image names
+
+ gaussian_blur_kernel: the parameter to control the
+
+ """
+
+ device = torch.device('cuda')
+
+ assert gaussian_blur_kernel >= 0
+ if metric == "FID":
+ is_blur_img = True
+ if gaussian_blur_kernel == 0:
+ is_blur_img = False
+
+ feat_model = build_feature_extractor(mode='clean', root_dir=root_dir, device=device)
+ # print(f"evaluation_gen_path:{gen_inst_path}")
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image')
+ FID_score = compute_fid_folder_scores(
+ gen_inst_names_full, gt_inst_names_full,
+ feat_model, batch_size=batch_size, num_workers=num_workers,
+ is_blur_img=is_blur_img, gaussian_blur_kernel=gaussian_blur_kernel)
+
+ print(f"The FID_score {FID_score}, blur_image:{is_blur_img}, gaussian_kernel_size:{gaussian_blur_kernel}")
+ return {metric: FID_score}
+
+ elif metric == "FID-Img":
+ is_blur_img = False
+ gaussian_blur_kernel = 0
+ feat_model = build_feature_extractor(mode='clean', root_dir=root_dir, device=device)
+ print(f'start evluation FID-Img over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image')
+ FID_score = compute_video_fid_folder_scores(
+ gen_inst_names_full, gt_inst_names_full, feat_model,
+ is_blur_img, gaussian_blur_kernel, batch_size=batch_size,
+ num_workers=num_workers, is_sample_frames=is_sample_frame,
+ sample_frames=number_sample_frames)
+
+ print(f"The FID-Img:{FID_score}, is_blur:{is_blur_img}, gaussian_kernel:{gaussian_blur_kernel}, is_sample:{is_sample_frame}, num_sam_frame:{number_sample_frames}")
+ return {metric: FID_score}
+
+ elif metric == "IS":
+
+ is_blur_img = True
+ if gaussian_blur_kernel == 0:
+ is_blur_img = False
+
+ feat_model = build_feature_extractor(mode='clean_InceptionScore', root_dir=root_dir, device=device)
+ print(f'start evluation inception scores over {len(gen_inst_names_full)} generated Image')
+ IS_score_mean, IS_score_std = compute_inception_scores(
+ gen_inst_name_full=gen_inst_names_full, batch_size=batch_size,
+ num_workers=num_workers, feat_model=feat_model, is_blur_img=is_blur_img,
+ gaussian_blur_kernel=gaussian_blur_kernel, num_splits=num_splits)
+
+ print(f"The inception_score mean/std:{IS_score_mean}/{IS_score_std}={IS_score_mean/IS_score_std}, num_splits:{num_splits}, blur_image:{is_blur_img}, gaussian_kernel_size:{gaussian_blur_kernel}")
+ return {'IS_score_mean': IS_score_mean, 'IS_score_std': IS_score_std}
+
+ elif metric in ['FVD-3DRN50', "FVD-3DInception"]:
+
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image/Video')
+ feat_model = build_feature_extractor(mode=metric, root_dir=root_dir, device=device, sample_duration=sample_duration)
+ FVD_score = compute_fid_video_scores(
+ gen_inst_names_full, gt_inst_names_full, feat_model,
+ mode=metric, sample_duration=sample_duration,
+ batch_size=batch_size, num_workers=num_workers)
+
+ print(f"The {metric} {FVD_score}, duration:{sample_duration}")
+ return {metric: FVD_score}
+
+ elif metric == 'MAE':
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image/Video')
+ FVD_score = compute_fid_video_scores(
+ gen_inst_names_full, gt_inst_names_full, None,
+ mode=metric, sample_duration=sample_duration,
+ batch_size=batch_size, num_workers=num_workers)
+ print(f"The MAE_score {FVD_score}, duration:{sample_duration}")
+ return {metric: FVD_score}
+ elif metric in ['SSIM', 'L1', 'PSNR']:
+
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image/Video')
+ ssim_l1_score = compute_ssim_l1_psnr(
+ gen_inst_names_full, gt_inst_names_full,
+ mode=metric)
+
+ print(f"The {metric} {ssim_l1_score}")
+ return {metric: ssim_l1_score}
+ elif metric == 'LPIPS':
+
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image/Video')
+ lpips_score = compute_lpips(
+ gen_inst_names_full, gt_inst_names_full)
+
+ print(f"The {metric} {lpips_score}")
+ return {metric: lpips_score}
+ elif metric == "dtSSD":
+ print(f'start evluation {metric} over {len(gen_inst_names_full)} generated Image/Video and {len(gt_inst_names_full)} gt Image/Video')
+ dtssd_score = compute_dtssd_video_scores(gen_inst_names_full, gt_inst_names_full, sample_duration=sample_duration)
+ print(f"The {metric} {dtssd_score}")
+ return {metric: dtssd_score}
+ else:
+ print("we are not support the metric you specified, please contact me")
+ raise NotImplementedError
+
+
+def get_all_eval_scores(
+ root_dir, path_gen, path_gt, metrics,
+ batch_size=1, blur=0, number_sample_frames=8,
+ num_gen=None, num_gt=None, num_splits=1, sample_duration=8,
+ num_workers=16):
+ number_sample_frames = min(sample_duration, number_sample_frames)
+ if root_dir not in path_gen:
+ path_gen = os.path.join(root_dir, path_gen)
+ if root_dir not in path_gt:
+ path_gt = os.path.join(root_dir, path_gt)
+ gen_inst_names_v, gt_inst_names_v = [], []
+ gen_inst_names_i, gt_inst_names_i = [], []
+ res_all = {}
+ type2metric = {'fid-img': 'FID-Img', 'fid': 'FID', 'mae': 'MAE', "dtssd": "dtSSD",
+ 'fid-vid': "FVD-3DRN50", 'fvd': "FVD-3DInception", 'is': 'IS',
+ 'l1': 'L1', 'ssim': 'SSIM', 'lpips': 'LPIPS', 'psnr': 'PSNR'}
+ empty_gen_folder_v, empty_gt_folder_v = False, False
+ empty_gen_folder_i, empty_gt_folder_i = False, False
+ for type in metrics:
+ if type.lower() in ['fid-img', 'fvd', 'fid-vid', 'mae', "dtssd"]:
+ if empty_gen_folder_v or empty_gt_folder_v:
+ print(f"Empty gen/gt folder {path_gen}, {path_gt}")
+ break
+ if len(gen_inst_names_v) == 0:
+ gen_inst_names_v = glob.glob(f"{path_gen}/*.gif") + glob.glob(f"{path_gen}/*.mp4") + glob.glob(f"{path_gen}/*.png") + glob.glob(f"{path_gen}/*.jpg")
+ gt_inst_names_v = glob.glob(f"{path_gt}/*.gif") + glob.glob(f"{path_gt}/*.mp4") + glob.glob(f"{path_gt}/*.png") + glob.glob(f"{path_gt}/*.jpg")
+ gen_inst_names_v = [osp.basename(gen_inst) for gen_inst in gen_inst_names_v]
+ gen_inst_names_v.sort()
+ gt_inst_names_v = [osp.basename(gt_inst) for gt_inst in gt_inst_names_v]
+ gt_inst_names_v.sort()
+ if num_gen is not None:
+ gen_inst_names_v = gen_inst_names_v[:num_gen]
+ if num_gt is not None:
+ gt_inst_names_v = gt_inst_names_v[:num_gt]
+ empty_gen_folder_v = len(gen_inst_names_v) == 0
+ empty_gt_folder_v = len(gt_inst_names_v) == 0
+
+ if not empty_gen_folder_v:
+ gen_inst_names_full_v = []
+ for gen_name in tqdm(gen_inst_names_v, desc=f'load_gen for {metrics}'):
+ gen_inst_names_full_v.append(osp.join(path_gen, gen_name))
+ if not empty_gt_folder_v:
+ gt_inst_names_full_v = []
+ for gt_name in tqdm(gt_inst_names_v, desc=f'load_gt for {metrics}'):
+ gt_inst_names_full_v.append(osp.join(path_gt, gt_name))
+ elif type.lower() in ['fid', 'is', 'ssim', 'l1', 'lpips', 'psnr']:
+ if empty_gen_folder_i or empty_gt_folder_i:
+ break
+ if len(gen_inst_names_i) == 0:
+ gen_inst_names_i = glob.glob(f"{path_gen}/*.png")
+ gt_inst_names_i = glob.glob(f"{path_gt}/*.png")
+ gen_inst_names_i += glob.glob(f"{path_gen}/*.jpg")
+ gt_inst_names_i += glob.glob(f"{path_gt}/*.jpg")
+ gen_inst_names_i = [osp.basename(gen_inst) for gen_inst in gen_inst_names_i]
+ gen_inst_names_i.sort()
+ gt_inst_names_i = [osp.basename(gt_inst) for gt_inst in gt_inst_names_i]
+ gt_inst_names_i.sort()
+ if num_gen is not None:
+ gen_inst_names_i = gen_inst_names_i[:num_gen]
+ if num_gt is not None:
+ gt_inst_names_i = gt_inst_names_i[:num_gt]
+ empty_gen_folder_i = len(gen_inst_names_i) == 0
+ empty_gt_folder_i = len(gt_inst_names_i) == 0
+
+ if not empty_gen_folder_i:
+ gen_inst_names_full_i = []
+ for gen_name in tqdm(gen_inst_names_i, desc=f'load_gen for {metrics}'):
+ gen_inst_names_full_i.append(osp.join(path_gen, gen_name))
+ if not empty_gt_folder_i:
+ gt_inst_names_full_i = []
+ for gt_name in tqdm(gt_inst_names_i, desc=f'load_gt for {metrics}'):
+ gt_inst_names_full_i.append(osp.join(path_gt, gt_name))
+ elif type in ['clean-fid']:
+ print(f'skipping caching file path for {type}')
+ else:
+ print(f"we are not support the metric you specified: {type}")
+ break
+
+ # when calculating the FID, you need to specify:
+ # path_gen, gen_inst_names, path_gt, gt_inst_names,
+ # gaussian_blur_kernel = 0 means that we do not blur the images
+ # batch_size, the default value is 128, which is acceptable, you can scale it up.
+ if type == 'fid':
+ if empty_gen_folder_i or empty_gt_folder_i:
+ print(f"Empty gen/gt folder {path_gen}, {path_gt}")
+ break
+ fid_batch_size = min(batch_size, min(len(gen_inst_names_i), len(gt_inst_names_i)))
+ res = evaluation_visual_creation(
+ gen_inst_names_full_i, fid_batch_size,
+ num_workers, root_dir, gt_inst_names_full_i,
+ metric=type2metric[type], gaussian_blur_kernel=blur,
+ num_splits=-1,
+ is_sample_frame=False, number_sample_frames=1, sample_duration=-1)
+ elif type == 'clean-fid':
+ from cleanfid import fid
+ score = fid.compute_fid(path_gen, path_gt)
+ res = {'clean-fid': score}
+
+ # when calculating the Inception_score, you need to specify:
+ # path_gen, gen_inst_names,
+ # gaussian_blur_kernel = 0 means that we do not blur the images, the DALL-E also calcuate the IS-1, IS-2, ..., IS-K, you can change it.
+ # batch_size, the default value is 128, which is acceptable, you can scale it up.
+ # num_split, default is 1, cogview sets num_split=1, but DM-GAN sets num_split=10, you can change it as you want.
+ elif type == 'is':
+ if empty_gen_folder_i:
+ print(f"Empty gen folder {path_gen}")
+ break
+ is_batch_size = min(batch_size, len(gen_inst_names_i))
+ res = evaluation_visual_creation(
+ gen_inst_names_full_i, is_batch_size,
+ num_workers, root_dir, None, None, metric=type2metric[type],
+ gaussian_blur_kernel=blur, num_splits=num_splits,
+ is_sample_frame=False, number_sample_frames=1,
+ sample_duration=-1)
+
+ # when calculating the FID-img, you need to specify:
+ # path_gen, gen_inst_names, path_gt, gt_inst_names,
+ # gaussian_blur_kernel = 0 means that we do not blur the images, FID-1, FID-2, ..., FID-K, you can change it.
+ # batch_size, the default value is 128, which is acceptable, you can scale it up.
+ # is_sample_frame, if False, we calcuate all frames decoded from videos. num_sample_frames, the parameters you need to specify when you want to sample frames from video
+ elif type in ['fid-img', 'fid-vid', 'fvd', 'mae', "dtssd"]:
+ if empty_gen_folder_v or empty_gt_folder_v:
+ print(f"Empty gen/gt folder {path_gen}, {path_gt}")
+ break
+ v_batch_size = min(batch_size, min(
+ len(gen_inst_names_v), len(gt_inst_names_v)))
+ res = evaluation_visual_creation(
+ gen_inst_names_full_v, v_batch_size,
+ num_workers, root_dir, gt_inst_names_full_v,
+ metric=type2metric[type], gaussian_blur_kernel=blur, num_splits=-1,
+ is_sample_frame=False, number_sample_frames=number_sample_frames, sample_duration=sample_duration)
+ elif type in ['ssim', 'l1', 'psnr']:
+ if empty_gen_folder_i or empty_gt_folder_i:
+ print(f"Empty gen/gt folder {path_gen}, {path_gt}")
+ break
+ res = evaluation_visual_creation(
+ gen_inst_names_full_i, 1,
+ 0, root_dir, gt_inst_names_full_i,
+ metric=type2metric[type], gaussian_blur_kernel=0, num_splits=-1,
+ is_sample_frame=False, number_sample_frames=1, sample_duration=-1)
+ elif type in ['lpips']:
+ if empty_gen_folder_i or empty_gt_folder_i:
+ print(f"Empty gen/gt folder {path_gen}, {path_gt}")
+ break
+ lpips_batch_size = min(batch_size, min(
+ len(gen_inst_names_i), len(gt_inst_names_i)))
+ res = evaluation_visual_creation(
+ gen_inst_names_full_i, lpips_batch_size,
+ num_workers, root_dir, gt_inst_names_full_i,
+ metric=type2metric[type], gaussian_blur_kernel=blur,
+ num_splits=-1,
+ is_sample_frame=False, number_sample_frames=1, sample_duration=-1)
+ res_all.update(res)
+ return res_all
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--root_dir', type=str, default="/f_ndata/G")
+ parser.add_argument('--path_gen', type=str, default="sdm/SDM_KLF8_S512_MSCOCO/eval_visu/pred")
+ parser.add_argument('--path_gt', type=str, default="dataset/mscoco/val2017")
+ parser.add_argument('--num_gen', type=int, default=None)
+ parser.add_argument('--num_gt', type=int, default=None)
+ parser.add_argument('--type', type=str, default='fid', nargs="+")
+ parser.add_argument('--blur', type=int, default=0)
+ parser.add_argument('--num_splits', type=int, default=1)
+ parser.add_argument('--number_sample_frames', type=int, default=8)
+ parser.add_argument('--sample_duration', type=int, default=8)
+ parser.add_argument('--batch_size', type=int, default=1)
+ parser.add_argument('--num_workers', type=int, default=16)
+ parser.add_argument('--write_metric_to', type=str, default=None)
+
+ args = parser.parse_args()
+
+ res_all = get_all_eval_scores(
+ root_dir=args.root_dir,
+ path_gen=args.path_gen, path_gt=args.path_gt,
+ metrics=args.type, batch_size=args.batch_size,
+ number_sample_frames=args.number_sample_frames, num_gen=args.num_gen,
+ num_gt=args.num_gt, num_splits=args.num_splits,
+ sample_duration=args.sample_duration, num_workers=args.num_workers)
+ print(res_all)
+ if args.write_metric_to is not None:
+ json.dump(res_all, open(args.write_metric_to, "w"))
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/readme.md b/One-to-All-Animation/benchmark/DisCo/tool/metrics/readme.md
new file mode 100644
index 0000000000000000000000000000000000000000..9adf60fc536617f4e90ac6120e73788974e812ab
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/readme.md
@@ -0,0 +1,5 @@
+### requirments
+
+sudo apt-get update
+sudo apt-get install ffmpeg
+pip install ffmpeg-python
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/resize.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/resize.py
new file mode 100644
index 0000000000000000000000000000000000000000..62183cbc27f47579701eb0a94ddc3e702d1da7de
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/resize.py
@@ -0,0 +1,132 @@
+"""
+Helpers for resizing with multiple CPU cores
+"""
+import numpy as np
+import torch
+from PIL import Image
+import os
+import torch.nn.functional as F
+
+dict_name_to_filter = {
+ "PIL": {
+ "bicubic": Image.BICUBIC,
+ "bilinear": Image.BILINEAR,
+ "nearest": Image.NEAREST,
+ "lanczos": Image.LANCZOS,
+ "box": Image.BOX
+ },
+}
+
+
+def build_resizer(mode):
+ if mode == "clean":
+ return make_resizer("PIL", False, "bicubic", (299, 299))
+ # if using legacy tensorflow, do not manually resize outside the network
+ elif mode == "legacy_tensorflow":
+ return lambda x: x
+ elif mode == "legacy_pytorch":
+ return make_resizer("PyTorch", False, "bilinear", (299, 299))
+ else:
+ raise ValueError(f"Invalid mode {mode} specified")
+
+
+"""
+Construct a function that resizes a numpy image based on the
+flags passed in.
+"""
+
+def make_resizer(library, quantize_after, filter, output_size):
+ if library == "PIL" and quantize_after:
+ def func(x):
+ x = Image.fromarray(x)
+ x = x.resize(output_size, resample=dict_name_to_filter[library][filter])
+ x = np.asarray(x).astype(np.uint8)
+ return x
+
+ elif library == "PIL" and not quantize_after:
+ s1, s2 = output_size
+
+ def resize_single_channel(x_np):
+ img = Image.fromarray(x_np.astype(np.float32), mode='F')
+ img = img.resize(output_size, resample=dict_name_to_filter[library][filter])
+ return np.asarray(img).reshape(s1, s2, 1)
+
+ def func(x):
+ x = [resize_single_channel(x[:, :, idx]) for idx in range(3)]
+ x = np.concatenate(x, axis=2).astype(np.float32)
+ return x
+
+ elif library == "PyTorch":
+ import warnings
+ # ignore the numpy warnings
+ warnings.filterwarnings("ignore")
+
+ def func(x):
+ x = torch.Tensor(x.transpose((2, 0, 1)))[None, ...]
+ x = F.interpolate(x, size=output_size,
+ mode=filter, align_corners=False)
+ x = x[0, ...].cpu().data.numpy().transpose((1, 2, 0)).clip(0, 255)
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+
+ elif library == "TensorFlow":
+ import warnings
+ # ignore the numpy warnings
+ warnings.filterwarnings("ignore")
+ import tensorflow as tf
+
+ def func(x):
+ x = tf.constant(x)[tf.newaxis, ...]
+ x = tf.image.resize(x, output_size, method=filter)
+ x = x[0, ...].numpy().clip(0, 255)
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+
+ elif library == "OpenCV":
+ import cv2
+ name_to_filter = {
+ "bilinear": cv2.INTER_LINEAR,
+ "bicubic": cv2.INTER_CUBIC,
+ "lanczos": cv2.INTER_LANCZOS4,
+ "nearest": cv2.INTER_NEAREST,
+ "area": cv2.INTER_AREA
+ }
+
+ def func(x):
+ x = cv2.resize(
+ x, output_size, interpolation=name_to_filter[filter])
+ if quantize_after:
+ x = x.astype(np.uint8)
+ return x
+ else:
+ raise NotImplementedError('library [%s] is not include' % library)
+ return func
+
+
+class FolderResizer(torch.utils.data.Dataset):
+ def __init__(self, files, outpath, fn_resize, output_ext=".png"):
+ self.files = files
+ self.outpath = outpath
+ self.output_ext = output_ext
+ self.fn_resize = fn_resize
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ path = str(self.files[i])
+ img_np = np.asarray(Image.open(path))
+ img_resize_np = self.fn_resize(img_np)
+ # swap the output extension
+ basename = os.path.basename(path).split(".")[0] + self.output_ext
+ outname = os.path.join(self.outpath, basename)
+ if self.output_ext == ".npy":
+ np.save(outname, img_resize_np)
+ elif self.output_ext == ".png":
+ img_resized_pil = Image.fromarray(img_resize_np)
+ img_resized_pil.save(outname)
+ else:
+ raise ValueError("invalid output extension")
+ return 0
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/resnet3d.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/resnet3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..74e1bceadd5ee3bb62816236d640a2c622248cce
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/resnet3d.py
@@ -0,0 +1,252 @@
+# -*- encoding: utf-8 -*-
+'''
+@Time :2021/10/13 18:25:35
+@Author :Yongfei Liu
+@Email :liuyf3@shanghaitech.edu.cn
+'''
+
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from torch.autograd import Variable
+import math
+from functools import partial
+
+__all__ = ['ResNet', 'resnet10', 'resnet18', 'resnet34',
+ 'resnet50', 'resnet101', 'resnet152', 'resnet200']
+
+
+def conv3x3x3(in_planes, out_planes, stride=1):
+ # 3x3x3 convolution with padding
+ return nn.Conv3d(in_planes, out_planes, kernel_size=3,
+ stride=stride, padding=1, bias=False)
+
+
+def downsample_basic_block(x, planes, stride):
+ out = F.avg_pool3d(x, kernel_size=1, stride=stride)
+ zero_pads = torch.Tensor(out.size(0), planes - out.size(1),
+ out.size(2), out.size(3),
+ out.size(4)).zero_()
+ if isinstance(out.data, torch.cuda.FloatTensor):
+ zero_pads = zero_pads.cuda()
+
+ out = Variable(torch.cat([out.data, zero_pads], dim=1))
+
+ return out
+
+
+class BasicBlock(nn.Module):
+ expansion = 1
+
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
+ super(BasicBlock, self).__init__()
+ self.conv1 = conv3x3x3(inplanes, planes, stride)
+ self.bn1 = nn.BatchNorm3d(planes)
+ self.relu = nn.ReLU(inplace=True)
+ self.conv2 = conv3x3x3(planes, planes)
+ self.bn2 = nn.BatchNorm3d(planes)
+ self.downsample = downsample
+ self.stride = stride
+
+ def forward(self, x):
+ residual = x
+
+ out = self.conv1(x)
+ out = self.bn1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.bn2(out)
+
+ if self.downsample is not None:
+ residual = self.downsample(x)
+
+ out += residual
+ out = self.relu(out)
+
+ return out
+
+
+class Bottleneck(nn.Module):
+ expansion = 4
+
+ def __init__(self, inplanes, planes, stride=1, downsample=None):
+ super(Bottleneck, self).__init__()
+ self.conv1 = nn.Conv3d(inplanes, planes, kernel_size=1, bias=False)
+ self.bn1 = nn.BatchNorm3d(planes)
+ self.conv2 = nn.Conv3d(planes, planes, kernel_size=3, stride=stride,
+ padding=1, bias=False)
+ self.bn2 = nn.BatchNorm3d(planes)
+ self.conv3 = nn.Conv3d(planes, planes * 4, kernel_size=1, bias=False)
+ self.bn3 = nn.BatchNorm3d(planes * 4)
+ self.relu = nn.ReLU(inplace=True)
+ self.downsample = downsample
+ self.stride = stride
+
+ def forward(self, x):
+ residual = x
+
+ out = self.conv1(x)
+ out = self.bn1(out)
+ out = self.relu(out)
+
+ out = self.conv2(out)
+ out = self.bn2(out)
+ out = self.relu(out)
+
+ out = self.conv3(out)
+ out = self.bn3(out)
+
+ if self.downsample is not None:
+ residual = self.downsample(x)
+
+ out += residual
+ out = self.relu(out)
+
+ return out
+
+
+class ResNet(nn.Module):
+
+ def __init__(self, block, layers, sample_size, sample_duration, shortcut_type='B', num_classes=400, last_fc=True):
+ self.last_fc = last_fc
+
+ self.inplanes = 64
+ super(ResNet, self).__init__()
+ self.conv1 = nn.Conv3d(3, 64, kernel_size=7, stride=(1, 2, 2),
+ padding=(3, 3, 3), bias=False)
+ self.bn1 = nn.BatchNorm3d(64)
+ self.relu = nn.ReLU(inplace=True)
+ self.maxpool = nn.MaxPool3d(kernel_size=(3, 3, 3), stride=2, padding=1)
+ self.layer1 = self._make_layer(block, 64, layers[0], shortcut_type)
+ self.layer2 = self._make_layer(
+ block, 128, layers[1], shortcut_type, stride=2)
+ self.layer3 = self._make_layer(
+ block, 256, layers[2], shortcut_type, stride=2)
+ self.layer4 = self._make_layer(
+ block, 512, layers[3], shortcut_type, stride=2)
+ last_duration = math.ceil(sample_duration / 16)
+ last_size = math.ceil(sample_size / 32)
+ self.avgpool = nn.AvgPool3d(
+ (last_duration, last_size, last_size), stride=1)
+ self.fc = nn.Linear(512 * block.expansion, num_classes)
+
+ for m in self.modules():
+ if isinstance(m, nn.Conv3d):
+ n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
+ m.weight.data.normal_(0, math.sqrt(2. / n))
+ elif isinstance(m, nn.BatchNorm3d):
+ m.weight.data.fill_(1)
+ m.bias.data.zero_()
+
+ def _make_layer(self, block, planes, blocks, shortcut_type, stride=1):
+ downsample = None
+ if stride != 1 or self.inplanes != planes * block.expansion:
+ if shortcut_type == 'A':
+ downsample = partial(downsample_basic_block,
+ planes=planes * block.expansion,
+ stride=stride)
+ else:
+ downsample = nn.Sequential(
+ nn.Conv3d(self.inplanes, planes * block.expansion,
+ kernel_size=1, stride=stride, bias=False),
+ nn.BatchNorm3d(planes * block.expansion)
+ )
+
+ layers = []
+ layers.append(block(self.inplanes, planes, stride, downsample))
+ self.inplanes = planes * block.expansion
+ for i in range(1, blocks):
+ layers.append(block(self.inplanes, planes))
+
+ return nn.Sequential(*layers)
+
+ def forward(self, x):
+ x = self.conv1(x)
+ x = self.bn1(x)
+ x = self.relu(x)
+ x = self.maxpool(x)
+
+ x = self.layer1(x)
+ x = self.layer2(x)
+ x = self.layer3(x)
+ x = self.layer4(x)
+
+ x = self.avgpool(x)
+
+ x = x.view(x.size(0), -1)
+ if self.last_fc:
+ x = self.fc(x)
+
+ return x
+
+
+def get_fine_tuning_parameters(model, ft_begin_index):
+ if ft_begin_index == 0:
+ return model.parameters()
+
+ ft_module_names = []
+ for i in range(ft_begin_index, 5):
+ ft_module_names.append('layer{}'.format(ft_begin_index))
+ ft_module_names.append('fc')
+
+ parameters = []
+ for k, v in model.named_parameters():
+ for ft_module in ft_module_names:
+ if ft_module in k:
+ parameters.append({'params': v})
+ break
+ else:
+ parameters.append({'params': v, 'lr': 0.0})
+
+ return parameters
+
+
+def resnet10(**kwargs):
+ """Constructs a ResNet-18 model.
+ """
+ model = ResNet(BasicBlock, [1, 1, 1, 1], **kwargs)
+ return model
+
+
+def resnet18(**kwargs):
+ """Constructs a ResNet-18 model.
+ """
+ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
+ return model
+
+
+def resnet34(**kwargs):
+ """Constructs a ResNet-34 model.
+ """
+ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
+ return model
+
+
+def resnet50(**kwargs):
+ """Constructs a ResNet-50 model.
+ """
+ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
+ return model
+
+
+def resnet101(**kwargs):
+ """Constructs a ResNet-101 model.
+ """
+ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
+ return model
+
+
+def resnet152(**kwargs):
+ """Constructs a ResNet-101 model.
+ """
+ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
+ return model
+
+
+def resnet200(**kwargs):
+ """Constructs a ResNet-101 model.
+ """
+ model = ResNet(Bottleneck, [3, 24, 36, 3], **kwargs)
+ return model
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/ssim_l1_lpips_psnr.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/ssim_l1_lpips_psnr.py
new file mode 100644
index 0000000000000000000000000000000000000000..e027b0c59bf054dc987072685fa0acab6954f285
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/ssim_l1_lpips_psnr.py
@@ -0,0 +1,108 @@
+from skimage.metrics import structural_similarity as ssim_eval
+import numpy as np
+import cv2
+from tqdm import tqdm
+import os
+from PIL import Image
+from torchvision import transforms
+import lpips
+from math import log10, sqrt
+
+
+def psnr_eval(original, compressed):
+
+ mse = np.mean((original.astype(np.float64) - compressed.astype(np.float64)) ** 2)
+ if(mse == 0): # MSE is zero means no noise is present in the signal .
+ # Therefore PSNR have no importance.
+ return 100
+ max_pixel = 255.0
+ psnr = 20 * log10(max_pixel / sqrt(mse))
+ return psnr
+
+
+def load_image(path):
+ if os.path.exists(path):
+ image = Image.open(path)
+ if not image.mode == "RGB":
+ image = image.convert("RGB")
+ else:
+ image = None
+ return image
+
+
+def l1_eval(imageA, imageB):
+ err = np.absolute((imageA.astype("float") - imageB.astype("float")))
+ err /= float(imageA.shape[0] * imageA.shape[1])
+ return err
+
+
+def compute_ssim_l1_psnr(gen_inst_name_full, gt_inst_name_full, mode):
+ gen_inst_name_full = sorted(gen_inst_name_full)
+ gt_inst_name_full = sorted(gt_inst_name_full)
+
+ scores = []
+ for gen_path, gt_path in tqdm(zip(gen_inst_name_full, gt_inst_name_full)):
+ gen_filename = os.path.splitext(
+ os.path.basename(gen_path))[0]
+ gt_filename = os.path.splitext(
+ os.path.basename(gt_path))[0]
+
+ assert gen_filename == gt_filename, f"file mismatch: {gen_filename} vs {gt_filename}"
+
+ image1 = cv2.imread(gen_path)
+ image2 = cv2.imread(gt_path)
+ if image1 is None:
+ print(f"Failed to load image from {gen_path}")
+ # Check if gen_path is a symlink
+ if os.path.islink(gen_path):
+ target_path = os.readlink(gen_path)
+ print(f"The symbolic link {gen_path} points to {target_path}")
+ else:
+ print(f"{gen_path} is not a symbolic link.")
+ return None
+
+ # Resize images to the same dimensions, if needed
+ if image1.shape != image2.shape:
+ image1 = cv2.resize(image1, (image2.shape[1], image2.shape[0]))
+
+ if mode == 'L1':
+ score = l1_eval(image1, image2)
+ elif mode == 'PSNR':
+ score = psnr_eval(image1, image2)
+ else:
+ # ssim_value = ssim(image1, image2, multichannel=True)
+ image1_gray = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY)
+ image2_gray = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY)
+
+ # Compute SSIM between two images
+ (score, _) = ssim_eval(image1_gray, image2_gray, full=True)
+ scores.append(score)
+
+ score_ave = np.mean(scores)
+ return score_ave
+
+
+def compute_lpips(gen_inst_name_full, gt_inst_name_full,device='cuda'):
+ gen_inst_name_full = sorted(gen_inst_name_full)
+ gt_inst_name_full = sorted(gt_inst_name_full)
+ convert_tensor = transforms.ToTensor()
+ loss_fn_vgg = lpips.LPIPS(net='vgg').to(device)
+
+ scores = []
+ for gen_path, gt_path in tqdm(zip(gen_inst_name_full, gt_inst_name_full)):
+ gen_filename = os.path.splitext(
+ os.path.basename(gen_path))[0]
+ gt_filename = os.path.splitext(
+ os.path.basename(gt_path))[0]
+
+ assert gen_filename == gt_filename, 'file mismatch'
+
+ image1 = convert_tensor(load_image(gen_path)).unsqueeze(0).to(device)
+ image2 = convert_tensor(load_image(gt_path)).unsqueeze(0).to(device)
+
+ score = loss_fn_vgg(image1, image2).cpu().item()
+
+ scores.append(score)
+
+ score_ave = np.mean(scores)
+ return score_ave
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/metrics/utils.py b/One-to-All-Animation/benchmark/DisCo/tool/metrics/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..fac7a4e3e6519ceb686a9f88a95c703bb81b9cfd
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/metrics/utils.py
@@ -0,0 +1,526 @@
+import re
+import os
+from pathlib import Path
+from random import gauss
+import numpy as np
+import torch
+import torchvision
+from PIL import Image, ImageFilter, ImageSequence
+import cv2
+import torch.nn.functional as F
+import ffmpeg
+import random
+import imageio
+
+from tool.metrics.resize import build_resizer, make_resizer
+
+def check_Image(path):
+ try:
+ img_pil = Image.open(path).convert('RGB')
+ return True
+ except:
+ print(f"{path} can not open, delete")
+ return False
+
+class ResizeDataset(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, size=(299, 299), fn_resize=None):
+ self.files = files
+ self.transforms = torchvision.transforms.ToTensor()
+ self.size = size
+ self.fn_resize = fn_resize
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ path = str(self.files[i])
+ if ".npy" in path:
+ img_np = np.load(path)
+ else:
+ img_pil = Image.open(path).convert('RGB')
+ img_np = np.array(img_pil)
+
+ # fn_resize expects a np array and returns a np array
+ img_resized = self.fn_resize(img_np)
+
+ # ToTensor() converts to [0,1] only if input in uint8
+ if img_resized.dtype == "uint8":
+ img_t = self.transforms(np.array(img_resized))*255
+ elif img_resized.dtype == "float32":
+ img_t = self.transforms(img_resized)
+
+ return img_t
+
+
+class ResizeDatasetBlur(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, size=(299, 299), fn_resize=None, is_blur=False, gaussian_kernel=5):
+ self.files = files
+ self.transforms = torchvision.transforms.ToTensor()
+ self.size = size
+ self.fn_resize = fn_resize
+ self.is_blur = is_blur
+ self.gaussian_kernel = gaussian_kernel
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+
+ path = str(self.files[i])
+ if ".npy" in path:
+ img_np = np.load(path)
+ else:
+ img_pil = Image.open(path).convert('RGB')
+ # if self.is_blur:
+ # img_pil = img_pil.filter(ImageFilter.GaussianBlur(radius=self.gaussian_kernel))
+ img_np = np.array(img_pil)
+
+ # fn_resize expects a np array and returns a np array
+ img_resized = self.fn_resize(img_np).astype(np.float32)
+ # if self.is_blur:
+ # img_resized = cv2.GaussianBlur(img_resized, (self.gaussian_kernel, self.gaussian_kernel), 0)
+
+ if self.is_blur:
+ # if self.gaussian_kernel % 2 == 0:
+ img_resized = Image.fromarray(img_resized.astype(np.uint8))
+ img_resized = img_resized.filter(ImageFilter.GaussianBlur(radius=self.gaussian_kernel))
+ img_resized = np.array(img_resized).astype(np.float32)
+ # else:
+ # img_resized = cv2.GaussianBlur(img_resized, (self.gaussian_kernel, self.gaussian_kernel), 0)
+
+ img_t = self.transforms(img_resized)
+
+ return img_t
+
+
+class ResizeDatasetInceptionScoreBlur(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, size=(299, 299), fn_resize=None, is_blur=False, gaussian_kernel=5):
+ self.files = files
+
+ self.transform = torchvision.transforms.ToTensor()
+ self.pixel_mean = torch.as_tensor(np.array([0.485, 0.456, 0.406])).unsqueeze(1).unsqueeze(1) * 255.0 # 3*1*1
+ self.pixel_std = torch.as_tensor(np.array([0.229, 0.224, 0.225])).unsqueeze(1).unsqueeze(1)*255.0 # 3*1*1
+
+ self.size = size
+ self.fn_resize = fn_resize
+ self.is_blur = is_blur
+ self.gaussian_kernel = gaussian_kernel
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ path = str(self.files[i])
+ if ".npy" in path:
+ img_np = np.load(path)
+ else:
+ img_pil = Image.open(path).convert('RGB')
+ img_np = np.array(img_pil)
+
+ img_resized = self.fn_resize(img_np).astype(np.float32)
+ if self.is_blur:
+ # if self.gaussian_kernel % 2 == 0:
+ img_resized = Image.fromarray(img_resized.astype(np.uint8))
+ img_resized = img_resized.filter(ImageFilter.GaussianBlur(radius=self.gaussian_kernel))
+ img_resized = np.array(img_resized).astype(np.float32)
+ # else:
+ # img_resized = cv2.GaussianBlur(img_resized, (self.gaussian_kernel, self.gaussian_kernel), 0)
+ img_t = self.transform(img_resized) # 3*h*w because the float32 format, the value are still in 0-255
+ img_t = (img_t - self.pixel_mean) / self.pixel_std
+ img_t = img_t.float()
+
+ return img_t
+
+
+class ResizeDatasetFIDBlur(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, size=(299, 299), fn_resize=None, is_blur=False, gaussian_kernel=5):
+ self.files = files
+
+ self.transform = torchvision.transforms.ToTensor()
+ self.pixel_mean = torch.as_tensor(np.array([[0.485, 0.456, 0.406]])).unsqueeze(1).unsqueeze(1) * 255.0 # 3*1*1
+ self.pixel_std = torch.as_tensor(np.array([0.229, 0.224, 0.225])).unsqueeze(1).unsqueeze(1)*255.0 # 3*1*1
+
+ self.size = size
+ self.fn_resize = fn_resize
+ self.is_blur = is_blur
+ self.gaussian_kernel = gaussian_kernel
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ path = str(self.files[i])
+ if ".npy" in path:
+ img_np = np.load(path)
+ else:
+ img_pil = Image.open(path).convert('RGB')
+ img_np = np.array(img_pil)
+
+ img_resized = self.fn_resize(img_np).astype(np.float32)
+ if self.is_blur:
+ # if self.gaussian_kernel % 2 == 0:
+ img_resized = Image.fromarray(img_resized.astype(np.uint8))
+ img_resized = img_resized.filter(ImageFilter.GaussianBlur(radius=self.gaussian_kernel))
+ img_resized = np.array(img_resized).astype(np.float32)
+ # else:
+ # img_resized = cv2.GaussianBlur(img_resized, (self.gaussian_kernel, self.gaussian_kernel), 0)
+
+ img_t = self.transform(img_resized) # 3*h*w because the float32 format, the value are still in 0-255
+ img_t = (img_t - self.pixel_mean) / self.pixel_std
+
+ return img_t
+
+
+def resize_numpyimg(x):
+ x = Image.fromarray(x)
+ x = x.resize((64, 64))
+ x = np.asarray(x).astype(np.uint8)
+ return x
+
+
+class ResizeDatasetFIDVideoBlur(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, size=(299, 299), fn_resize=None, is_blur=False, gaussian_kernel=5, is_sample_frames=False, sample_frames=10):
+ self.files = files
+
+ self.transform = torchvision.transforms.ToTensor()
+ self.pixel_mean = torch.as_tensor(np.array([[0.485, 0.456, 0.406]])).unsqueeze(1).unsqueeze(1) * 255.0 # 3*1*1
+ self.pixel_std = torch.as_tensor(np.array([0.229, 0.224, 0.225])).unsqueeze(1).unsqueeze(1)*255.0 # 3*1*1
+
+ self.size = size
+ self.fn_resize = fn_resize
+ self.is_blur = is_blur
+ self.gaussian_kernel = gaussian_kernel
+ self.sample_frames = sample_frames
+ self.is_sample_frames = is_sample_frames
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ try:
+ path = str(self.files[i])
+ probe = ffmpeg.probe(path)
+ video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
+ width = int(video_stream['width'])
+ height = int(video_stream['height'])
+ out, _ = (ffmpeg.input(path).output('pipe:', format='rawvideo', pix_fmt='rgb24').run(capture_stdout=True, quiet=True))
+ video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3])
+ num_frame = video.shape[0]
+ frame_ids = list(range(num_frame))
+
+ if self.is_sample_frames and self.sample_frames < num_frame:
+ # frame_ids = random.choice(frame_ids, self.sample_frames)
+ print(path, num_frame, self.sample_frames)
+ frame_ids = frame_ids[:self.sample_frames]
+
+ # TODO resize img
+ # video_new = []
+ # for fid in frame_ids:
+ # video_new.append(resize_numpyimg(video[fid]))
+ # video = np.stack(video_new)
+
+
+ img_tensor = []
+ for fid in frame_ids:
+ img_np = video[fid]
+ img_resized = self.fn_resize(img_np).astype(np.float32)
+ if self.is_blur:
+ if self.gaussian_kernel % 2 == 0:
+ img_resized = Image.fromarray(img_resized)
+ img_resized = img_resized.filter(ImageFilter.GaussianBlur(radius=self.gaussian_kernel))
+ img_resized = np.array(img_resized).astype(np.float32)
+ else:
+ img_resized = cv2.GaussianBlur(img_resized, (self.gaussian_kernel, self.gaussian_kernel), 0)
+
+ img_t = self.transform(img_resized) # 3*h*w because the float32 format, the value are still in 0-255
+ img_tensor.append(img_t)
+
+ img_tensor = torch.stack(img_tensor, dim=0) # N*3*H*W
+ return img_tensor
+ except Exception as e:
+ print(f'index {i} skipped because {e}')
+ return self.__getitem__(np.random.randint(0, self.__len__() - 1))
+
+
+class DatasetFVDVideo(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, sample_duration=16, mode='FVD-3DRN50', img_size=112):
+ self.files = files
+
+ self.pixel_mean = torch.as_tensor(np.array([114.7748, 107.7354, 99.4750]))
+ self.img_size = img_size
+ self.sample_duration = sample_duration
+ self.mode = mode
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+
+ path = str(self.files[i])
+ out, _ = (ffmpeg.input(path).filter('scale', self.img_size, self.img_size).output('pipe:', format='rawvideo', pix_fmt='rgb24').run(capture_stdout=True, quiet=True))
+ video = np.frombuffer(out, np.uint8).reshape([-1, self.img_size, self.img_size, 3]) # t*h*w*3
+ video = torch.as_tensor(video.copy()).float()
+ num_v = video.shape[0]
+
+ if num_v % self.sample_duration != 0:
+ num_v_ag = self.sample_duration - num_v % self.sample_duration
+ video_aug = video[[-1], :, :, :].repeat(num_v_ag, 1, 1, 1)
+ video = torch.cat([video, video_aug], dim=0)
+ num_seg = num_v // self.sample_duration + 1
+ else:
+ num_seg = num_v // self.sample_duration
+
+ if self.mode == 'FVD-3DRN50':
+ video = video - self.pixel_mean
+ elif self.mode == "FVD-3DInception":
+ video = video / 127.5 - 1
+
+ video = video.view(num_seg, self.sample_duration, self.img_size, self.img_size, 3).contiguous().permute(0, 4, 1, 2, 3).float() # num_seg, 3, sample_during h, w
+
+ return video
+
+
+def save_video_from_numpy_array(array, output_filename, fps=3):
+ assert array.dtype == 'uint8', "The input array must be of dtype uint8"
+
+ with imageio.get_writer(output_filename, fps=fps) as writer:
+ for frame in array:
+ writer.append_data(frame)
+
+
+def gif_to_nparray(gif_path):
+ gif = Image.open(gif_path)
+ frames = [np.array(frame.copy().convert('RGB'), dtype=np.uint8) for frame in ImageSequence.Iterator(gif)]
+ video = np.stack(frames)
+ return video
+
+
+class DatasetFVDVideoResize(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, sample_duration=16, mode='FVD-3DRN50', img_size=112, return_name=False):
+ self.files = files
+
+ self.pixel_mean = torch.as_tensor(np.array([114.7748, 107.7354, 99.4750]))
+ self.img_size = img_size
+ self.sample_duration = sample_duration
+ self.mode = mode
+ self.resize_func = make_resizer("PIL", False, "bicubic", (img_size, img_size))
+ self.return_name = return_name
+
+ def __len__(self):
+ return len(self.files)
+
+ def __getitem__(self, i):
+ try:
+ path = str(self.files[i])
+
+ if Path(path).suffix == '.gif':
+ video = gif_to_nparray(path)
+ else:
+ probe = ffmpeg.probe(path)
+ video_stream = next((stream for stream in probe['streams'] if stream['codec_type'] == 'video'), None)
+ width = int(video_stream['width'])
+ height = int(video_stream['height'])
+ out, _ = (ffmpeg.input(path).output('pipe:', format='rawvideo', pix_fmt='rgb24').run(capture_stdout=True, quiet=True))
+ video = np.frombuffer(out, np.uint8).reshape([-1, height, width, 3])
+
+ #if video.shape[0] != 10:
+ # print('not 10, but', video.shape[0])
+ # return self.__getitem__(0)
+
+ # TODO resize img
+ # frame_ids = video.shape[0]
+ # video_new = []
+ # for fid in range(frame_ids):
+ # video_new.append(resize_numpyimg(video[fid]))
+ # video = np.stack(video_new)
+
+
+ video_resize = []
+ for vim in video:
+ vim_resize = self.resize_func(vim)
+ video_resize.append(vim_resize)
+
+ video = np.stack(video_resize, axis=0)
+ # import ipdb; ipdb.set_trace()
+ video = torch.as_tensor(video.copy()).float()
+ num_v = video.shape[0]
+
+ if num_v % self.sample_duration != 0 and self.mode == "FVD-3DRN50":
+ num_v_ag = self.sample_duration - num_v % self.sample_duration
+ video_aug = video[[-1], :, :, :].repeat(num_v_ag, 1, 1, 1)
+ video = torch.cat([video, video_aug], dim=0)
+ num_seg = num_v // self.sample_duration + 1
+ else:
+ num_seg = num_v // self.sample_duration
+
+ if self.mode == 'FVD-3DRN50':
+ video = video - self.pixel_mean
+ video = video.view(num_seg, self.sample_duration, self.img_size, self.img_size, 3).contiguous().permute(0, 4, 1, 2, 3).float()
+ elif self.mode == "FVD-3DInception" or self.mode == 'MAE':
+ video = video / 127.5 - 1
+ video = video.unsqueeze(0).permute(0, 4, 1, 2, 3).float() # num_seg, 3, sample_during h, w
+
+ if self.return_name:
+ return video, Path(path).stem
+ return video
+ except Exception as e:
+ print(f'{i} skipped beacase {e}')
+ return self.__getitem__(np.random.randint(0, self.__len__() - 1))
+
+
+class DatasetFVDVideoFromFramesResize(torch.utils.data.Dataset):
+ """
+ A placeholder Dataset that enables parallelizing the resize operation
+ using multiple CPU cores
+
+ files: list of all frame files in the folder
+ fn_resize: function that takes an np_array as input [0,255]
+ """
+
+ def __init__(self, files, sample_duration=16, mode='FVD-3DRN50', img_size=112, return_name=False):
+ frame_format1 = r"^(TiktokDance_\d+_)(\d+)(\D*\.\w+)$"
+ frame_format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\D*\.\w+)$"
+ frame_format3 = r"^(\d+_\d+_1x1__)(\d+)(.\D*\.\w+)$"
+ frame_format4 = r"^(S\d{3}C\d{3}P\d{3}R\d{3}A\d{3}_)(\d{4})(\D*\.\w+)$"
+
+ # self.files = files
+ files = sorted(files)
+ self.video_frames = {}
+ for file in files:
+ file_name = Path(file).name
+ file_parent = Path(file).parent
+ if re.match(frame_format1, file_name):
+ folder_format_re = frame_format1
+ elif re.match(frame_format2, file_name):
+ folder_format_re = frame_format2
+ elif re.match(frame_format3, file_name):
+ folder_format_re = frame_format3
+ elif re.match(frame_format4, file_name):
+ folder_format_re = frame_format4
+ else:
+ print(f"Frame name '{file_name}' does not match any format")
+ continue
+
+ match = re.match(folder_format_re, file_name)
+ frame_index = int(match.group(2))
+
+ self.video_frames[file_name] = [file]
+ for i in range(1, sample_duration):
+ next_frame_file_name = match.group(1) + str(frame_index + i).zfill(len(match.group(2))) + match.group(3)
+ next_frame_file_path = Path(file_parent, next_frame_file_name)
+ if not next_frame_file_path.exists():
+ del self.video_frames[file_name]
+ break
+ self.video_frames[file_name].append(next_frame_file_path.as_posix())
+
+ self.pixel_mean = torch.as_tensor(np.array([114.7748, 107.7354, 99.4750]))
+ self.img_size = img_size
+ self.sample_duration = sample_duration
+ self.mode = mode
+ self.return_name = return_name
+ self.resize_func = make_resizer("PIL", False, "bicubic", (img_size, img_size))
+
+ def __len__(self):
+ return len(self.video_frames)
+
+ def __getitem__(self, i):
+ try:
+ video_name = list(self.video_frames.keys())[i]
+ frame_list = []
+ for frame_path in self.video_frames[video_name]:
+ frame = Image.open(frame_path).convert('RGB')
+ frame_list.append(np.array(frame))
+ video = np.stack(frame_list, axis=0)
+
+ video_resize = []
+ for vim in video:
+ vim_resize = self.resize_func(vim)
+ video_resize.append(vim_resize)
+
+ video = np.stack(video_resize, axis=0)
+ # import ipdb; ipdb.set_trace()
+ video = torch.as_tensor(video.copy()).float()
+ num_v = video.shape[0]
+
+ if num_v % self.sample_duration != 0 and self.mode == "FVD-3DRN50":
+ num_v_ag = self.sample_duration - num_v % self.sample_duration
+ video_aug = video[[-1], :, :, :].repeat(num_v_ag, 1, 1, 1)
+ video = torch.cat([video, video_aug], dim=0)
+ num_seg = num_v // self.sample_duration + 1
+ else:
+ num_seg = num_v // self.sample_duration
+
+ if self.mode == 'FVD-3DRN50':
+ video = video - self.pixel_mean
+ video = video.view(num_seg, self.sample_duration, self.img_size, self.img_size, 3).contiguous().permute(0, 4, 1, 2, 3).float()
+ elif self.mode == "FVD-3DInception" or self.mode == 'MAE':
+ video = video / 127.5 - 1
+ video = video.unsqueeze(0).permute(0, 4, 1, 2, 3).float() # num_seg, 3, sample_during h, w
+
+ if self.return_name:
+ return video, Path(video_name).stem
+ return video
+ except Exception as e:
+ print(f'{i} skipped beacase {e}')
+ return self.__getitem__(np.random.randint(0, self.__len__() - 1))
+
+
+
+EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
+ 'tif', 'tiff', 'webp', 'npy'}
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/prepare.py b/One-to-All-Animation/benchmark/DisCo/tool/prepare.py
new file mode 100644
index 0000000000000000000000000000000000000000..c791511df6ef8478f3885eee6004e16df273bdc2
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/prepare.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+import shutil
+from pathlib import Path
+from tqdm import tqdm
+import argparse
+
+# 定义跳过的目录名列表
+SKIP_VIDEOS = {
+ "mmexport1758617134089",
+ "mmexport1758617147981",
+ "mmexport1758617110699",
+ "mmexport1758617160088",
+ "mmexport1758617106367",
+}
+
+def copy_pred_gt(src_base: Path, dst_base: Path):
+ pred_dst = dst_base / "pred"
+ gt_dst = dst_base / "gt"
+ pred_dst.mkdir(parents=True, exist_ok=True)
+ gt_dst.mkdir(parents=True, exist_ok=True)
+
+ # 遍历 MimicMotion 下的所有编号文件夹
+ for video_dir in sorted(src_base.iterdir()):
+ if not video_dir.is_dir():
+ continue
+
+ # 跳过名单中的 video_dir
+ if video_dir.name in SKIP_VIDEOS:
+ print(f"[SKIP] 跳过视频: {video_dir.name}")
+ continue
+
+ pred_src = video_dir / "pred"
+ gt_src = video_dir / "gt"
+
+ # 目标 clip 文件夹(只为没跳过的创建)
+ pred_out = pred_dst / video_dir.name
+ gt_out = gt_dst / video_dir.name
+ pred_out.mkdir(parents=True, exist_ok=True)
+ gt_out.mkdir(parents=True, exist_ok=True)
+
+ # 复制 pred
+ if pred_src.exists():
+ for frame in tqdm(sorted(pred_src.iterdir()), desc=f"COPY pred {video_dir.name}", unit="frame"):
+ if frame.is_file():
+ shutil.copy2(frame, pred_out / frame.name)
+
+ # 复制 gt
+ if gt_src.exists():
+ for frame in tqdm(sorted(gt_src.iterdir()), desc=f"COPY gt {video_dir.name}", unit="frame"):
+ if frame.is_file():
+ shutil.copy2(frame, gt_out / frame.name)
+
+ print(f"[DONE] 已生成到 {dst_base}")
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="批量复制 MimicMotion 下所有视频的 pred/gt 到新目录(保留原文件名)")
+ parser.add_argument("-i", "--input_dir", type=str, required=True, help="原始 MimicMotion 根目录")
+ parser.add_argument("-o", "--output_dir", type=str, required=True, help="新目录 MimicMotion_update")
+ args = parser.parse_args()
+
+ copy_pred_gt(Path(args.input_dir), Path(args.output_dir))
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/test_SD2 b/One-to-All-Animation/benchmark/DisCo/tool/test_SD2
new file mode 100644
index 0000000000000000000000000000000000000000..6c4a1df733e72b1aabfcb87599f7ea0009591e02
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/test_SD2
@@ -0,0 +1,21 @@
+import requests
+import torch
+from PIL import Image
+from io import BytesIO
+
+from diffusers import StableUnCLIPImg2ImgPipeline
+
+#Start the StableUnCLIP Image variations pipeline
+pipe = StableUnCLIPImg2ImgPipeline.from_pretrained(
+ "/datadrive_d/wangtan/azure_storage/vigstandard_data/linjli/debug_output/video_sythesis/diffusers/stable-diffusion-2-1-unclip", torch_dtype=torch.float16, variation="fp16"
+)
+pipe = pipe.to("cuda")
+
+#Get image from URL
+url = "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/tarsila_do_amaral.png"
+response = requests.get(url)
+init_image = Image.open(BytesIO(response.content)).convert("RGB")
+
+#Pipe to make the variation
+images = pipe(init_image, height=256, width=256).images
+images[0].save("/home/tan/tarsila_variation.png")
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/gen_gifs_for_fvd.py b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_gifs_for_fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..1dcbce06214a5dd5d7c549b2d0beefdc9c1582cb
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_gifs_for_fvd.py
@@ -0,0 +1,124 @@
+import glob
+import math
+from collections import defaultdict
+from tqdm import tqdm
+from PIL import Image
+import numpy as np
+import imageio
+import threading
+import os
+import sys
+pythonpath = os.path.abspath(
+ os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
+print(pythonpath)
+sys.path.insert(0, pythonpath)
+
+class Preprocess(threading.Thread):
+ def __init__(self, data, begin_idx, end_idx, gif_root, frames_len, fps, use_tqdm=False, overwrite=False, format="gif"):
+ threading.Thread.__init__(self)
+ self.data = data
+ self.begin_idx = begin_idx
+ self.end_idx = end_idx
+ self.use_tqdm = use_tqdm
+ self.gif_root = gif_root
+ self.frames_len = frames_len
+ self.fps = fps
+ self.end_idx = self.end_idx - self.frames_len
+ self.overwrite = overwrite
+ self.format = format
+
+ def run(self):
+ vid = "_".join(os.path.splitext(os.path.basename(self.data[0]))[0].split("_")[:2])
+ it = tqdm(range(self.begin_idx, self.end_idx), desc=f"{vid}") if self.use_tqdm else range(self.begin_idx, self.end_idx)
+ for idx in it:
+ file = self.data[idx]
+ image = imageio.imread(file)
+ base_name = os.path.splitext(os.path.basename(file))[0]
+ if os.path.exists(os.path.join(self.gif_root, f'{base_name}.gif')) and not self.overwrite:
+ continue
+ images = [image]
+ for i in range(1, self.frames_len):
+ try:
+ file = self.data[idx+i]
+ image = imageio.imread(file)
+ except Exception as e:
+ print(e, f"curr_idx:{idx+i}", f"begin_idx:{self.begin_idx}", f"end_idx:{self.end_idx}", f"data_len: {len(self.data)}")
+ images.append(image)
+
+ if self.format == "gif":
+ imageio.mimsave(os.path.join(self.gif_root, f'{base_name}.gif'), images, fps=self.fps)
+ elif self.format == "mp4":
+ # imageio.mimsave(os.path.join(self.gif_root, f'{base_name}.mp4'), images, fps=self.fps)
+ imageio.mimsave(os.path.join(self.gif_root, f'{base_name}.mp4'), images, fps=self.fps, quality=10, macro_block_size=None)
+ else:
+ raise NotImplementedError
+
+
+def compose_gif(img_path, gif_frames, fps, num_workers, overwrite=False, format="gif"):
+ if img_path[-1] == "/":
+ img_path = img_path[:-1]
+ suffix = f"_{format}" if gif_frames == 16 else f"_{gif_frames}frames{format}"
+ base = os.path.basename(img_path) + suffix
+ root = os.path.dirname(img_path)
+ gif_root = os.path.join(root, base)
+ if not os.path.exists(gif_root):
+ os.mkdir(gif_root)
+ inst_names = glob.glob(f"{img_path}/*.png")
+ inst_names = sorted(inst_names)
+
+ vid2files = defaultdict(list)
+ for path in inst_names:
+ vid = "_".join(os.path.splitext(os.path.basename(path))[0].split("_")[:2])
+ vid2files[vid].append(path)
+
+ for vid, inst_paths in vid2files.items():
+ pool = []
+ per_num = math.ceil(len(inst_paths) / num_workers)
+ cur_idx = 0
+ for idx in range(num_workers):
+ begin_idx = cur_idx
+ end_idx = cur_idx + per_num
+ if end_idx > len(inst_paths):
+ end_idx = len(inst_paths)
+ pool.append(
+ Preprocess(
+ inst_paths, begin_idx, end_idx, gif_root,
+ gif_frames, fps, idx==0, overwrite=overwrite, format=format))
+ cur_idx = end_idx
+
+ for idx in range(num_workers):
+ pool[idx].start()
+
+ for idx in range(num_workers):
+ pool[idx].join()
+
+ return gif_root
+
+
+if __name__ == "__main__":
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ #parser.add_argument('--root_dir', type=str, default="/home/t-mni/blob/chenfeipremiumblock/data/G")
+ parser.add_argument('--root_dir', type=str, default="/f_ndata/G")
+ parser.add_argument('--path_gen', type=str, default="sdm/SDM_KLF8_S512_MSCOCO/eval_visu/pred")
+ parser.add_argument('--path_gt', type=str, default="dataset/mscoco/val2017")
+ parser.add_argument('--gif_frames', type=int, default=4)
+ parser.add_argument('--gif_fps', type=float, default=1.6)
+ parser.add_argument('--overwrite', type=bool, default=False)
+ parser.add_argument('--num_workers', type=int, default=16)
+ parser.add_argument("--format", type=str, default="mp4", choices=["gif", "mp4"])
+
+ args = parser.parse_args()
+
+ if args.root_dir not in args.path_gen:
+ args.path_gen = os.path.join(args.root_dir, args.path_gen)
+ if args.root_dir not in args.path_gt:
+ args.path_gt = os.path.join(args.root_dir, args.path_gt)
+ print(f"compose_gif for pred")
+ path_gen_gif = compose_gif(args.path_gen, args.gif_frames,
+ args.gif_fps, args.num_workers, overwrite=args.overwrite, format=args.format)
+ print(f"compose_gif for gt")
+ path_gt_gif = compose_gif(args.path_gt, args.gif_frames,
+ args.gif_fps, args.num_workers, overwrite=args.overwrite, format=args.format)
+ print(path_gen_gif, path_gt_gif)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid.py b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a506002b06634fd6376d9c969b8d81c0b108122
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid.py
@@ -0,0 +1,29 @@
+import cv2
+import numpy as np
+import os
+from tqdm import tqdm
+
+video_img_source_path = ''
+
+
+fps = 30
+size = (256, 256)
+codec = cv2.VideoWriter_fourcc(*"mp4v")
+
+# Initialize video writer
+video_writer = cv2.VideoWriter("{}_vid_output.mp4".format(video_img_source_path), codec, fps, size)
+folder_path = video_img_source_path
+# Get a list of all files in the folder
+files = os.listdir(folder_path)
+# Filter the list to only include image filesd
+image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+num_frm = len(image_files)
+
+for image_fname_ in image_files:
+ image_fname = '{}/{}'.format(folder_path,image_fname_)
+ frame = cv2.imread(image_fname)
+ # Write frames to video
+ video_writer.write(frame)
+
+# Release resources
+video_writer.release()
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_command.py b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_command.py
new file mode 100644
index 0000000000000000000000000000000000000000..2a814d38237d446fdbea6b0b65ed4c24459398d6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_command.py
@@ -0,0 +1,34 @@
+import cv2
+import numpy as np
+import os
+import argparse
+from tqdm import tqdm
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(description='Get Video')
+ parser.add_argument('--img_path', default=None, type=str, help='image frame path')
+ args = parser.parse_args()
+
+ video_img_source_path = args.img_path
+ fps = 30
+ size = (256, 256)
+ codec = cv2.VideoWriter_fourcc(*"mp4v")
+
+ # Initialize video writer
+ video_writer = cv2.VideoWriter("{}_vid_output.mp4".format(video_img_source_path), codec, fps, size)
+ folder_path = video_img_source_path
+ # Get a list of all files in the folder
+ files = os.listdir(folder_path)
+ # Filter the list to only include image filesd
+ image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ num_frm = len(image_files)
+
+ for image_fname_ in image_files:
+ image_fname = '{}/{}'.format(folder_path, image_fname_)
+ frame = cv2.imread(image_fname)
+ # Write frames to video
+ video_writer.write(frame)
+
+ # Release resources
+ video_writer.release()
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_folder.py b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_folder.py
new file mode 100644
index 0000000000000000000000000000000000000000..b211a3b3b589512d64e015bfb529a1b86fd5f7a1
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/gen_vid_folder.py
@@ -0,0 +1,55 @@
+import cv2
+import numpy as np
+import os
+from tqdm import tqdm
+# Define video settings
+
+
+folder_name = ''
+save_folder_name = ''
+
+sub_folder_name_list = os.listdir(folder_name)
+
+for idx, sub_folder_name in enumerate(sub_folder_name_list):
+ print(sub_folder_name)
+ # video_img_source_path = os.path.join(folder_name, sub_folder_name, 'eval_step_7080', 'pred_gs3.0_scale-cond1.0-ref1.0')
+ video_img_source_path = os.path.join(folder_name, sub_folder_name, 'eval_step_7200', 'pred_gs3.0_scale-cond1.0-ref1.0')
+ # video_img_source_path = os.path.join(folder_name, sub_folder_name, 'eval_step_17790', 'pred_gs3.0_scale-cond1.0-ref1.0')
+ if save_folder_name is None:
+ save_path = video_img_source_path
+ else: # use specific save folder
+ save_path = os.path.join(save_folder_name, sub_folder_name, 'pred_gs3.0_scale-cond1.0-ref1.0')
+ os.makedirs(save_path, exist_ok=True)
+
+ # if exists
+ video_save_path = "{}_vid_output.mp4".format(save_path)
+ if os.path.isfile(video_save_path) and os.path.getsize(video_save_path)>10000:
+ print('has done, skip this')
+ continue
+
+ fps = 30
+ size = (256, 256)
+ codec = cv2.VideoWriter_fourcc(*"mp4v")
+
+ # Get a list of all files in the folder
+ folder_path = video_img_source_path
+ try:
+ files = os.listdir(folder_path)
+ except:
+ print('load frame wrong, skip this')
+ continue
+
+ # Initialize video writer
+ video_writer = cv2.VideoWriter(video_save_path, codec, fps, size)
+ # Filter the list to only include image filesd
+ image_files = [file for file in files if file.endswith(".jpg") or file.endswith(".png") or file.endswith(".jpeg")]
+ num_frm = len(image_files)
+
+ for image_fname_ in image_files:
+ image_fname = '{}/{}'.format(folder_path,image_fname_)
+ frame = cv2.imread(image_fname)
+ # Write frames to video
+ video_writer.write(frame)
+
+ # Release resources
+ video_writer.release()
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/reencode_vid_folder_forvis.py b/One-to-All-Animation/benchmark/DisCo/tool/video/reencode_vid_folder_forvis.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e744f2218b0bacf545b2b9871cdf5d7174a1fc0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/reencode_vid_folder_forvis.py
@@ -0,0 +1,26 @@
+
+import os
+
+
+folder_name = ''
+save_folder_name = ''
+
+sub_folder_name_list = os.listdir(folder_name)
+sub_folder_name_list = [file for file in sub_folder_name_list if not 'json' in file]
+sub_folder_name_list.sort()
+
+for idx, sub_folder_name in enumerate(sub_folder_name_list):
+ print(sub_folder_name)
+
+ video_source_path = os.path.join(folder_name, sub_folder_name, 'cond_vid_output.mp4')
+ video_target_path = os.path.join(folder_name, sub_folder_name, 'cond_vid_output_reencode.mp4')
+
+ assert os.path.exists(video_source_path)
+
+ if os.path.exists(video_target_path):
+ print('remove the previous file')
+ os.remove(video_target_path)
+ os.system(f'ffmpeg -i {video_source_path} -c:v libx264 -c:a aac -strict -2 {video_target_path}')
+
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video.sh b/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video.sh
new file mode 100644
index 0000000000000000000000000000000000000000..c2700411364ef8903ecefaeda484e9586620f5ef
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video.sh
@@ -0,0 +1,18 @@
+export PYTHONUNBUFFERED=TRUE
+python tool/video/gen_vid_folder_forvis.py --start_idx 0 --end_idx 200 > tool/video/runsh/cond_log1.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 200 --end_idx 400 > tool/video/runsh/cond_log2.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 400 --end_idx 600 > tool/video/runsh/cond_log3.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 600 --end_idx 800 > tool/video/runsh/cond_log4.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 800 --end_idx 1000 > tool/video/runsh/cond_log5.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 1000 --end_idx 1200 > tool/video/runsh/cond_log6.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 1200 --end_idx 1400 > tool/video/runsh/cond_log7.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 1400 --end_idx 1700 > tool/video/runsh/cond_log8.txt &
+
+#export PYTHONUNBUFFERED=TRUE
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1400 --end_idx 1600 > tool/video/runsh/cond_log8.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1600 --end_idx 1800 > tool/video/runsh/cond_log9.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1800 --end_idx 2000 > tool/video/runsh/cond_log10.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 2000 --end_idx 2200 > tool/video/runsh/cond_log11.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 2200 --end_idx 2400 > tool/video/runsh/cond_log12.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 2400 --end_idx 2600 > tool/video/runsh/cond_log13.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 2600 --end_idx 2800 > tool/video/runsh/cond_log14.txt &
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video_demo.sh b/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video_demo.sh
new file mode 100644
index 0000000000000000000000000000000000000000..84a3a3d81ca6d11d3085ceededfd287dadc66911
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/runsh/process_video_demo.sh
@@ -0,0 +1,13 @@
+export PYTHONUNBUFFERED=TRUE
+python tool/video/gen_vid_folder_forvis.py --start_idx 0 --end_idx 200 --gen_idx 1 > tool/video/runsh/cond_log11.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 200 --end_idx 400 --gen_idx 1 > tool/video/runsh/cond_log12.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 400 --end_idx 600 --gen_idx 1 > tool/video/runsh/cond_log13.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 600 --end_idx 800 > tool/video/runsh/cond_log4.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 800 --end_idx 1000 > tool/video/runsh/cond_log5.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1000 --end_idx 1200 > tool/video/runsh/cond_log6.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1200 --end_idx 1400 > tool/video/runsh/cond_log7.txt &
+#python tool/video/gen_vid_folder_forvis.py --start_idx 1400 --end_idx 1700 > tool/video/runsh/cond_log8.txt &
+
+python tool/video/gen_vid_folder_forvis.py --start_idx 0 --end_idx 200 --gen_idx 0 > tool/video/runsh/log11.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 200 --end_idx 400 --gen_idx 0 > tool/video/runsh/log12.txt &
+python tool/video/gen_vid_folder_forvis.py --start_idx 400 --end_idx 600 --gen_idx 0 > tool/video/runsh/log13.txt &
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_gifs_for_fvd_subfolders.py b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_gifs_for_fvd_subfolders.py
new file mode 100644
index 0000000000000000000000000000000000000000..05ca9e74205263e9bad4e90591e31b20dd536feb
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_gifs_for_fvd_subfolders.py
@@ -0,0 +1,106 @@
+import argparse
+import threading
+from pathlib import Path
+
+import imageio
+from tqdm import tqdm
+
+
+def process_subfolder(subfolder, output_folder, fps, pbar, semaphore, format):
+ # Decrease the semaphore count
+ with semaphore:
+ # Initialize empty frames list
+ frames = []
+
+ # Read the frames in alphabetical order
+ png_files = sorted(Path(subfolder).glob("*.png"))
+ jpg_files = sorted(Path(subfolder).glob("*.jpg"))
+ frames_path = png_files + jpg_files
+
+ for frame_path in frames_path:
+ try:
+ frames.append(imageio.imread(str(frame_path)))
+ except Exception as e:
+ print(f"Couldn't read file {frame_path} because: {str(e)}")
+ continue
+
+ # Skip this subfolder if no frames could be read
+ if not frames:
+ print(f"No frames could be read from {subfolder.name}")
+ return
+
+ # Create output video
+ output_path = Path(output_folder, f"{subfolder.name}.{format}")
+ imageio.mimwrite(output_path, frames, fps=fps)
+
+ pbar.set_description(
+ f"Processed {subfolder.name}, which contains {len(frames)} frames"
+ )
+ pbar.update(1)
+
+
+def create_gif_from_folder(input_folder, output_folder, fps, num_workers, format):
+ # Ensure the output folder exists
+ Path(output_folder).mkdir(parents=True, exist_ok=True)
+
+ # Collect subfolders
+ subfolders = [sf for sf in Path(input_folder).iterdir() if sf.is_dir()]
+
+ # Initialize tqdm progress bar
+ pbar = tqdm(total=len(subfolders), desc="Creating GIFs")
+
+ # Create a thread for each subfolder
+ threads = []
+ semaphore = threading.Semaphore(num_workers)
+ for subfolder in subfolders:
+ thread = threading.Thread(
+ target=process_subfolder,
+ args=(subfolder, output_folder, fps, pbar, semaphore, format),
+ )
+ threads.append(thread)
+ thread.start()
+
+ # Wait for all threads to finish
+ for thread in threads:
+ thread.join()
+
+ pbar.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument(
+ "-i",
+ "--input_folder",
+ type=str,
+ required=True,
+ help="Input folder path containing subfolders with frames",
+ )
+ parser.add_argument(
+ "-o",
+ "--output_folder",
+ type=str,
+ default=None,
+ help="Output folder path to save generated gifs. If not specified, '_gif' is appended to the input folder name.",
+ )
+ parser.add_argument(
+ "-f",
+ "--fps",
+ type=int,
+ default=3,
+ help="Frames per second for the generated GIFs",
+ )
+ parser.add_argument(
+ "-n", "--num_workers", type=int, default=16, help="Number of worker threads"
+ )
+ parser.add_argument("--format", type=str, default="mp4", choices=["gif", "mp4"])
+ args = parser.parse_args()
+
+ # If output folder is not specified, append '_gif' to the input folder name
+ args.input_folder = args.input_folder.rstrip("/")
+ if args.output_folder is None:
+ args.output_folder = str(Path(args.input_folder).resolve()) + f"_{args.format}"
+
+ create_gif_from_folder(
+ args.input_folder, args.output_folder, args.fps, args.num_workers, args.format
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid.py b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid.py
new file mode 100644
index 0000000000000000000000000000000000000000..709ac515f657c363c0a6f758e2687830e2b6d287
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid.py
@@ -0,0 +1,102 @@
+import argparse
+import re
+from pathlib import Path
+
+import cv2
+from tqdm import tqdm
+
+
+def assemble_frames_to_videos(input_folder_path, output_folder_path, fps=30):
+ # Define the two formats
+ format1 = r"^(TiktokDance_\d+_)(\d+)(\D+\.\w+)$"
+ format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\D+\.\w+)$"
+ format3 = r"^(S\d{3}C\d{3}P\d{3}R\d{3}A\d{3}_)(\d{4})(\D*\.\w+)$"
+
+ # Create a Path object
+ input_path = Path(input_folder_path)
+ assert input_path.exists(), f"Input folder '{input_folder_path}' does not exist"
+ output_path = Path(output_folder_path)
+ if not output_path.exists():
+ output_path.mkdir(parents=True)
+
+ # Use a dictionary to group frame file paths by video names
+ frames_dict = {}
+
+ # Iterate over image files in the directory
+ for img_file in input_path.glob("*"):
+ # Use the regex that matches the file name
+ if re.match(format1, img_file.name):
+ format_regex = format1
+ elif re.match(format2, img_file.name):
+ format_regex = format2
+ elif re.match(format3, img_file.name):
+ format_regex = format3
+ else:
+ print(f"File name '{img_file.name}' does not match any format")
+ continue # skip if the file name does not match either format
+
+ match = re.match(format_regex, img_file.name)
+ video_name = match.group(1)[:-1] # Remove the trailing underscore
+ frame_index = int(match.group(2))
+
+ # Add the frame file path to the corresponding group
+ if video_name not in frames_dict:
+ frames_dict[video_name] = []
+ frames_dict[video_name].append((frame_index, img_file))
+
+ print(f"Found {len(frames_dict)} videos")
+
+ # Iterate over groups to create videos
+ for video_name, frames in tqdm(frames_dict.items(), desc="Assembling videos"):
+ # Sort frames by index
+ frames.sort(key=lambda x: x[0])
+
+ # Load the first frame to get the frame size
+ frame0 = cv2.imread(str(frames[0][1]))
+ frame_size = (frame0.shape[1], frame0.shape[0])
+
+ # Create a VideoWriter object
+ fourcc = cv2.VideoWriter_fourcc(
+ *"mp4v"
+ ) # 'mp4v' is a codec used for .mp4 videos
+ output_video_path = output_path / f"{video_name}.mp4"
+ video_out = cv2.VideoWriter(str(output_video_path), fourcc, fps, frame_size)
+
+ # Write frames to the video
+ for _, img_file in tqdm(
+ frames, desc=f"Writing frames for video '{video_name}'"
+ ):
+ frame = cv2.imread(str(img_file))
+ video_out.write(frame)
+
+ # Release the VideoWriter
+ video_out.release()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Assemble frames into videos")
+ parser.add_argument(
+ "-i",
+ "--input_folder",
+ required=True,
+ type=str,
+ help="Input folder path containing frames",
+ )
+ parser.add_argument(
+ "-o",
+ "--output_folder",
+ default="",
+ type=str,
+ help="Output folder path for videos",
+ )
+ parser.add_argument(
+ "--fps", default=30, type=int, help="Frames per second for the output videos"
+ )
+
+ args = parser.parse_args()
+
+ args.input_folder = args.input_folder.rstrip("/")
+ if args.output_folder == "":
+ args.output_folder = args.input_folder + "_videos"
+
+ assemble_frames_to_videos(args.input_folder, args.output_folder, args.fps)
diff --git a/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid_subfolders.py b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid_subfolders.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f6fa72cadce317191c8bab466b49ebb7a609339
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/tool/video/yz_gen_vid_subfolders.py
@@ -0,0 +1,135 @@
+import argparse
+import re
+from pathlib import Path
+
+import cv2
+from tqdm import tqdm
+
+
+def assemble_frames_to_videos(input_folder_path, output_folder_path, fps=30, interval=8):
+ # Define the two formats
+ folder_format1 = r"^(TiktokDance_\d+_)(\d+)(\D+)$"
+ folder_format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\D+)$"
+
+ frame_format1 = r"^(TiktokDance_\d+_)(\d+)(\D*\.\w+)$"
+ frame_format2 = r"^(TiktokDance_\d+_\d+_1x1_)(\d+)(\D*\.\w+)$"
+
+ # Create a Path object
+ input_path = Path(input_folder_path)
+ assert input_path.exists(), f"Input folder '{input_folder_path}' does not exist"
+ output_path = Path(output_folder_path)
+ if not output_path.exists():
+ output_path.mkdir(parents=True)
+
+ # Use a dictionary to group frame file paths by video names
+ frames_dict = {}
+ subfolders = sorted(list(input_path.glob("*")))
+
+ for i, folder in tqdm(enumerate(subfolders), desc="reading folders", total=len(subfolders)):
+ if not folder.is_dir():
+ print(f"ignoring non-folder file {folder.name}")
+ continue
+ if re.match(folder_format1, folder.name):
+ folder_format_regex = folder_format1
+ match1 = True
+ elif re.match(folder_format2, folder.name):
+ folder_format_regex = folder_format2
+ match1 = False
+ else:
+ print(f"Folder name '{folder.name}' does not match any format")
+ continue
+
+ match = re.match(folder_format_regex, folder.name)
+ video_name = match.group(1)[:-1] # Remove the trailing underscore
+ folder_index = int(match.group(2))
+
+ end_of_video = False
+ if i == len(subfolders) - 1:
+ end_of_video = True
+ elif match1 and subfolders[i + 1].name[:18] != folder.name[:18]:
+ end_of_video = True
+ elif not match1 and subfolders[i + 1].name[:23] != folder.name[:23]:
+ end_of_video = True
+
+ if match1 and (folder_index - 1) % interval != 0 and not end_of_video: # assume folder_index starts from 1 if match1
+ print(f"skipping folder {folder.name}")
+ continue
+ if not match1 and folder_index % interval != 0 and not end_of_video: # assume folder_index starts from 0 if not match1
+ print(f"skipping folder {folder.name}")
+ continue
+
+ if video_name not in frames_dict:
+ frames_dict[video_name] = []
+ for frame in folder.glob("*"):
+ if re.match(frame_format1, frame.name):
+ frame_format_regex = frame_format1
+ elif re.match(frame_format2, frame.name):
+ frame_format_regex = frame_format2
+ else:
+ print(f"Frame name '{frame.name}' does not match any format")
+ continue
+
+ match = re.match(frame_format_regex, frame.name)
+ frame_index = int(match.group(2))
+ if frame_index >= len(frames_dict[video_name]):
+ frames_dict[video_name].append((frame_index, frame))
+ else:
+ frames_dict[video_name][frame_index] = (frame_index, frame)
+
+ print(f"Found {len(frames_dict)} videos")
+
+ # Iterate over groups to create videos
+ for video_name, frames in tqdm(frames_dict.items(), desc="Assembling videos"):
+ # Sort frames by index
+ frames.sort(key=lambda x: x[0])
+
+ # Load the first frame to get the frame size
+ frame0 = cv2.imread(str(frames[0][1]))
+ frame_size = (frame0.shape[1], frame0.shape[0])
+
+ # Create a VideoWriter object
+ fourcc = cv2.VideoWriter_fourcc(
+ *"mp4v"
+ ) # 'mp4v' is a codec used for .mp4 videos
+ output_video_path = output_path / f"{video_name}.mp4"
+ video_out = cv2.VideoWriter(str(output_video_path), fourcc, fps, frame_size)
+
+ # Write frames to the video
+ for _, img_file in tqdm(
+ frames, desc=f"Writing frames for video '{video_name}'"
+ ):
+ frame = cv2.imread(str(img_file))
+ video_out.write(frame)
+
+ # Release the VideoWriter
+ video_out.release()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Assemble frames into videos")
+ parser.add_argument(
+ "-i",
+ "--input_folder",
+ required=True,
+ type=str,
+ help="Input folder path containing frames",
+ )
+ parser.add_argument(
+ "-o",
+ "--output_folder",
+ default="",
+ type=str,
+ help="Output folder path for videos",
+ )
+ parser.add_argument(
+ "--fps", default=30, type=int, help="Frames per second for the output videos"
+ )
+ parser.add_argument("--interval", default=7, type=int, help="Interval between subfolders")
+
+ args = parser.parse_args()
+
+ args.input_folder = args.input_folder.rstrip("/")
+ if args.output_folder == "":
+ args.output_folder = args.input_folder + "_videos"
+
+ assemble_frames_to_videos(args.input_folder, args.output_folder, args.fps, args.interval)
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/args.py b/One-to-All-Animation/benchmark/DisCo/utils/args.py
new file mode 100644
index 0000000000000000000000000000000000000000..6eea4c0b85a99f3b4c3c92157e6681c4d8b9010c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/args.py
@@ -0,0 +1,424 @@
+from utils.lib import *
+from utils.dist import dist_init
+from config import BasicArgs
+from utils.wutils_ldm import import_filename
+
+
+def str_to_bool(value):
+ if value.lower() in {'false', 'f', '0', 'no', 'n'}:
+ return False
+ elif value.lower() in {'true', 't', '1', 'yes', 'y'}:
+ return True
+ raise ValueError(f'{value} is not a valid boolean value')
+
+
+def parse_with_config(parsed_args):
+ """This function will set args based on the input config file.
+ (1) it only overwrites unset parameters,
+ i.e., these parameters not set from user command line input
+ (2) it also sets configs in the config file but declared in the parser
+ """
+ # convert to EasyDict object,
+ # enabling access from attributes even for nested config
+ # e.g., args.train_datasets[0].name
+ args = edict(vars(parsed_args))
+ if args.config is not None:
+ config_args = json.load(open(args.config))
+ override_keys = {arg[2:].split("=")[0] for arg in sys.argv[1:]
+ if arg.startswith("--")}
+ for k, v in config_args.items():
+ if k not in override_keys:
+ setattr(args, k, v)
+ del args.config
+ return args
+
+
+def parse_with_cf(parsed_args):
+ """This function will set args based on the input config file.
+ (1) it only overwrites unset parameters,
+ i.e., these parameters not set from user command line input
+ (2) it also sets configs in the config file but declared in the parser
+ """
+ # convert to EasyDict object,
+ # enabling access from attributes even for nested config
+ # e.g., args.train_datasets[0].name
+ args = edict(vars(parsed_args))
+ if os.path.exists(parsed_args.cf):
+ cf = import_filename(parsed_args.cf)
+ config_args = edict(vars(cf.Args))
+ override_keys = {arg[2:].split("=")[0] for arg in sys.argv[1:]
+ if arg.startswith("--")}
+ for k, v in config_args.items():
+ if k not in override_keys:
+ setattr(args, k, v)
+ else:
+ raise NotImplementedError('Config filename %s does not exist.' % args.cf)
+ return args
+
+
+def update_args(parsed_args, args):
+ for key in vars(parsed_args):
+ val = getattr(parsed_args, key)
+ if key in ["epochs", "train_batch_size", "eval_batch_size", "train_yaml", "val_yaml", "learning_rate"]:
+ if val is None:
+ continue
+ if key == "log_dir":
+ if val is None:
+ continue
+ else:
+ val = os.path.join(BasicArgs.root_dir, parsed_args.log_dir)
+ if key == "root_dir":
+ continue
+ setattr(args, key, val)
+ return args
+
+
+class Args(object):
+ """Shared options for pre-training and downstream tasks.
+ For each downstream task, implement a get_*_args function,
+ see `get_pretraining_args()`
+
+ Usage:
+ >>> shared_configs = SharedConfigs()
+ >>> pretraining_config = shared_configs.get_pretraining_args()
+ """
+
+ def __init__(self, desc="shared config"):
+ parser = argparse.ArgumentParser(description=desc)
+ parser.add_argument('--root_dir', default=None, type=str)
+ parser.add_argument('--cf', default=None, type=str, required=True)
+ parser.add_argument('--pretrained_model', default=None, type=str)
+ parser.add_argument('--pretrained_model_lora', default=None, type=str)
+ parser.add_argument('--pretrained_model_controlnet', default=None, type=str)
+ parser.add_argument('--debug', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--debug_seed', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--debug_dataloader', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--log_dir', default=None, type=str)
+ parser.add_argument('--deepspeed',
+ help="use deepspeed", type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--use_amp', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--seed', type=int, default=42,
+ help="random seed for initialization.")
+ parser.add_argument('--fix_dist_seed', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--tiktok_data_root', default=None, type=str)
+ # parser.add_argument('--tiktok_ann_root', default=None, type=str)
+
+ # input
+ parser.add_argument("--img_size", default=256, type=int,
+ help="image input size")
+ parser.add_argument("--max_video_len", default=4, type=int,
+ help="frame input length")
+ parser.add_argument("--debug_max_video_len", default=4, type=int,
+ help="debug frame input length")
+ parser.add_argument("--conds", default=[], #
+ nargs='+', type=str,
+ choices=["poses", "masks", "densepose", "hed", "canny_100_200", "midas", "mlsd_0.1_0.1", "uniformer"],
+ help="used in uni-controlnet/tsv datasets")
+
+ # Model setting
+ parser.add_argument('--gradient_checkpointing', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--find_unused_parameters', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--enable_xformers_memory_efficient_attention', type=str_to_bool,
+ nargs='?', const=True, default=False)
+
+ # SD related
+ parser.add_argument(
+ "--trainable_modules", type=str, nargs='+', default=None)
+ parser.add_argument("--scale_factor", default=0.18215, type=float,
+ help="scale factor in SD")
+ parser.add_argument("--loss_target", default="noise", type=str,
+ choices=["noise", "x0", "mixed"],
+ help="unet_loss_target")
+ parser.add_argument("--x0_steps", default=200, type=int,
+ help="steps to calc x0 loss")
+ parser.add_argument('--pretrained_model_path', default='diffusers/stable-diffusion-v1-4', type=str)
+
+ # training configs
+ parser.add_argument("--num_workers", default=4, type=int,
+ help="number of workers")
+ parser.add_argument('--node_split_sampler',
+ help="use node_split_sampler", type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--gradient_accumulate_steps', default=1, type=int)
+ parser.add_argument('--max_grad_norm', default=-1, type=float)
+ parser.add_argument('--learning_rate', default=5e-6, type=float)
+ parser.add_argument("--decay", default=1e-3, type=float,
+ help="Weight deay.")
+ parser.add_argument("--warmup_ratio", default=0.1, type=float,
+ help="warm up ratio of lr")
+ parser.add_argument("--max_train_samples", default=None, type=int,
+ help="number train samples")
+ parser.add_argument("--debug_max_train_samples", default=100, type=int,
+ help="number train samples in debug mode")
+ parser.add_argument("--drop_text", default=1.0, type=float, # drop text only activate in args.null_caption
+ help="prob to drop text")
+ # Note that tbs/ebs is the Global batch size = GPU_PER_NODE * NODE_COUNT * LOCAL_BATCH_SIZE
+ parser.add_argument('--local_train_batch_size', default=1, type=int)
+ parser.add_argument('--epochs', default=10, type=int)
+ parser.add_argument('--eval_step', default=5, type=float)
+ parser.add_argument('--save_step', default=5, type=float)
+ parser.add_argument('--do_train', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--train_yaml', default=None, type=str)
+ parser.add_argument('--resume', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--null_caption', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--refer_sdvae', type=str_to_bool, # use sd vae to process the reference image
+ nargs='?', const=True, default=False)
+ parser.add_argument('--controlnet_conditioning_scale_cond', default=1.0, type=float)
+ parser.add_argument('--controlnet_conditioning_scale_ref', default=1.0, type=float)
+
+ ### for temporal disco
+ parser.add_argument("--nframes", type=int, default=8, help="the number of frames for synthesis")
+ parser.add_argument("--frame_interval", type=int, default=1, help="frame interval for synthesis")
+ parser.add_argument("--eval_sample_interval", type=float, default=1, help="eval interval for fast evalaution, only valid for video datasets")
+ parser.add_argument("--train_sample_interval", type=float, default=1, help="train interval for fast training")
+
+ ### reference image attention
+ parser.add_argument("--unet_unfreeze_type", default=None, type=str, # if set --freeze_unet=False, will ft all the unet
+ choices=["crossattn-kv", "crossattn", "transblocks", "all", "null"],
+ help="which structure of unet will be unfreezed")
+ parser.add_argument('--controlnet_attn', type=str_to_bool,
+ nargs='?', const=True, default=False, help="if use ref image to replace the text prompt in controlnet")
+ parser.add_argument('--use_cfg', type=str_to_bool,
+ nargs='?', const=True, default=False, help="if use classifier free guidance for image")
+
+ ### reference image attention with clip
+ parser.add_argument('--refer_clip_preprocess', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use clip preprocess in diffusers to process the reference image')
+ parser.add_argument('--refer_clip_proj', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use pretrained clip visual projection layer for the reference image')
+
+ ### reference image attention with clip + combine controlnet path
+ parser.add_argument('--ref_null_caption', type=str_to_bool, # use null caption for the reference controlnet path
+ nargs='?', const=True, default=False)
+ parser.add_argument('--combine_clip_local', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use local clip feature in combine controlnet path (a bit messey here)')
+ parser.add_argument('--combine_use_mask', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if add mask annotation to the (attn + controlnet) structure; default: attn human pose; controlnet background')
+ parser.add_argument("--drop_ref", default=0., type=float, # drop the reference image during trianing?
+ help="prob to drop reference image")
+ parser.add_argument('--my_adapter', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use my adapter?')
+
+ ### no crop in training, resize after generation (post resize)
+ parser.add_argument('--pos_resize_img', type=str_to_bool,
+ nargs='?', const=True, default=False, help='resize img to the targe size after generation?')
+ parser.add_argument("--fg_variation", default=0., type=float,
+ help="if add foreground variation during training")
+ parser.add_argument('--strong_aug_stage2', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use strong aug in stage 1 for warm up?')
+ parser.add_argument('--strong_rand_stage2', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use strong rand in stage 2 for warm up?')
+
+ ### stage 1, warm up with training attribute
+ parser.add_argument('--strong_aug_stage1', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if use strong aug in stage 1 for warm up?')
+ parser.add_argument('--stage1_pretrain_path', default=None, type=str,
+ help='if use stage 1 attribute pretraining to initialize the model (unet + ref controlnet')
+ parser.add_argument('--stage2_only_pose', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if only train pose controlnet in the 2nd stage')
+ parser.add_argument('--constant_lr', type=str_to_bool,
+ nargs='?', const=True, default=False, help='no linear lr decay?')
+
+
+ ### SD-2-1 args
+ parser.add_argument('--SD2_not_add_image_emb_noise', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if not add noise to image embedding? default add noise')
+ # evaluation configs
+ parser.add_argument('--val_yaml', default=None, type=str)
+ parser.add_argument("--max_eval_samples", default=None, type=int,
+ help="number eval samples")
+ parser.add_argument("--debug_max_eval_samples", default=20, type=int,
+ help="number eval samples")
+ parser.add_argument('--pose_normalize', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--normalize_by_1st_frm', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ # Note that tbs/ebs is the Global batch size = GPU_PER_NODE * NODE_COUNT * LOCAL_BATCH_SIZE
+ parser.add_argument('--local_eval_batch_size', default=1, type=int)
+ parser.add_argument('--eval_visu', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--eval_visu_trainsample', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--eval_visu_imagefolder', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--eval_visu_changepose', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if change pose from the other data source?')
+ parser.add_argument('--eval_visu_changefore', type=str_to_bool,
+ nargs='?', const=True, default=False, help='if change foreground from the other data source?')
+
+ parser.add_argument('--eval_save_filename', default='eval_visu', type=str)
+ parser.add_argument('--eval_before_train', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--eval_scheduler', default="ddim", type=str,
+ choices=["pndms", "ddpm", 'ddim'],
+ help="frame interpolation mode")
+ parser.add_argument('--eval_enc_dec_only', type=str_to_bool,
+ nargs='?', const=True, default=False)
+ parser.add_argument('--num_inf_videos_per_prompt', default=1, type=int)
+ parser.add_argument('--num_inference_steps', default=50, type=int)
+ parser.add_argument('--guidance_scale', default=3, type=float)
+ parser.add_argument('--stepwise_sample_depth',default=-1, type=int)
+ parser.add_argument('--interpolation', default=None, type=str,
+ choices=["copy", "average", 'interpolate',
+ 'average_noise', None],
+ help="frame interpolation mode")
+ parser.add_argument('--interpolate_mode',default=None, type=str,
+ choices=["nearest", "bilinear", 'trilinear', 'area', 'nearest-exact', None],
+ help="frame interpolation mode")
+
+ ### save the visualization file?
+ parser.add_argument('--visu_save', type=str_to_bool, # if True, means save the visualization file with each filename
+ nargs='?', const=True, default=False)
+
+ ### stage3 ft on specific images
+ parser.add_argument('--freeze_pose', type=str_to_bool,
+ nargs='?', const=True, default=False, help='freeze the pose path?')
+ parser.add_argument('--freeze_background', type=str_to_bool,
+ nargs='?', const=True, default=False, help='freeze the background path?')
+ parser.add_argument('--ft_img_num', default=0, type=int, help='use how many frame as the training sample? 0 denote all')
+ parser.add_argument('--ft_one_ref_image', type=str_to_bool,
+ nargs='?', const=True, default=True, help='only use first frame as the ref image?')
+ parser.add_argument('--ft_iters', default=None, type=int)
+
+
+ ### dreampose baseline ###
+ parser.add_argument("--s1", default=1.0, type=float, # the param s1 for dreampose
+ help="the param s1 for dreampose")
+ parser.add_argument("--s2", default=1.0, type=float, # the param s2 for dreampose
+ help="the param s2 for dreampose")
+
+ ### stage 3 ft ###
+ parser.add_argument("--ft_idx", default=None, type=str, # if set --freeze_unet=False, will ft all the unet
+ help="ft video idx from web folder")
+
+ ### stage 2 ref mode ###
+ parser.add_argument("--ref_mode", default='first', type=str,
+ help="ref mode")
+ self.parser = parser
+
+ def parse_args(self):
+ parsed_args = self.parser.parse_args()
+ if parsed_args.root_dir:
+ BasicArgs.root_dir = parsed_args.root_dir
+ else:
+ parsed_args.root_dir = BasicArgs.root_dir
+ parsed_args.pretrained_model_path = os.path.join(parsed_args.root_dir, parsed_args.pretrained_model_path)
+ args = parse_with_cf(parsed_args)
+ if args.debug:
+ args.max_video_len = getattr(args, 'debug_max_video_len', 1)
+ args.max_train_samples = getattr(args, 'debug_max_train_samples', 100)
+ args.max_eval_samples = getattr(args, 'debug_max_eval_samples', 20)
+ args.num_workers = 0
+ args.epochs = 2
+ args.eval_step = 1
+ args.save_step = 1
+ if hasattr(args, 'debug_train_yaml'):
+ args.train_yaml = args.debug_train_yaml
+ if hasattr(args, 'debug_val_yaml'):
+ args.val_yaml = args.debug_val_yaml
+
+ args.n_gpu = T.cuda.device_count() # local size
+ args.local_size = args.n_gpu
+ if args.root_dir not in args.log_dir:
+ args.log_dir = os.path.join(args.root_dir, args.log_dir)
+
+ # if len(args.conds) > 0:
+ # args.log_dir += "_".join(args.conds)
+
+ # args.wandb_project = [
+ # p_.replace(".py", "")
+ # for p_ in args.cf.split("/")
+ # if p_ != "config" and p_ != "."]
+ # args.wandb_project = [args.method_name] + args.log_dir.split('/')[-2:]
+ args.wandb_project = args.log_dir.split('/')[-2:]
+ # args.project_name = "/".join(
+ # args.wandb_project)
+ args.project_name = args.wandb_project[1]
+ # args.wandb_project = args.task_name #args.wandb_project[0]
+ args.wandb_project = args.wandb_project[0]
+
+ if args.stepwise_sample_depth == -1:
+ args.interpolation = None
+ args.interpolate_mode = None
+ if args.interpolation != "interpolate":
+ args.interpolate_mode = None
+
+ assert args.eval_step > 0, "eval_step must be positive"
+ assert args.save_step > 0, "save_step must be positive"
+
+ dist_init(args)
+ args.dist = args.distributed
+ args.nodes = args.num_nodes
+ args.world_size = args.num_gpus
+ args.train_batch_size = args.local_train_batch_size * args.world_size
+ args.eval_batch_size = args.local_eval_batch_size * args.world_size
+ return args
+
+
+sharedArgs = Args()
+
+
+# def get_args(distributed=True):
+# args = sharedArgs.parse_args()
+# dist_init(args, distributed)
+
+# if not args.distributed:
+# args.deepspeed = False
+
+# args.effective_batch_size = args.size_batch * args.num_gpus
+# if os.path.exists(args.path_ckpt):
+# path_ckpt_dir = os.path.dirname(args.path_ckpt)
+# training_args = f"{path_ckpt_dir}/args.json"
+# if os.path.exists(training_args):
+# args = update_args(args)
+# return args
+
+
+# def update_args(args):
+# path_ckpt_dir = os.path.dirname(args.path_ckpt)
+# training_args = edict(json.load(open(f"{path_ckpt_dir}/args.json", "r")))
+
+# print("===============Loaded model training args=================")
+# print(f"\t\t{json.dumps(training_args)}")
+# print("===============Default args=================")
+# print(f"\t\t{json.dumps(args)}")
+# toUpdate = [
+# "vis_backbone", "vis_backbone_size", "temporal_fusion",
+# "imagenet", "kinetics", "swinbert",
+# "txt_backbone", "fusion_encoder",
+# "txt_backbone_embed_only", "tokenizer", "mask_pos", "fuse_type",
+# "num_fuse_block_t2i", "num_fuse_block_i2t"]
+# if args.size_epoch == 0:
+# toUpdate += ['size_frame', 'size_txt', 'size_img', 'img_transform']
+# args.imagenet_norm = False
+# for key in training_args:
+# if key == "imagenet_norm":
+# args.imagenet_norm = training_args.imagenet_norm
+# if key in toUpdate:
+# args[key] = training_args[key]
+# if "vidswin" in key:
+# new_key = key.replace("vidswin", "vis_backbone")
+# print(f"Make old key compatible, old: {key}, new {new_key}")
+# args[new_key] = training_args[key]
+# if "backbone" in key and not (
+# 'vis_backbone' in key or 'txt_backbone' in key):
+# new_key = key.replace("backbone", "vis_backbone")
+# print(f"Make old key compatible, old: {key}, new {new_key}")
+# if new_key in toUpdate:
+# args[new_key] = training_args[key]
+# if "vis_backbone" not in training_args and "backbone" not in training_args:
+# print(f"Evaluating models without specific backbone,"
+# f"revert to default: vidswin")
+# args.vis_backbone = "vidswin"
+# return args
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/basic_utils.py b/One-to-All-Animation/benchmark/DisCo/utils/basic_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..5ab3e08c0cadaf7de8690bc34df8e98e7a284b85
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/basic_utils.py
@@ -0,0 +1,204 @@
+import os
+import json
+import zipfile
+import numpy as np
+import pickle
+import torch
+
+
+def load_pickle(filename):
+ with open(filename, "rb") as f:
+ return pickle.load(f)
+
+
+def save_pickle(data, filename):
+ with open(filename, "wb") as f:
+ pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL)
+
+
+def is_jsonable(x):
+ try:
+ json.dumps(x)
+ return True
+ except:
+ return False
+
+
+def load_json(filename):
+ with open(filename, "r") as f:
+ return json.load(f)
+
+
+def save_json(data, filename, save_pretty=False, sort_keys=False):
+ with open(filename, "w") as f:
+ if save_pretty:
+ f.write(json.dumps(data, indent=4, sort_keys=sort_keys))
+ else:
+ json.dump(data, f)
+
+
+def load_jsonl(filename):
+ with open(filename, "r") as f:
+ return [json.loads(l.strip("\n")) for l in f.readlines()]
+
+
+def save_jsonl(data, filename):
+ """data is a list"""
+ with open(filename, "w") as f:
+ f.write("\n".join([json.dumps(e) for e in data]))
+
+
+def concat_json_list(filepaths, save_path):
+ json_lists = []
+ for p in filepaths:
+ json_lists += load_json(p)
+ save_json(json_lists, save_path)
+
+
+def save_lines(list_of_str, filepath):
+ with open(filepath, "w") as f:
+ f.write("\n".join(list_of_str))
+
+
+def read_lines(filepath):
+ with open(filepath, "r") as f:
+ return [e.strip("\n") for e in f.readlines()]
+
+
+def mkdirp(p):
+ if not os.path.exists(p):
+ os.makedirs(p)
+
+
+def flat_list_of_lists(l):
+ """flatten a list of lists [[1,2], [3,4]] to [1,2,3,4]"""
+ return [item for sublist in l for item in sublist]
+
+
+def convert_to_seconds(hms_time):
+ """ convert '00:01:12' to 72 seconds.
+ :hms_time (str): time in comma separated string, e.g. '00:01:12'
+ :return (int): time in seconds, e.g. 72
+ """
+ times = [float(t) for t in hms_time.split(":")]
+ return times[0] * 3600 + times[1] * 60 + times[2]
+
+
+def get_video_name_from_url(url):
+ return url.split("/")[-1][:-4]
+
+
+def merge_dicts(list_dicts):
+ merged_dict = list_dicts[0].copy()
+ for i in range(1, len(list_dicts)):
+ merged_dict.update(list_dicts[i])
+ return merged_dict
+
+
+def l2_normalize_np_array(np_array, eps=1e-5):
+ """np_array: np.ndarray, (*, D), where the last dim will be normalized"""
+ return np_array / (np.linalg.norm(np_array, axis=-1, keepdims=True) + eps)
+
+
+def make_zipfile(src_dir, save_path, enclosing_dir="", exclude_dirs=None, exclude_extensions=None,
+ exclude_dirs_substring=None):
+ """make a zip file of root_dir, save it to save_path.
+ exclude_paths will be excluded if it is a subdir of root_dir.
+ An enclosing_dir is added is specified.
+ """
+ abs_src = os.path.abspath(src_dir)
+ with zipfile.ZipFile(save_path, "w") as zf:
+ for dirname, subdirs, files in os.walk(src_dir):
+ if exclude_dirs is not None:
+ for e_p in exclude_dirs:
+ if e_p in subdirs:
+ subdirs.remove(e_p)
+ if exclude_dirs_substring is not None:
+ to_rm = []
+ for d in subdirs:
+ if exclude_dirs_substring in d:
+ to_rm.append(d)
+ for e in to_rm:
+ subdirs.remove(e)
+ arcname = os.path.join(enclosing_dir, dirname[len(abs_src) + 1:])
+ zf.write(dirname, arcname)
+ for filename in files:
+ if exclude_extensions is not None:
+ if os.path.splitext(filename)[1] in exclude_extensions:
+ continue # do not zip it
+ absname = os.path.join(dirname, filename)
+ arcname = os.path.join(enclosing_dir, absname[len(abs_src) + 1:])
+ zf.write(absname, arcname)
+
+
+class AverageMeter(object):
+ """Computes and stores the average and current/max/min value"""
+ def __init__(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+ self.max = -1e10
+ self.min = 1e10
+ self.reset()
+
+ def reset(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+ self.max = -1e10
+ self.min = 1e10
+
+ def update(self, val, n=1):
+ self.max = max(val, self.max)
+ self.min = min(val, self.min)
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
+
+
+def dissect_by_lengths(np_array, lengths, dim=0, assert_equal=True):
+ """Dissect an array (N, D) into a list a sub-array,
+ np_array.shape[0] == sum(lengths), Output is a list of nd arrays, singlton dimention is kept"""
+ if assert_equal:
+ assert len(np_array) == sum(lengths)
+ length_indices = [0, ]
+ for i in range(len(lengths)):
+ length_indices.append(length_indices[i] + lengths[i])
+ if dim == 0:
+ array_list = [np_array[length_indices[i]:length_indices[i+1]] for i in range(len(lengths))]
+ elif dim == 1:
+ array_list = [np_array[:, length_indices[i]:length_indices[i + 1]] for i in range(len(lengths))]
+ elif dim == 2:
+ array_list = [np_array[:, :, length_indices[i]:length_indices[i + 1]] for i in range(len(lengths))]
+ else:
+ raise NotImplementedError
+ return array_list
+
+
+def get_ratio_from_counter(counter_obj, threshold=200):
+ keys = counter_obj.keys()
+ values = counter_obj.values()
+ filtered_values = [counter_obj[k] for k in keys if k > threshold]
+ return float(sum(filtered_values)) / sum(values)
+
+
+def get_rounded_percentage(float_number, n_floats=2):
+ return round(float_number * 100, n_floats)
+
+
+def move_to_cuda(batch):
+ if isinstance(batch, torch.Tensor):
+ return batch.cuda(non_blocking=True)
+ elif isinstance(batch, list):
+ new_batch = [move_to_cuda(t) for t in batch]
+ elif isinstance(batch, tuple):
+ new_batch = tuple(move_to_cuda(t) for t in batch)
+ elif isinstance(batch, dict):
+ new_batch = {n: move_to_cuda(t) for n, t in batch.items()}
+ else:
+ return batch
+ return new_batch
+
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/cloud_storage.py b/One-to-All-Animation/benchmark/DisCo/utils/cloud_storage.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa4e56ab6c803354da1403ab0342e1982ad624fa
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/cloud_storage.py
@@ -0,0 +1,1312 @@
+import contextlib
+import time
+import sys
+from .common import get_mpi_local_size, get_mpi_local_rank, get_mpi_rank, get_mpi_size
+from .common import get_azfuse_env
+from .tsv_io import robust_open_to_write
+from .common import query_all_opened_file_in_system
+from .common import ensure_remove_file
+from .common import has_handle
+from .common import get_file_size
+from .common import hash_sha1
+from .common import parallel_imap
+from .common import acquireLock, hash_sha1, releaseLock
+from .common import write_to_file
+from .common import limited_retry_agent
+import shutil
+import multiprocessing as mp
+import os.path as op
+from .common import ensure_remove_dir
+from azure.storage.blob import BlockBlobService
+from azure.storage.common.storageclient import logger
+import glob
+from pprint import pformat
+from .common import load_from_yaml_file
+from .common import cmd_run
+import subprocess as sp
+from .common import parse_iteration
+import logging
+from .common import qd_tqdm as tqdm
+import os
+from .common import ensure_directory
+logger.propagate = False
+from deprecated import deprecated
+
+
+def create_cloud_storage(x=None, config_file=None, config=None):
+ if config is not None:
+ return CloudStorage(config)
+ if config_file is None:
+ #config_file = './aux_data/configs/{}blob_account.yaml'.format(x)
+ config_file = './aux_data/storage_account/{}.yaml'.format(x)
+ config = load_from_yaml_file(config_file)
+ c = CloudStorage(config)
+ return c
+
+def azcopy_upload(src, dest_url, dest_key):
+ cmd = [get_azcopy(), '--source',
+ src,
+ '--destination',
+ dest_url,
+ '--exclude-older',
+ '--dest-key',
+ "{}".format(dest_key),
+ '--quiet',
+ '--parallel-level',
+ '32']
+ resume_file = '/tmp/azure.' + hash_sha1([src, dest_url]) + '.jnl'
+ cmd.append('--resume')
+ cmd.append(resume_file)
+ if op.isdir(src):
+ cmd.append('--recursive')
+ cmd_run(cmd, shell=True)
+
+def blob_upload_qdoutput(src_path, dest_path, client):
+ to_copy = get_to_copy_file_for_qdoutput(src_path, dest_path)
+ for f, d in to_copy:
+ client.az_upload2(f, d)
+
+def get_to_copy_file_for_qdoutput(src_path, dest_path):
+ # upload all the files under src_path
+ to_copy = []
+ all_src_file = glob.glob(op.join(src_path, '*'))
+ exclude_suffix = ['txt', 'zip']
+ for f in all_src_file:
+ if op.isfile(f) and not any(f.endswith(s) for s in exclude_suffix):
+ to_copy.append((f, op.join(dest_path, op.basename(f))))
+
+ # for the model and the tested files, only upload the best
+ all_src_file = glob.glob(op.join(src_path, 'snapshot',
+ 'model_iter_*.caffemodel'))
+ all_src_file.extend(glob.glob(op.join(src_path, 'snapshot',
+ 'model_iter_*.pt')))
+ all_iter = [parse_iteration(f) for f in all_src_file]
+ max_iters = max(all_iter)
+ need_copy_files = [f for f, i in zip(all_src_file, all_iter) if i == max_iters]
+ dest_snapshot = op.join(dest_path, 'snapshot')
+ for f in need_copy_files:
+ to_copy.append((f, op.join(dest_snapshot, op.basename(f))))
+ if f.endswith('.caffemodel'):
+ f = f.replace('.caffemodel', '.solverstate')
+ to_copy.append((f, op.join(dest_snapshot, op.basename(f))))
+ return to_copy
+
+def blob_upload(src, dst, c=None):
+ if c is None:
+ c = create_cloud_storage('vig')
+ c.az_upload2(src, dst)
+
+def get_root_all_full_expid(full_expid_prefix, all_blob_name):
+ # full_expid_prefix can be the folder of full_expid; or with some prefix so
+ # that we can filter
+ if all(b.startswith(full_expid_prefix + '/') for b in all_blob_name):
+ root = full_expid_prefix
+ else:
+ root = op.dirname(full_expid_prefix)
+ all_full_expid = set(b[len(root) + 1:].split('/')[0] for b in
+ all_blob_name if b.startswith(root))
+ return root, all_full_expid
+
+def get_azcopy():
+ # this is v10
+ azcopy = op.expanduser('~/code/azcopy/azcopy')
+ if not op.isfile(azcopy):
+ azcopy = 'azcopy'
+ return azcopy
+
+def get_leaf_names(all_fname):
+ # build the tree first
+ from ete3 import Tree
+ root = Tree()
+ for fname in all_fname:
+ components = fname.split('/')
+ curr = root
+ for com in components:
+ currs = [c for c in curr.children if c.name == com]
+ if len(currs) == 0:
+ curr = curr.add_child(name=com)
+ else:
+ assert len(currs) == 1
+ curr = currs[0]
+ result = []
+ for node in root.iter_leaves():
+ ans = [s.name for s in node.get_ancestors()[:-1]]
+ ans.insert(0, node.name)
+ result.append('/'.join([a for a in ans[::-1]]))
+ return result
+
+def blob_download_qdoutput(src_path, target_folder):
+ c = create_cloud_storage('vig')
+ c.blob_download_qdoutput(src_path, target_folder)
+
+def create_cloud_fuse(config=None):
+ if config is None:
+ if 'QD_CLOUD_FUSE_CONFIG_FILE' in os.environ:
+ fname = os.environ['QD_CLOUD_FUSE_CONFIG_FILE']
+ else:
+ fname = 'aux_data/configs/cloud_fuse_multi.yaml'
+ #fname = 'aux_data/configs/cloud_fuse.yaml'
+ config = load_from_yaml_file(fname)
+ assert not isinstance(config, dict)
+ return AzFuse(config)
+
+def garbage_collection_for_cloud_fuse_loop(local_folders, total_size_limit):
+ logging.info('size limit = {}'.format(total_size_limit))
+ from .common import find_mount_point, list_to_dict
+ mount_path = [(find_mount_point(l), l) for l in local_folders]
+ mount2paths = list_to_dict(mount_path, 0)
+ while True:
+ try:
+ for m, paths in mount2paths.items():
+ curr_limit = total_size_limit
+ if curr_limit < 1:
+ x = shutil.disk_usage(m)
+ curr_limit = x.total * total_size_limit
+ garbage_collection_for_cloud_fuse(paths, curr_limit)
+ except:
+ from .common import print_trace
+ print_trace()
+ time.sleep(10)
+
+def garbage_collection_for_cloud_fuse(local_folders, total_size_limit):
+ infos = []
+ for local_folder in local_folders:
+ for root, _, files in os.walk(local_folder):
+ for f in files:
+ if f.startswith('.') or f.endswith('.tmp'):
+ continue
+ f = op.join(root, f)
+ if op.isfile(f):
+ info = {
+ 'fname': f,
+ 'size_in_bytes': get_file_size(f),
+ 'last_access_time': op.getatime(f),
+ }
+ infos.append(info)
+ we_used_total = sum(i['size_in_bytes'] for i in infos)
+ if we_used_total < total_size_limit:
+ return
+ # we need to delete
+ need_to_delete = we_used_total - total_size_limit
+
+ opened = set(query_all_opened_file_in_system())
+ logging.info('queried {} opened files in system'.format(len(opened)))
+ for i in infos:
+ i['has_handle'] = has_handle(i['fname'], opened)
+ infos = sorted(infos, key=lambda i: i['last_access_time'])
+
+ deleted = []
+ skip_deleted = []
+ for i in infos:
+ if i['has_handle']:
+ skip_deleted.append(i['fname'])
+ else:
+ ensure_remove_file(i['fname'])
+ need_to_delete -= i['size_in_bytes']
+ deleted.append(i['fname'])
+ if need_to_delete < 0:
+ break
+ logging.info(
+ 'total size limit = {},'
+ 'need to delete = {},'
+ 'all occupied = {},'
+ 'deleted = {},'
+ 'skip deleted = {}'
+ .format(
+ total_size_limit,
+ we_used_total - total_size_limit,
+ sum([i['size_in_bytes'] for i in infos]),
+ pformat(deleted),
+ pformat(skip_deleted),
+ )
+ )
+
+def async_upload_thread_entry_old(async_upload_queue):
+ time_to_exit = False
+ account2cloud = {}
+ while not time_to_exit:
+ all_info = []
+ r = async_upload_queue.get()
+ if r == None:
+ time_to_exit = True
+ else:
+ all_info.append(r)
+ if len(all_info) > 0:
+ async_upload_files(all_info, account2cloud)
+
+def async_upload_thread_entry(async_upload_queue):
+ time_to_exit = False
+ account2cloud = {}
+ while not time_to_exit:
+ all_info = []
+ r = async_upload_queue.get()
+ if r == None:
+ time_to_exit = True
+ else:
+ all_info.append(r)
+ while async_upload_queue.qsize() > 0:
+ r2 = async_upload_queue.get()
+ if r2 is None:
+ time_to_exit = True
+ else:
+ all_info.append(r2)
+ if len(all_info) > 0:
+ async_upload_files(all_info, account2cloud)
+
+def async_upload_files(infos, account2cloud):
+ lock_fd = acquire_azcopy_lock()
+ rd_cd_ac_and_sn = [[(i['remote'],
+ i['cache'],
+ i['storage_account']),
+ i['sub_name']]
+ for i in infos if
+ op.isfile(op.join(i['cache'], i['sub_name']))]
+ from .common import list_to_dict
+ rd_cd_ac_to_sns = list_to_dict(rd_cd_ac_and_sn, 0)
+ for (rd, cd, ac), sns in rd_cd_ac_to_sns.items():
+ if ac not in account2cloud:
+ account2cloud[ac] = create_cloud_storage(ac)
+ if op.basename(rd[:-1] if rd.endswith('/') else rd) == op.basename(cd[:-1] if cd.endswith('/') else cd):
+ file_list = '/tmp/{}'.format(hash_sha1(pformat(sns)))
+ write_to_file('\n'.join(sns), file_list)
+ account2cloud[ac].upload(
+ cd,
+ rd,
+ file_list=file_list,
+ )
+ else:
+ for sn in sns:
+ account2cloud[ac].upload(
+ op.join(cd, sn),
+ op.join(rd, sn),
+ )
+ releaseLock(lock_fd)
+ for i in infos:
+ if i.get('clear_cache_after_upload'):
+ ensure_remove_file(op.join(i['cache'], i['sub_name']))
+
+def acquire_azcopy_lock():
+ lock_fd = acquireLock(op.join('/tmp', 'lock_azcopy_fuse'))
+ return lock_fd
+
+def get_ready_file(remote_path):
+ return remote_path + '.ready'
+
+def sync_remote_path(remote_path, from_account, to_accounts):
+ all_account = [from_account] + to_accounts
+ remote_ready_file = get_ready_file(remote_path)
+ ready = [True] + [a.file_exists(remote_ready_file)
+ for a in to_accounts]
+ while any(not r for r in ready):
+ num_ready = sum(ready)
+ num_not_ready = len(ready) - num_ready
+ num_copy = min(num_ready, num_not_ready)
+ copy_from_account = [all_account[i] for i, r in enumerate(ready)
+ if r][:num_copy]
+ copy_to_account_idx = [i for i, r in enumerate(ready) if
+ not r][:num_copy]
+ copy_to_account = [all_account[i] for i in copy_to_account_idx]
+ def copy(x):
+ from_account, to_account = x
+ limited_retry_agent(
+ 5,
+ to_account.upload,
+ remote_path, remote_path, from_blob=from_account
+ )
+ #to_account.upload(
+ #remote_path, remote_path, from_blob=from_account
+ #)
+ limited_retry_agent(
+ 5,
+ to_account.upload_stream,
+ b'done', remote_ready_file
+ )
+ #to_account.upload_stream(b'done', remote_ready_file)
+ parallel_imap(
+ copy,
+ list(zip(copy_from_account, copy_to_account)),
+ )
+ for i in copy_to_account_idx:
+ ready[i] = True
+
+class AzFuse(object):
+ # gradually deprecate CloudFuse()
+ def __init__(self, config):
+ # config is a list of dictionary (local, remote, cache, storage_account)
+ for c in config:
+ c['local'] = op.abspath(c['local'])
+ self.config = config
+
+ accounts = set([c['storage_account'] for c in self.config])
+ self.account2cloud = {a: create_cloud_storage(a) for a in accounts}
+
+ self.invoked_collector = False
+ self.async_upload_enabled = False
+ self.async_upload_queue = None
+ self.async_upload_thread = None
+ self.remove_cache_after_upload = False
+ self.shm_as_upload_tmp = False
+
+ self._aux_accounts = None
+
+ @property
+ def aux_accounts(self):
+ if self._aux_accounts is None:
+ aux_env = get_azfuse_env('AUXILIARY_STORAGE_ACCOUNTS')
+ if aux_env is None:
+ self._aux_accounts = []
+ else:
+ self._aux_accounts = [create_cloud_storage(a) for a in aux_env.split(',')]
+ return self._aux_accounts
+
+ def launch_async_upload_thread(self):
+ self.async_upload_queue = mp.Queue()
+ p = mp.Process(target=async_upload_thread_entry,
+ args=(self.async_upload_queue,))
+ p.start()
+ return p
+
+ def ensure_init_async_upload_thread(self):
+ if self.async_upload_thread is None:
+ self.async_upload_thread = self.launch_async_upload_thread_entry()
+
+ def isfile(self, fname):
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ return op.isfile(fname)
+ remote_file = op.join(info['remote'], info['sub_name'])
+ return self.account2cloud[info['storage_account']].file_exists(remote_file)
+
+ def rm(self, fname):
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ return os.remove(fname)
+ remote_file = op.join(info['remote'], info['sub_name'])
+ cache_file = op.join(info['cache'], info['sub_name'])
+ if op.isfile(cache_file):
+ os.remove(cache_file)
+ return self.account2cloud[info['storage_account']].rm(remote_file)
+
+ @contextlib.contextmanager
+ def async_upload(self, enabled, shm_as_tmp=False):
+ old = self.async_upload_enabled
+ self.async_upload_enabled = enabled
+ if enabled:
+ thread = self.launch_async_upload_thread()
+ self.shm_as_upload_tmp = shm_as_tmp
+ yield
+ if enabled:
+ self.async_upload_queue.put(None)
+ thread.join()
+ self.async_upload_enabled = old
+ self.shm_as_upload_tmp = False
+
+ def get_file_size(self, fname):
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ return get_file_size(fname)
+ remote_file = op.join(info['remote'], info['sub_name'])
+ cache_file = op.join(info['cache'], info['sub_name'])
+ if op.isfile(cache_file):
+ return get_file_size(cache_file)
+ return self.account2cloud[info['storage_account']].query_info(
+ remote_file)['size_in_bytes']
+
+ def clear_cache(self, folder):
+ info = self.get_remote_cache(folder)
+ t = op.join(info['cache'], info['sub_name'])
+ logging.info(t)
+ ensure_remove_dir(t)
+ ensure_remove_file(t)
+
+ def ensure_cache(self, fname_or_fs,
+ touch_cache_if_exist=False,
+ allow_aux_storage=False,
+ ):
+ if isinstance(fname_or_fs, str):
+ fname = fname_or_fs
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ return
+ remote_file = op.join(info['remote'], info['sub_name'])
+ cache_file = op.join(info['cache'], info['sub_name'])
+ cloud = self.account2cloud[info['storage_account']]
+ self.ensure_remote_to_cache(
+ remote_file, cache_file, cloud,
+ touch_cache_if_exist=touch_cache_if_exist,
+ cache_lock=info['cache_lock'],
+ allow_aux_storage=allow_aux_storage,
+ )
+ elif isinstance(fname_or_fs, (tuple, list)) and len(fname_or_fs) > 0:
+ # for multiple files, we can download them at the same time rather
+ # than one by one
+ fnames = fname_or_fs
+ remote_cache_infos = [self.get_remote_cache(f) for f in fnames]
+ remote_cache_infos = [info for info in remote_cache_infos if len(info) > 0]
+ if touch_cache_if_exist:
+ exist_infos = [info for info in remote_cache_infos if op.isfile(op.join(info['cache'], info['sub_name']))]
+ for info in exist_infos:
+ os.utime(op.join(info['cache'], info['sub_name']), None)
+ remote_cache_infos = [info for info in remote_cache_infos if
+ not op.isfile(op.join(info['cache'], info['sub_name']))]
+ if len(remote_cache_infos) > 0:
+ lock_fd = self.acquireLock()
+ # we need to check again
+ remote_cache_infos = [info for info in remote_cache_infos if
+ not op.isfile(op.join(info['cache'], info['sub_name']))]
+ remote_cache_infos = [((info['remote'], info['cache']), info) for info in remote_cache_infos]
+ from .common import list_to_dict
+ rd_cd_to_infos = list_to_dict(remote_cache_infos, 0)
+ for (rd, cd), infos in rd_cd_to_infos.items():
+ sns = [i['sub_name'] for i in infos]
+ assert all(i['storage_account'] == infos[0]['storage_account'] for i in infos)
+
+ assert all(i['cache_lock'] == infos[0]['cache_lock'] for i in infos)
+ cache_lock = infos[0]['cache_lock']
+ if cache_lock:
+ cache_lock_file = cd + '.lockfile'
+ cache_lock_pt = acquireLock(cache_lock_file)
+ sns = [s for s in sns if not op.isfile(op.join(cd, s))]
+ if len(sns) > 0:
+ file_list = '/tmp/{}'.format(hash_sha1(pformat(sns)))
+ write_to_file('\n'.join(sns), file_list)
+ cloud = self.account2cloud[infos[0]['storage_account']]
+ cloud.az_download(
+ rd,
+ cd,
+ is_folder=False,
+ file_list=file_list,
+ tmp_first=False,
+ sync=False,
+ retry=1,
+ )
+ for s in sns:
+ if not op.isfile(op.join(cd, s)):
+ logging.error((op.join(cd, s), file_list))
+ if cache_lock:
+ releaseLock(cache_lock_pt)
+ releaseLock(lock_fd)
+
+ def open(self, fname, mode):
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ if mode in ['r', 'rb']:
+ return open(fname, mode)
+ else:
+ assert mode in ['w', 'wb'], f'{mode} is not supported'
+ return robust_open_to_write(fname, mode)
+ if mode in ['r', 'rb']:
+ return self.open_to_read(info, mode)
+ else:
+ # append is not support
+ assert mode in ['w', 'wb'], f'{mode} is not supported'
+ return self.open_to_write(info, mode)
+
+ @contextlib.contextmanager
+ def open_to_write(self, info, mode):
+ remote_file = op.join(info['remote'], info['sub_name'])
+ if self.shm_as_upload_tmp:
+ import copy
+ info = copy.deepcopy(info)
+ assert info['cache'][0] == '/'
+ info['cache'] = op.join('/dev/shm', info['cache'][1:])
+ info['clear_cache_after_upload'] = True
+ cache_file = op.join(info['cache'], info['sub_name'])
+ while op.isfile(cache_file):
+ info['cache'] += '_'
+ cache_file = op.join(info['cache'], info['sub_name'])
+ logging.warning('use another cache file: {}'
+ .format(cache_file))
+ cache_file = op.join(info['cache'], info['sub_name'])
+ tmp_cache_file = cache_file + '.tmpwrite'
+ ensure_directory(op.dirname(tmp_cache_file))
+ with open(tmp_cache_file, mode) as fp:
+ yield fp
+ os.rename(tmp_cache_file, cache_file)
+ if self.async_upload_enabled:
+ self.async_upload_queue.put(info)
+ else:
+ cloud = self.account2cloud[info['storage_account']]
+ self.cache_to_remote(cache_file, remote_file, cloud)
+ if self.remove_cache_after_upload:
+ ensure_remove_file(cache_file)
+
+ def open_to_read(self, info, mode):
+ start = time.time()
+ remote_file = op.join(info['remote'], info['sub_name'])
+ cache_file = op.join(info['cache'], info['sub_name'])
+ cloud = self.account2cloud[info['storage_account']]
+ self.ensure_remote_to_cache(remote_file, cache_file, cloud,
+ cache_lock=info.get('cache_lock'))
+ after_to_cache = time.time()
+ ret = open(cache_file, mode)
+ after_open = time.time()
+ if after_open - start > 10:
+ logging.warning('download {} to {}: {}; open cache: {}'.format(
+ remote_file, cache_file, after_to_cache - start, after_open - after_to_cache,
+ ))
+ return ret
+
+ def ensure_del_cache(self, fname):
+ info = self.get_remote_cache(fname)
+ if len(info) == 0:
+ return
+ cache_file = op.join(info['cache'], info['sub_name'])
+ #if has_handle(cache_file):
+ #logging.warning('{} is used by some process'.format(
+ #cache_file))
+ #return False
+ ensure_remove_file(cache_file)
+ #return True
+
+ def ensure_invoke_garbage_collect(self):
+ # if the current occupied files take more than 0.5. Then, remove the
+ # oldest files
+ if self.invoked_collector:
+ return
+ self.invoked_collector = True
+ local_caches = [c['cache'] for c in self.config]
+ local_caches = list(set(local_caches))
+ # 1TB
+ limit = float(os.environ.get('QD_CLOUD_FUSE_GARBAGE_COLLECTION_MAX',
+ '{}'.format(0.5)))
+ t = mp.Process(
+ target=garbage_collection_for_cloud_fuse_loop,
+ args=(local_caches, limit),
+ daemon=True,
+ )
+ t.start()
+ self.garbage_collector = t
+
+ #--------------------------------------------------------------
+ def acquireLock(self, x=None):
+ # all files share one lock
+ return acquire_azcopy_lock()
+
+ def get_remote_cache(self, fname):
+ fname = op.abspath(fname)
+ infos = [c for c in self.config if fname.startswith(c['local'] + '/')]
+ if len(infos) == 0:
+ return {}
+ info = infos[0]
+ local_folder = info['local']
+ remote_folder, cache_folder = info['remote'], info['cache']
+ sub_name = fname[len(local_folder) + 1:]
+ d = op.dirname(sub_name)
+ sub = op.basename(sub_name)
+ return {
+ 'remote': op.join(remote_folder, d),
+ 'cache': op.join(cache_folder, d),
+ 'sub_name': sub,
+ 'storage_account': info['storage_account'],
+ 'cache_lock': info.get('cache_lock', False),
+ }
+
+ def remote_to_cache(self, remote_file, cache_file, cloud, cache_lock,
+ allow_aux_storage=False,
+ ):
+ if op.isfile(cache_file) or op.isdir(cache_file):
+ return
+ if allow_aux_storage and self.aux_accounts:
+ self.copy_to_aux_then_download(remote_file, cache_file, cloud)
+ else:
+ lock_fd = self.acquireLock()
+ if cache_lock:
+ cache_lock_pt = acquireLock(cache_file + '.lockfile')
+ if not op.isfile(cache_file) and not op.isdir(cache_file):
+ cloud.az_download(
+ remote_file, cache_file,
+ #sync=False,
+ #is_folder=False,
+ retry=5,
+ )
+ # the following is slower
+ #self.cloud.download_to_path(
+ #remote_file, cache_file, max_connections=10)
+ if cache_lock:
+ releaseLock(cache_lock_pt)
+ #ensure_remove_file(cache_file + '.lockfile')
+ releaseLock(lock_fd)
+
+ def copy_to_aux_then_download(self, remote_path, cache_path, cloud):
+ aux_accounts = self.aux_accounts
+ storage_accounts = [cloud] + aux_accounts
+ node_rank = get_mpi_rank() // get_mpi_local_size()
+ idx = node_rank % len(storage_accounts)
+ selected = storage_accounts[idx]
+ remote_ready_file = get_ready_file(remote_path)
+ if idx != 0:
+ if not selected.file_exists(remote_ready_file):
+ copy_lock_path = remote_path + '.copy.lock'
+ lease_id = cloud.acquire_lock(copy_lock_path)
+ if not selected.file_exists(remote_ready_file):
+ sync_remote_path(remote_path, cloud, aux_accounts)
+ cloud.release_lock(lease_id, copy_lock_path)
+ assert selected.file_exists(remote_ready_file)
+ if not op.isfile(cache_path) and not op.isdir(cache_path):
+ lock_fd = self.acquireLock()
+ if not op.isfile(cache_path) and not op.isdir(cache_path):
+ selected.az_download(
+ remote_path,
+ cache_path,
+ )
+ releaseLock(lock_fd)
+
+ def copy_to_aux_then_download_old(self, remote_path, cache_path, cloud):
+ # this is dependent on the mpirun launcher. currently, we are good, but
+ # it may not be working well in non-mpirun env
+ #num_node = get_mpi_size() // get_mpi_local_size()
+ aux_accounts = self.aux_accounts
+ #if len(aux_accounts) > num_node:
+ #aux_accounts = aux_accounts[:num_node]
+ if get_mpi_rank() == 0:
+ sync_remote_path(remote_path, cloud, aux_accounts)
+ storage_accounts = [cloud] + aux_accounts
+ node_rank = get_mpi_rank() // get_mpi_local_size()
+ idx = node_rank % len(storage_accounts)
+ selected = storage_accounts[idx]
+ remote_ready_file = get_ready_file(remote_path)
+ if idx != 0:
+ while not selected.file_exists(remote_ready_file):
+ logging.warning('waiting {}/{}'.format(
+ selected,
+ remote_ready_file))
+ time.sleep(5)
+ if not op.isfile(cache_path) and not op.isdir(cache_path):
+ lock_fd = self.acquireLock()
+ if not op.isfile(cache_path) and not op.isdir(cache_path):
+ selected.az_download(
+ remote_path,
+ cache_path,
+ )
+ releaseLock(lock_fd)
+ def cache_to_remote(self, cache_file, remote_file, cloud):
+ lock_fd = self.acquireLock()
+ assert op.isfile(cache_file)
+ cloud.upload(cache_file, remote_file)
+ releaseLock(lock_fd)
+
+ def ensure_remote_to_cache(self, remote_file, cache_file, cloud,
+ touch_cache_if_exist=False,
+ cache_lock=False,
+ allow_aux_storage=False,
+ ):
+ if op.isfile(cache_file):
+ if touch_cache_if_exist:
+ os.utime(cache_file, None)
+ else:
+ self.remote_to_cache(remote_file, cache_file, cloud, cache_lock,
+ allow_aux_storage=allow_aux_storage,
+ )
+
+ def list(self, folder, recursive=False):
+ info = self.get_remote_cache(folder)
+ if len(info) == 0:
+ return glob.glob(op.join(folder, '*'), recursive=recursive)
+ else:
+ cloud = self.account2cloud[info['storage_account']]
+ remote_folder = op.join(info['remote'], info['sub_name'])
+ ret = list(cloud.list_blob_names(remote_folder + '/'))
+
+ if not recursive:
+ return [r.replace(remote_folder, folder) for r in ret if op.dirname(r) == remote_folder]
+ else:
+ return [r.replace(remote_folder, folder) for r in ret]
+
+class CloudStorage(object):
+ def __init__(self, config=None):
+ if config is None:
+ config_file = 'aux_data/configs/azure_blob_account.yaml'
+ config = load_from_yaml_file(config_file)
+ account_name = config['account_name']
+ account_key = config.get('account_key')
+ self.sas_token = config.get('sas_token')
+ self.container_name = config['container_name']
+ self.account_name = account_name
+ self.account_key = account_key
+ self._block_blob_service = None
+
+ def __repr__(self):
+ return 'CloudStorage(account={}, container={})'.format(
+ self.account_name,
+ self.container_name,
+ )
+
+ @property
+ def block_blob_service(self):
+ if self._block_blob_service is None:
+ self._block_blob_service = BlockBlobService(
+ account_name=self.account_name,
+ account_key=self.account_key,
+ sas_token=self.sas_token)
+ return self._block_blob_service
+
+ def list_blob_names(self, prefix=None, creation_time_larger_than=None):
+ if creation_time_larger_than is not None:
+ creation_time_larger_than = creation_time_larger_than.timestamp()
+ return (b.name for b in self.block_blob_service.list_blobs(
+ self.container_name,
+ prefix=prefix)
+ if b.properties.creation_time.timestamp() > creation_time_larger_than)
+ else:
+ ret = self.block_blob_service.list_blob_names(self.container_name, prefix=prefix)
+ return ret
+
+ def du_max_depth_1(self, path, deleted=False):
+ from collections import defaultdict
+ ret = defaultdict(int)
+ for info in tqdm(self.iter_blob_info(path, deleted=deleted)):
+ assert info['name'].startswith(path)
+ root = info['name'][len(path):]
+ if root.startswith('/'):
+ root = root[1:]
+ root = root.split('/')[0]
+ ret[root] += info['size_in_bytes']
+ return ret
+
+ def rm_prefix(self, prefix):
+ all_path = self.list_blob_names(prefix)
+ for p in all_path:
+ logging.info('deleting {}'.format(p))
+ self.rm(p)
+
+ def rm(self, path):
+ self.block_blob_service.delete_blob(self.container_name, path)
+
+ def acquire_lock(self, path):
+ while True:
+ try:
+ lease_id = self.block_blob_service.acquire_blob_lease(
+ self.container_name,
+ path)
+ return lease_id
+ except Exception as ex:
+ if ex.error_code == 'BlobNotFound':
+ self.upload_stream(b'done', path)
+ elif ex.error_code == 'LeaseAlreadyPresent':
+ logging.info('waiting lease')
+ time.sleep(5)
+ else:
+ raise
+
+ def release_lock(self, lease_id, path):
+ self.block_blob_service.release_blob_lease(
+ self.container_name,
+ path,
+ lease_id,
+ )
+
+ def iter_blob_info(self, prefix=None,
+ creation_time_larger_than=None,
+ deleted=False,
+ ):
+ def valid(b):
+ c1 = creation_time_larger_than is None or b.properties.creation_time.timestamp() > creation_time_larger_than.timestamp()
+ c2 = b.name.startswith(prefix)
+ return c1 and c2 and (not deleted or b.deleted)
+ for b in self.block_blob_service.list_blobs(
+ self.container_name,
+ prefix=prefix,
+ include='deleted' if deleted else None,
+ ):
+ if valid(b):
+ yield {
+ 'name': b.name,
+ 'size_in_bytes': b.properties.content_length,
+ 'creation_time': b.properties.creation_time,
+ }
+
+ def list_blob_info(self, prefix=None, creation_time_larger_than=None):
+ return list(self.iter_blob_info(prefix, creation_time_larger_than))
+
+ def get_url(self, blob_name):
+ from azure.storage.blob.models import BlobPermissions
+ permission = BlobPermissions(read=True)
+ import datetime
+ expiry = datetime.datetime.now() + datetime.timedelta(days=30)
+ sas = self.block_blob_service.generate_blob_shared_access_signature(
+ self.container_name, blob_name,
+ permission=permission,
+ expiry=expiry,
+ )
+ url = self.block_blob_service.make_blob_url(self.container_name,
+ blob_name)
+ return '{}?{}'.format(url, sas)
+
+ def upload_stream(self, s, name, force=False):
+ if not force and self.block_blob_service.exists(self.container_name,
+ name):
+ return self.block_blob_service.make_blob_url(
+ self.container_name,
+ name)
+ else:
+ if type(s) is bytes:
+ self.block_blob_service.create_blob_from_bytes(
+ self.container_name,
+ name,
+ s)
+ else:
+ self.block_blob_service.create_blob_from_stream(
+ self.container_name,
+ name,
+ s)
+ return self.block_blob_service.make_blob_url(
+ self.container_name,
+ name)
+
+ def upload_folder(self, folder, target_prefix):
+ def remove_tailing(x):
+ if x.endswith('/') or x.endswith('\\'):
+ x = x[:-1]
+ return x
+ folder = remove_tailing(folder)
+ target_prefix = remove_tailing(target_prefix)
+ for root, dirs, files in os.walk(folder):
+ for f in files:
+ src_file = op.join(root, f)
+ assert src_file.startswith(folder)
+ target_file = src_file.replace(folder, target_prefix)
+ self.upload_file(src_file, target_file)
+ for d in dirs:
+ self.upload_folder(op.join(root, d),
+ op.join(target_prefix, d))
+
+ def upload_file(self, src_file, target_file):
+ logging.info('uploading {} to {}'.format(src_file, target_file))
+ #import time
+ #start_time = time.time()
+ bar = [None]
+ last = [0]
+ def upload_callback(curr, total):
+ if total < 1024 ** 3:
+ return
+ if bar[0] is None:
+ bar[0] = tqdm(total=total, unit_scale=True)
+ bar[0].update(curr - last[0])
+ last[0] = curr
+ if target_file.startswith('/'):
+ logging.info('remove strarting slash for {}'.format(target_file))
+ target_file = target_file[1:]
+ self.block_blob_service.create_blob_from_path(
+ self.container_name,
+ target_file,
+ src_file,
+ max_connections=8,
+ progress_callback=upload_callback)
+
+ def az_upload(self, src_dir, dest_dir):
+ # this is using the old version of azcopy. prefer to use az_upload2
+ dest_url = op.join('https://{}.blob.core.windows.net'.format(self.account_name),
+ self.container_name, dest_dir)
+ if self.account_key:
+ azcopy_upload(src_dir, dest_url, self.account_key)
+ else:
+ raise Exception
+
+ @deprecated('use upload()')
+ def az_sync(self, src_dir, dest_dir):
+ self.upload(src_dir, dest_dir)
+
+ def upload(self, src_dir, dest_dir, from_blob=None, file_list=None):
+ if from_blob is None:
+ self.upload_from_local(src_dir, dest_dir, file_list=file_list)
+ else:
+ assert file_list is None
+ self.upload_from_another(src_dir, dest_dir, from_blob)
+
+ def upload_from_another(self, src_dir, dest_dir, from_blob):
+ assert self.sas_token
+ cmd = []
+ cmd.append(get_azcopy())
+ if from_blob.dir_exists(src_dir) and not self.dir_exists(dest_dir):
+ # in this case, azcopy will copy the local folder under the
+ # destination folder, and thus we have to use the folder of
+ # dest_dir as the dest_dir.
+ assert op.basename(src_dir) == op.basename(dest_dir)
+ dest_dir = op.dirname(dest_dir)
+ cmd.append('cp')
+ else:
+ if self.exists(dest_dir):
+ cmd.append('sync')
+ else:
+ cmd.append('cp')
+ url = 'https://{}.blob.core.windows.net'.format(from_blob.account_name)
+ url = op.join(url, from_blob.container_name, src_dir)
+ assert self.sas_token.startswith('?')
+ from_url = url
+ url = url + from_blob.sas_token
+ cmd.append(url)
+
+ url = 'https://{}.blob.core.windows.net'.format(self.account_name)
+ if dest_dir.startswith('/'):
+ dest_dir = dest_dir[1:]
+ url = op.join(url, self.container_name, dest_dir)
+ assert self.sas_token.startswith('?')
+ data_url = url
+ url = url + self.sas_token
+ cmd.append(url)
+
+ if from_blob.dir_exists(src_dir):
+ cmd.append('--recursive')
+ if from_url == data_url:
+ logging.info('no need to sync data as url is exactly the same')
+ return data_url, url
+ if int(os.environ.get('QD_AZCOPY_NO_LOG', '0')):
+ import subprocess
+ stdout = subprocess.DEVNULL
+ else:
+ stdout = None
+ cmd_run(cmd, stdout=stdout, stderr=sp.PIPE)
+ return data_url, url
+
+ def upload_from_local(self, src_dir, dest_dir, file_list=None):
+ assert self.sas_token
+ cmd = []
+ cmd.append(get_azcopy())
+ if file_list is not None or (op.isdir(src_dir) and not
+ self.dir_exists(dest_dir)):
+ # in this case, azcopy will copy the local folder under the
+ # destination folder, and thus we have to use the folder of
+ # dest_dir as the dest_dir.
+ assert op.basename(src_dir) == op.basename(dest_dir)
+ dest_dir = op.dirname(dest_dir)
+ cmd.append('cp')
+ else:
+ if file_list is None and self.exists(dest_dir):
+ cmd.append('sync')
+ else:
+ cmd.append('cp')
+ cmd.append(op.realpath(src_dir))
+ url = 'https://{}.blob.core.windows.net'.format(self.account_name)
+ if dest_dir.startswith('/'):
+ dest_dir = dest_dir[1:]
+ url = op.join(url, self.container_name, dest_dir)
+ assert self.sas_token.startswith('?')
+ data_url = url
+ url = url + self.sas_token
+ cmd.append(url)
+ if op.isdir(src_dir):
+ cmd.append('--recursive')
+ if file_list:
+ cmd.append('--list-of-files')
+ cmd.append(file_list)
+ if int(os.environ.get('QD_AZCOPY_NO_LOG', '0')):
+ import subprocess
+ stdout = subprocess.DEVNULL
+ else:
+ stdout = None
+ cmd_run(cmd, stdout=stdout)
+ return data_url, url
+
+ @deprecated('use upload')
+ def az_upload2(self, src_dir, dest_dir, sync=False):
+ return self.upload(src_dir, dest_dir)
+
+ def query_info(self, path):
+ try:
+ p = self.block_blob_service.get_blob_properties(self.container_name, path)
+ except:
+ logging.info('{}: {}'.format(self.container_name, path))
+ raise
+ result = {
+ 'size_in_bytes': p.properties.content_length,
+ 'creation_time': p.properties.creation_time,
+ }
+ return result
+
+ def az_download_all(self, remote_path, local_path):
+ all_blob_name = list(self.list_blob_names(remote_path))
+ all_blob_name = get_leaf_names(all_blob_name)
+ for blob_name in all_blob_name:
+ target_file = blob_name.replace(remote_path, local_path)
+ if not op.isfile(target_file):
+ self.az_download(blob_name, target_file,
+ sync=False)
+
+ def is_folder(self, remote_path):
+ remote_path = op.normpath(remote_path)
+ def is_folder_once():
+ is_folder = False
+ for x in self.list_blob_names(remote_path + '/'):
+ is_folder = True
+ break
+ return is_folder
+ return limited_retry_agent(
+ 10,
+ is_folder_once,
+ )
+
+ def az_download_each(self, remote_path, local_path):
+ # if it is a folder, we will download each file individually
+ if remote_path.startswith('/'):
+ remote_path = remote_path[1:]
+ if remote_path.endswith('/'):
+ remote_path = remote_path[:-1]
+ is_folder = self.is_folder(remote_path)
+ if is_folder:
+ all_remote_file = self.list_blob_names(remote_path + '/')
+ all_local_file = [op.join(local_path, r[len(remote_path) + 1:])
+ for r in all_remote_file]
+ else:
+ all_remote_file = [remote_path]
+ all_local_file = [local_path]
+ for r, l in zip(all_remote_file, all_local_file):
+ self.az_download(r, l, sync=True)
+
+ def az_download(self,
+ remote_path,
+ local_path,
+ sync=True,
+ is_folder=None,
+ tmp_first=True,
+ file_list=None,
+ retry=5,
+ ):
+ limited_retry_agent(retry, self.az_download_once,
+ remote_path, local_path, sync,
+ is_folder, tmp_first, file_list)
+
+
+ def az_download_once(self,
+ remote_path,
+ local_path,
+ sync=True,
+ is_folder=None,
+ tmp_first=True,
+ file_list=None,
+ ):
+ if remote_path.startswith('/'):
+ remote_path = remote_path[1:]
+ if remote_path.endswith('/'):
+ remote_path = remote_path[:-1]
+ if is_folder is None:
+ is_folder = self.is_folder(remote_path)
+ if sync and tmp_first:
+ logging.info('if sync, no need to save to temp first')
+ tmp_first = False
+ if is_folder:
+ if not sync and op.isdir(local_path) and tmp_first:
+ if len(os.listdir(local_path)) > 0:
+ logging.error('ignore to download from {} to {}'
+ ' since destination is not empty'.format(
+ remote_path,
+ local_path,
+ ))
+ return
+ ensure_remove_dir(local_path)
+ else:
+ if sync:
+ if tmp_first:
+ sync = False
+ elif not op.isfile(local_path):
+ sync = False
+ ensure_directory(op.dirname(local_path))
+ origin_local_path = local_path
+ if tmp_first:
+ local_path = local_path + '.tmp'
+ ensure_directory(op.dirname(local_path))
+ assert self.sas_token
+ cmd = []
+ cmd.append(get_azcopy())
+ if sync:
+ cmd.append('sync')
+ else:
+ cmd.append('cp')
+ url = 'https://{}.blob.core.windows.net'.format(self.account_name)
+ url = '/'.join([url, self.container_name, remote_path])
+ assert self.sas_token.startswith('?')
+ data_url = url
+ url = url + self.sas_token
+ cmd.append(url)
+ if file_list:
+ # requirements from file_list
+ assert op.basename(local_path) == op.basename(remote_path)
+ cmd.append(op.dirname(op.realpath(local_path)))
+ else:
+ cmd.append(op.realpath(local_path))
+ if is_folder:
+ cmd.append('--recursive')
+ if sync:
+ # azcopy's requirement
+ ensure_directory(local_path)
+ else:
+ ensure_directory(op.dirname(local_path))
+ if file_list:
+ cmd.append('--list-of-files')
+ cmd.append(file_list)
+ # too much logs. ignore them
+ if int(os.environ.get('QD_AZCOPY_NO_LOG', '0')):
+ import subprocess
+ stdout = subprocess.DEVNULL
+ else:
+ stdout = None
+ try:
+ cmd_run(cmd, stdout=stdout)
+ except:
+ logging.warning(pformat(cmd))
+ raise
+ if tmp_first:
+ if not op.isfile(local_path) and not op.isdir(local_path):
+ logging.error('{} not exists; {}/{}'.format(
+ local_path, origin_local_path, op.isfile(origin_local_path)))
+ os.rename(local_path, origin_local_path)
+ return data_url, url
+
+ def download_to_path(self, blob_name, local_path,
+ max_connections=2):
+ dir_path = op.dirname(local_path)
+ if op.isfile(dir_path) and get_file_size(dir_path) == 0:
+ os.remove(dir_path)
+ ensure_directory(dir_path)
+ tmp_local_path = local_path + '.tmp'
+ pbar = {}
+ def progress_callback(curr, total):
+ if len(pbar) == 0:
+ pbar['tqdm'] = tqdm(total=total, unit_scale=True)
+ pbar['last'] = 0
+ pbar['count'] = 0
+ pbar['count'] += 1
+ if pbar['count'] > 100:
+ pbar['tqdm'].update(curr - pbar['last'])
+ pbar['last'] = curr
+ pbar['count'] = 0
+ self.block_blob_service.get_blob_to_path(self.container_name,
+ blob_name, tmp_local_path,
+ progress_callback=progress_callback,
+ max_connections=max_connections)
+ os.rename(tmp_local_path, local_path)
+
+ def download_to_stream(self, blob_name, s, max_connections=2):
+ pbar = {}
+ def progress_callback(curr, total):
+ if len(pbar) == 0:
+ pbar['tqdm'] = tqdm(total=total, unit_scale=True)
+ pbar['last'] = 0
+ pbar['count'] = 0
+ pbar['count'] += 1
+ if pbar['count'] > 1:
+ pbar['tqdm'].update(curr - pbar['last'])
+ pbar['last'] = curr
+ pbar['count'] = 0
+ self.block_blob_service.get_blob_to_stream(self.container_name,
+ blob_name,
+ s,
+ max_connections=max_connections,
+ progress_callback=progress_callback,
+ )
+
+ def exists(self, path):
+ return self.file_exists(path) or self.dir_exists(path)
+
+ def file_exists(self, path):
+ fp = acquireLock('/tmp/{}.lock'.format(hash_sha1(path)))
+ result = limited_retry_agent(
+ 5,
+ self.block_blob_service.exists,
+ self.container_name, path
+ )
+ #result = self.block_blob_service.exists(self.container_name, path)
+ releaseLock(fp)
+ return result
+
+ def dir_exists(self, dir_path):
+ return self.is_folder(dir_path)
+
+ @deprecated('no longer used')
+ def blob_download_qdoutput(
+ self,
+ src_path,
+ target_folder,
+ latest_only=True,
+ creation_time_larger_than=None,
+ too_large_limit_in_gb=None,
+ ignore_base_fname_patterns=None,
+ dry_run=False,
+ ):
+ def is_in_snapshot(b):
+ parts = list(b.split('/'))
+ return 'snapshot' in parts and parts.index('snapshot') < len(parts) - 1
+ all_blob_name = list(self.list_blob_names(
+ src_path,
+ creation_time_larger_than))
+ # remove snapshot/model_iter/abc.bin
+ clean = []
+ for b in all_blob_name:
+ parts = list(b.split('/'))
+ if 'snapshot' in parts and \
+ parts.index('snapshot') < len(parts) - 2:
+ continue
+ else:
+ clean.append(b)
+ all_blob_name = clean
+
+ all_blob_name = get_leaf_names(all_blob_name)
+ in_snapshot_blobs = [b for b in all_blob_name if is_in_snapshot(b)]
+ not_in_snapshot_blobs = [b for b in all_blob_name if not is_in_snapshot(b)]
+ try:
+ not_in_snapshot_blobs.remove(src_path)
+ except:
+ pass
+ try:
+ not_in_snapshot_blobs.remove(src_path + '/snapshot')
+ except:
+ pass
+ need_download_blobs = []
+ need_download_blobs.extend(not_in_snapshot_blobs)
+ iters = [parse_iteration(f) for f in in_snapshot_blobs]
+ if len(iters) > 0 and latest_only:
+ max_iters = max(iters)
+ need_download_blobs.extend([f for f, i in zip(in_snapshot_blobs, iters) if i ==
+ max_iters or f.endswith('.report')])
+ need_download_blobs.extend([f for f, i in zip(in_snapshot_blobs, iters) if
+ i == -2])
+ to_remove = []
+ for i, b1 in enumerate(need_download_blobs):
+ for b2 in need_download_blobs:
+ if b1 != b2 and b2.startswith(b1) and b2.startswith(b1 + '/'):
+ to_remove.append(b1)
+ break
+ for t in to_remove:
+ need_download_blobs.remove(t)
+ need_download_blobs = [t for t in need_download_blobs
+ if not t.endswith('.tmp')]
+ f_target_f = [(f, f.replace(src_path, target_folder)) for f in
+ need_download_blobs]
+ f_target_f = [(f, target_f) for f, target_f in f_target_f if not op.isfile(target_f)]
+ f_target_f = [(f, target_f) for f, target_f in f_target_f if len(f) > 0]
+
+ if ignore_base_fname_patterns is not None:
+ import re
+ result = []
+ for f, target_f in f_target_f:
+ if any(re.match(p, f) is not None for p in
+ ignore_base_fname_patterns):
+ logging.info('ignore {} due to reg pattern matching'.format(f))
+ else:
+ result.append((f, target_f))
+ f_target_f = result
+
+ if too_large_limit_in_gb is not None:
+ logging.info('before size filtering = {}'.format(len(f_target_f)))
+ f_target_f = [(f, target_f) for f, target_f in f_target_f if
+ self.query_info(f)['size_in_bytes'] / 1024. ** 3 <=
+ too_large_limit_in_gb]
+ logging.info('after size filtering = {}'.format(len(f_target_f)))
+ for f, target_f in tqdm(f_target_f):
+ logging.info('download {} to {}'.format(f, target_f))
+ try:
+ if not dry_run:
+ self.az_download(f, target_f)
+ except:
+ pass
+ #self.download_to_path(f, target_f)
+
+if __name__ == '__main__':
+ from .common import init_logging
+ from .common import parse_general_args
+ init_logging()
+ kwargs = parse_general_args()
+ logging.info('param:\n{}'.format(pformat(kwargs)))
+ function_name = kwargs['type']
+ del kwargs['type']
+ locals()[function_name](**kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/common.py b/One-to-All-Animation/benchmark/DisCo/utils/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4a00bc436a4306d99b10c1b5d82d3d6d22c6cb6
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/common.py
@@ -0,0 +1,3986 @@
+#import matplotlib
+#matplotlib.use('Agg')
+import contextlib
+from PIL import Image
+from io import BytesIO
+import yaml
+from collections import OrderedDict
+#import progressbar
+import json
+import traceback
+import random
+import sys
+import os
+import math
+import multiprocessing as mp
+from multiprocessing import Process
+from multiprocessing import Event
+import logging
+import functools
+import numpy as np
+import glob
+import re
+from tqdm import tqdm
+try:
+ from itertools import izip as zip
+except ImportError:
+ # in python3, we don't need itertools.izip since zip is izip
+ pass
+import time
+#import matplotlib.pyplot as plt
+from pprint import pprint
+from pprint import pformat
+import numpy as np
+import os.path as op
+import re
+import base64
+import cv2
+#import psutil
+import shutil
+import argparse
+import subprocess as sp
+from datetime import datetime
+from future.utils import viewitems
+#from ete3 import Tree
+try:
+ # py3
+ from urllib.request import urlopen, Request
+ from urllib.request import HTTPError
+except ImportError:
+ # py2
+ from urllib2 import urlopen, Request
+ from urllib2 import HTTPError
+import copy
+#from deprecated import deprecated
+import io
+
+from PIL import ImageFile
+#https://stackoverflow.com/questions/12984426/python-pil-ioerror-image-file-truncated-with-big-images
+ImageFile.LOAD_TRUNCATED_IMAGES = True
+
+
+def get_sys_memory_usage_info():
+ out = cmd_run(['free'], return_output=True)
+ import ipdb;ipdb.set_trace(context=15)
+ lines = out.split('\n')
+ headers = lines[0].strip().split(' ')
+ headers = [h for h in headers if len(h) > 0]
+ mem = lines[1]
+ x1, x2 = mem.split(':')
+ assert 'Mem' == x1
+ values = [int(i) for i in x2.split(' ') if len(i) > 0]
+ assert len(headers) == len(values)
+ return dict(zip(headers, values))
+
+def get_mem_usage_in_bytes():
+ import os, psutil
+ process = psutil.Process(os.getpid())
+ return process.memory_info().rss # in bytes
+
+def print_type_memory_usage():
+ from pympler import muppy, summary
+ all_objects = muppy.get_objects()
+ sum1 = summary.summarize(all_objects)
+ summary.print_(sum1)
+
+def encode_np(x):
+ compressed_array = io.BytesIO()
+ np.savez_compressed(compressed_array, x)
+ return base64.b64encode(compressed_array.getvalue())
+
+def decode_np(s):
+ s = base64.b64decode(s)
+ return np.load(io.BytesIO(s))['arr_0']
+
+def print_trace():
+ import traceback
+ traceback.print_exc()
+
+def get_trace():
+ import traceback
+ return traceback.format_exc()
+
+def try_once(func):
+ def func_wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ logging.info('ignore error \n{}'.format(str(e)))
+ print_trace()
+ return func_wrapper
+
+def master_process_run(func):
+ def func_wrapper(*args, **kwargs):
+ if get_mpi_rank() == 0:
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ logging.info('ignore error \n{}'.format(str(e)))
+ print_trace()
+ return func_wrapper
+
+@try_once
+def try_delete(f):
+ os.remove(f)
+
+def list_to_nested_dict(xs, idxes):
+ rest_idxes = set(range(len(xs[0]))).difference(idxes)
+ result = {}
+ for r in xs:
+ curr_result = result
+ for i in idxes[:-1]:
+ if r[i] not in curr_result:
+ curr_result[r[i]] = {}
+ curr_result = curr_result[r[i]]
+ key = r[idxes[-1]]
+ if key not in curr_result:
+ curr_result[key] = []
+ value = [r[i] for i in rest_idxes]
+ if len(value) == 1:
+ value = value[0]
+ curr_result[key].append(value)
+ return result
+
+def make_by_pattern_result(data, pattern_results):
+ for p, result in pattern_results:
+ match_result = re.match(p, data)
+ if match_result is not None:
+ return result
+
+def make_by_pattern_maker(data, pattern_makers):
+ for p, maker in pattern_makers:
+ match_result = re.match(p, data)
+ if match_result is not None:
+ return maker()
+
+def is_positive_uhrs_verified(r):
+ uhrs = r['uhrs']
+ y, n = uhrs.get('1', 0), uhrs.get('2', 0)
+ return y > n
+
+def is_negative_uhrs_verified(r):
+ uhrs = r['uhrs']
+ y, n = uhrs.get('1', 0), uhrs.get('2', 0)
+ return n > y
+
+def find_float_tolorance_unequal(d1, d2):
+ # return a list of string. Each string means a path where the value is
+ # different
+ from past.builtins import basestring
+ if all(isinstance(x, basestring) for x in [d1, d2]) or \
+ all(type(x) is bool for x in [d1, d2]):
+ if d1 != d2:
+ return ['0']
+ else:
+ return []
+ if type(d1) is int and type(d2) is int:
+ if d1 == d2:
+ return []
+ else:
+ return ['0']
+ if type(d1) in [int, float] and type(d2) in [int, float]:
+ equal = abs(d1 - d2) <= 0.00001 * abs(d1)
+ if equal:
+ return []
+ else:
+ return ['0']
+ if isinstance(d1, (dict, OrderedDict)) and isinstance(d2, (dict, OrderedDict)):
+ if len(d1) != len(d2):
+ return ['0']
+ path_d1 = dict_get_all_path(d1, with_type=True)
+ result = []
+ for p in path_d1:
+ v1 = dict_get_path_value(d1, p, with_type=True)
+ if not dict_has_path(d2, p, with_type=True):
+ result.append(p)
+ else:
+ v2 = dict_get_path_value(d2, p, with_type=True)
+ curr_result = find_float_tolorance_unequal(v1, v2)
+ for r in curr_result:
+ result.append(p + '$' + r)
+ return result
+ if isinstance(d1, np.ndarray) and isinstance(d2, np.ndarray):
+ diff = np.absolute((d1 - d2)).sum()
+ s = np.absolute(d1).sum()
+ equal = diff < 1e-5 * s
+ if equal:
+ return []
+ else:
+ return ['0']
+ if type(d1) in [tuple, list] and type(d2) in [tuple, list]:
+ if len(d1) != len(d2):
+ return ['-1']
+ result = []
+ for i, (x1, x2) in enumerate(zip(d1, d2)):
+ curr_result = find_float_tolorance_unequal(x1, x2)
+ for r in curr_result:
+ result.append('{}${}'.format(i, r))
+ return result
+ if type(d1) != type(d2):
+ return ['0']
+ else:
+ import torch
+ if isinstance(d1, torch.Tensor):
+ diff = (d1 - d2).float().abs().sum()
+ s = d1.float().abs().sum()
+ if float(s) < 1e-5:
+ equal = diff < 1e-5
+ else:
+ equal = float(diff / s) < 1e-5
+ if equal:
+ return []
+ else:
+ return ['0']
+ else:
+ raise Exception('unknown type')
+
+def float_tolorance_equal(d1, d2, check_order=True):
+ from past.builtins import basestring
+ if isinstance(d1, basestring) and isinstance(d2, basestring):
+ return d1 == d2
+ if type(d1) in [int, float] and type(d2) in [int, float]:
+ return abs(d1 - d2) <= 0.00001 * abs(d1)
+ if type(d1) != type(d2) and \
+ (not (type(d1) in [tuple, list] and
+ type(d2) in [tuple, list])):
+ return False
+ if type(d1) in [dict, OrderedDict]:
+ if len(d1) != len(d2):
+ return False
+ for k in d1:
+ if k not in d2:
+ return False
+ v1, v2 = d1[k], d2[k]
+ if not float_tolorance_equal(v1, v2):
+ return False
+ return True
+ elif type(d1) in [tuple, list]:
+ if len(d1) != len(d2):
+ return False
+ if not check_order:
+ d1 = sorted(d1, key=lambda x: pformat(x))
+ d2 = sorted(d2, key=lambda x: pformat(x))
+ for x1, x2 in zip(d1, d2):
+ if not float_tolorance_equal(x1, x2, check_order):
+ return False
+ return True
+ elif type(d1) is bool:
+ return d1 == d2
+ elif d1 is None:
+ return d1 == d2
+ elif type(d1) is datetime:
+ if d1.tzinfo != d2.tzinfo:
+ return d1.replace(tzinfo=d2.tzinfo) == d2
+ else:
+ return d1 == d2
+ elif type(d1) is np.ndarray:
+ if not float_tolorance_equal(d1.shape, d2.shape, check_order=True):
+ return False
+ return np.absolute(d1 - d2).sum() <= 1e-5 * np.absolute(d1).sum()
+ elif type(d1) in [np.float64]:
+ return np.absolute(d1 - d2).sum() <= 1e-5 * np.absolute(d1).sum()
+ else:
+ import torch
+ if type(d1) is torch.Tensor:
+ diff = (d1 - d2).abs().sum()
+ s = d1.abs().sum()
+ if s < 1e-5:
+ return diff < 1e-5
+ else:
+ return diff / s < 1e-5
+ else:
+ raise Exception('unknown type')
+
+def case_incensitive_overlap(all_terms):
+ all_lower_to_term = [{t.lower(): t for t in terms} for terms in all_terms]
+ all_lowers = [set(l.keys()) for l in all_lower_to_term]
+ anchor = all_lowers[0].intersection(*all_lowers[1:])
+
+ return [[lower_to_term[l] for l in anchor]
+ for lower_to_term in all_lower_to_term]
+
+def get_executable():
+ return sys.executable
+
+def collect_process_info():
+ result = {}
+ for process in psutil.process_iter():
+ result[process.pid] = {}
+ result[process.pid]['username'] = process.username()
+ result[process.pid]['time_spent_in_hour'] = (int(time.time()) -
+ process.create_time()) / 3600.0
+ result[process.pid]['cmdline'] = ' '.join(process.cmdline())
+ return result
+
+def remote_run(str_cmd, ssh_info, return_output=False):
+ cmd = ['ssh', '-t', '-t', '-o', 'StrictHostKeyChecking no']
+ for key in ssh_info:
+ if len(key) > 0 and key[0] == '-':
+ cmd.append(key)
+ cmd.append(str(ssh_info[key]))
+ cmd.append('{}@{}'.format(ssh_info['username'], ssh_info['ip']))
+ if is_cluster(ssh_info):
+ prefix = 'source ~/.bashrc && export PATH=/usr/local/nvidia/bin:$PATH && '
+ else:
+ cs = []
+ # don't use anaconda since caffe is slower under anaconda because of the
+ # data preprocessing. not i/o
+ cs.append('source ~/.bashrc')
+ if 'conda' in get_executable():
+ cs.append('export PATH=$HOME/anaconda3/bin:\$PATH')
+ cs.append('export LD_LIBRARY_PATH=$HOME/anaconda3/lib:\$LD_LIBRARY_PATH')
+ cs.append('export PATH=/usr/local/nvidia/bin:\$PATH')
+ cs.append('export OMP_NUM_THREADS=1')
+ prefix = ' && '.join(cs) + ' && '
+
+ suffix = ' && hostname'
+ ssh_command = '{}{}{}'.format(prefix, str_cmd, suffix)
+ # this will use the environment variable like what you have after ssh
+ ssh_command = 'bash -i -c "{}"'.format(ssh_command)
+ cmd.append(ssh_command)
+ return cmd_run(cmd, return_output)
+
+def compile_by_docker(src_zip, docker_image, dest_zip):
+ # compile the qd zip file and generate another one by compiling. so that
+ # there is no need to compile it again.
+ src_fname = op.basename(src_zip)
+ src_folder = op.dirname(src_zip)
+
+ docker_src_folder = '/tmpwork'
+ docker_src_zip = op.join(docker_src_folder, src_fname)
+ docker_out_src_fname = src_fname + '.out.zip'
+ docker_out_zip = op.join(docker_src_folder, docker_out_src_fname)
+ out_zip = op.join(src_folder, docker_out_src_fname)
+ docker_compile_folder = '/tmpcompile'
+ cmd = ['docker', 'run',
+ '-v', '{}:{}'.format(src_folder, docker_src_folder),
+ docker_image,
+ ]
+ cmd.append('/bin/bash')
+ cmd.append('-c')
+ compile_cmd = [
+ 'mkdir -p {}'.format(docker_compile_folder),
+ 'cd {}'.format(docker_compile_folder),
+ 'unzip {}'.format(docker_src_zip),
+ 'bash compile.aml.sh',
+ 'zip -yrv x.zip *',
+ 'cp x.zip {}'.format(docker_out_zip),
+ 'chmod a+rw {}'.format(docker_out_zip),
+ ]
+ cmd.append(' && '.join(compile_cmd))
+ cmd_run(cmd)
+ ensure_directory(op.dirname(dest_zip))
+ copy_file(out_zip, dest_zip)
+
+def zip_qd(out_zip, options=None):
+ ensure_directory(op.dirname(out_zip))
+ cmd = [
+ 'zip',
+ '-uyrv',
+ out_zip,
+ '*',
+ ]
+ if options:
+ cmd.extend(options)
+ else:
+ cmd.extend([
+ '-x',
+ '\*src/CCSCaffe/\*',
+ '-x',
+ '\*src/build/lib.linux-x86_64-2.7/\*',
+ '-x',
+ '\*build/lib.linux-x86_64-2.7/\*',
+ '-x',
+ '\*build/temp.linux-x86_64-2.7/\*',
+ '-x',
+ '\*build/lib.linux-x86_64-3.5/\*',
+ '-x',
+ '\*build/temp.linux-x86_64-3.5/\*',
+ '-x',
+ '\*build/lib.linux-x86_64-3.7/\*',
+ '-x',
+ 'assets\*',
+ '-x',
+ '\*build/temp.linux-x86_64-3.7/\*',
+ '-x',
+ '\*build/lib.linux-x86_64-3.6/\*',
+ '-x',
+ '\*build/temp.linux-x86_64-3.6/\*',
+ '-x',
+ '\*src/detectron2/datasets/\*',
+ '-x',
+ '\*src/CCSCaffe/models/\*',
+ '-x',
+ '\*src/CCSCaffe/data/\*',
+ '-x',
+ '\*src/CCSCaffe/examples/\*',
+ '-x',
+ '\*src/detectron2/output\*',
+ '-x',
+ 'aux_data/yolo9k/\*',
+ '-x',
+ 'visualization\*',
+ '-x',
+ 'output\*',
+ '-x',
+ 'data\*',
+ '-x',
+ '\*.build_release\*',
+ '-x',
+ '\*.build_debug\*',
+ '-x',
+ '\*.build\*',
+ '-x',
+ '\*tmp_run\*',
+ '-x',
+ '\*src/CCSCaffe/MSVC/\*',
+ '-x',
+ '\*.pyc',
+ '-x',
+ '\*.so',
+ '-x',
+ '\*.o',
+ '-x',
+ '\*src/CCSCaffe/docs/tutorial/\*',
+ '-x',
+ '\*src/CCSCaffe/matlab/\*',
+ '-x',
+ '\*.git\*',
+ '-x',
+ '\*src/qd_classifier/.cache/\*',
+ '\*wandb\*',
+ ])
+ cmd_run(cmd, working_dir=os.getcwd(), shell=True)
+
+def func_retry_agent(info, func, *args, **kwargs):
+ i = 0
+ num = info.get('retry_times', -1)
+ throw_if_fail = info.get('throw_if_fail')
+ while True:
+ try:
+ return func(*args, **kwargs)
+ except Exception:
+ logging.info('fails: try {}-th time'.format(i))
+ print_trace()
+ i = i + 1
+ if num > 0 and i >= num:
+ if throw_if_fail:
+ raise
+ else:
+ break
+ import time
+ time.sleep(random.random() * 5)
+
+def limited_retry_agent(num, func, *args, **kwargs):
+ for i in range(num):
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ logging.warning('fails with \n{}: tried {}/{}-th time'.format(
+ e,
+ i + 1,
+ num,
+ ))
+ import time
+ print_trace()
+ if i == num - 1:
+ #raise
+ pass
+ else:
+ t = random.random() * 5
+ time.sleep(t)
+
+def retry_agent(func, *args, **kwargs):
+ return func_retry_agent(
+ {'retry_times': -1},
+ func, *args, **kwargs,
+ )
+
+def ensure_copy_folder(src_folder, dst_folder, dst_host=None):
+ if op.isfile(src_folder):
+ opt = '-vz'
+ else:
+ opt = '-ravz'
+ src_folder = src_folder + '/'
+ if dst_host:
+ cmd_run(['ssh', dst_host, 'mkdir', '-p', op.dirname(dst_folder)])
+ if not dst_host:
+ ensure_directory(dst_folder)
+ cmd_run('rsync {} {} {} --progress'.format(
+ opt,
+ src_folder, dst_folder).split(' '))
+ else:
+ cmd_run('rsync {} {} {}:{} --progress'.format(
+ opt,
+ src_folder, dst_host, dst_folder).split(' '))
+
+def get_current_time_as_str():
+ return datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
+
+def iter_swap_param_simple(swap_params):
+ if isinstance(swap_params, dict):
+ swap_params = [[k, v] for k, v in swap_params.items()]
+ num = len(swap_params)
+ for p in swap_params:
+ if type(p[1]) is not list and type(p[1]) is not tuple:
+ p[1] = [p[1]]
+ counts = [len(p[1]) for p in swap_params]
+ assert all(c > 0 for c in counts)
+ idx = [0] * num
+
+ while True:
+ result = {}
+ for p, i in zip(swap_params, idx):
+ result[p[0]] = p[1][i]
+ yield result
+
+ for i in range(num - 1, -1, -1):
+ idx[i] = idx[i] + 1
+ if idx[i] < counts[i]:
+ break
+ else:
+ idx[i] = 0
+ if i == 0:
+ return
+
+def iter_swap_param(swap_params):
+ if isinstance(swap_params, dict):
+ swap_params = [(k, v) for k, v in swap_params.items()]
+ num = len(swap_params)
+ for p in swap_params:
+ if type(p[1]) is not list and type(p[1]) is not tuple:
+ p[1] = [p[1]]
+ counts = [len(p[1]) for p in swap_params]
+ empty_keys = [k for k, vs in swap_params if len(vs) == 0]
+ assert len(empty_keys) == 0, empty_keys
+ idx = [0] * num
+
+ while True:
+ result = {}
+ for p, i in zip(swap_params, idx):
+ key = p[0]
+ value = p[1][i]
+ if isinstance(key, tuple):
+ for sub_key, sub_value in zip(key, value):
+ dict_update_path_value(result, sub_key, sub_value)
+ else:
+ dict_update_path_value(result, key, value)
+ yield result
+
+ for i in range(num - 1, -1, -1):
+ idx[i] = idx[i] + 1
+ if idx[i] < counts[i]:
+ break
+ else:
+ idx[i] = 0
+ if i == 0:
+ return
+
+def gen_uuid():
+ import uuid
+ return uuid.uuid4().hex
+
+def remove_dir(d):
+ ensure_remove_dir(d)
+
+def ensure_remove_file(d):
+ if op.isfile(d) or op.islink(d):
+ try:
+ os.remove(d)
+ except:
+ pass
+
+@try_once
+def ensure_remove_dir(d):
+ is_dir = op.isdir(d)
+ is_link = op.islink(d)
+ if is_dir:
+ if not is_link:
+ shutil.rmtree(d)
+ else:
+ os.unlink(d)
+
+def split_to_chunk_to_range(n, num_chunk=None, num_task_each_chunk=None):
+ if num_task_each_chunk is None:
+ num_task_each_chunk = (n + num_chunk - 1) // num_chunk
+ result = []
+ i = 0
+ while True:
+ start = i * num_task_each_chunk
+ end = start + num_task_each_chunk
+ if start >= n:
+ break
+ if end > n:
+ end = n
+ result.append([start, end])
+ i = i + 1
+ return result
+
+def split_to_chunk(all_task, num_chunk=None, num_task_each_chunk=None):
+ if num_task_each_chunk is None:
+ num_task_each_chunk = (len(all_task) + num_chunk - 1) // num_chunk
+ result = []
+ i = 0
+ while True:
+ start = i * num_task_each_chunk
+ end = start + num_task_each_chunk
+ if start >= len(all_task):
+ break
+ if end > len(all_task):
+ end = len(all_task)
+ result.append(all_task[start:end])
+ i = i + 1
+ return result
+
+def hash_sha1(s):
+ import hashlib
+ if type(s) is not str:
+ s = pformat(s)
+ return hashlib.sha1(s.encode('utf-8')).hexdigest()
+
+def copy_file(src, dest):
+ tmp = dest + '.tmp'
+ # we use rsync because it could output the progress
+ cmd_run('rsync {} {} --progress'.format(src, tmp).split(' '))
+ os.rename(tmp, dest)
+
+def ensure_copy_file(src, dest):
+ ensure_directory(op.dirname(dest))
+ if not op.isfile(dest):
+ copy_file(src, dest)
+
+def decode_to_str(x):
+ try:
+ return x.decode('utf-8')
+ except UnicodeDecodeError:
+ return x.decode('latin-1')
+
+def cmd_run(list_cmd,
+ return_output=False,
+ env=None,
+ working_dir=None,
+ stdin=sp.PIPE,
+ shell=False,
+ dry_run=False,
+ silent=False,
+ process_input=None,
+ stdout=None,
+ stderr=None,
+ no_commute=False,
+ timeout=None,
+ ):
+ if not silent:
+ x = ' '.join(map(str, list_cmd)) if isinstance(list_cmd, list) else list_cmd
+ logging.info('start to cmd run: {}'.format(x))
+ if working_dir:
+ logging.info(working_dir)
+ # if we dont' set stdin as sp.PIPE, it will complain the stdin is not a tty
+ # device. Maybe, the reson is it is inside another process.
+ # if stdout=sp.PIPE, it will not print the result in the screen
+ e = os.environ.copy()
+ if 'SSH_AUTH_SOCK' in e:
+ del e['SSH_AUTH_SOCK']
+ if working_dir:
+ ensure_directory(working_dir)
+ if env:
+ for k in env:
+ e[k] = env[k]
+ if dry_run:
+ # we need the log result. Thus, we do not return at teh very beginning
+ return
+ if not return_output:
+ #if env is None:
+ #p = sp.Popen(list_cmd, stdin=sp.PIPE, cwd=working_dir)
+ #else:
+ p = sp.Popen(' '.join(list_cmd) if shell else list_cmd,
+ stdin=stdin,
+ env=e,
+ shell=shell,
+ stdout=stdout,
+ cwd=working_dir,
+ stderr=stderr,
+ )
+ if not no_commute:
+ message = p.communicate(input=process_input, timeout=timeout)
+ if p.returncode != 0:
+ message = 'message = {}; cmd = {}'.format(
+ message, ' '.join(list_cmd))
+ if stderr == sp.PIPE and not p.stderr:
+ message += '; stderr = {}'.format(p.stderr.read().decode())
+ raise ValueError(message)
+ return message
+ else:
+ return p
+ else:
+ if isinstance(list_cmd, list) and shell:
+ list_cmd = ' '.join(list_cmd)
+ message = sp.check_output(list_cmd,
+ env=e,
+ cwd=working_dir,
+ shell=shell,
+ timeout=timeout,
+ )
+ if not silent:
+ logging.info('finished the cmd run')
+ return decode_to_str(message)
+
+def parallel_imap(func, all_task, num_worker=16):
+ if num_worker > 0:
+ #from multiprocessing import Pool
+ from pathos.multiprocessing import Pool
+ m = Pool(num_worker)
+ result = []
+ for x in qd_tqdm(m.imap(func, all_task), total=len(all_task)):
+ result.append(x)
+ # there are some error comes out from os.fork() and which says
+ # OSError: [Errno 24] Too many open files.
+ # self.pid = os.fork()
+ # here, we explicitly close the pool and see if it helps. note, this is
+ # not verified to work, if we still see that kind of error message, we
+ # need other solutions
+ m.close()
+ m.join()
+ return result
+ else:
+ result = []
+ for t in all_task:
+ result.append(func(t))
+ return result
+
+def get_azfuse_env(v, d=None):
+ # this is for back-compatibility only
+ qd_k = 'QD_' + v
+ if qd_k in os.environ:
+ return os.environ[qd_k]
+ azfuse_k = 'AZFUSE_' + v
+ if azfuse_k in os.environ:
+ return os.environ[azfuse_k]
+ return d
+
+def get_tmp_folder():
+ folder = os.environ.get('QD_TMP_FOLDER', '/raid/tmp')
+ return folder
+
+# use parallel_imap if possible
+def parallel_map(func, all_task, num_worker=16):
+ if num_worker > 0:
+ from pathos.multiprocessing import ProcessingPool as Pool
+ with Pool(num_worker) as m:
+ result = m.map(func, all_task)
+ return result
+ else:
+ result = []
+ for t in all_task:
+ result.append(func(t))
+ return result
+
+def url_to_file_by_wget(url, fname):
+ ensure_directory(op.dirname(fname))
+ cmd_run(['wget', url, '-O', fname])
+
+@functools.lru_cache(maxsize=1)
+def logging_once(s):
+ logging.info(s)
+
+# this is specifically for azure blob url, where the last 1k bytes operation is
+# not supported. We have to first find the length and then find the start
+# point
+def get_url_fsize(url):
+ result = cmd_run(['curl', '-sI', url], return_output=True)
+ for row in result.split('\n'):
+ ss = [s.strip() for s in row.split(':')]
+ if len(ss) == 2 and ss[0] == 'Content-Length':
+ size_in_bytes = int(ss[1])
+ return size_in_bytes
+
+def url_to_file_by_curl(url, fname, bytes_start=None, bytes_end=None):
+ ensure_directory(op.dirname(fname))
+ if bytes_start == 0 and bytes_end == 0:
+ cmd_run(['touch', fname])
+ return
+ if bytes_start is None:
+ bytes_start = 0
+ elif bytes_start < 0:
+ size = get_url_fsize(url)
+ bytes_start = size + bytes_start
+ if bytes_start < 0:
+ bytes_start = 0
+ if bytes_end is None:
+ # -f: if it fails, no output will be sent to output file
+ if bytes_start == 0:
+ cmd_run(['curl', '-f',
+ url, '--output', fname])
+ else:
+ cmd_run(['curl', '-f', '-r', '{}-'.format(bytes_start),
+ url, '--output', fname])
+ else:
+ # curl: end is inclusive
+ cmd_run(['curl', '-f', '-r', '{}-{}'.format(bytes_start, bytes_end - 1),
+ url, '--output', fname])
+
+def url_to_bytes(url):
+ try:
+ fp = urlopen(url, timeout=30)
+ buf = fp.read()
+ real_url = fp.geturl()
+ if real_url != url and (not real_url.startswith('https') or
+ real_url.replace('https', 'http') != url):
+ logging.info('new url = {}; old = {}'.format(fp.geturl(), url))
+ # the image gets redirected, which means the image is not available
+ return None
+ return buf
+ except HTTPError as err:
+ logging.error("url: {}; error code {}; message: {}".format(
+ url, err.code, err.msg))
+ return None
+ except:
+ import traceback
+ logging.error("url: {}; unknown {}".format(
+ url, traceback.format_exc()))
+ return None
+
+def url_to_str(url):
+ try:
+ fp = urlopen(url, timeout=30)
+ buf = fp.read()
+ real_url = fp.geturl()
+ if real_url != url and (not real_url.startswith('https') or
+ real_url.replace('https', 'http') != url):
+ logging.info('new url = {}; old = {}'.format(fp.geturl(), url))
+ # the image gets redirected, which means the image is not available
+ return None
+ if type(buf) is str:
+ # py2
+ return buf
+ else:
+ # py3
+ return buf.decode()
+ except HTTPError as err:
+ logging.error("url: {}; error code {}; message: {}".format(
+ url, err.code, err.msg))
+ return None
+ except:
+ logging.error("url: {}; unknown {}".format(
+ url, traceback.format_exc()))
+ return None
+
+def image_url_to_bytes(url):
+ req = Request(url, headers={
+ "User-Agent": "Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"})
+ try:
+ response = urlopen(req, None, 10)
+ if response.code != 200:
+ logging.info("url: {}, error code: {}".format(url, response.code))
+ return None
+ data = response.read()
+ response.close()
+ return data
+ except Exception as e:
+ logging.info("error downloading: {}".format(e))
+ return None
+
+def str_to_image(buf):
+ image = np.asarray(bytearray(buf), dtype='uint8')
+ im = cv2.imdecode(image, cv2.IMREAD_COLOR)
+ return im
+
+def bytes_to_image(bs):
+ image = np.asarray(bytearray(bs), dtype='uint8')
+ return cv2.imdecode(image, cv2.IMREAD_COLOR)
+
+def url_to_image(url):
+ buf = url_to_bytes(url)
+ if buf is None:
+ return None
+ else:
+ image = np.asarray(bytearray(buf), dtype='uint8')
+ return cv2.imdecode(image, cv2.IMREAD_COLOR)
+
+def normalize_to_str(s):
+ if sys.version_info.major == 3:
+ return s.encode("ascii", "ignore").decode()
+ else:
+ if type(s) is str:
+ s = s.decode('unicode_escape')
+ import unicodedata
+ return unicodedata.normalize('NFKD', s).encode('ascii','ignore')
+
+def query_wiki_info(query_term):
+ query_term = '{} site:en.wikipedia.org'.format(query_term)
+ rls = limited_retry_agent(10, scrape_bing_general_rich, query_term, 1)
+ if not rls:
+ return {'query_term': query_term}
+ rl = rls[0]
+ n_title = normalize_to_str(rl['title'])
+ result = re.match('(.*) - Wikipedia', n_title)
+ if result:
+ best_name = result.groups()[0]
+ else:
+ best_name = query_term
+ result = {
+ 'query_term': query_term,
+ 'best_name': best_name,
+ 'wiki_tile': rl['title'],
+ 'norm_wiki_title': normalize_to_str(rl['title']),
+ 'wiki_url': rl['url']}
+ #logging.info(pformat(result))
+ return result
+
+def scrape_bing_general_rich(query_term, depth):
+ '''
+ note, the order of url list is not the same as the web query. Even we keep
+ the order of how to add it to the result, the order is still not the same.
+ '''
+ # we might add duplicated terms. need 1) deduplicate, 2) keep the order
+ # when it is added
+ import requests
+ import xml.etree.ElementTree as ET
+ format_str = \
+ 'http://www.bing.com/search?q={}&form=MONITR&qs=n&format=pbxml&first={}&count={}&fdpriority=premium&mkt=en-us'
+ start = 0
+ all_result = []
+ while True:
+ count = min(depth - start, 150)
+ if count <= 0:
+ break
+ query_str = format_str.format(query_term, start, count)
+ start = start + count
+ r = requests.get(query_str, allow_redirects=True)
+ content = r.content
+ #content = urllib2.urlopen(query_str).read()
+ root = ET.fromstring(content)
+ for t in root.iter('k_AnswerDataKifResponse'):
+ if t.text is None:
+ continue
+ text_result = json.loads(t.text)
+ if 'results' not in text_result:
+ continue
+ results = text_result['results']
+ for r in results:
+ rl = {k.lower() : r[k] for k in r}
+ if 'url' in rl and 'title' in rl and len(rl['title']) > 0:
+ all_result.append(rl)
+ url_to_result = {}
+ for rl in all_result:
+ url = rl['url']
+ if url not in url_to_result:
+ url_to_result[url] = rl
+
+ return list(url_to_result.values())
+
+def request_by_browser(url):
+ from selenium.webdriver.chrome.options import Options
+ from selenium import webdriver
+ import bs4
+ chrome_options = Options()
+ chrome_options.add_argument("--headless")
+ driver = webdriver.Chrome(options=chrome_options)
+ driver.get(url)
+ soup = bs4.BeautifulSoup(driver.page_source, features='lxml')
+ # if we return immediately, the page_source might not be ready
+ time.sleep(1)
+ soup = bs4.BeautifulSoup(driver.page_source, features='lxml')
+ return soup
+
+def iter_bing_visual_search(query_url, origin_url=True):
+ format_str = 'http://www.bing.com/images/searchbyimage?FORM=IRSBIQ&cbir=sbi&imgurl={0}'
+ # the following two parameters are not valid
+ #format_str += '&first=100'
+ #format_str += '&count=10'
+ bing_url = format_str.format(query_url)
+ soup = request_by_browser(bing_url)
+ html_keywords = ['richImage relImg', 'richImage relProd flyout']
+ alts = ['See related image detail', 'See related product detail']
+ caption_classes = ['span', 'a']
+ for html_key_word, alt, caption_class in zip(html_keywords, alts, caption_classes):
+ for i, container in enumerate(soup.find_all(class_= html_key_word)):
+ # one container has one image and one caption container. we will
+ # extract the image and the caption, which might be helpful in the
+ # future
+ info = {'rank': i}
+ info['html_keyword'] = html_key_word
+ # original url
+ if origin_url:
+ imgs = container.find_all(class_='richImgLnk')
+ if len(imgs) == 1:
+ img = imgs[0]
+ url = 'http://www.bing.com/images/search' + img.attrs['href']
+ result = request_by_browser(url)
+ imgs = result.find_all(alt='See the source image')
+ if len(imgs) == 1:
+ img = imgs[0]
+ url = img.attrs['src']
+ info['url'] = url
+
+ # bing cache image
+ imgs = container.find_all('img', alt=alt)
+ if len(imgs) == 1:
+ bing_cache_url = 'http://www.bing.com' + imgs[0].attrs['src']
+ info['bing_cache_url'] = bing_cache_url
+
+ captions = container.find_all(caption_class, class_='tit')
+ if len(captions) == 1:
+ cap = captions[0]
+ info['caption'] = cap.text
+ yield info
+
+def scrape_bing_general(query_term, depth):
+ '''
+ note, the order of url list is not the same as the web query. Even we keep
+ the order of how to add it to the result, the order is still not the same.
+ '''
+ # we might add duplicated terms. need 1) deduplicate, 2) keep the order
+ # when it is added
+ import requests
+ import xml.etree.ElementTree as ET
+ format_str = \
+ 'http://www.bing.com/search?q={}&form=MONITR&qs=n&format=pbxml&first={}&count={}&fdpriority=premium&mkt=en-us'
+ start = 0
+ all_url = []
+ while True:
+ count = min(depth - start, 150)
+ if count <= 0:
+ break
+ query_str = format_str.format(query_term, start, count)
+ start = start + count
+ r = requests.get(query_str, allow_redirects=True)
+ content = r.content
+ #content = urllib2.urlopen(query_str).read()
+ root = ET.fromstring(content)
+ for t in root.iter('k_AnswerDataKifResponse'):
+ if t.text is None:
+ continue
+ text_result = json.loads(t.text)
+ if 'results' not in text_result:
+ continue
+ results = text_result['results']
+ for r in results:
+ rl = {k.lower() : r[k] for k in r}
+ if 'url' in rl:
+ url = rl['url']
+ all_url.append(url)
+ return list(set(all_url))
+
+def scrape_bing(query_term, depth, trans_bg=False):
+ ''' this is for image; for text, use scrape_bing_general
+ e.g. scrape_bing('elder person', 300)
+ '''
+ import requests
+ import xml.etree.ElementTree as ET
+ format_str = \
+ 'http://www.bing.com/images/search?q={}&form=MONITR&qs=n&format=pbxml&first={}&count={}&fdpriority=premium&mkt=en-us'
+ start = 0
+ all_url = []
+ while True:
+ count = min(depth - start, 150)
+ if count <= 0:
+ break
+ query_str = format_str.format(query_term, start, count)
+ if trans_bg:
+ query_str += "&&qft=+filterui:photo-transparent"
+ start = start + count
+ logging.info(query_str)
+ r = requests.get(query_str, allow_redirects=True)
+ content = r.content
+ #content = urllib2.urlopen(query_str).read()
+ root = ET.fromstring(content)
+ for t in root.iter('k_AnswerDataKifResponse'):
+ results = json.loads(t.text)['results']
+ for r in results:
+ rl = {k.lower() : r[k] for k in r}
+ media_url = rl.get('mediaurl', '')
+ #url = rl.get('url', '')
+ #title = rl.get('title', '')
+ all_url.append(media_url)
+ break
+ return all_url
+
+
+def calculate_correlation_between_terms(iter1, iter2):
+ label_to_num1 = {}
+ label_to_num2 = {}
+ ll_to_num = {}
+
+ for (k1, str_rects1), (k2, str_rects2) in zip(iter1, iter2):
+ assert k1 == k2, 'keys should be aligned ({} != {})'.format(k1, k2)
+ rects1 = json.loads(str_rects1)
+ rects2 = json.loads(str_rects2)
+ for r in rects1:
+ c = r['class']
+ label_to_num1[c] = label_to_num1.get(c, 0) + 1
+ for r in rects2:
+ c = r['class']
+ label_to_num2[c] = label_to_num2.get(c, 0) + 1
+ for r1 in rects1:
+ for r2 in rects2:
+ i = calculate_iou(r1['rect'], r2['rect'])
+ if i > 0.01:
+ k = (r1['class'], r2['class'])
+ ll_to_num[k] = ll_to_num.get(k, 0) + i
+ ll_correlation = [(ll[0], ll[1], 1. * ll_to_num[ll] / (label_to_num1[ll[0]]
+ + label_to_num2[ll[1]] - ll_to_num[ll]))
+ for ll in ll_to_num]
+ ll_correlation = [(left, right, c) for left, right, c in ll_correlation
+ if left.lower() != right.lower()]
+ ll_correlation = sorted(ll_correlation, key=lambda x: -x[2])
+
+ return ll_correlation
+
+def json_dump(obj):
+ # order the keys so that each operation is deterministic though it might be
+ # slower
+ return json.dumps(obj, sort_keys=True, separators=(',', ':'))
+
+def set_if_not_exist(d, key, value):
+ if key not in d:
+ d[key] = value
+
+def print_as_html(table, html_output):
+ from jinja2 import Environment, FileSystemLoader
+ j2_env = Environment(loader=FileSystemLoader('./'), trim_blocks=True)
+ # find the cols with longest length. If it does not include all cols, then
+ # append those not included
+ _, cols = max([(len(table[row]), table[row]) for row in table],
+ key=lambda x: x[0])
+ cols = list(cols)
+ for row in table:
+ for c in table[row]:
+ if c not in cols:
+ cols.append(c)
+ r = j2_env.get_template('aux_data/html_template/table_viewer.html').render(
+ table=table,
+ rows=table.keys(),
+ cols=cols)
+ write_to_file(r, html_output)
+
+def jinja_render(template, **kwargs):
+ if len(kwargs) == 0:
+ return read_to_buffer(template).decode()
+ from jinja2 import Environment, FileSystemLoader
+ j2_env = Environment(loader=FileSystemLoader('./'), trim_blocks=True)
+ return j2_env.get_template(template).render(
+ **kwargs,
+ )
+
+def parse_general_args():
+ parser = argparse.ArgumentParser(description='General Parser')
+ parser.add_argument('-c', '--config_file', help='config file',
+ type=str)
+ parser.add_argument('-p', '--param', help='parameter string, yaml format',
+ type=str)
+ parser.add_argument('-bp', '--base64_param', help='base64 encoded yaml format',
+ type=str)
+ args = parser.parse_args()
+ kwargs = {}
+ if args.config_file:
+ logging.info('loading parameter from {}'.format(args.config_file))
+ configs = load_from_yaml_file(args.config_file)
+ for k in configs:
+ kwargs[k] = configs[k]
+ if args.base64_param:
+ configs = load_from_yaml_str(base64.b64decode(args.base64_param))
+ for k in configs:
+ if k not in kwargs:
+ kwargs[k] = configs[k]
+ elif kwargs[k] == configs[k]:
+ continue
+ else:
+ logging.info('overwriting {} to {} for {}'.format(kwargs[k],
+ configs[k], k))
+ kwargs[k] = configs[k]
+ if args.param:
+ configs = load_from_yaml_str(args.param)
+ dict_ensure_path_key_converted(configs)
+ for k in configs:
+ if k not in kwargs:
+ kwargs[k] = configs[k]
+ elif kwargs[k] == configs[k]:
+ continue
+ else:
+ logging.info('overwriting {} to {} for {}'.format(kwargs[k],
+ configs[k], k))
+ kwargs[k] = configs[k]
+ return kwargs
+
+class ProgressBar(object):
+ def __init__(self, maxval):
+ assert maxval > 0
+ self.maxval = maxval
+
+ def __enter__(self):
+ self.pbar = progressbar.ProgressBar(maxval=self.maxval).start()
+ return self
+
+ def __exit__(self, t, v, traceback):
+ self.update(self.maxval)
+ sys.stdout.write('\n')
+
+ def update(self, i):
+ self.pbar.update(i)
+
+#@deprecated('use tsv_io.concat_files')
+def concat_files(ins, out):
+ ensure_directory(op.dirname(out))
+ out_tmp = out + '.tmp'
+ with open(out_tmp, 'wb') as fp_out:
+ for i, f in enumerate(ins):
+ logging.info('concating {}/{} - {}'.format(i, len(ins), f))
+ with open(f, 'rb') as fp_in:
+ shutil.copyfileobj(fp_in, fp_out, 1024*1024*10)
+ os.rename(out_tmp, out)
+
+def get_mpi_rank():
+ if 'RANK' in os.environ:
+ return int(os.environ['RANK'])
+ return int(os.environ.get('OMPI_COMM_WORLD_RANK', '0'))
+
+def get_mpi_size():
+ if 'WORLD_SIZE' in os.environ:
+ return int(os.environ['WORLD_SIZE'])
+ return int(os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))
+
+def get_mpi_local_rank():
+ if 'LOCAL_RANK' in os.environ:
+ return int(os.environ['LOCAL_RANK'])
+ return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK', '0'))
+
+def get_mpi_local_size():
+ if 'LOCAL_SIZE' in os.environ:
+ return int(os.environ['LOCAL_SIZE'])
+ return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_SIZE', '1'))
+
+def load_class_ap(full_expid, predict_file):
+ # the normal map
+ report_file = op.splitext(predict_file)[0] + '.report'
+ fname = op.join('output', full_expid, 'snapshot', report_file +
+ '.class_ap.json')
+ if op.isfile(fname):
+ return json.loads(read_to_buffer(fname))
+
+ glob_pattern = op.splitext(predict_file)[0] + '.neg_aware_gmap*report'
+ fnames = glob.glob(op.join('output', full_expid, 'snapshot',
+ glob_pattern))
+ if len(fnames) > 0 and op.isfile(fnames[0]):
+ fname = fnames[0]
+ result = load_from_yaml_file(fname)
+ return {'overall': {'0.5': {'class_ap': result['class_ap']}}}
+
+
+def calculate_ap_by_true_list(corrects, total):
+ precision = (1. * np.cumsum(corrects)) / np.arange(1, 1 + len(corrects))
+ if np.sum(corrects) == 0:
+ return 0
+ return np.sum(precision * corrects) / total
+
+def calculate_ap_by_true_list_count_num(corrects, total):
+ precision = (1. * np.cumsum(corrects)) / np.arange(1, 1 + len(corrects))
+ if np.sum(corrects) == 0:
+ return 0
+ return np.sum(precision) / len(precision) * np.sum(corrects) / total
+
+def calculate_weighted_ap_by_true_list(corrects, weights, total):
+ precision = np.cumsum(corrects * weights) / (np.cumsum(weights) + 0.0001)
+ if total == 0:
+ return 0
+ return np.mean(precision) * np.sum(corrects) / total
+
+def calculate_ap_by_true_list_100(corrects, confs, total):
+ precision = (1. * np.cumsum(corrects)) / map(lambda x: 100. * (1 - x) + 1, confs)
+ return np.sum(precision * corrects) / total
+
+def calculate_image_ap_weighted(predicts, gts, weights):
+ corrects, _ = match_prediction_to_gt(predicts, gts)
+ return calculate_weighted_ap_by_true_list(corrects, weights, len(gts))
+
+def match_prediction_to_gt(predicts, gts, iou_th=0.5):
+ matched = [False] * len(gts)
+ corrects = np.zeros(len(predicts))
+ match_idx = [-1] * len(predicts)
+ for j, p in enumerate(predicts):
+ idx_gts = [(i, g) for i, g in enumerate(gts) if not matched[i]]
+ if len(idx_gts) == 0:
+ # max does not support empty input
+ continue
+ idx_gt_ious = [(i, g, calculate_iou(p, g)) for i, g in idx_gts]
+ max_idx, _, max_iou = max(idx_gt_ious, key=lambda x: x[-1])
+ if max_iou > iou_th:
+ matched[max_idx] = True
+ corrects[j] = 1
+ match_idx[j] = max_idx
+ return corrects, match_idx
+
+def calculate_image_ap(predicts, gts, count_num=False):
+ '''
+ a list of rects, use 2 to return more info
+ '''
+ corrects, _ = match_prediction_to_gt(predicts, gts)
+ if not count_num:
+ return calculate_ap_by_true_list(corrects, len(gts))
+ else:
+ return calculate_ap_by_true_list_count_num(corrects, len(gts))
+
+
+def calculate_image_ap2(predicts, gts):
+ '''
+ a list of rects
+ '''
+ corrects, match_idx = match_prediction_to_gt(predicts, gts)
+ return calculate_ap_by_true_list(corrects, len(gts)), match_idx
+
+def get_parameters_by_full_expid(full_expid):
+ yaml_file = op.join('output', full_expid, 'parameters.yaml')
+ if not op.isfile(yaml_file):
+ return None
+ param = load_from_yaml_file(yaml_file)
+ if 'data' not in param:
+ param['data'], param['net'] = parse_data_net(full_expid,
+ param['expid'])
+ return param
+
+def get_all_model_expid():
+ names = os.listdir('./output')
+ return names
+
+def get_target_images(predicts, gts, cat, threshold):
+ image_aps = []
+ for key in predicts:
+ rects = predicts[key]
+ curr_gt = [g for g in gts[key] if cat == 'any' or g['class'] == cat]
+ curr_pred = [p for p in predicts[key] if cat == 'any' or (p['class'] == cat and
+ p['conf'] > threshold)]
+ if len(curr_gt) == 0 and len(curr_pred) == 0:
+ continue
+ curr_pred = sorted(curr_pred, key=lambda x: -x['conf'])
+ ap = calculate_image_ap([p['rect'] for p in curr_pred],
+ [g['rect'] for g in curr_gt])
+ image_aps.append((key, ap))
+ image_aps = sorted(image_aps, key=lambda x: x[1])
+ #image_aps = sorted(image_aps, key=lambda x: -x[1])
+ target_images = [key for key, ap in image_aps]
+ return target_images, image_aps
+
+def readable_confusion_entry(entry):
+ '''
+ entry: dictionary, key: label, value: count
+ '''
+ label_count = [(label, entry[label]) for label in entry]
+ label_count.sort(key=lambda x: -x[1])
+ total = sum([count for label, count in label_count])
+ percent = [1. * count / total for label, count in label_count]
+ cum_percent = np.cumsum(percent)
+ items = []
+ for i, (label, count) in enumerate(label_count):
+ if i >= 5:
+ continue
+ items.append((label, '{}'.format(count), '{:.1f}'.format(100. *
+ percent[i]),
+ '{:.1f}'.format(100. * cum_percent[i])))
+ return items
+
+def get_all_tree_data():
+ names = sorted(os.listdir('./data'))
+ return [name for name in names
+ if op.isfile(op.join('data', name, 'root_enriched.yaml'))]
+
+def parse_test_data_with_version_with_more_param(predict_file):
+ pattern = \
+ 'model(?:_iter)?_-?[0-9]*[e]?\.(?:caffemodel|pth\.tar|pth|pt)\.(.*)\.(trainval|train|test|train_[0-9]*_[0-9]*)\..*?(\.v[0-9])?\.(?:predict|report)'
+ match_result = re.match(pattern, predict_file)
+ if match_result:
+ assert match_result
+ result = match_result.groups()
+ if result[2] is None:
+ v = 0
+ else:
+ v = int(result[2][2])
+ return result[0], result[1], v
+
+def parse_test_data_with_version(predict_file):
+ # with version
+ result = parse_test_data_with_version_with_more_param(predict_file)
+ if result is not None:
+ return result
+ #model_iter_0040760.TaxCaptionBot.trainval.predict.report
+ all_pattern = [
+ 'model(?:_iter)?_-?[0-9]*[e]?\.(?:caffemodel|pth\.tar|pth|pt)\.(.*)\.(trainval|train|test|val)\.(\.v[0-9])?(?:predict|report)',
+ 'model_iter_[0-9]*\.(.*)\.(trainval|train|test|val)\..*predict\.(?:ir_acc|caption|vqa_acc)\.report',
+ 'model(?:_iter)?_-?[0-9]*[e]?\.(.*)\.(trainval|train|test|val)\.(\.v[0-9])?.*(?:predict|report|tsv)',
+ 'model_iter_[0-9]*\.(.*)\.([a-zA-Z0-9]+)\..*predict\.(?:ir_acc|caption|vqa_acc)\.report',
+ ]
+ for p in all_pattern:
+ match_result = re.match(p, predict_file)
+ if match_result is not None:
+ result = match_result.groups()
+ if len(result) == 2 or result[2] is None:
+ v = 0
+ else:
+ v = int(result[2][2:])
+ return result[0], result[1], v
+
+ pattern = \
+ 'model(?:_iter)?_-?[0-9]*[e]?\.(?:caffemodel|pth\.tar|pth|pt)\.([^\.]*).*?(\.v[0-9])?\.(?:predict|report)'
+ match_result = re.match(pattern, predict_file)
+ assert match_result
+ result = match_result.groups()
+ if result[1] is None:
+ v = 0
+ else:
+ v = int(result[1][2:])
+ return result[0], 'test', v
+
+def parse_test_data(predict_file):
+ return parse_test_data_with_version(predict_file)[:2]
+
+def parse_data(full_expid):
+ all_data = os.listdir('data/')
+ candidates = [data for data in all_data if full_expid.startswith(data)]
+ max_length = max([len(c) for c in candidates])
+ return [c for c in candidates if len(c) == max_length][0]
+
+def parse_iteration(file_name):
+ patterns = [
+ '.*model(?:_iter)?_([0-9]*)\..*',
+ '.*model(?:_iter)?_([0-9]*)e\..*',
+ '.*model(?:_iter)?_([0-9]*)$',
+ ]
+ for p in patterns:
+ r = re.match(p, file_name)
+ if r is not None:
+ return int(float(r.groups()[0]))
+ logging.info('unable to parse the iterations for {}'.format(file_name))
+ return -2
+
+def parse_snapshot_rank(predict_file):
+ '''
+ it could be iteration, or epoch
+ '''
+ pattern = 'model_iter_([0-9]*)e*\.|model_([0-9]*)e*\.pth'
+ match_result = re.match(pattern, predict_file)
+ if match_result is None:
+ return -1
+ else:
+ matched_iters = [r for r in match_result.groups() if r is not None]
+ assert len(matched_iters) == 1
+ return int(matched_iters[0])
+
+def get_all_predict_files(full_expid):
+ model_folder = op.join('output', full_expid, 'snapshot')
+
+ predict_files = []
+
+ found = glob.glob(op.join(model_folder, '*.predict'))
+ predict_files.extend([op.basename(f) for f in found])
+
+ found = glob.glob(op.join(model_folder, '*.predict.tsv'))
+ predict_files.extend([op.basename(f) for f in found])
+
+ iterations = [(parse_snapshot_rank(p), p) for p in predict_files]
+ iterations.sort(key=lambda x: -x[0])
+ return [p for i, p in iterations]
+
+def dict_to_list(d, idx):
+ result = []
+ for k in d:
+ vs = d[k]
+ for v in vs:
+ try:
+ r = []
+ # if v is a list or tuple
+ r.extend(v[:idx])
+ r.append(k)
+ r.extend(v[idx: ])
+ except TypeError:
+ r = []
+ if idx == 0:
+ r.append(k)
+ r.append(v)
+ else:
+ assert idx == 1
+ r.append(v)
+ r.append(k)
+ result.append(r)
+ return result
+
+def list_to_dict_unique(l, idx):
+ result = list_to_dict(l, idx)
+ for key in result:
+ result[key] = list(set(result[key]))
+ return result
+
+def list_to_dict(l, idx, keep_one=False):
+ result = OrderedDict()
+ for x in l:
+ if x[idx] not in result:
+ result[x[idx]] = []
+ y = x[:idx] + x[idx + 1:]
+ if not keep_one and len(y) == 1:
+ y = y[0]
+ result[x[idx]].append(y)
+ return result
+
+def generate_lineidx(filein, idxout):
+ idxout_tmp = idxout + '.tmp'
+ with open(filein, 'r') as tsvin, open(idxout_tmp,'w') as tsvout:
+ fsize = os.fstat(tsvin.fileno()).st_size
+ fpos = 0
+ fbar_last_pos = 0
+ fbar = qd_tqdm(total=fsize, unit_scale=True)
+ while fpos!=fsize:
+ tsvout.write(str(fpos)+"\n");
+ tsvin.readline()
+ fpos = tsvin.tell();
+ fbar.update(fpos - fbar_last_pos)
+ fbar_last_pos = fpos
+ os.rename(idxout_tmp, idxout)
+
+def drop_second_batch_in_bn(net):
+ assert net.layer[0].type == 'TsvBoxData'
+ assert net.layer[1].type == 'TsvBoxData'
+ slice_batch_layers = [l for l in net.layer if l.name == 'slice_batch']
+ assert len(slice_batch_layers) == 1
+ slice_batch_layer = slice_batch_layers[0]
+ slice_point = slice_batch_layer.slice_param.slice_point[0]
+
+ for i, l in enumerate(net.layer):
+ if l.type == 'BatchNorm':
+ top_name = l.top[0]
+ top_name2 = top_name + '_n'
+ l.top[0] = top_name2
+ for m in net.layer[i + 1:]:
+ for j, b in enumerate(m.bottom):
+ if b == top_name:
+ m.bottom[j] = top_name2
+ for j, t in enumerate(m.top):
+ if t == top_name:
+ m.top[j] = top_name2
+
+ all_origin_layer = []
+ for l in net.layer:
+ all_origin_layer.append(l)
+ all_layer = []
+ for l in all_origin_layer:
+ if l.type != 'BatchNorm':
+ all_layer.append(l)
+ continue
+ bn_input = l.bottom[0]
+ bn_output = l.top[0]
+
+ slice_layer = net.layer.add()
+ slice_layer.name = l.name + '/slice'
+ slice_layer.type = 'Slice'
+ slice_layer.bottom.append(bn_input)
+ slice_layer.top.append(l.name + '/slice0')
+ slice_layer.top.append(l.name + '/slice1')
+ slice_layer.slice_param.axis = 0
+ slice_layer.slice_param.slice_point.append(slice_point)
+ all_layer.append(slice_layer)
+
+ l.bottom.remove(l.bottom[0])
+ l.bottom.append(l.name + '/slice0')
+ l.top.remove(l.top[0])
+ l.top.append(l.name + '/slice0')
+ all_layer.append(l)
+
+ fix_bn_layer = net.layer.add()
+ fix_bn_layer.name = l.name + '/bn1'
+ fix_bn_layer.bottom.append(l.name + '/slice1')
+ fix_bn_layer.top.append(l.name + '/slice1')
+ fix_bn_layer.type = 'BatchNorm'
+ for _ in range(3):
+ p = fix_bn_layer.param.add()
+ p.lr_mult = 0
+ p.decay_mult = 0
+ fix_bn_layer.batch_norm_param.use_global_stats = True
+ all_layer.append(fix_bn_layer)
+
+ cat_layer = net.layer.add()
+ cat_layer.name = l.name + '/concat'
+ cat_layer.type = 'Concat'
+ cat_layer.bottom.append(l.name + '/slice0')
+ cat_layer.bottom.append(l.name + '/slice1')
+ cat_layer.top.append(bn_output)
+ cat_layer.concat_param.axis = 0
+ all_layer.append(cat_layer)
+
+ while len(net.layer) > 0:
+ net.layer.remove(net.layer[0])
+ net.layer.extend(all_layer)
+
+def fix_net_bn_layers(net, num_bn_fix):
+ for l in net.layer:
+ if l.type == 'BatchNorm':
+ if num_bn_fix > 0:
+ l.batch_norm_param.use_global_stats = True
+ num_bn_fix = num_bn_fix - 1
+ else:
+ break
+
+def is_cluster(ssh_info):
+ return '-p' in ssh_info and '-i' not in ssh_info
+
+def visualize_net(net):
+ delta = 0.000001
+ data_values = []
+ for key in net.blobs:
+ data_value = np.mean(np.abs(net.blobs[key].data))
+ data_values.append(data_value + delta)
+ diff_values = []
+ for key in net.blobs:
+ diff_values.append(np.mean(np.abs(net.blobs[key].diff))
+ + delta)
+ param_keys = []
+ param_data = []
+ for key in net.params:
+ for i, b in enumerate(net.params[key]):
+ param_keys.append('{}_{}'.format(key, i))
+ param_data.append(np.mean(np.abs(b.data)) + delta)
+ param_diff = []
+ for key in net.params:
+ for i, b in enumerate(net.params[key]):
+ param_diff.append(np.mean(np.abs(b.diff)) + delta)
+
+ xs = range(len(net.blobs))
+ plt.gcf().clear()
+ plt.subplot(2, 1, 1)
+
+ plt.semilogy(xs, data_values, 'r-o')
+ plt.semilogy(xs, diff_values, 'b-*')
+ plt.xticks(xs, net.blobs.keys(), rotation='vertical')
+ plt.grid()
+
+ plt.subplot(2, 1, 2)
+ xs = range(len(param_keys))
+ plt.semilogy(xs, param_data, 'r-o')
+ plt.semilogy(xs, param_diff, 'b-*')
+ plt.xticks(xs, param_keys, rotation='vertical')
+ plt.grid()
+ plt.draw()
+ plt.pause(0.001)
+
+def visualize_train(solver):
+ plt.figure()
+ features = []
+ for i in range(100):
+ visualize_net(solver.net)
+ solver.step(10)
+
+def network_input_to_image(data, mean_value, std_value=[1.0,1.0,1.0]):
+ all_im = []
+ for d in data:
+ im = (d.transpose((1, 2, 0))
+ * np.asarray(std_value).reshape(1, 1, 3)
+ + np.asarray(mean_value).reshape(1, 1, 3)
+ ).astype(np.uint8).copy()
+ all_im.append(im)
+ return all_im
+
+def remove_data_augmentation(data_layer):
+ assert data_layer.type == 'TsvBoxData'
+ data_layer.box_data_param.jitter = 0
+ data_layer.box_data_param.hue = 0
+ data_layer.box_data_param.exposure = 1
+ data_layer.box_data_param.random_scale_min = 1
+ data_layer.box_data_param.random_scale_max = 1
+ data_layer.box_data_param.fix_offset = True
+ data_layer.box_data_param.saturation = True
+
+def check_best_iou(biases, gt_w, gt_h, n):
+ def iou(gt_w, gt_h, w, h):
+ inter = min(gt_w, w) * min(gt_h, h)
+ return inter / (gt_w * gt_h + w * h - inter)
+
+ best_iou = -1
+ best_n = -1
+ for i in range(len(biases) / 2):
+ u = iou(gt_w, gt_h, biases[2 * i], biases[2 * i + 1])
+ if u > best_iou:
+ best_iou = u
+ best_n = i
+ assert best_n == n
+
+def calculate_iou1(rect0, rect1):
+ '''
+ x0, y1, x2, y3
+ '''
+ w = min(rect0[2], rect1[2]) - max(rect0[0], rect1[0]) + 1
+ if w < 0:
+ return 0
+ h = min(rect0[3], rect1[3]) - max(rect0[1], rect1[1]) + 1
+ if h < 0:
+ return 0
+ i = w * h
+ a1 = (rect1[2] - rect1[0] + 1) * (rect1[3] - rect1[1] + 1)
+ a0 = (rect0[2] - rect0[0] + 1) * (rect0[3] - rect0[1] + 1)
+ if a0 == 0 and a1 == 0 and i == 0:
+ return 1.
+ return 1. * i / (a0 + a1 - i)
+
+def calculate_iou_xywh(r0, r1):
+ r0 = [r0[0] - r0[2] / 2.,
+ r0[1] - r0[3] / 2.,
+ r0[0] + r0[2] / 2.,
+ r0[1] + r0[3] / 2.]
+ r1 = [r1[0] - r1[2] / 2.,
+ r1[1] - r1[3] / 2.,
+ r1[0] + r1[2] / 2.,
+ r1[1] + r1[3] / 2.]
+
+ return calculate_iou(r0, r1)
+
+def calculate_iou(rect0, rect1):
+ '''
+ x0, y1, x2, y3
+ '''
+ w = min(rect0[2], rect1[2]) - max(rect0[0], rect1[0])
+ if w < 0:
+ return 0
+ h = min(rect0[3], rect1[3]) - max(rect0[1], rect1[1])
+ if h < 0:
+ return 0
+ i = w * h
+ a1 = (rect1[2] - rect1[0]) * (rect1[3] - rect1[1])
+ a0 = (rect0[2] - rect0[0]) * (rect0[3] - rect0[1])
+ if a0 == 0 and a1 == 0 and i == 0:
+ return 1.
+ return 1. * i / (a0 + a1 - i)
+
+#def process_run(func, *args, **kwargs):
+ #def internal_func(queue):
+ #result = func(*args, **kwargs)
+ #queue.put(result)
+ #queue = mp.Queue()
+ #p = Process(target=internal_func, args=(queue,))
+ #p.start()
+ #p.join()
+ #assert p.exitcode == 0
+ #return queue.get()
+
+class ExceptionWrapper(object):
+ def __init__(self, m):
+ self.message = m
+
+def process_run(func, *args, **kwargs):
+ def internal_func(queue):
+ try:
+ result = func(*args, **kwargs)
+ queue.put(result)
+ except Exception:
+ queue.put(ExceptionWrapper(traceback.format_exc()))
+ queue = mp.Queue()
+ p = Process(target=internal_func, args=(queue,))
+ p.start()
+ result = queue.get()
+ p.join()
+ if isinstance(result, ExceptionWrapper):
+ raise Exception(result.message)
+ return result
+
+def setup_yaml():
+ """ https://stackoverflow.com/a/8661021 """
+ represent_dict_order = lambda self, data: self.represent_mapping('tag:yaml.org,2002:map', data.items())
+ yaml.add_representer(OrderedDict, represent_dict_order)
+ try:
+ yaml.add_representer(unicode, unicode_representer)
+ except NameError:
+ logging.info('python 3 env')
+
+def init_logging():
+ np.seterr(divide = "raise", over="warn", under="warn", invalid="raise")
+
+ ch = logging.StreamHandler(stream=sys.stdout)
+ ch.setLevel(logging.INFO)
+ logger_fmt = logging.Formatter('%(asctime)s.%(msecs)03d %(process)d:%(filename)s:%(lineno)s %(funcName)10s(): %(message)s')
+ ch.setFormatter(logger_fmt)
+
+ root = logging.getLogger()
+ root.handlers = []
+ root.addHandler(ch)
+ root.setLevel(logging.INFO)
+
+ setup_yaml()
+
+def ensure_directory(path):
+ if path == '' or path == '.':
+ return
+ if path != None and len(path) > 0:
+ assert not op.isfile(path), '{} is a file'.format(path)
+ if not os.path.exists(path) and not op.islink(path):
+ try:
+ os.makedirs(path, exist_ok=True)
+ except FileExistsError:
+ # Ignore the exception since the directory already exists.
+ pass
+ except:
+ if os.path.isdir(path):
+ # another process has done makedir
+ pass
+ else:
+ raise
+
+def parse_pattern(pattern, s):
+ result = parse_pattern_as_is(pattern, s)
+ if result is None:
+ return
+ return [float(g) for g in result]
+
+def parse_pattern_as_is(pattern, s):
+ result = re.search(pattern, s)
+ if result is None:
+ return result
+ return [g for g in result.groups()]
+
+def iter_match_document(pattern, fname):
+ for line in read_lines(fname):
+ result = parse_pattern_as_is(pattern, line)
+ if result is None:
+ continue
+ yield result
+
+def parse_yolo_log(log_file):
+ pattern = 'loss_xy: ([0-9, .]*); loss_wh: ([0-9, .]*); '
+ pattern = pattern + 'loss_objness: ([0-9, .]*); loss_class: ([0-9, .]*)'
+
+ base_log_lines = read_lines(log_file)
+ xys = []
+ whs = []
+ loss_objnesses = []
+ loss_classes = []
+ for line in base_log_lines:
+ gs = parse_pattern(pattern, line)
+ if gs is None:
+ continue
+ idx = 0
+ xys.append(float(gs[idx]))
+ idx = idx + 1
+ whs.append(float(gs[idx]))
+ idx = idx + 1
+ loss_objnesses.append(float(gs[idx]))
+ idx = idx + 1
+ loss_classes.append(float(gs[idx]))
+
+ return xys, whs, loss_objnesses, loss_classes
+
+def parse_nums(p, log_file):
+ result = []
+ for line in read_lines(log_file):
+ gs = parse_pattern(p, line)
+ if gs is None:
+ continue
+ result.append(gs)
+ return result
+
+def parse_yolo_log_st(log_file):
+ p = 'region_loss_layer\.cpp:1138] ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*)'
+ ss = parse_nums(p, log_file)
+ p = 'region_loss_layer\.cpp:1140] ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*), ([0-9]*)'
+ tt = parse_nums(p, log_file)
+ return ss, tt
+
+def parse_yolo_log_acc(log_file):
+ p = 'Region Avg IOU: ([0-9, .]*), Class: ([0-9, .]*), '
+ p = p + 'Obj: ([0-9, .]*), No Obj: ([0-9, .]*), Avg Recall: ([0-9, .]*), count: ([0-9]*)'
+ all_ious = []
+ all_probs = []
+ all_obj = []
+ all_noobj = []
+ all_recall = []
+ all_count = []
+ for line in read_lines(log_file):
+ gs = parse_pattern(p, line)
+ if gs is None:
+ continue
+ all_ious.append(gs[0])
+ all_probs.append(gs[1])
+ all_obj.append(gs[2])
+ all_noobj.append(gs[3])
+ all_recall.append(gs[4])
+ all_count.append(gs[5])
+ return all_ious, all_probs, all_obj, all_noobj, all_recall, all_count
+
+
+def read_lines(file_name, **kwargs):
+ with open(file_name, 'r', **kwargs) as fp:
+ for line in fp:
+ yield line
+
+#@deprecated('use tsv_io.read_to_buffer')
+def read_to_buffer(file_name):
+ with open(file_name, 'rb') as fp:
+ all_line = fp.read()
+ return all_line
+
+class Model(object):
+ def __init__(self, test_proto_file, train_proto_file, model_param, mean_value, scale, model_iter):
+ self.test_proto_file = test_proto_file
+ self.model_param = model_param
+ self.mean_value = mean_value
+ self.model_iter = model_iter
+ self.scale = scale
+ self.train_proto_file = train_proto_file
+
+def adjust_tree_prediction_threshold(n, tree_th):
+ found = False
+ for l in n.layer:
+ if l.type == 'SoftmaxTreePrediction':
+ found = True
+ l.softmaxtreeprediction_param.threshold = tree_th
+ assert found
+
+def remove_nms(n):
+ for l in n.layer:
+ if l.type == 'RegionOutput':
+ l.region_output_param.nms = -1
+ if l.type == 'RegionPrediction':
+ l.region_prediction_param.nms = -1
+
+def update_conv_channels(net, factor, skip):
+ c = 0
+ s = 0
+ for l in net.layer:
+ if l.type == 'Convolution':
+ if s < skip:
+ s = s + 1
+ continue
+ o = l.convolution_param.num_output
+ l.convolution_param.num_output = int(o * factor)
+ c = c + 1
+ logging.info('updated {} layers for channel factor'.format(c))
+
+def get_channel(net, blob_name):
+ for l in net.layer:
+ if l.type == 'Convolution':
+ assert len(l.top) == 1
+ if l.top[0] == blob_name:
+ return l.convolution_param.num_output
+ assert False, 'not found'
+
+def fix_net_parameters(net, last_fixed_param):
+ found = False
+ no_param_layers = set(['TsvBoxData', 'ReLU', 'Pooling', 'Reshape',
+ 'EuclideanLoss', 'Sigmoid'])
+ unknown_layers = []
+ for l in net.layer:
+ if l.type == 'Convolution' or l.type == 'Scale':
+ if l.type == 'Convolution':
+ assert len(l.param) >= 1
+ else:
+ if len(l.param) == 0:
+ p = l.param.add()
+ p.lr_mult = 0
+ p.decay_mult = 0
+ if l.scale_param.bias_term:
+ p = l.param.add()
+ p.lr_mult = 0
+ p.decay_mult = 0
+ for p in l.param:
+ p.lr_mult = 0
+ p.decay_mult = 0
+ elif l.type == 'BatchNorm':
+ l.batch_norm_param.use_global_stats = True
+ else:
+ if l.type not in no_param_layers:
+ unknown_layers.append(l.type)
+ if l.name == last_fixed_param:
+ for b in l.bottom:
+ l.propagate_down.append(False)
+ found = True
+ break
+ assert len(unknown_layers) == 0, ', '.join(unknown_layers)
+ assert found
+
+def set_no_bias(net, layer_name):
+ for l in net.layer:
+ if l.name == layer_name:
+ assert l.type == 'Convolution'
+ l.convolution_param.bias_term = False
+ if len(l.param) == 2:
+ del l.param[1]
+ else:
+ assert len(l.param) == 0
+ return
+ assert False
+
+def add_yolo_angular_loss_regularizer(net, **kwargs):
+ for l in net.layer:
+ if l.name == 'angular_loss':
+ logging.info('angular loss exists')
+ return
+ conf_layer = None
+ for l in net.layer:
+ if l.name == 'conf':
+ conf_layer = l
+ assert 'conf' in l.top
+ found_t_label = False
+ for l in net.layer:
+ if 't_label' in l.top:
+ found_t_label = True
+ break
+ assert conf_layer and found_t_label
+
+ conf_layer.param[0].name = 'conf_w'
+ CA = conf_layer.convolution_param.num_output
+ assert len(conf_layer.bottom) == 1
+ num_feature = get_channel(net, conf_layer.bottom[0])
+
+ param_layer = net.layer.add()
+ param_layer.name = 'param_conf_w'
+ param_layer.type = 'Parameter'
+ param_layer.parameter_param.shape.dim.append(CA)
+ param_layer.parameter_param.shape.dim.append(num_feature)
+ param_layer.parameter_param.shape.dim.append(1)
+ param_layer.parameter_param.shape.dim.append(1)
+ param_layer.top.append('conf_w')
+ p = param_layer.param.add()
+ p.name = 'conf_w'
+
+ layer = net.layer.add()
+ layer.name = 'angular_loss'
+ layer.type = 'Python'
+ layer.bottom.append(conf_layer.bottom[0])
+ layer.bottom.append('t_label')
+ layer.bottom.append('conf_w')
+ layer.python_param.module = 'kcenter_exp'
+ layer.python_param.layer = 'YoloAngularLossLayer'
+ layer.propagate_down.append(True)
+ layer.propagate_down.append(False)
+ layer.propagate_down.append(False)
+ layer.top.append('angular_loss')
+ weight = kwargs.get('yolo_angular_loss_weight', 1)
+ layer.loss_weight.append(weight)
+
+def add_yolo_low_shot_regularizer(net, low_shot_label_idx):
+ assert net.layer[-1].type == 'RegionLoss'
+ assert net.layer[-2].type == 'Convolution'
+ assert net.layer[-1].bottom[0] == net.layer[-2].top[0]
+ assert net.layer[-2].convolution_param.kernel_size[0] == 1
+ assert net.layer[-2].convolution_param.kernel_h == 0
+ assert net.layer[-2].convolution_param.kernel_w == 0
+
+ num_classes = net.layer[-1].region_loss_param.classes
+ num_anchor = len(net.layer[-1].region_loss_param.biases) / 2
+
+ param_dim1 = net.layer[-2].convolution_param.num_output
+ param_dim2 = get_channel(net, net.layer[-2].bottom[0])
+
+ # add the parameter name into the convolutional layer
+ last_conv_param_name = 'last_conv_param_low_shot'
+ net.layer[-2].param[0].name = last_conv_param_name
+
+ # add the parameter layer to expose the parameter
+ param_layer = net.layer.add()
+ param_layer.type = 'Parameter'
+ param_layer.name = 'param_last_conv'
+ param_layer.top.append(last_conv_param_name)
+ p = param_layer.param.add()
+ p.name = last_conv_param_name
+ p.lr_mult = 1
+ p.decay_mult = 1
+ param_layer.parameter_param.shape.dim.append(param_dim1)
+ param_layer.parameter_param.shape.dim.append(param_dim2)
+
+ # add the regularizer layer
+ reg_layer = net.layer.add()
+ reg_layer.type = 'Python'
+ reg_layer.name = 'equal_norm'
+ reg_layer.bottom.append(last_conv_param_name)
+ reg_layer.top.append('equal_norm')
+ reg_layer.loss_weight.append(1)
+ reg_layer.python_param.module = 'equal_norm_loss'
+ reg_layer.python_param.layer = 'YoloAlignNormToBaseLossLayer'
+ reg_param = {'num_classes': num_classes,
+ 'low_shot_label_idx': low_shot_label_idx,
+ 'num_anchor': num_anchor}
+ reg_layer.python_param.param_str = json.dumps(reg_param)
+
+def update_kernel_active(net, kernel_active, kernel_active_skip):
+ assert False, 'use update_kernel_active2'
+ c = 0
+ skipped = 0
+ logging.info('{}-{}'.format(kernel_active, kernel_active_skip));
+ for l in net.layer:
+ if l.type == 'Convolution':
+ if skipped < kernel_active_skip:
+ skipped = skipped + 1
+ logging.info('skiping to update active kernel')
+ continue
+ l.convolution_param.kernel_active = kernel_active
+ c = c + 1
+
+ logging.info('update {} layers'.format(c))
+
+
+def plot_to_file(xs, ys, file_name, **kwargs):
+ fig = plt.figure()
+ semilogy = kwargs.get('semilogy')
+ if all(isinstance(x, str) for x in xs):
+ xs2 = range(len(xs))
+ #plt.xticks(xs2, xs, rotation=15, ha='right')
+ plt.xticks(xs2, xs, rotation='vertical')
+ xs = xs2
+ if type(ys) is dict:
+ for key in ys:
+ if semilogy:
+ plt.semilogy(xs, ys[key], '-o')
+ else:
+ plt.plot(xs, ys[key], '-o')
+ else:
+ if semilogy:
+ plt.semilogy(xs, ys, '-o')
+ else:
+ plt.plot(xs, ys, '-o')
+ plt.grid()
+ if 'ylim' in kwargs:
+ plt.ylim(kwargs['ylim'])
+ ensure_directory(op.dirname(file_name))
+ plt.tight_layout()
+ # explicitly remove the file because philly does not support overwrite
+ if op.isfile(file_name):
+ try:
+ os.remove(file_name)
+ except:
+ logging.info('{} exists but could not be deleted'.format(
+ file_name))
+ fig.savefig(file_name)
+ plt.close(fig)
+
+def parse_training_time(log_file):
+ log = read_to_buffer(log_file)
+ all_time_cost = []
+ all_iters = []
+ for line in log.split('\n'):
+ m = re.match('.*Iteration.*iter\/s, ([0-9\.]*)s\/([0-9]*) iters.*', line)
+ if m:
+ r = m.groups()
+ time_cost = float(r[0])
+ iters = float(r[1])
+ all_iters.append(iters)
+ all_time_cost.append(time_cost)
+ return all_iters, all_time_cost
+
+def encode_expid(prefix, *args):
+ parts = [prefix]
+ for (t, a) in args:
+ p = ''
+ if a != None:
+ if type(a) == str:
+ a = a.replace(':', '_')
+ if t != None and len(t) > 0:
+ p = p + '_{}'.format(t)
+ p = p + '_{}'.format(a)
+ parts.append(p)
+ return ''.join(parts)
+
+def unicode_representer(dumper, uni):
+ node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni)
+ return node
+
+def dump_to_yaml_bytes(context):
+ return yaml.dump(context, default_flow_style=False,
+ encoding='utf-8', allow_unicode=True)
+
+def dump_to_yaml_str(context):
+ return dump_to_yaml_bytes(context).decode()
+
+def write_to_yaml_file(context, file_name):
+ ensure_directory(op.dirname(file_name))
+ with open(file_name, 'w') as fp:
+ yaml.dump(context, fp, default_flow_style=False,
+ encoding='utf-8', allow_unicode=True)
+
+def load_from_yaml_str(s):
+ return yaml.load(s, Loader=yaml.UnsafeLoader)
+
+def load_from_yaml_file(file_name):
+ # do not use QDFile.open as QDFile.open depends on this function
+ with exclusive_open_to_read(file_name, 'r') as fp:
+ #with open(file_name, 'r') as fp:
+ data = load_from_yaml_str(fp)
+ while isinstance(data, dict) and '_base_' in data:
+ b = op.join(op.dirname(file_name), data['_base_'])
+ result = load_from_yaml_file(b)
+ assert isinstance(result, dict)
+ del data['_base_']
+ all_key = get_all_path(data, with_list=False)
+ for k in all_key:
+ v = dict_get_path_value(data, k)
+ dict_update_path_value(result, k, v)
+ data = result
+ return data
+
+#@deprecated('use qd.tsv_io.write_to_file')
+def write_to_file(contxt, file_name, append=False):
+ p = os.path.dirname(file_name)
+ ensure_directory(p)
+ if type(contxt) is str:
+ contxt = contxt.encode()
+ flag = 'wb'
+ if append:
+ flag = 'ab'
+ with open(file_name, flag) as fp:
+ fp.write(contxt)
+
+#@deprecated('use qd.tsv_io.load_list_file')
+def load_list_file(fname):
+ with open(fname, 'r') as fp:
+ lines = fp.readlines()
+ result = [line.strip() for line in lines]
+ if len(result) > 0 and result[-1] == '':
+ result = result[:-1]
+ return result
+
+class LoopProcess(Process):
+ def __init__(self, group=None, target=None, name=None, args=(), kwargs={}):
+ '''
+ same signiture with Process.__init__
+ The process will keep running the function of target and will wait for
+ several seconds in between. This is useful to run some monitoring job
+ or regular job
+ '''
+ super(LoopProcess, self).__init__(group, target, name, args, kwargs)
+ self._exit = Event()
+
+ def run(self):
+ sleep_time = 5
+ while not self._exit.is_set():
+ if self._target:
+ self._target(*self._args, **self._kwargs)
+ time.sleep(sleep_time)
+
+ def init_shutdown(self):
+ self._exit.set()
+
+class PyTee(object):
+ def __init__(self, logstream, stream_name):
+ valid_streams = ['stderr','stdout'];
+ if stream_name not in valid_streams:
+ raise IOError("valid stream names are %s" % ', '.join(valid_streams))
+ self.logstream = logstream
+ self.stream_name = stream_name;
+ def __del__(self):
+ pass;
+ def write(self, data): #tee stdout
+ self.logstream.write(data);
+ self.fstream.write(data);
+ self.logstream.flush();
+ self.fstream.flush();
+
+ def flush(self):
+ self.logstream.flush();
+ self.fstream.flush();
+
+ def __enter__(self):
+ if self.stream_name=='stdout' :
+ self.fstream = sys.stdout
+ sys.stdout = self;
+ else:
+ self.fstream = sys.stderr
+ sys.stderr = self;
+ self.fstream.flush();
+ def __exit__(self, _type, _value, _traceback):
+ if self.stream_name=='stdout' :
+ sys.stdout = self.fstream;
+ else:
+ sys.stderr = self.fstream;
+
+def parse_basemodel_with_depth(net):
+ '''
+ darknet19->darknet19
+ darknet19_abc->darknet19
+ '''
+ if '_' not in net:
+ return net
+ else:
+ i = net.index('_')
+ return net[: i]
+
+def worth_create(base, derived, buf_second=0):
+ if not op.isfile(base) and \
+ not op.islink(base) and \
+ not op.isdir(base):
+ return False
+ if os.path.isfile(derived) and \
+ os.path.getmtime(derived) > os.path.getmtime(base) - buf_second:
+ return False
+ else:
+ return True
+
+def basename_no_ext(file_name):
+ return op.splitext(op.basename(file_name))[0]
+
+def default_data_path(dataset):
+ '''
+ use TSVDataset instead
+ '''
+ proj_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)));
+ result = {}
+ data_root = os.path.join(proj_root, 'data', dataset)
+ result['data_root'] = data_root
+ result['source'] = os.path.join(data_root, 'train.tsv')
+ result['trainval'] = op.join(data_root, 'trainval.tsv')
+ result['test_source'] = os.path.join(data_root, 'test.tsv')
+ result['labelmap'] = os.path.join(data_root, 'labelmap.txt')
+ result['source_idx'] = os.path.join(data_root, 'train.lineidx')
+ result['test_source_idx'] = os.path.join(data_root, 'test.lineidx')
+ return result
+
+class FileProgressingbar:
+ fileobj = None
+ pbar = None
+ def __init__(self, fileobj, keyword='Test'):
+ fileobj.seek(0,os.SEEK_END)
+ flen = fileobj.tell()
+ fileobj.seek(0,os.SEEK_SET)
+ self.fileobj = fileobj
+ widgets = ['{}: '.format(keyword), progressbar.AnimatedMarker(),' ', progressbar.Percentage(), ' ', progressbar.Bar(), ' ', progressbar.ETA()]
+ self.pbar = progressbar.ProgressBar(widgets=widgets, maxval=flen).start()
+ def update(self):
+ self.pbar.update(self.fileobj.tell())
+
+def is_pil_image(image):
+ from PIL import Image
+ return isinstance(image, Image.Image)
+
+def encoded_from_img(im, quality=None, save_type=None):
+ if save_type is None:
+ save_type = 'jpg'
+ assert save_type in ['jpg', 'png']
+ if not is_pil_image(im):
+ if quality:
+ x = cv2.imencode('.{}'.format(save_type), im,
+ (cv2.IMWRITE_JPEG_QUALITY, quality))[1]
+ else:
+ x = cv2.imencode('.{}'.format(save_type), im)[1]
+ else:
+ if save_type in ['jpg', None]:
+ save_type = 'JPEG'
+ import io
+ x = io.BytesIO()
+ im.save(x, format=save_type)
+ x = x.getvalue()
+ return base64.b64encode(x)
+
+def encode_image(im, quality=None):
+ if quality:
+ x = cv2.imencode('.jpg', im, (cv2.IMWRITE_JPEG_QUALITY, quality))[1]
+ else:
+ x = cv2.imencode('.jpg', im)[1]
+ return x.tobytes()
+
+def is_valid_image(im):
+ return im is not None and all(x != 0 for x in im.shape)
+
+def pilimg_from_base64(imagestring):
+ try:
+ import io
+ jpgbytestring = base64.b64decode(imagestring)
+ image = Image.open(io.BytesIO(jpgbytestring))
+ image = image.convert('RGB')
+ return image
+ except:
+ return None
+
+def img_from_base64(imagestring):
+ try:
+ jpgbytestring = base64.b64decode(imagestring)
+ nparr = np.frombuffer(jpgbytestring, np.uint8)
+ r = cv2.imdecode(nparr, cv2.IMREAD_COLOR);
+ return r
+ except:
+ return None;
+
+def img_from_bytes(jpgbytestring):
+ try:
+ nparr = np.frombuffer(jpgbytestring, np.uint8)
+ r = cv2.imdecode(nparr, cv2.IMREAD_COLOR);
+ return r
+ except:
+ return None
+
+def img_from_base64_ignore_rotation(str_im):
+ jpgbytestring = base64.b64decode(str_im)
+ nparr = np.frombuffer(jpgbytestring, np.uint8)
+ im = cv2.imdecode(nparr, cv2.IMREAD_IGNORE_ORIENTATION);
+ return im
+
+def encode_decode_im(im, quality):
+ with BytesIO() as output:
+ im.save(output, 'JPEG', quality=quality)
+ im = Image.open(output).convert('RGB')
+ return im
+
+def int_rect(rect, enlarge_factor=1.0, im_h=None, im_w=None):
+ assert(len(rect) == 4)
+ left, top, right, bot = rect
+ rw = right - left
+ rh = bot - top
+
+ new_x = int(left + (1.0 - enlarge_factor) * rw / 2.0)
+ new_y = int(top + (1.0 - enlarge_factor) * rh / 2.0)
+ new_w = int(math.ceil(enlarge_factor * rw))
+ new_h = int(math.ceil(enlarge_factor * rh))
+ if im_h and im_w:
+ new_x = np.clip(new_x, 0, im_w)
+ new_y = np.clip(new_y, 0, im_h)
+ new_w = np.clip(new_w, 0, im_w - new_x)
+ new_h = np.clip(new_h, 0, im_h - new_y)
+
+ return list(map(int, [new_x, new_y, new_x + new_w, new_y + new_h]))
+
+def is_valid_rect(rect):
+ return len(rect) == 4 and rect[0] < rect[2] and rect[1] < rect[3]
+
+def pass_key_value_if_has(d_from, from_key, d_to, to_key):
+ if from_key in d_from:
+ d_to[to_key] = d_from[from_key]
+
+def dict_update_nested_dict(a, b, overwrite=True):
+ for k, v in b.items():
+ if k not in a:
+ dict_update_path_value(a, k, v)
+ else:
+ if isinstance(dict_get_path_value(a, k), dict) and isinstance(v, dict):
+ dict_update_nested_dict(dict_get_path_value(a, k), v, overwrite)
+ else:
+ if overwrite:
+ dict_update_path_value(a, k, v)
+
+def dict_ensure_path_key_converted(a):
+ for k in list(a.keys()):
+ v = a[k]
+ if '$' in k:
+ parts = k.split('$')
+ x = {}
+ x_curr = x
+ for p in parts[:-1]:
+ x_curr[p] = {}
+ x_curr = x_curr[p]
+ if isinstance(v, dict):
+ dict_ensure_path_key_converted(v)
+ x_curr[parts[-1]] = v
+ dict_update_nested_dict(a, x)
+ del a[k]
+ else:
+ if isinstance(v, dict):
+ dict_ensure_path_key_converted(v)
+
+def query_values_by_path_suffix(job_in_scheduler, suffix, default=None):
+ found = []
+ for p in get_all_path(job_in_scheduler, leaf_only=False):
+ if p.endswith(suffix):
+ v = dict_get_path_value(job_in_scheduler, p)
+ found.append(v)
+ return found
+
+# this is to get value, rather than values, which is misleading
+#@deprecated('use query_values_by_path_suffix')
+def query_path_by_suffix(job_in_scheduler, suffix, default=None):
+ found = []
+ for p in get_all_path(job_in_scheduler, leaf_only=False):
+ if p.endswith(suffix):
+ v = dict_get_path_value(job_in_scheduler, p)
+ found.append(v)
+ if len(found) == 1:
+ return found[0]
+ elif len(found) > 1:
+ if all(f == found[0] for f in found[1:]):
+ return found[0]
+ else:
+ raise ValueError
+ else:
+ return default
+
+def get_all_path(d, with_type=False, leaf_only=True, with_list=True):
+ assert not with_type, 'will not support'
+ all_path = []
+
+ if isinstance(d, dict):
+ for k, v in d.items():
+ all_sub_path = get_all_path(
+ v, with_type, leaf_only=leaf_only, with_list=with_list)
+ all_path.extend([k + '$' + p for p in all_sub_path])
+ if not leaf_only or len(all_sub_path) == 0:
+ all_path.append(k)
+ elif (isinstance(d, tuple) or isinstance(d, list)) and with_list:
+ for i, _v in enumerate(d):
+ all_sub_path = get_all_path(
+ _v, with_type,
+ leaf_only=leaf_only,
+ with_list=with_list,
+ )
+ all_path.extend(['{}$'.format(i) + p for p in all_sub_path])
+ if not leaf_only or len(all_sub_path) == 0:
+ all_path.append('{}'.format(i))
+ return all_path
+
+def dict_get_all_path(d, with_type=False, leaf_only=True):
+ all_path = []
+ for k, v in viewitems(d):
+ if with_type:
+ if type(k) is str:
+ k = 's' + k
+ elif type(k) is int:
+ k = 'i' + str(k)
+ else:
+ raise NotImplementedError
+ if isinstance(v, dict):
+ all_sub_path = dict_get_all_path(
+ v, with_type, leaf_only=leaf_only)
+ all_path.extend([k + '$' + p for p in all_sub_path])
+ if not leaf_only:
+ all_path.append(k)
+ elif isinstance(v, tuple) or isinstance(v, list):
+ for i, _v in enumerate(v):
+ prefix = '' if not with_type else 'i'
+ if isinstance(_v, (dict, list)):
+ all_sub_path = dict_get_all_path(
+ _v, with_type,
+ leaf_only=leaf_only)
+ all_path.extend([k + '${}{}$'.format(prefix, i) + p for p in all_sub_path])
+ else:
+ all_path.append(k + '${}{}'.format(prefix, i))
+ if not leaf_only:
+ all_path.append(k)
+ else:
+ all_path.append(k)
+ return all_path
+
+def dict_parse_key(k, with_type):
+ if with_type:
+ if k[0] == 'i':
+ return int(k[1:])
+ else:
+ return k[1:]
+ return k
+
+def dict_has_path(d, p, with_type=False):
+ ps = p.split('$')
+ cur_dict = d
+ while True:
+ if len(ps) > 0:
+ k = dict_parse_key(ps[0], with_type)
+ if isinstance(cur_dict, dict) and k in cur_dict:
+ cur_dict = cur_dict[k]
+ ps = ps[1:]
+ elif isinstance(cur_dict, list):
+ try:
+ k = int(k)
+ except:
+ return False
+ cur_dict = cur_dict[k]
+ ps = ps[1:]
+ else:
+ return False
+ else:
+ return True
+
+
+def dict_set_path_if_not_exist(param, k, v):
+ if not dict_has_path(param, k):
+ dict_update_path_value(param, k, v)
+ return True
+ else:
+ return False
+
+def dict_update_path_value(d, p, v):
+ ps = p.split('$')
+ while True:
+ if len(ps) == 1:
+ d[ps[0]] = v
+ break
+ else:
+ if ps[0] not in d:
+ d[ps[0]] = {}
+ d = d[ps[0]]
+ ps = ps[1:]
+
+def dict_remove_path(d, p):
+ ps = p.split('$')
+ assert len(ps) > 0
+ cur_dict = d
+ need_delete = ()
+ while True:
+ if len(ps) == 1:
+ if len(need_delete) > 0 and len(cur_dict) == 1:
+ del need_delete[0][need_delete[1]]
+ else:
+ del cur_dict[ps[0]]
+ return
+ else:
+ if len(cur_dict) == 1:
+ if len(need_delete) == 0:
+ need_delete = (cur_dict, ps[0])
+ else:
+ need_delete = (cur_dict, ps[0])
+ cur_dict = cur_dict[ps[0]]
+ ps = ps[1:]
+
+def dict_get_path_value(d, p, with_type=False):
+ ps = p.split('$')
+ cur_dict = d
+ while True:
+ if len(ps) > 0:
+ k = dict_parse_key(ps[0], with_type)
+ if isinstance(cur_dict, (tuple, list)):
+ cur_dict = cur_dict[int(k)]
+ else:
+ cur_dict = cur_dict[k]
+ ps = ps[1:]
+ else:
+ return cur_dict
+
+def get_file_size(f):
+ return os.stat(f).st_size
+
+def convert_to_yaml_friendly(result):
+ if type(result) is dict:
+ for key, value in result.items():
+ if isinstance(value, dict):
+ result[key] = convert_to_yaml_friendly(value)
+ elif isinstance(value, np.floating):
+ result[key] = float(value)
+ elif isinstance(value, np.ndarray):
+ raise NotImplementedError()
+ elif type(value) in [int, str, float, bool]:
+ continue
+ else:
+ raise NotImplementedError()
+ else:
+ raise NotImplementedError()
+ return result
+
+def natural_key(text):
+ import re
+ result = []
+ for c in re.split(r'([0-9]+(?:[.][0-9]*)?)', text):
+ try:
+ result.append(float(c))
+ except:
+ continue
+ return result
+
+def natural_sort(strs, key=None):
+ if key is None:
+ strs.sort(key=natural_key)
+ else:
+ strs.sort(key=lambda s: natural_key(key(s)))
+
+def get_pca(x, com):
+ x -= np.mean(x, axis = 0)
+ cov = np.cov(x, rowvar=False)
+ from scipy import linalg as LA
+ evals , evecs = LA.eigh(cov)
+ total_val = np.sum(evals)
+ idx = np.argsort(evals)[::-1]
+ evecs = evecs[:,idx]
+ evals = evals[idx]
+ component_val = np.sum(evals[:com])
+ logging.info('kept: {}/{}={}'.format(component_val,
+ total_val, component_val / total_val))
+ a = np.dot(x, evecs[:, :com])
+ return a
+
+def plot_distribution(x, y, color=None, fname=None):
+ import seaborn as sns
+ x = sns.jointplot(x, y, kind='kde',
+ color=color)
+ if fname:
+ x.savefig(fname)
+ plt.close()
+ else:
+ plt.show()
+
+g_key_to_cache = {}
+def run_if_not_memory_cached(func, *args, **kwargs):
+ force = False
+ if '__force' in kwargs:
+ if kwargs['__force']:
+ force = True
+ del kwargs['__force']
+ if '__key' in kwargs:
+ key = kwargs.pop('__key')
+ else:
+ import pickle as pkl
+ key = hash_sha1(pkl.dumps(OrderedDict({'arg': pformat(args), 'kwargs':
+ pformat(kwargs), 'func_name': func.__name__})))
+ global g_key_to_cache
+
+ if key in g_key_to_cache and not force:
+ return g_key_to_cache[key]
+ else:
+ result = func(*args, **kwargs)
+ g_key_to_cache[key] = result
+ return result
+
+def run_if_not_cached(func, *args, **kwargs):
+ force = False
+ if '__force' in kwargs:
+ if kwargs['__force']:
+ force = True
+ del kwargs['__force']
+
+ import pickle as pkl
+ key = hash_sha1(pkl.dumps(OrderedDict({'arg': pformat(args), 'kwargs':
+ pformat(kwargs), 'func_name': func.__name__})))
+ cache_folder = op.expanduser('/tmp/run_if_not_cached/')
+ cache_file = op.join(cache_folder, key)
+
+ if op.isfile(cache_file) and not force:
+ return pkl.loads(read_to_buffer(cache_file))
+ else:
+ result = func(*args, **kwargs)
+ write_to_file(pkl.dumps(result), cache_file)
+ return result
+
+def convert_to_command_line(param, script):
+ logging.info(pformat(param))
+ x = copy.deepcopy(param)
+ result = "python {} -bp {}".format(
+ script,
+ base64.b64encode(dump_to_yaml_bytes(x)).decode())
+ return result
+
+def print_table(a_to_bs, all_key=None, latex=False, **kwargs):
+ if len(a_to_bs) == 0:
+ return
+ if not latex:
+ all_line = get_table_print_lines(a_to_bs, all_key)
+ logging.info('\n{}'.format('\n'.join(all_line)))
+ else:
+ from qd.latex_writer import print_simple_latex_table
+ if all_key is None:
+ all_key = list(set(a for a_to_b in a_to_bs for a in a_to_b))
+ all_key = sorted(all_key)
+ x = print_simple_latex_table(a_to_bs,
+ all_key, **kwargs)
+ logging.info('\n{}'.format(x))
+ return x
+
+def get_table_print_lines(a_to_bs, all_key):
+ if len(a_to_bs) == 0:
+ logging.info('no rows')
+ return []
+ if not all_key:
+ all_key = []
+ for a_to_b in a_to_bs:
+ all_key.extend(a_to_b.keys())
+ all_key = sorted(list(set(all_key)))
+ all_width = [max([len(str(a_to_b.get(k, ''))) for a_to_b in a_to_bs] +
+ [len(k)]) for k in all_key]
+ row_format = ' '.join(['{{:{}}}'.format(w) for w in all_width])
+
+ all_line = []
+ line = row_format.format(*all_key)
+ all_line.append(line.strip())
+ for a_to_b in a_to_bs:
+ line = row_format.format(*[str(a_to_b.get(k, '')) for k in all_key])
+ all_line.append(line)
+ return all_line
+
+def is_hvd_initialized():
+ try:
+ import horovod.torch as hvd
+ hvd.size()
+ return True
+ except ImportError:
+ return False
+ except ValueError:
+ return False
+
+def get_user_name():
+ import getpass
+ return getpass.getuser()
+
+def decode_general_cmd(extraParam):
+ re_result = re.match('.*python (?:scripts|src)/.*\.py -bp (.*)', extraParam)
+ if re_result and len(re_result.groups()) == 1:
+ ps = load_from_yaml_str(base64.b64decode(re_result.groups()[0]))
+ return ps
+
+def print_job_infos(all_job_info):
+ all_key = [
+ 'cluster',
+ 'status',
+ 'appID-s',
+ 'result',
+ 'elapsedTime',
+ 'elapsedFinished',
+ 'mem_used',
+ 'gpu_util',
+ 'speed',
+ 'left']
+ keys = ['data', 'net', 'expid']
+ meta_keys = ['num_gpu']
+ all_key.extend(keys)
+ all_key.extend(meta_keys)
+
+ # find the keys whose values are the same
+ def all_equal(x):
+ assert len(x) > 0
+ return all(y == x[0] for y in x[1:])
+
+ if len(all_job_info) > 1:
+ equal_keys = [k for k in all_key if all_equal([j.get(k) for j in all_job_info])]
+ if len(equal_keys) > 0:
+ logging.info('equal key values for all jobs')
+ print_table(all_job_info[0:1], all_key=equal_keys)
+ all_key = [k for k in all_key if not all_equal([j.get(k) for j in all_job_info])]
+
+ print_table(all_job_info, all_key=all_key)
+
+def parse_eta_in_hours(left):
+ pattern = '(?:([0-9]*) day[s]?, )?([0-9]*):([0-9]*):([0-9]*)'
+ result = re.match(pattern, left)
+ if result:
+ gs = result.groups()
+ gs = [float(g) if g else 0 for g in gs]
+ assert int(gs[0]) == gs[0]
+ days = int(gs[0])
+ hours = gs[1] + gs[2] / 60. + gs[3] / 3600
+ return days, hours
+ return -1, -1
+
+def attach_philly_maskrcnn_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ # Philly, maskrcnn-benchmark log
+ pattern = '([0-9\. :-]): .*: eta: (.*) iter: [0-9]*[ ]*speed: ([0-9\.]*).*'
+
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left, speed = result.groups()
+ job_info['speed'] = speed
+ from datetime import datetime, timezone
+ now = datetime.now(timezone.utc)
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ delay = (now - log_time).total_seconds()
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h({:.1f}s)'.format(d, h, delay)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def calc_eta(days, hours):
+ from datetime import timedelta
+ x = datetime.now() + timedelta(days=days, hours=hours + 1)
+ return '{}/{}-{}'.format(x.month, x.day, x.hour)
+
+def attach_mmask_caption_itp_multi_line_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'.*(202[0-9:\ \-\.]+)\,.* (?:train|mmask_caption|mmask_pretrain)\.py\:.*(?:train)\(\):.*eta[ ]*:(.*) iter: [0-9]*'
+ #2020-10-13 20:15:24 [21ddde126d88bf2a12f76f300ddaac02-ps-0, 10.43.224.4] [1,0]:2020-10-13 20:15:23,329.329 mmask_caption.py:186 train(): eta : 3:37:16 iter: 2460 max mem : 4541
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left = result.groups()
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left.strip())
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_mmask_aml_multi_line_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'(202[0-9:\ \-\.]+)\,.* (?:mmask_caption|mmask_pretrain)\.py\:.*(?:train)\(\):.*eta[ ]*:(.*) iter: [0-9]*'
+ #2020-10-08 03:00:47,292.292 mmask_caption.py:186 train(): eta : 3:40:55 iter: 1900 max mem : 4541
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left = result.groups()
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left.strip())
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_itp_mmask_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'.*:(.*),.* (?:trainer|mmask_pretrain)\.py.*(?:do_train|do_train_dict|train)\(\): eta: (.*) iter: [0-9]*.*'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left = result.groups()
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_itp_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'.*:(.*),.*(?:base_trainer|trainer|mmask_pretrain|image_text_retrieval|vqa)\.py.*(?:do_train|_logistics|do_train_dict|train|old_train)\(\): eta:[ ]*(.*) iter: [0-9]*[ ]*speed: ([0-9\.]*).*'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left, speed = result.groups()
+ job_info['speed'] = speed
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_aml_maskrcnn_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'(.*),.* (?:mmask_pretrain|trainer|vqa)\.py.*(?:old_train|train|do_train|do_train_dict)\(\): eta: (.*) iter: [0-9]*[ ]*speed: ([0-9\.]*).*'
+
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left, speed = result.groups()
+ job_info['speed'] = speed
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_aml_detectron2_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ pattern = r'(.*),.* events\.py.*eta: (.*) iter: [0-9]*.*'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left = result.groups()
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def attach_philly_caffe_log_if_is(all_log, job_info):
+ for log in reversed(all_log):
+ # philly, caffe log
+ pattern = '.*solver\.cpp:[0-9]*] Iteration [0-9]* \(.* iter\/s, ([0-9\.]*s\/100) iters, left: ([0-9\.]*h)\), loss = [0-9\.]*'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ job_info['speed'], job_info['left'] = result.groups()
+ return True
+ return False
+
+def attach_gpu_utility_from_log(all_log, job_info):
+ for log in reversed(all_log):
+ # philly, caffe log aml_server or philly_server log
+ pattern = '.*_server.py:.*monitor.*\[(.*)\]'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ try:
+ all_info = json.loads('[{}]'.format(result.groups()[0].replace('\'', '\"')))
+ min_gpu_mem = min([i['mem_used'] for i in all_info])
+ max_gpu_mem = max([i['mem_used'] for i in all_info])
+ min_gpu_util = min([i['gpu_util'] for i in all_info])
+ max_gpu_util = max([i['gpu_util'] for i in all_info])
+ # GB
+ job_info['mem_used'] = '{}-{}'.format(round(min_gpu_mem/1024, 1),
+ round(max_gpu_mem/1024., 1))
+ job_info['gpu_util'] = '{}-{}'.format(min_gpu_util, max_gpu_util)
+ return True
+ except:
+ return False
+ return False
+
+def attach_log_parsing_result(job_info):
+ # run unit test if modified
+ logs = job_info.get('latest_log')
+ if logs is None:
+ return
+ all_log = logs.split('\n')
+ del job_info['latest_log']
+ attach_gpu_utility_from_log(all_log, job_info)
+ if attach_itp_log_if_is(all_log, job_info):
+ return
+ if attach_philly_maskrcnn_log_if_is(all_log, job_info):
+ return
+ if attach_aml_maskrcnn_log_if_is(all_log, job_info):
+ return
+ if attach_philly_caffe_log_if_is(all_log, job_info):
+ return
+ if attach_aml_detectron2_log_if_is(all_log, job_info):
+ return
+ if attach_itp_mmask_log_if_is(all_log, job_info):
+ return
+ if attach_mmask_aml_multi_line_log_if_is(all_log, job_info):
+ return
+ if attach_mmask_caption_itp_multi_line_log_if_is(all_log, job_info):
+ return
+ # the following is designed to cover any examples
+ if attach_any_log(all_log, job_info):
+ return
+
+def attach_any_log(all_log, job_info):
+ # to check the correctness, run: py.test --ipdb src/qd/unittest/test_qd_common.py -k test_attach_any_log
+ for log in reversed(all_log):
+ pattern = r'([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}).*\.py.*\(\): eta:[ ]*(.*) iter: [0-9]*[ ]*speed: ([0-9\.]*).*'
+ result = re.match(pattern, log)
+ if result and result.groups():
+ log_time, left, speed = result.groups()
+ job_info['speed'] = speed
+ from dateutil.parser import parse
+ log_time = parse(log_time)
+ job_info['log_time'] = log_time
+ # log_time here is UTC. convert it to local time
+ d, h = parse_eta_in_hours(left)
+ job_info['left'] = '{}-{:.1f}h'.format(d, h)
+ job_info['eta'] = calc_eta(d, h)
+ return True
+ return False
+
+def print_offensive_folder(folder):
+ all_folder = os.listdir(folder)
+ name_to_size = {}
+ for i, f in enumerate(qd_tqdm(all_folder)):
+ sec = 60 * 10
+ f = op.join(folder, f)
+ size = run_if_not_cached(get_folder_size, f, sec)
+ name_to_size[f] = size
+ logging.info('{}: {}'.format(f, size))
+ logging.info(', '.join([op.basename(n) for n, s in name_to_size.items() if
+ s < 0]))
+
+def get_folder_size(f, sec):
+ cmd = ['du', '--max-depth=0', f]
+ import subprocess
+ from subprocess import check_output
+ try:
+ out = check_output(cmd, timeout=sec)
+ except subprocess.TimeoutExpired:
+ logging.info('{}'.format(f))
+ return -1
+ out = out.decode()
+ size = [x.strip() for x in out.split('\t')][0]
+ return int(size)
+
+class make_namespace_by_dict(object):
+ def __init__(self, d):
+ for k in d:
+ v = d[k]
+ if type(v) is dict:
+ self.__dict__[k] = make_namespace_by_dict(v)
+ else:
+ self.__dict__[k] = v
+ def clone(self):
+ c = copy.deepcopy(self.__dict__)
+ return make_namespace_by_dict(c)
+
+ def __repr__(self):
+ return '{}'.format(pformat(self.__dict__))
+
+@try_once
+def try_get_cpu_info():
+ command = 'cat /proc/cpuinfo'
+ return os.popen(command).read().strip()
+
+# ---------------------------------------------------- pytorch speed analysis
+def create_speed_node(info):
+ node = Tree()
+ node.add_features(**info)
+ return node
+
+def speed_tree_insert(root, node):
+ while True:
+ need_merge_nodes = [c for c in root.children
+ if is_child_parent(c.name, node.name)]
+ if len(need_merge_nodes) > 0:
+ for x in need_merge_nodes:
+ x.detach()
+ for x in need_merge_nodes:
+ node.add_child(x)
+ root.add_child(node)
+ return
+ go_deeper_nodes = [c for c in root.children if
+ is_child_parent(node.name, c.name)]
+ if len(go_deeper_nodes) == 0:
+ root.add_child(node)
+ return
+ else:
+ assert len(go_deeper_nodes) == 1
+ root = go_deeper_nodes[0]
+
+def is_child_parent(c, p):
+ if p == '':
+ return True
+ return c.startswith(p + '.')
+
+def speed_trees_insert(roots, info):
+ node = create_speed_node(info)
+ # we assume the name are not equal
+ need_merge_nodes = [r for r in roots
+ if is_child_parent(r.name, info['name'])]
+ if len(need_merge_nodes) > 0:
+ for x in need_merge_nodes:
+ node.add_child(x)
+ roots.remove(x)
+ roots.append(node)
+ return
+ need_insert_roots = [r for r in roots
+ if is_child_parent(info['name'], r.name)]
+ if len(need_insert_roots) == 0:
+ roots.append(node)
+ elif len(need_insert_roots) == 1:
+ speed_tree_insert(need_insert_roots[0], node)
+ else:
+ raise Exception()
+
+def build_speed_tree(component_speeds):
+ roots = []
+ for c in component_speeds:
+ speed_trees_insert(roots, c)
+ return roots
+
+def get_vis_str(component_speeds):
+ roots = build_speed_tree(component_speeds)
+ if len(roots) == 0:
+ return ''
+ assert len(roots) == 1, roots
+ root = roots[0]
+ for n in root.iter_search_nodes():
+ n.global_avg_in_ms = round(1000. * n.global_avg, 1)
+ for n in root.iter_search_nodes():
+ s = sum([c.global_avg for c in n.children])
+ n.unique_in_ms = round(1000. * (n.global_avg - s), 1)
+ return root.get_ascii(attributes=
+ ['name', 'global_avg_in_ms', 'unique_in_ms', 'count'])
+
+def create_vis_net_file(speed_yaml, vis_txt):
+ info = load_from_yaml_file(speed_yaml)
+ if type(info) is list:
+ info = info[0]
+ assert type(info) is dict
+ component_speeds = info['meters']
+ write_to_file(get_vis_str(component_speeds), vis_txt)
+
+# ---------------------------------------------------------------------
+
+def dict_add(d, k, v):
+ if k not in d:
+ d[k] = v
+ else:
+ d[k] += v
+
+def calc_mean(x):
+ return sum(x) / len(x)
+
+def compare_gmap_evals(all_eval_file,
+ label_to_testcount=None,
+ output_prefix='out'):
+ result = ['\n']
+ all_result = [load_from_yaml_file(f) for f in all_eval_file]
+ all_cat2map = [result['class_ap'] for result in all_result]
+
+ cats = list(all_cat2map[0].keys())
+ gains = [all_cat2map[1][c] - all_cat2map[0][c] for c in cats]
+
+ all_info = [{'name': c, 'acc_gain': g} for c, g in zip(cats, gains)]
+ all_info = sorted(all_info, key=lambda x: x['acc_gain'])
+
+ all_map = [sum(cat2map.values()) / len(cat2map) for cat2map in all_cat2map]
+ result.append('all map = {}'.format(', '.join(
+ map(lambda x: str(round(x, 3)), all_map))))
+
+ non_zero_cats = [cat for cat, ap in all_cat2map[0].items()
+ if all_cat2map[1][cat] > 0 and ap > 0]
+ logging.info('#non zero cat = {}'.format(len(non_zero_cats)))
+ for cat2map in all_cat2map:
+ logging.info('non zero cat mAP = {}'.format(
+ calc_mean([cat2map[c] for c in non_zero_cats])))
+
+ if label_to_testcount is not None:
+ all_valid_map = [calc_mean([ap for cat, ap in cat2map.items() if
+ label_to_testcount.get(cat, 0) >
+ 50]) for cat2map in all_cat2map]
+ result.append('all valid map = {}'.format(', '.join(
+ map(lambda x: str(round(x, 3)), all_valid_map))))
+ valid_cats = set([l for l, c in label_to_testcount.items() if c > 50])
+
+ max_aps = [max([cat2map[c] for cat2map in all_cat2map]) for c in cats]
+ max_map = sum(max_aps) / len(max_aps)
+ result.append('max map = {:.3f}'.format(max_map))
+
+ for info in all_info:
+ for k in info:
+ if type(info[k]) is float:
+ info[k] = round(info[k], 2)
+ result.extend(get_table_print_lines(all_info[:5] + all_info[-6:], ['name',
+ 'acc_gain',
+ ]))
+ if label_to_testcount is not None:
+ result.append('valid cats only:')
+ all_valid_info = [i for i in all_info if i['name'] in valid_cats]
+ result.extend(get_table_print_lines(all_valid_info[:5] + all_valid_info[-6:],
+ ['name', 'acc_gain',
+ ]))
+
+ all_acc_gain = [info['acc_gain'] for info in all_info]
+ logging.info('\n'.join(result))
+
+ plot_to_file(list(range(len(all_acc_gain))),
+ all_acc_gain,
+ output_prefix + '.png')
+
+def merge_class_names_by_location_id(anno):
+ if any('location_id' in a for a in anno):
+ assert all('location_id' in a for a in anno)
+ location_id_rect = [(a['location_id'], a) for a in anno]
+ from .common import list_to_dict
+ location_id_to_rects = list_to_dict(location_id_rect, 0)
+ merged_anno = []
+ for _, rects in location_id_to_rects.items():
+ r = copy.deepcopy(rects[0])
+ r['class'] = [r['class']]
+ r['class'].extend((rects[i]['class'] for i in range(1,
+ len(rects))))
+ r['conf'] = [r.get('conf', 1)]
+ r['conf'].extend((rects[i].get('conf', 1) for i in range(1,
+ len(rects))))
+ merged_anno.append(r)
+ return merged_anno
+ else:
+ assert all('location_id' not in a for a in anno)
+ for a in anno:
+ a['class'] = [a['class']]
+ a['conf'] = [a.get('conf', 1.)]
+ return anno
+
+def softnms_c(rects, threshold=0, method=2, **kwargs):
+ from fast_rcnn.nms_wrapper import soft_nms
+ nms_input = np.zeros((len(rects), 5), dtype=np.float32)
+ for i, r in enumerate(rects):
+ nms_input[i, 0:4] = r['rect']
+ nms_input[i, -1] = r['conf']
+ nms_out = soft_nms(nms_input, threshold=threshold,
+ method=method, **kwargs)
+ return [{'rect': list(map(float, x[:4])), 'conf': float(x[-1])} for x in nms_out]
+
+def softnms(rects, th=0.5):
+ rects = copy.deepcopy(rects)
+ result = []
+ while len(rects) > 0:
+ max_idx = max(range(len(rects)), key=lambda i:
+ rects[i]['conf'])
+ max_det = rects[max_idx]
+ result.append(max_det)
+ rects.remove(max_det)
+ for j in range(len(rects)):
+ j_rect = rects[j]
+ ij_iou = calculate_iou1(max_det['rect'], j_rect['rect'])
+ rects[j]['conf'] *= math.exp(-ij_iou * ij_iou / th)
+ return result
+
+def acquireLock(lock_f='/tmp/lockfile.LOCK'):
+ import fcntl
+ ensure_directory(op.dirname(lock_f))
+ locked_file_descriptor = open(lock_f, 'w+')
+ fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
+ return locked_file_descriptor
+
+@contextlib.contextmanager
+def acquire_lock(lock_f):
+ import fcntl
+ ensure_directory(op.dirname(lock_f))
+ locked_file_descriptor = open(lock_f, 'w+')
+ fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
+ yield locked_file_descriptor
+ locked_file_descriptor.close()
+
+def releaseLock(locked_file_descriptor):
+ locked_file_descriptor.close()
+
+def inject_yolo_by_maskrcnn_log_to_board(fname, folder):
+ keys = ['loss',
+ 'cls',
+ 'o_noobj',
+ 'o_obj',
+ 'wh',
+ 'xy',
+ 'time',
+ 'data',
+ ]
+ pattern = ''.join('.*{}: ([0-9\.]*) \(([0-9\.]*)\).*'.format(k)for k in keys)
+ pattern = '.*iter: ([0-9]*) .*' + 'speed: ([0-9\.]*) images/sec' + pattern
+ logging.info(pattern)
+ all_loss = []
+ result = parse_nums(pattern, fname)
+ result_keys = ['iteration', 'speed']
+ for k in keys:
+ result_keys.append(k + '_medium')
+ result_keys.append(k + '_mean')
+ all_loss = [dict(zip(result_keys, r)) for r in result]
+
+ logging.info(len(all_loss))
+ from torch.utils.tensorboard import SummaryWriter
+ wt = SummaryWriter(log_dir=folder)
+ for loss_info in all_loss:
+ for k in result_keys:
+ if k == 'iteration':
+ continue
+ wt.add_scalar(tag=k, scalar_value=loss_info[k],
+ global_step=loss_info['iteration'])
+
+def inject_maskrcnn_log_to_board(fname, folder, keys=None):
+ if keys is None:
+ keys = ['loss',
+ 'criterion_loss',
+ #'loss_box_reg',
+ #'loss_classifier',
+ #'loss_objectness',
+ #'loss_rpn_box_reg',
+ 'time',
+ 'data',
+ ]
+ pattern = ''.join('.*{}: ([0-9\.]*) \(([0-9\.]*)\).*'.format(k)for k in keys)
+ pattern = '.*iter: ([0-9]*) .*' + 'speed: ([0-9\.]*) images/sec' + pattern
+ logging.info(pattern)
+ all_loss = []
+ result = parse_nums(pattern, fname)
+ result_keys = ['iteration', 'speed']
+ for k in keys:
+ result_keys.append(k + '_medium')
+ result_keys.append(k + '_mean')
+ all_loss = [dict(zip(result_keys, r)) for r in result]
+
+ logging.info(len(all_loss))
+ from torch.utils.tensorboard import SummaryWriter
+ wt = SummaryWriter(log_dir=folder)
+ for loss_info in all_loss:
+ for k in result_keys:
+ if k == 'iteration':
+ continue
+ wt.add_scalar(tag=k, scalar_value=loss_info[k],
+ global_step=loss_info['iteration'])
+
+class DummyCfg(object):
+ # provide a signature of clone(), used by maskrcnn checkpointer
+ def clone(self):
+ return
+
+def save_frame_yaml(fn):
+ assert not op.isfile(fn)
+ assert fn.endswith('.yaml')
+ info = get_frame_info(1)
+ write_to_yaml_file(info, fn)
+
+def get_frame_info(last=0):
+ import inspect
+ frame = inspect.currentframe()
+ frames = inspect.getouterframes(frame)
+ frame = frames[1 + last].frame
+ args, _, _, vs = inspect.getargvalues(frame)
+ info = {i: vs[i] for i in args}
+ info['_func'] = frame.f_code.co_name
+ info['_filepath'] = frame.f_code.co_filename
+ return info
+
+def print_frame_info():
+ import inspect
+ frame = inspect.currentframe()
+ frames = inspect.getouterframes(frame)
+ frame = frames[1].frame
+ args, _, _, vs = inspect.getargvalues(frame)
+ info = []
+ info.append('func name = {}'.format(inspect.getframeinfo(frame)[2]))
+ for i in args:
+ try:
+ info.append('{} = {}'.format(i, vs[i]))
+ except:
+ info.append('type({}) = {}'.format(i, type(vs[i])))
+ continue
+ logging.info('; '.join(info))
+
+def merge_speed_info(speed_yamls, out_yaml):
+ write_to_yaml_file([load_from_yaml_file(y) for y in speed_yamls
+ if op.isfile(y)], out_yaml)
+
+def merge_speed_vis(vis_files, out_file):
+ from .common import ensure_copy_file
+ if len(vis_files) > 0 and op.isfile(vis_files[0]):
+ ensure_copy_file(vis_files[0], out_file)
+
+def merge_dict_to_cfg(dict_param, cfg):
+ """merge the key, value pair in dict_param into cfg
+
+ :dict_param: TODO
+ :cfg: TODO
+ :returns: TODO
+
+ """
+ def trim_dict(d, c):
+ """remove all the keys in the dictionary of d based on the existance of
+ cfg
+ """
+ to_remove = [k for k in d if k not in c]
+ for k in to_remove:
+ del d[k]
+ to_check = [(k, d[k]) for k in d if d[k] is dict]
+ for k, t in to_check:
+ trim_dict(t, getattr(c, k))
+ trimed_param = copy.deepcopy(dict_param)
+ trim_dict(trimed_param, cfg)
+ from yacs.config import CfgNode
+ cfg.merge_from_other_cfg(CfgNode(trimed_param))
+
+def execute_func(info):
+ # info = {'from': module; 'import': func_name, 'param': dict}
+ from importlib import import_module
+ modules = import_module(info['from'])
+ if 'func' in info and 'param' in info:
+ return getattr(getattr(modules, info['import']), info['func'])(**info['param'])
+ elif ('param' not in info) and ('args' not in info):
+ return getattr(modules, info['import'])()
+ elif ('param' in info) and ('args' not in info):
+ return getattr(modules, info['import'])(**info['param'])
+ elif ('param' not in info) and ('args' in info):
+ return getattr(modules, info['import'])(*info['args'])
+ else:
+ return getattr(modules, info['import'])(*info['args'], **info['param'])
+
+def detect_error_codes(log_file):
+ all_line = read_to_buffer(log_file).decode().split('\n')
+ error_codes = []
+ for _, line in enumerate(all_line):
+ if "raise RuntimeError('NaN encountered!')" in line:
+ error_codes.append('NaN')
+ return list(set(error_codes))
+
+def insensitive_glob(pattern):
+ def either(c):
+ return '[%s%s]' % (c.lower(), c.upper()) if c.isalpha() else c
+ return glob.glob(''.join(map(either, pattern)))
+
+def list_dir(folder):
+ return [f for f in os.listdir(folder) if op.isdir(op.join(folder, f))]
+
+def replace_place_holder(p, place_holder):
+ if isinstance(p, dict):
+ for k, v in p.items():
+ if type(v) == str and v.startswith('$'):
+ p[k] = place_holder[v[1:]]
+ else:
+ replace_place_holder(v, place_holder)
+ elif isinstance(p, list) or isinstance(p, tuple):
+ for i, x in enumerate(p):
+ if isinstance(x, str) and x.startswith('$'):
+ p[i] = place_holder[x[1:]]
+ else:
+ replace_place_holder(x, place_holder)
+
+def execute_pipeline(all_processor):
+ only_processors = [p for p in all_processor if p.get('only')]
+ need_check_processors = only_processors if len(only_processors) > 0 else all_processor
+ result = {}
+ result['process_result'] = []
+ place_holder = {}
+ for p in need_check_processors:
+ replace_place_holder(p, place_holder)
+ if p.get('ignore', False):
+ continue
+ if 'execute_if_true_else_break' in p:
+ r = execute_func(p['execute_if_true_else_break'])
+ if not r:
+ result['result'] = 'prereq_failed'
+ result['failed_prereq'] = p['execute_if_true_else_break']
+ break
+ if p.get('continue_if_true_else_break'):
+ r = execute_func(p['execute'])
+ if not r:
+ result['result'] = 'prereq_failed'
+ result['failed_prereq'] = p['execute']
+ break
+ else:
+ continue
+ if p.get('force', False):
+ r = run_if_not_cached(execute_func, p['execute'],
+ __force=True)
+ else:
+ r = run_if_not_cached(execute_func, p['execute'])
+ if 'output' in p:
+ place_holder[p['output']] = r
+ else:
+ if r is not None:
+ result['process_result'].append({'process_info': p, 'return': r})
+ if p.get('stop_after'):
+ logging.info('skip the rest since stop_after=True')
+ break
+ result['place_holder'] = place_holder
+ if 'result' not in result:
+ result['result'] = 'pass'
+ return result
+
+def remove_empty_keys_(ds):
+ keys = set([k for d in ds for k in d])
+ empty_keys = [k for k in keys if all(d.get(k) is None for d in ds)]
+ for k in empty_keys:
+ for d in ds:
+ if k in d:
+ del d[k]
+
+def max_iter_mult(m, factor):
+ if isinstance(m, int):
+ return int(m * factor)
+ elif isinstance(m, str):
+ assert m.endswith('e')
+ return '{}e'.format(int(float(m[:-1]) * factor))
+ else:
+ raise NotImplementedError
+
+def remove_empty_coco_style(rects, w, h):
+ rects = [r for r in rects if r.get('iscrowd', 0) == 0]
+ ret = []
+ for r in rects:
+ x1, y1, x2, y2 = r['rect']
+ x1 = min(w, max(0, x1))
+ x2 = min(w, max(0, x2))
+ y1 = min(h, max(0, y1))
+ y2 = min(h, max(0, y2))
+ if y2 > y1 and x2 > x1:
+ r['rect'] = [x1, y1, x2, y2]
+ ret.append(r)
+ return ret
+
+def join_hints(hints, sep='_'):
+ parts = []
+ for h in hints:
+ if isinstance(h, dict):
+ parts.append(hash_sha1(h['hint'])[-h['max']:])
+ else:
+ parts.append(str(h))
+ return sep.join(parts)
+
+def qd_tqdm(*args, **kwargs):
+ desc = kwargs.get('desc', '')
+ import inspect
+ frame = inspect.currentframe()
+ frames = inspect.getouterframes(frame)
+ frame = frames[1].frame
+ line_number = frame.f_lineno
+ fname = op.basename(frame.f_code.co_filename)
+ message = '{}:{}'.format(fname, line_number)
+
+ if 'desc' in kwargs:
+ kwargs['desc'] = message + ' ' + desc
+ else:
+ kwargs['desc'] = message
+
+ if 'mininterval' not in kwargs:
+ # every 2 secons; default is 0.1 second which is too frequent
+ kwargs['mininterval'] = 2
+
+ return tqdm(*args, **kwargs)
+
+def get_opened_files():
+ import psutil
+ proc = psutil.Process()
+ return proc.open_files()
+
+def print_opened_files():
+ logging.info(pformat(get_opened_files()))
+
+def save_parameters(param, folder):
+ time_str = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
+
+ write_to_yaml_file(param, op.join(folder,
+ 'parameters_{}.yaml'.format(time_str)))
+ # save the env parameters
+ # convert it to dict for py3
+ write_to_yaml_file(dict(os.environ), op.join(folder,
+ 'env_{}.yaml'.format(time_str)))
+
+def exclusive_open_to_read(fname, mode='r'):
+ disable_lock = os.environ.get('QD_DISABLE_EXCLUSIVE_READ_BY_LOCK')
+ if disable_lock is not None:
+ disable_lock = int(disable_lock)
+ if not disable_lock:
+ user_name = get_user_name()
+ lock_fd = acquireLock(op.join('/tmp',
+ '{}_lock_{}'.format(user_name, hash_sha1(fname))))
+ #try:
+ # in AML, it could fail with Input/Output error. If it fails, we will
+ # use azcopy as a fall back solution for reading
+ if fname.endswith(".8b") and not os.environ["QD_USE_LINEIDX_8B"]:
+ fp = limited_retry_agent(1, open, fname, mode)
+ else:
+ fp = limited_retry_agent(10, open, fname, mode)
+ if not disable_lock:
+ releaseLock(lock_fd)
+ return fp
+
+def inject_log_to_board(fname, folder, pattern, keys):
+ logging.info(pattern)
+ # from qd.qd_common import iter_match_document
+ from .common import iter_match_document
+
+ from torch.utils.tensorboard import SummaryWriter
+ wt = SummaryWriter(log_dir=folder)
+ x_keys = [k['key'] for k in keys if k['is_x']]
+ x_key_time = any([
+ k for k in keys
+ if k['is_x'] and k.get('type') == 'time'
+ ])
+ if len(x_keys) == 1:
+ x_key = x_keys[0]
+ if len(x_keys) == 0:
+ x_key = None
+ added = 0
+ for i, r in enumerate(iter_match_document(pattern, fname)):
+ info = {}
+ for k, x in zip(keys, r):
+ if not k.get('type'):
+ info[k['key']] = float(x)
+ elif k['type'] == 'time':
+ info[k['key']] = datetime.datetime.strptime(
+ x, '%Y-%m-%d %H:%M:%S')
+ added += 1
+ for k, v in info.items():
+ if x_key and k == x_key:
+ continue
+ args = {'tag': k, 'scalar_value': v}
+ if not x_key_time:
+ if x_key:
+ args['global_step'] = info[x_key]
+ else:
+ args['global_step'] = i
+ else:
+ args['walltime'] = (info[x_key]-datetime.datetime(1970,1,1)).total_seconds()
+ wt.add_scalar(**args)
+ #wt.add_scalar(tag=k, scalar_value=v, global_step=info[x_key])
+ logging.info(added)
+
+def auto_parse_log_line(line):
+ must_have = ['iter', 'speed', 'loss', 'lr']
+ result = {}
+ if not all(m in line for m in must_have):
+ # in this case, we will try to parse if there is like acc = {}
+ if '=' not in line:
+ return result
+ parts = re.split(':|,|;', line)
+ #parts = line.split(':')
+ for p in parts:
+ if '=' in p:
+ sub_parts = p.split('=')
+ if len(sub_parts) != 2:
+ continue
+ k, v = map(lambda x: x.strip(), sub_parts)
+ try:
+ result[k] = float(v)
+ except:
+ continue
+ if len(result) > 0:
+ matched = re.match('([0-9-\s:]+)', list(line.split(','))[0])
+ if matched is not None:
+ x = matched.groups()[0]
+ try:
+ result['time'] = datetime.strptime(
+ x.strip(), '%Y-%m-%d %H:%M:%S')
+ except:
+ return {}
+ return result
+ else:
+ parts = line.split(' ')
+ #([0-9-\s:]*)
+ for p in parts:
+ kv = list(map(lambda x: x.strip(), p.split(':')))
+ if len(kv) != 2:
+ continue
+ key = kv[0]
+ vs = list(map(lambda x: x.strip(' ()'), kv[1].split(' ')))
+ for idx_v, v in enumerate(vs):
+ try:
+ v1 = float(vs[0])
+ if len(vs) > 1:
+ result[key + '_{}'.format(idx_v)] = v1
+ else:
+ result[key] = v1
+ except:
+ continue
+ if len(result):
+ matched = re.match('([0-9-\s:]*)', line)
+ x = matched.groups()[0]
+ try:
+ result['time'] = datetime.strptime(
+ x.strip(), '%Y-%m-%d %H:%M:%S')
+ except:
+ pass
+
+ return result
+
+
+def identity(x):
+ # only used in pipeline
+ return x
+
+def recursive_type_convert(info, t, convert_func):
+ if isinstance(info, (tuple, list)):
+ return [recursive_type_convert(i, t, convert_func) for i in info]
+ elif isinstance(info, dict):
+ return dict((k, recursive_type_convert(v, t, convert_func)) for k, v in info.items())
+ elif isinstance(info, t):
+ return convert_func(info)
+ else:
+ return info
+
+def blobfuse_umount(mount_folder):
+ cmd = ['sudo', 'umount', mount_folder]
+ cmd_run(cmd)
+
+def blobfuse_mount(account_name, container_name, account_key,
+ mount_folder, cache_folder):
+ ensure_directory(mount_folder)
+ ensure_directory(cache_folder)
+ cmd = [
+ 'blobfuse',
+ mount_folder,
+ '--tmp-path={}'.format(cache_folder),
+ '--container-name={}'.format(container_name),
+ ]
+ env = {
+ 'AZURE_STORAGE_ACCOUNT': account_name,
+ 'AZURE_STORAGE_ACCESS_KEY': account_key,
+ }
+ cmd_run(cmd, env=env)
+
+def blobfuse_mount_from_config(config, mount_folder):
+ info = load_from_yaml_file(config)
+ cache_folder = '/mnt/blobfuse/cache/{}'.format(hash_sha1(mount_folder))
+ blobfuse_mount(
+ account_name=info['account_name'],
+ container_name=info['container_name'],
+ account_key=info['account_key'],
+ mount_folder=mount_folder,
+ cache_folder=cache_folder,
+ )
+
+def query_all_opened_file_in_system():
+ fs = []
+ for proc in psutil.process_iter():
+ for proc in psutil.process_iter():
+ try:
+ for item in proc.open_files():
+ fs.append(item.path)
+ except Exception:
+ pass
+ return list(set(fs))
+
+def has_handle(fpath, opened_files=None):
+ fpath = op.abspath(op.realpath(fpath))
+ if opened_files is None:
+ for proc in psutil.process_iter():
+ try:
+ for item in proc.open_files():
+ if fpath == item.path:
+ return True
+ except Exception:
+ pass
+ return False
+ else:
+ return fpath in opened_files
+
+def submit_to_evalai(fname, message, challenge_id, phase_id):
+ # if fname is too long, it will fail
+ copy_file(fname, '/tmp/a.json')
+ fname = '/tmp/a.json'
+ cmd = [
+ 'evalai',
+ 'challenge',
+ str(challenge_id),
+ 'phase',
+ str(phase_id), 'submit', '--file',
+ fname,
+ '--private'
+ ]
+ input = 'y\n{}\n\n\n\n\n'.format(message)
+ import subprocess as sp
+ try:
+ submission_command_stdout = cmd_run(cmd,
+ process_input=input.encode(),
+ stdout=sp.PIPE,
+ )[0].decode("utf-8")
+ except Exception as ex:
+ #ensure_remove_file('/tmp/a.json')
+ if 'The maximum number of submission for today' in str(ex):
+ logging.info(str(ex))
+ return
+ else:
+ raise
+ submission_id_regex = re.search("evalai submission ([0-9]+)", submission_command_stdout)
+ submission_id = submission_id_regex.group(0).split()[-1]
+ cmd = ["evalai", "submission", submission_id, "result"]
+ #ensure_remove_file('/tmp/a.json')
+ return ' '.join(cmd)
+
+def submit_to_evalai_for_vqa(fname, message, std=False):
+ if std:
+ return submit_to_evalai(fname, message, 830, 1794)
+ else:
+ return submit_to_evalai(fname, message, 830, 1793)
+
+def submit_to_evalai_for_textvqa(fname, message, std=False):
+ if std:
+ return submit_to_evalai(fname, message, 874, 1821)
+ else:
+ return submit_to_evalai(fname, message, 874, 1820)
+
+def submit_to_evalai_for_vizwizvqa(fname, message, std=False):
+ if std:
+ return submit_to_evalai(fname, message, 1560, 3115)
+ else:
+ return submit_to_evalai(fname, message, 1560, 3114)
+
+def submit_to_evalai_for_vizwizvqa2021(fname, message, std=False):
+ if std:
+ return submit_to_evalai(fname, message, 743, 1593)
+ else:
+ return submit_to_evalai(fname, message, 743, 1592)
+
+def submit_to_evalai_for_vizwizvqa2022(fname, message, phase='std'):
+ if phase == 'std':
+ return submit_to_evalai(fname, message, 1560, 3115)
+ elif phase == 'challenge':
+ return submit_to_evalai(fname, message, 1560, 3116)
+
+def submit_to_evalai_for_nocaps_xd(fname, split, message):
+ challenge_id = 464
+ if split == 'val':
+ phase_id = 962
+ else:
+ assert split == 'test'
+ phase_id = 963
+ return submit_to_evalai(
+ fname, message, challenge_id, phase_id)
+
+def submit_to_evalai_for_nocaps(fname, split, message):
+ challenge_id = 464
+ if split == 'val':
+ phase_id = 962
+ else:
+ assert split == 'test'
+ phase_id = 963
+ return submit_to_evalai(
+ fname, message, challenge_id, phase_id)
+
+def submit_to_evalai_for_vizwiz(fname, phase, message):
+ challenge_id = 739
+ if phase == 'dev':
+ phase_id = 1579
+ else:
+ assert phase == 'std'
+ phase_id = 1580
+ return submit_to_evalai(
+ fname, message, challenge_id, phase_id)
+
+def submit_to_evalai_for_textcap(fname, phase, message):
+ challenge_id = 906
+ if phase == 'val':
+ phase_id = 1872
+ else:
+ assert phase == 'test'
+ phase_id = 1873
+ return submit_to_evalai(
+ fname, message, challenge_id, phase_id)
+
+def recover_stdout_error():
+ import sys
+ sys.stdout = sys.__stdout__
+ sys.stderr = sys.__stderr__
+
+def switch_case(switch, case, default):
+ if isinstance(switch, (list, tuple)):
+ path = '$'.join(map(str, switch))
+ if dict_has_path(case, path):
+ return dict_get_path_value(case, path)
+ else:
+ return default
+ else:
+ return case.get(switch, default)
+
+class wb(object):
+ initialized = False
+ enabled = True
+
+ @classmethod
+ def ensure_initialized(cls):
+ if not cls.initialized:
+ cls.initialized = True
+ cls.enabled = int(os.environ.get('QD_WANDB_ENABLED', '0'))
+ if get_mpi_rank() != 0:
+ cls.enabled = False
+ if cls.enabled:
+ try:
+ import wandb
+ # https://docs.wandb.ai/library/init#init-start-error
+ wandb.init(settings=wandb.Settings(start_method="fork"))
+ except:
+ print_trace()
+ logging.info('init fails, disable wandb')
+ cls.enabled = False
+
+ @classmethod
+ def watch(cls, *args, **kwargs):
+ cls.ensure_initialized()
+ if cls.enabled:
+ import wandb
+ wandb.watch(*args, **kwargs)
+
+ @classmethod
+ def log(cls, *args, **kwargs):
+ cls.ensure_initialized()
+ if cls.enabled:
+ import wandb
+ wandb.log(*args, **kwargs)
+
+def get_wandb_project(project):
+ if len(project) > 64:
+ from qd.qd_common import hash_sha1
+ project = project[:64] + '_' + hash_sha1(project)
+ return project
+
+def query_log_by_wandb_project(project):
+ project = get_wandb_project(project)
+ import wandb
+
+ api = wandb.Api()
+ all_record = []
+ for r in api.runs(project):
+ df = r.history()
+ records = df.to_dict('records')
+ all_record.extend(records)
+ all_record = sorted(all_record, key=lambda x: x['_timestamp'])
+ return all_record
+
+def find_mount_point(path):
+ path = op.abspath(path)
+ while not op.ismount(path):
+ path = op.dirname(path)
+ return path
+
+@contextlib.contextmanager
+def robust_open_to_write(fname, mode):
+ tmp = fname + '.tmp'
+ ensure_directory(op.dirname(tmp))
+ with open(tmp, mode) as fp:
+ yield fp
+ os.rename(tmp, fname)
+
+if __name__ == '__main__':
+ init_logging()
+ kwargs = parse_general_args()
+ logging.info('param:\n{}'.format(pformat(kwargs)))
+ function_name = kwargs['type']
+ del kwargs['type']
+ locals()[function_name](**kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/db.py b/One-to-All-Animation/benchmark/DisCo/utils/db.py
new file mode 100644
index 0000000000000000000000000000000000000000..37357f3fb23932244832cfbd8dce731767f0876a
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/db.py
@@ -0,0 +1,675 @@
+from .common import list_to_dict
+from .common import load_from_yaml_file
+from .common import gen_uuid
+from pymongo import MongoClient
+import pymongo
+import copy
+from bson import ObjectId
+from datetime import datetime
+from collections import OrderedDict
+from collections import defaultdict
+import logging
+from tqdm import tqdm
+from .common import print_table
+from .common import try_once
+
+def create_mongodb_client():
+ config = load_from_yaml_file('./aux_data/configs/mongodb_credential.yaml')
+ host = config['host']
+ return MongoClient(host)
+
+def create_bbverification_db(db_name='qd', collection_name='uhrs_bounding_box_verification'):
+ '''
+ use create_bbverificationdb_client since the naming is not precise
+ '''
+ return BoundingBoxVerificationDB(db_name, collection_name)
+
+def create_bbverificationdb_client(db_name='qd',
+ collection_name='uhrs_bounding_box_verification'):
+ return BoundingBoxVerificationDB(db_name, collection_name)
+
+def objectid_to_str(result):
+ # convert the type of ObjectId() to string
+ result = list(result)
+ for r in result:
+ r['_id'] = str(r['_id'])
+ return result
+
+def ensure_objectid(result):
+ for r in result:
+ if type(r['_id']) is str:
+ r['_id'] = ObjectId(r['_id'])
+
+def ensure_to_objectid(r):
+ if type(r) is str:
+ return ObjectId(r)
+ else:
+ return r
+
+def create_annotation_db():
+ return AnnotationDB()
+
+class AnnotationDB(object):
+ '''
+ gradually move all the Annotation db related function call to this wrapper.
+ The related table incldues: image, ground_truth, label, prediction_result
+ '''
+ def __init__(self):
+ self._qd = create_mongodb_client()
+ self._gt = self._qd['qd']['ground_truth']
+ self._label = self._qd['qd']['label']
+ self._acc = self._qd['qd']['acc']
+ self._phillyjob = self._qd['qd']['phillyjob']
+ self._cluster = self._qd['qd']['cluster']
+ import getpass
+ self._judge = self._qd['qd']['judge']
+ self.username = getpass.getuser()
+
+ def add_meta_data(self, kwargs):
+ if 'create_time' not in kwargs:
+ kwargs['create_time'] = datetime.now()
+ if 'username' not in kwargs:
+ kwargs['username'] = self.username
+ kwargs['update_time'] = datetime.now()
+
+ def insert_judge(self, **kwargs):
+ self.add_meta_data(kwargs)
+ self._judge.insert_one(kwargs)
+
+ def insert_cluster_summary(self, **kwargs):
+ self.add_meta_data(kwargs)
+ self._cluster.insert_one(kwargs)
+
+ def insert_phillyjob(self, **kwargs):
+ # use self.add_meta_data
+ self.add_meta_data(kwargs)
+ self._phillyjob.insert_one(kwargs)
+
+ def insert_acc(self, **kwargs):
+ self.add_meta_data(kwargs)
+ self._acc.insert_one(kwargs)
+
+ def insert_label(self, **kwargs):
+ if 'uuid' not in kwargs:
+ kwargs['uuid'] = gen_uuid()
+ if 'create_time' not in kwargs:
+ kwargs['create_time'] = datetime.now()
+
+ self._label.insert_one(kwargs)
+
+ def insert_one(self, collection_name, **kwargs):
+ self.add_meta_data(kwargs)
+ result = self._qd['qd'][collection_name].insert_one(kwargs)
+ return result
+
+ def remove_phillyjob(self, **kwargs):
+ self._phillyjob.delete_many(kwargs)
+
+ def delete_many(self, collection_name, **kwargs):
+ self._qd['qd'][collection_name].delete_many(kwargs)
+
+ def update_one(self, doc_name, query, update, **kwargs):
+ return self._qd['qd'][doc_name].update_one(
+ query,
+ update,
+ **kwargs
+ )
+
+ def update_many(self, doc_name, query, update):
+ if '$set' in update:
+ update['$set']['update_time'] = datetime.now()
+ return self._qd['qd'][doc_name].update_many(query, update)
+
+ def update_phillyjob(self, query, update):
+ return self._phillyjob.update_many(query, {'$set': update})
+
+ def iter_judge(self, **kwargs):
+ return self._judge.find(kwargs)
+
+ def iter_phillyjob(self, **kwargs):
+ return self._phillyjob.find(kwargs)
+
+ def iter_general(self, table_name, **kwargs):
+ return self._qd['qd'][table_name].find(kwargs).sort('create_time', -1)
+
+ def iter_acc(self, **query):
+ return self._acc.find(query)
+
+ def update_one_acc(self, query, update):
+ self._acc.update_one(query, update)
+
+ def iter_unique_test_info_in_acc(self):
+ pipeline = [
+ {'$group': {'_id': {'test_data': '$test_data',
+ 'test_split': '$test_split',
+ 'test_version': '$test_version'}}}
+ ]
+ for result in self._acc.aggregate(pipeline):
+ yield result['_id']
+
+ def exist_acc(self, **query):
+ try:
+ next(self.iter_acc(**query))
+ return True
+ except:
+ return False
+
+ # label related
+ def update_label(self, query, update):
+ self._label.update_one(query, update)
+
+ def iter_label(self):
+ return self._label.find()
+
+ def iter_query_label(self, query):
+ return self._label.find(query)
+
+ def build_label_index(self):
+ self._label.create_index([('uuid', 1)], unique=True)
+ self._label.create_index([('unique_name', 1)], unique=True,
+ collation={'locale': 'en', 'strength':2})
+
+ def create_index(self, collection, *args, **kwargs):
+ self._qd['qd'][collection].create_index(*args, **kwargs)
+
+ def drop_ground_truth_index(self):
+ self._gt.drop_indexes()
+
+ def build_job_index(self):
+ self._phillyjob.create_index([('create_time', 1)])
+ self._phillyjob.create_index([('appID', 1)], unique=True)
+
+ def build_ground_truth_index(self):
+ self._gt.create_index([('data', 1),
+ ('split', 1),
+ ('key', 1),
+ ('class', 1)])
+ self._gt.create_indexes
+ self._gt.create_index([('data', 1),
+ ('split', 1),
+ ('class', 1)])
+ self._gt.create_index([('data', 1),
+ ('split', 1),
+ ('class', 1),
+ ('version', 1)])
+ # used for deleting all before inserting
+ self._gt.create_index([('data', 1),
+ ('split', 1),
+ ('version', 1)])
+
+class BoundingBoxVerificationDB(object):
+ status_requested = 'requested'
+ status_retrieved = 'retrieved'
+ status_submitted = 'submitted'
+ status_completed = 'completed'
+ status_merged = 'merged'
+ urgent_priority_tier = -10000
+ def __init__(self, db_name='qd', collection_name='uhrs_bounding_box_verification'):
+ self.client = None
+ self.db_name = db_name
+ self.collection_name = collection_name
+
+ def query_by_pipeline(self, pipeline):
+ result = self.collection.aggregate(pipeline, allowDiskUse=True)
+ return list(result)
+
+ def query_verified_correct_rects(self, data, split, key):
+ pipeline = [{'$match': {'data': data,
+ 'split': split,
+ 'key': key,
+ 'interpretation_result': 1,
+ 'status': {'$in': [self.status_completed,
+ self.status_merged]}}},
+ ]
+ return [info['rect'] for info in self.query_by_pipeline(pipeline)]
+
+ def query_verified_incorrect_rects(self, data, split, key):
+ pipeline = [{'$match': {'data': data,
+ 'split': split,
+ 'key': key,
+ 'interpretation_result': {'$ne': 1},
+ 'status': {'$in': [self.status_completed,
+ self.status_merged]}}},
+ ]
+ return [info['rect'] for info in self.query_by_pipeline(pipeline)]
+
+ def query_nonverified_rects(self, data, split, key):
+ pipeline = [{'$match': {'data': data,
+ 'split': split,
+ 'key': key,
+ 'status': {'$nin': [self.status_completed,
+ self.status_merged]}}},
+ ]
+ result = []
+ for info in self.query_by_pipeline(pipeline):
+ info['rect']['_id'] = str(info['_id'])
+ result.append(info['rect'])
+ return result
+
+ def request_by_insert(self, all_box_task):
+ def get_bb_task_id(rect_info):
+ from .common import hash_sha1
+ rect = rect_info['rect']
+ return hash_sha1([rect_info['url'], rect['class'], rect['rect']])
+ all_box_task = copy.deepcopy(all_box_task)
+ for b in all_box_task:
+ assert 'status' not in b
+ assert 'priority_tier' in b, 'priority' in b
+ assert 'url' in b
+ assert 'rect' in b
+ b['status'] = self.status_requested
+ b['last_update_time'] = {'last_{}'.format(self.status_requested):
+ datetime.now()}
+ if 'rect' not in b:
+ b['rect'] = b['rects'][0]
+ b['bb_task_id'] = get_bb_task_id(b)
+ self.collection.insert_many(all_box_task)
+
+ def retrieve(self, max_box, urgent_task=False):
+ assert max_box > 0
+ sort_config = OrderedDict()
+ sort_config['priority_tier'] = pymongo.ASCENDING
+ sort_config['priority'] = pymongo.ASCENDING
+ match_criteria = {'status': self.status_requested}
+ if urgent_task:
+ match_criteria['priority_tier'] = self.urgent_priority_tier
+ pipeline = [
+ {'$match': match_criteria},
+ {'$sort': sort_config},
+ {'$limit': max_box},
+ ]
+ result = self.query_by_pipeline(pipeline)
+ # we need to update the status to status_retrieved to avoid duplicate
+ # retrieve && submit
+ self.update_status([r['_id'] for r in result],
+ self.status_retrieved)
+ return objectid_to_str(result)
+
+ def update_priority_tier(self, all_id, new_priority_tier):
+ all_id = [ensure_to_objectid(i) for i in all_id]
+ self.collection.update_many({'_id': {'$in': all_id}},
+ {'$set': {'priority_tier': new_priority_tier}})
+
+ def update_status(self, all_id, new_status, allowed_original_statuses=None):
+ all_id = list(set(all_id))
+ for i in range(len(all_id)):
+ if type(all_id[i]) is str:
+ all_id[i] = ObjectId(all_id[i])
+ query = {'_id': {'$in': all_id}}
+ if allowed_original_statuses:
+ query['status'] = {'$in': allowed_original_statuses}
+ time_key = 'last_update_time.last_{}'.format(new_status)
+ result = self.collection.update_many(filter=query,
+ update={'$set': {'status': new_status,
+ time_key: datetime.now()}})
+
+ def reset_status_to_requested(self, all_bb_task):
+ self.update_status([b['_id'] for b in all_bb_task],
+ self.status_requested)
+
+ def submitted(self, submitted):
+ self.adjust_status(submitted, 'uhrs_submitted_result',
+ 'uhrs_submitted_result', self.status_submitted)
+
+ def adjust_status(self, uhrs_results, uhrs_result_field, db_field,
+ new_status, allowed_original_statuses=None):
+ uhrs_results = list(uhrs_results)
+ for s in uhrs_results:
+ assert uhrs_result_field in s
+ assert '_id' in s
+
+ ensure_objectid(uhrs_results)
+ all_id = [s['_id'] for s in uhrs_results]
+
+ # save the result from uhrs
+ for s in uhrs_results:
+ self.collection.update_one(filter={'_id': s['_id']},
+ update={'$set': {db_field: s[uhrs_result_field]}})
+
+ # update the status
+ self.update_status(all_id, new_status, allowed_original_statuses)
+
+ def query_submitted(self, topk=None):
+ pipeline = [
+ {'$match': {'status': self.status_submitted}},
+ ]
+ if topk:
+ pipeline.append({'$limit': topk})
+ result = self.query_by_pipeline(pipeline)
+ return objectid_to_str(result)
+
+ def complete(self, completed):
+ self.adjust_status(completed, 'uhrs_completed_result',
+ 'uhrs_completed_result',
+ self.status_completed,
+ allowed_original_statuses=[self.status_submitted])
+
+ def set_status_as_merged(self, all_id):
+ self.update_status(all_id, self.status_merged,
+ allowed_original_statuses=[self.status_completed])
+
+ def get_completed_uhrs_result(self, extra_match=None):
+ merge_multiple_verification = False # True if we submit one rect multiple times, not tested
+ match_criteria = {'status': self.status_completed}
+ if extra_match:
+ match_criteria.update(extra_match)
+
+ pipeline = [
+ {'$match': match_criteria},
+ ]
+
+ if merge_multiple_verification:
+ pipeline.append(
+ {'$group': {'_id': {'data': '$data',
+ 'split': '$split',
+ 'key': '$key',
+ 'bb_task_id': '$bb_task_id'},
+ 'rects': {'$first': '$rects'},
+ 'uhrs': {'$push': '$uhrs_completed_result'},
+ 'related_ids': {'$push': '$_id'},
+ }}
+ )
+ data_split_to_key_rects = defaultdict(list)
+ all_id = []
+ logging.info('querying the completed tasks')
+ for rect_info in tqdm(self.query_by_pipeline(pipeline)):
+ data = rect_info['data']
+ split = rect_info['split']
+ rect = rect_info['rect']
+ all_id.append(rect_info['_id'])
+ rect['uhrs'] = rect_info['uhrs_completed_result']
+ key = rect_info['key']
+ data_split_to_key_rects[(data, split)].append((key, rect))
+ return data_split_to_key_rects, all_id
+
+ @property
+ def collection(self):
+ if self.client is None:
+ self.client = create_mongodb_client()
+ self.collection.create_index([('data', pymongo.ASCENDING),
+ ('split', pymongo.ASCENDING),
+ ('key', pymongo.ASCENDING)])
+ self.collection.create_index([('data', pymongo.ASCENDING),
+ ('rects.0.class', pymongo.ASCENDING),
+ ('rects.0.from', pymongo.ASCENDING),
+ ('status', pymongo.ASCENDING),
+ ])
+ self.collection.create_index([('data', pymongo.ASCENDING),
+ ('rect.class', pymongo.ASCENDING),
+ ('rect.from', pymongo.ASCENDING),
+ ('status', pymongo.ASCENDING),
+ ])
+ self.collection.create_index([('data', pymongo.ASCENDING),
+ ('rects.0.class', pymongo.ASCENDING),
+ ('rects.0.from', pymongo.ASCENDING),
+ ('status', pymongo.ASCENDING),
+ ('priority', pymongo.ASCENDING),
+ ])
+ self.collection.create_index([('data', pymongo.ASCENDING),
+ ('rect.class', pymongo.ASCENDING),
+ ('rect.from', pymongo.ASCENDING),
+ ('status', pymongo.ASCENDING),
+ ('priority', pymongo.ASCENDING),
+ ])
+ self.collection.create_index([('data', pymongo.ASCENDING)])
+ self.collection.create_index([('priority_tier', pymongo.ASCENDING)])
+ self.collection.create_index([('status', pymongo.ASCENDING)])
+ self.collection.create_index([('priority', pymongo.ASCENDING)])
+ self.collection.create_index([('rects.0.from', pymongo.ASCENDING)])
+ self.collection.create_index([('rect.from', pymongo.ASCENDING)])
+ return self.client[self.db_name][self.collection_name]
+
+def inject_cluster_summary(info):
+ c = create_annotation_db()
+ c.insert_cluster_summary(**info)
+
+def update_cluster_job_db(all_job_info, collection_name='phillyjob'):
+ c = create_annotation_db()
+ existing_job_infos = list(c.iter_general(collection_name))
+
+ appID_to_record = {j['appID']: j for j in existing_job_infos}
+
+ for job_info in all_job_info:
+ non_value_keys = [k for k, v in job_info.items() if v is None]
+ for k in non_value_keys:
+ del job_info[k]
+ if job_info['appID'] in appID_to_record:
+ record = appID_to_record[job_info['appID']]
+ need_update = False
+ for k, v in job_info.items():
+ if k in ['elapsedTime', 'elapsedFinished']:
+ continue
+ if k == 'data_store':
+ v = sorted(v)
+ record[k] = sorted(v)
+ from .common import float_tolorance_equal
+ if k not in record or not float_tolorance_equal(record[k], v,
+ check_order=False):
+ need_update = True
+ logging.info('update because {} need to be changed from {}'
+ ' to {}'.format(k, record.get(k), v))
+ break
+ if need_update:
+ c.update_many(collection_name,
+ query={'appID': job_info['appID']},
+ update={'$set': job_info})
+ else:
+ try:
+ c.insert_one(collection_name, **job_info)
+ except:
+ # if two instances are running to inject to db, there might be
+ # a chance that a new job is inserted here at the same time.
+ # For the db, we make the appID unique, and one of the
+ # instances will fail. Thus, we just ignore the error here
+ from .common import print_trace
+ print_trace()
+
+@try_once
+def try_query_job_acc(*args, **kwargs):
+ query_job_acc(*args, **kwargs)
+
+def get_job_ids_by_scheduler_id(_ids):
+ from qd.gpucluster.job_scheduler import JobScheduler
+ c = create_annotation_db()
+ scheduler_info = [job_info for job_info in c.iter_general(
+ JobScheduler.collection,
+ _id={'$in': _ids},
+ )]
+ _id_to_scheduler = {s['_id']: s for s in scheduler_info}
+ return [{'scheduler_id': _id, 'appID': _id_to_scheduler[_id].get('appID')} for _id in _ids]
+
+def query_job_acc(job_ids, key='appID', inject=False,
+ must_have_any_in_predict=None,
+ not_have_any_in_predict=None,
+ metric_names=None):
+ if all(isinstance(i, ObjectId) for i in job_ids):
+ job_infos = get_job_ids_by_scheduler_id(job_ids)
+ else:
+ job_infos = job_ids
+ c = create_annotation_db()
+ query_param = {key: {'$in': [j['appID'] for j in job_infos]}}
+ jobs = list(c.iter_phillyjob(**query_param))
+ appID_to_info = {j['appID']: j for j in job_infos}
+ for j in jobs:
+ j.update(appID_to_info[j['appID']])
+ for j in jobs:
+ if all(k in j for k in ['data', 'net', 'expid']):
+ j['full_expid'] = '_'.join([str(j[k]) for k in ['data', 'net', 'expid']])
+ all_full_expid = []
+
+ for j in jobs:
+ if 'data' not in j or 'net' not in j or 'expid' not in j:
+ full_expid = 'U'
+ else:
+ full_expid = '_'.join(map(str, [j.get('data', ''), j.get('net',''),
+ j.get('expid', '')]))
+ all_full_expid.append(full_expid)
+ all_key = ['scheduler_id', 'appID', 'status', 'result', 'speed', 'left', 'eta',
+ 'full_expid', 'num_gpu', 'mem_used', 'gpu_util']
+ all_key = [k for k in all_key if any(j.get(k) is not None for j in jobs)]
+
+ #print_table([j for j in jobs if j['status'] == 'Failed'], all_key=all_key)
+ print_table(jobs, all_key=all_key)
+ if len(all_full_expid) == 0:
+ print_table(job_ids)
+
+ if inject:
+ for full_expid in all_full_expid:
+ from qd.process_tsv import inject_accuracy_one
+ inject_accuracy_one(full_expid)
+
+ query_acc_by_full_expid(all_full_expid,
+ must_have_any_in_predict=must_have_any_in_predict,
+ not_have_any_in_predict=not_have_any_in_predict,
+ metric_names=metric_names)
+
+def query_acc_by_full_expid(all_full_expid,
+ must_have_any_in_predict=None,
+ not_have_any_in_predict=None,
+ metric_names=None,
+ sort_row=True,
+ ):
+ c = create_annotation_db()
+ acc = list(c.iter_acc(full_expid={'$in': all_full_expid}))
+ full_expid_to_rank = {f: i for i, f in enumerate(all_full_expid)}
+ if not sort_row:
+ acc = sorted(acc, key=lambda x: full_expid_to_rank[x['full_expid']])
+ if metric_names is None:
+ metric_names = [
+ 'all-all',
+ 'overall$0.5$map',
+ 'overall$-1$map',
+ 'top1',
+ 'global_avg',
+ 'feat_eig_value_ratio',
+ 'feat_mean_value',
+ 'feat_eig_max_value_ratio',
+ 'Bleu_4',
+ 'METEOR',
+ 'ROUGE_L',
+ 'CIDEr',
+ 'SPICE',
+ 'attr',
+ 't2i$R@1',
+ 't2i$R@10',
+ 't2i$R@5',
+ 'i2t$R@1',
+ 'i2t$R@10',
+ 'i2t$R@5',
+ 'acc',
+ 'stvqa_acc',
+ 'stvqa_anls',
+ 'vqa_acc',
+ ]
+ acc = [a for a in acc if a['metric_name'] in metric_names]
+ if must_have_any_in_predict is not None:
+ acc = [a for a in acc if any(t in a['report_file'] for t in
+ must_have_any_in_predict)]
+ if not_have_any_in_predict is not None:
+ acc = [a for a in acc if all(t not in a['report_file'] for t in
+ not_have_any_in_predict)]
+ for a in acc:
+ del a['username']
+ del a['_id']
+ del a['create_time']
+ a['metric_value'] = round(a['metric_value'], 3)
+ del a['test_split']
+ del a['test_version']
+ if 'predict_file' in a:
+ del a['predict_file']
+ #del a['report_file']
+ del a['test_data']
+ from .common import natural_key
+ if sort_row:
+ acc = sorted(acc, key=lambda a: (
+ natural_key(a['full_expid']),
+ a['metric_value'],
+ ))
+ #from .common import remove_empty_keys_
+ #remove_empty_keys_(acc)
+ # group by metric names
+ all_metric = list(set([a['metric_name'] for a in acc]))
+ all_metric = sorted(all_metric)
+ fp_to_acc = {}
+ for a in acc:
+ fp = (a['full_expid'], a['report_file'])
+ if fp in fp_to_acc:
+ fp_to_acc[fp].append(a)
+ else:
+ fp_to_acc[fp] = [a]
+ all_x = []
+ for fp, accs in fp_to_acc.items():
+ x = {'full_expid': fp[0], 'report_file': fp[1]}
+ for m in all_metric:
+ x[m] = None
+ for a in accs:
+ x[a['metric_name']] = a['metric_value']
+ all_x.append(x)
+
+ all_key = ['full_expid']
+ all_key.extend(all_metric)
+ all_key.append('report_file')
+ # special case for caption prod
+ full_expid_to_infos = list_to_dict(
+ [(x['full_expid'], x) for x in all_x], 0)
+ all_extra = []
+ all_remove = []
+ merge_data = ['TaxGettyImagesClean.test', 'TaxUserInsertedClean.test', 'TaxCaptionBot.trainval']
+ for full_expid, infos in full_expid_to_infos.items():
+ for curr_info in infos:
+ if merge_data[0] not in curr_info['report_file']:
+ continue
+ is_merge = True
+ merge_infos = []
+ for i in range(1, len(merge_data)):
+ target = curr_info['report_file'].replace(merge_data[0], merge_data[i])
+ founds = [_i for _i in infos if _i['report_file'] == target]
+ if len(founds) == 0:
+ is_merge = False
+ break
+ merge_infos.append(founds[0])
+ if is_merge:
+ merge_infos.append(curr_info)
+ extra = {'full_expid': full_expid,
+ 'report_file': curr_info['report_file'].replace(merge_data[0], 'avg'),
+ }
+ for k in all_key[1:6]:
+ v = sum([i[k] for i in merge_infos]) / len(merge_infos)
+ extra[k] = round(v, 3)
+ all_extra.append(extra)
+ all_remove.extend(merge_infos)
+ for r in all_remove:
+ all_x.remove(r)
+ all_x.extend(all_extra)
+ remove_not_best_not_last_(all_x, all_metric)
+ print_table(all_x, all_key=all_key)
+
+def remove_not_best_not_last_(all_x, metric_keys):
+ full_expid_to_infos = list_to_dict(
+ [(x['full_expid'], x) for x in all_x], 0)
+ to_remove = []
+ for full_expid, infos in full_expid_to_infos.items():
+ for i in infos:
+ assert i['report_file'][10] == '_'
+ i['_iter'] = int(i['report_file'][11:18])
+ left = i['report_file'][18:]
+ assert i['report_file'][18] == '.'
+ i['_left'] = left
+ left_to_infos = list_to_dict([(i['_left'], i) for i in infos], 0)
+ for left, curr_infos in left_to_infos.items():
+ max_iter = max([i['_iter'] for i in curr_infos])
+ max_metric = [max([i[mk] for i in curr_infos]) for mk in
+ metric_keys]
+ for i in curr_infos:
+ if i['_iter'] != max_iter and \
+ all(i[k] != max_k for k, max_k in zip(metric_keys, max_metric)):
+ to_remove.append(i)
+ for t in to_remove:
+ all_x.remove(t)
+ for x in all_x:
+ del x['_iter']
+ del x['_left']
+
+
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/deepspeed.py b/One-to-All-Animation/benchmark/DisCo/utils/deepspeed.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6ba01dc5d07bcbe1de638d47899a3d436940fc4
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/deepspeed.py
@@ -0,0 +1,90 @@
+from .logger import LOGGER as logger
+from pprint import pformat
+import torch
+from .lib import WANDB_ENABLE
+
+
+def get_deepspeed_config(args):
+ use_fp16 = args.deepspeed # args.deepspeed_fp16
+ use_amp = not args.deepspeed # not args.deepspeed_fp16
+ # use_amp = True
+ # use_fp16 = False
+ # by default, if not use deepspeed fp16, will enable deepspeed amp
+ gradient_accumulate_steps = getattr(args, 'gradient_accumulate_steps', 1)
+ config_params = {
+ 'train_micro_batch_size_per_gpu': args.local_train_batch_size, # batch size per GPU without grandient accumulation
+ "gradient_accumulation_steps": gradient_accumulate_steps
+ }
+ if use_amp:
+ config_params['amp'] = {
+ 'enabled': True,
+ 'opt_level': 'O2',
+ }
+
+ if use_fp16:
+ config_params['fp16'] = {
+ 'enabled': True,
+ # "auto_cast": True,
+ }
+ if args.do_train:
+ config_params['zero_optimization'] = {
+ 'stage': 2,
+ "offload_optimizer": {
+ "device": "cpu",
+ "pin_memory": True},
+ "contiguous_gradients": True,
+ "overlap_comm": True,
+ "reduce_scatter": True, # default
+ "reduce_bucket_size": 5e8, # default
+ "allgather_bucket_size": 5e8, # default
+ "round_robin_gradients": True
+ }
+ config_params['zero_allow_untested_optimizer'] = True
+ if args.do_train:
+ gradient_clip = getattr(args, 'max_grad_norm', -1)
+ if gradient_clip > 0:
+ config_params['gradient_clipping'] = gradient_clip
+
+ config_params['flops_profiler'] = {
+ 'enabled': False,
+ 'profile_step': 1,
+ 'module_depth': -1,
+ 'top_modules': 3,
+ 'detailed': True,
+ }
+ # if WANDB_ENABLE:
+ # config_params['wandb'] = {
+ # "enabled": True,
+ # "group": args.wandb_project,
+ # "project": args.project_name
+ # }
+ config_params['tensorboard'] = {
+ "enabled": True,
+ "output_path": args.log_dir,
+ "job_name": "tensorboard_log"
+ }
+
+ # if hasattr(args, "zero_opt_stage") and args.zero_opt_stage > 0:
+
+ # if args.zero_opt_stage > 0:
+ # config_params['fp16'] = {
+ # 'enabled': True
+ # }
+
+ logger.info(pformat(config_params))
+ return config_params
+
+
+def fp32_to_fp16(batch):
+ # deepspeed does not auto cast inputs.
+ if isinstance(batch, torch.Tensor) and batch.dtype == torch.float32:
+ return batch.to(dtype=torch.half)
+ elif isinstance(batch, list):
+ new_batch = [fp32_to_fp16(t) for t in batch]
+ elif isinstance(batch, tuple):
+ new_batch = tuple(fp32_to_fp16(t) for t in batch)
+ elif isinstance(batch, dict):
+ new_batch = {n: fp32_to_fp16(t) for n, t in batch.items()}
+ else:
+ return batch
+ return new_batch
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/dist.py b/One-to-All-Animation/benchmark/DisCo/utils/dist.py
new file mode 100644
index 0000000000000000000000000000000000000000..64f9189ae53c9f86ae49d489e005686faba65b0c
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/dist.py
@@ -0,0 +1,419 @@
+"""
+This file contains primitives for multi-gpu communication.
+This is useful when doing distributed training.
+"""
+
+from utils.lib import *
+import torch
+import torch.distributed as dist
+import subprocess as sp
+from .logger import LOGGER
+
+
+def iter_tqdm(item):
+ if is_main_process():
+ return tqdm(item, ascii=True)
+ else:
+ return item
+
+
+def dist_init(args, distributed=True):
+ if distributed:
+ if 'OMPI_COMM_WORLD_SIZE' in os.environ:
+ master_addr = os.environ.get("MASTER_ADDR", 'localhost')
+ master_port = os.environ.get("MASTER_PORT", 12475)
+ master_uri = f"tcp://{master_addr}:{master_port}" #if master_addr else 'localhost'
+ world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
+ world_rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
+ local_rank = int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
+ args.num_gpus = world_size
+ args.word_size = args.num_gpus
+ args.distributed = True
+ args.local_rank = local_rank
+ args.rank = world_rank
+
+ args.num_nodes = world_size // args.local_size
+ args.node_id = int(args.rank / args.local_size)
+ if args.distributed:
+ LOGGER.info(
+ f"Init distributed training on "
+ f"local rank {args.local_rank}, "
+ f"global rank {world_rank}")
+ torch.cuda.set_device(args.local_rank)
+ dist.init_process_group(
+ backend='nccl',
+ init_method=master_uri,
+ world_size=world_size,
+ rank=world_rank,
+ timeout=timedelta(hours=5), # 5 hrs
+ )
+ synchronize()
+ elif 'WORLD_SIZE' in os.environ:
+ args.num_gpus = int(
+ os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1
+ args.word_size = args.num_gpus
+ local_rank = int(os.environ['LOCAL_RANK'])
+ rank = int(os.environ['RANK'])
+ args.distributed = True # args.num_gpus > 1
+ args.local_rank = local_rank
+ args.rank = rank
+ args.num_nodes = world_size // args.local_size # hardcoded
+ args.node_id = int(args.rank / args.local_size)
+ if args.distributed:
+ LOGGER.info(
+ f"Init distributed training on "
+ f"local rank {args.local_rank}")
+ torch.cuda.set_device(args.local_rank)
+ dist.init_process_group(
+ backend='nccl', init_method='env://',
+ timeout=timedelta(hours=5), # 5 hrs
+ )
+ synchronize()
+ else:
+ print("distributed training ... presumbly debug with 1 GPU")
+ args.num_gpus = 1
+ args.distributed = True
+ args.num_nodes = 1
+ args.word_size = args.num_gpus
+ args.local_rank = 0
+ args.rank = 0
+ args.num_nodes = 1
+ args.node_id = 0
+ os.environ['LOCAL_RANK'] = str(args.local_rank)
+ master_addr = os.environ.get("MASTER_ADDR", 'localhost')
+ master_port = os.environ.get("MASTER_PORT", 12475)
+ master_uri = f"tcp://{master_addr}:{master_port}" #if master_addr else 'localhost'
+ LOGGER.info(
+ f"Init distributed training on "
+ f"local rank {args.local_rank}")
+ torch.cuda.set_device(args.local_rank)
+ dist.init_process_group(
+ backend='nccl',
+ init_method=master_uri,
+ world_size=args.word_size,
+ rank=args.rank,
+ timeout=timedelta(hours=5), # 5 hrs
+ )
+ # raise ValueError(
+ # "Unable to init torch.distributed. Did not find WORLD_SIZE or OMPI_COMM_WORLD_SIZE in os.environ")
+ else:
+ print("no distributed training ...")
+ # no distributed training
+ args.num_gpus = torch.cuda.device_count()
+ args.word_size = args.num_gpus
+ args.num_nodes = 1
+ args.distributed = False
+ # Setting seed
+ set_seed(args)
+
+
+def _select_seed_randomly(min_seed_value: int = 0, max_seed_value: int = 255) -> int:
+ return random.randint(min_seed_value, max_seed_value)
+
+
+def validate_seed(seed):
+ max_seed_value = np.iinfo(np.uint32).max
+ min_seed_value = np.iinfo(np.uint32).min
+
+ if seed is None:
+ env_seed = os.environ.get("PL_GLOBAL_SEED")
+ if env_seed is None:
+ seed = _select_seed_randomly(min_seed_value, max_seed_value)
+ print(f"No seed found, seed set to {seed}")
+ else:
+ try:
+ seed = int(env_seed)
+ except ValueError:
+ seed = _select_seed_randomly(min_seed_value, max_seed_value)
+ print(f"Invalid seed found: {repr(env_seed)}, seed set to {seed}")
+ elif not isinstance(seed, int):
+ seed = int(seed)
+
+ if not (min_seed_value <= seed <= max_seed_value):
+ print(f"{seed} is not in bounds, numpy accepts from {min_seed_value} to {max_seed_value}")
+ seed = _select_seed_randomly(min_seed_value, max_seed_value)
+ return seed
+
+
+def set_seed(args):
+ seed, n_gpu = args.seed, args.num_gpus
+ if args.do_train and args.fix_dist_seed:
+ this_seed = validate_seed((args.rank+1)* seed)
+ else:
+ this_seed = validate_seed(seed)
+ print(f"Using seed {this_seed} for rank {args.rank}")
+ random.seed(this_seed)
+ np.random.seed(this_seed)
+ torch.random.manual_seed(this_seed)
+ # torch.cuda.manual_seed(this_seed)
+ if args.rank == 0:
+ print(f"Using seed {this_seed} for torch.cuda")
+ torch.cuda.manual_seed_all(this_seed)
+
+
+def get_world_size():
+ if 'WORLD_SIZE' in os.environ:
+ return int(os.environ['WORLD_SIZE'])
+ return int(os.environ.get('OMPI_COMM_WORLD_SIZE', '1'))
+
+
+def get_rank():
+ if 'RANK' in os.environ:
+ return int(os.environ['RANK'])
+ return int(os.environ.get('OMPI_COMM_WORLD_RANK', '0'))
+
+
+def get_local_rank():
+ if 'LOCAL_RANK' in os.environ:
+ return int(os.environ['LOCAL_RANK'])
+ return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_RANK', '0'))
+
+
+def get_local_size():
+ if 'LOCAL_SIZE' in os.environ:
+ return int(os.environ['LOCAL_SIZE'])
+ return int(os.environ.get('OMPI_COMM_WORLD_LOCAL_SIZE', '1'))
+
+
+def is_main_process():
+ if get_rank()==0:
+ try:
+ if torch.distributed.get_rank()==0:
+ return True
+ else:
+ return False
+ except RuntimeError:
+ return True
+ else:
+ return False
+
+# def is_main_process():
+# return get_rank() == 0
+
+
+def synchronize():
+ """
+ Helper function to synchronize (barrier) among all processes when
+ using distributed training
+ """
+ if not dist.is_available():
+ return
+ if not dist.is_initialized():
+ return
+ world_size = get_world_size()
+ if world_size == 1:
+ return
+ t = torch.randn((), device='cuda')
+ dist.all_reduce(t)
+ torch.cuda.synchronize()
+ return
+ # dist.barrier()
+
+
+def gather_on_master(data):
+ """Same as all_gather, but gathers data on master process only, using CPU.
+ Thus, this does not work with NCCL backend unless they add CPU support.
+
+ The memory consumption of this function is ~ 3x of data size. While in
+ principal, it should be ~2x, it's not easy to force Python to release
+ memory immediately and thus, peak memory usage could be up to 3x.
+ """
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ # serialized to a Tensor
+ buffer = pickle.dumps(data)
+ # trying to optimize memory, but in fact,
+ # it's not guaranteed to be released
+ del data
+ storage = torch.ByteStorage.from_buffer(buffer)
+ del buffer
+ tensor = torch.ByteTensor(storage)
+
+ # obtain Tensor size of each rank
+ local_size = torch.LongTensor([tensor.numel()])
+ size_list = [torch.LongTensor([0]) for _ in range(world_size)]
+ dist.all_gather(size_list, local_size)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+
+ if local_size != max_size:
+ padding = torch.ByteTensor(size=(max_size - local_size,))
+ tensor = torch.cat((tensor, padding), dim=0)
+ del padding
+
+ if is_main_process():
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.ByteTensor(size=(max_size,)))
+ dist.gather(tensor, gather_list=tensor_list, dst=0)
+ del tensor
+ else:
+ dist.gather(tensor, gather_list=[], dst=0)
+ del tensor
+ return
+
+ data_list = []
+ for tensor in tensor_list:
+ buffer = tensor.cpu().numpy().tobytes()
+ del tensor
+ data_list.append(pickle.loads(buffer))
+ del buffer
+
+ return data_list
+
+
+def all_gather(data):
+ """
+ Run all_gather on arbitrary picklable data (not necessarily tensors)
+ Args:
+ data: any picklable object
+ Returns:
+ list[data]: list of data gathered from each rank
+ """
+ world_size = get_world_size()
+ if world_size == 1:
+ return [data]
+
+ # serialized to a Tensor
+ buffer = pickle.dumps(data)
+ storage = torch.ByteStorage.from_buffer(buffer)
+ tensor = torch.ByteTensor(storage).to("cuda")
+
+ # obtain Tensor size of each rank
+ local_size = torch.LongTensor([tensor.numel()]).to("cuda")
+ size_list = [torch.LongTensor([0]).to("cuda") for _ in range(world_size)]
+ dist.all_gather(size_list, local_size)
+ size_list = [int(size.item()) for size in size_list]
+ max_size = max(size_list)
+
+ # receiving Tensor from all ranks
+ # we pad the tensor because torch all_gather does not support
+ # gathering tensors of different shapes
+ tensor_list = []
+ for _ in size_list:
+ tensor_list.append(torch.ByteTensor(size=(max_size,)).to("cuda"))
+ if local_size != max_size:
+ padding = torch.ByteTensor(size=(max_size - local_size,)).to("cuda")
+ tensor = torch.cat((tensor, padding), dim=0)
+ dist.all_gather(tensor_list, tensor)
+
+ data_list = []
+ for size, tensor in zip(size_list, tensor_list):
+ buffer = tensor.cpu().numpy().tobytes()[:size]
+ data_list.append(pickle.loads(buffer))
+
+ return data_list
+
+
+def reduce_dict(input_dict, average=True):
+ """
+ Args:
+ input_dict (dict): all the values will be reduced
+ average (bool): whether to do average or sum
+ Reduce the values in the dictionary from all processes
+ so that process with rank
+ 0 has the averaged results. Returns a dict with the same fields as
+ input_dict, after reduction.
+ """
+ world_size = get_world_size()
+ if world_size < 2:
+ return input_dict
+ with torch.no_grad():
+ names = []
+ values = []
+ # sort the keys so that they are consistent across processes
+ for k in sorted(input_dict.keys()):
+ names.append(k)
+ values.append(input_dict[k])
+ values = torch.stack(values, dim=0)
+ dist.reduce(values, dst=0)
+ if dist.get_rank() == 0 and average:
+ # only main process gets accumulated, so only divide by
+ # world_size in this case
+ values /= world_size
+ reduced_dict = {k: v for k, v in zip(names, values)}
+ return reduced_dict
+
+
+class NoOp(object):
+ """ useful for distributed training No-Ops """
+ def __getattr__(self, name):
+ return self.noop
+
+ def noop(self, *args, **kwargs):
+ return
+
+
+def decode_to_str(x):
+ try:
+ return x.decode('utf-8')
+ except UnicodeDecodeError:
+ return x.decode('latin-1')
+
+
+def cmd_run(list_cmd,
+ return_output=False,
+ env=None,
+ working_dir=None,
+ stdin=sp.PIPE,
+ shell=False,
+ dry_run=False,
+ silent=False,
+ process_input=None,
+ stdout=None,
+ ):
+ if not silent:
+ logging.info(
+ 'start to cmd run: {}'.format(' '.join(map(str, list_cmd))))
+ if working_dir:
+ logging.info(working_dir)
+ # if we dont' set stdin as sp.PIPE, it will complain the stdin is not a tty
+ # device. Maybe, the reson is it is inside another process.
+ # if stdout=sp.PIPE, it will not print the result in the screen
+ e = os.environ.copy()
+ if 'SSH_AUTH_SOCK' in e:
+ del e['SSH_AUTH_SOCK']
+ if working_dir:
+ os.makedirs(working_dir, exist_ok=True)
+ if env:
+ for k in env:
+ e[k] = env[k]
+ if dry_run:
+ # we need the log result. Thus, we do not return at teh very beginning
+ return
+ if not return_output:
+ # if env is None:
+ # p = sp.Popen(list_cmd, stdin=sp.PIPE, cwd=working_dir)
+ # else:
+ p = sp.Popen(' '.join(list_cmd) if shell else list_cmd,
+ stdin=stdin,
+ env=e,
+ shell=shell,
+ stdout=stdout,
+ cwd=working_dir)
+ message = p.communicate(input=process_input)
+ if p.returncode != 0:
+ raise ValueError(message)
+ return message
+ else:
+ if shell:
+ message = sp.check_output(
+ ' '.join(list_cmd),
+ env=e,
+ cwd=working_dir,
+ shell=True)
+ else:
+ message = sp.check_output(list_cmd,
+ env=e,
+ cwd=working_dir,
+ )
+ if not silent:
+ logging.info('finished the cmd run')
+ return decode_to_str(message)
+
+
+def broadcast(data, src=0):
+ output = dist.broadcast(data, src=src)
+ return output
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/lib.py b/One-to-All-Animation/benchmark/DisCo/utils/lib.py
new file mode 100644
index 0000000000000000000000000000000000000000..398be396ada824d102f7c4302aed57103e844ffc
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/lib.py
@@ -0,0 +1,36 @@
+
+import argparse, sys, os, io, base64, pickle, json, math, random
+from packaging import version
+import os.path as op
+import time, errno
+from easydict import EasyDict as edict
+from skimage.feature import hog as hog_feature
+from datetime import datetime
+from tqdm import tqdm
+import inspect
+
+import numpy as np
+import torch as T
+import torchvision as TV
+import torch.distributed as DIST
+
+import cv2
+from PIL import Image
+
+import transformers
+os.environ['TOKENIZERS_PARALLELISM'] = 'true'
+
+# from fairscale.nn.misc import checkpoint_wrapper
+from toolz.sandbox import unzip
+from collections import defaultdict
+from torch.utils.data import ConcatDataset
+from datetime import timedelta
+try:
+ import wandb
+ os.environ['WANDB_API_KEY'] = '' #TODO, update your WANDB API key here
+ WANDB_ENABLE = int(os.environ.get('WANDB_ENABLE', 1))
+ print('WANDB_ENABLE:', WANDB_ENABLE)
+except:
+ print("failed to load wandb")
+ WANDB_ENABLE = 0
+# import torchaudio
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/load_files.py b/One-to-All-Animation/benchmark/DisCo/utils/load_files.py
new file mode 100644
index 0000000000000000000000000000000000000000..f87eaa1007cd02f298215916d3594d894e4a140f
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/load_files.py
@@ -0,0 +1,85 @@
+import json
+import os
+import os.path as op
+import errno
+import yaml
+from collections import OrderedDict
+try:
+ from azfuse import File
+except ImportError:
+ print("azfuse is not installed")
+
+
+def load_labelmap_file(labelmap_file):
+ label_dict = None
+
+ if labelmap_file.endswith('json'):
+ label_dict = json.load(open(labelmap_file, 'r'))['label_to_idx']
+ label_dict = {key: val-1 for key, val in label_dict.items()}
+ return label_dict
+
+ if labelmap_file is not None and op.isfile(labelmap_file):
+ label_dict = OrderedDict()
+ with open(labelmap_file, 'r') as fp:
+ for line in fp:
+ label = line.strip().split('\t')[0]
+ if label in label_dict:
+ raise ValueError("Duplicate label " + label + " in labelmap.")
+ else:
+ label_dict[label] = len(label_dict)
+ return label_dict
+
+
+def config_dataset_file(data_dir, dataset_file):
+ if dataset_file:
+ if op.isfile(dataset_file):
+ dataset_file = dataset_file
+ elif op.isfile(op.join(data_dir, dataset_file)):
+ dataset_file = op.join(data_dir, dataset_file)
+ else:
+ raise ValueError("cannot find file: {}".format(dataset_file))
+ return dataset_file
+
+
+def load_linelist_file(linelist_file):
+ if linelist_file is not None:
+ line_list = []
+ with open(linelist_file, 'r') as fp:
+ for i in fp:
+ line_list.append(int(i.strip()))
+ return line_list
+
+
+def load_box_linelist_file(linelist_file):
+ if linelist_file is not None:
+ img_line_list = []
+ box_line_list = []
+ with open(linelist_file, 'r') as fp:
+ for i in fp:
+ idx = [int(_) for _ in i.strip().split('\t')]
+ img_line_list.append(idx[0])
+ box_line_list.append(idx[1])
+ return [img_line_list, box_line_list]
+
+
+def load_from_yaml_file(yaml_file):
+ try:
+ from azfuse import File
+ with File.open(yaml_file, 'r') as fp:
+ return yaml.load(fp.read(), Loader=yaml.CLoader)
+ except ImportError:
+ print("azfuse is not installed")
+ with open(yaml_file, 'r') as fp:
+ return yaml.load(fp, Loader=yaml.CLoader)
+
+
+def find_file_path_in_yaml(fname, root):
+ if fname is not None:
+ if op.isfile(fname):
+ return fname
+ elif op.isfile(op.join(root, fname)):
+ return op.join(root, fname)
+ else:
+ raise FileNotFoundError(
+ errno.ENOENT, os.strerror(errno.ENOENT), op.join(root, fname)
+ )
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/load_save.py b/One-to-All-Animation/benchmark/DisCo/utils/load_save.py
new file mode 100644
index 0000000000000000000000000000000000000000..1708e670aa9808b0613d20b76ba6baad32a39874
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/load_save.py
@@ -0,0 +1,338 @@
+"""
+saving utilities
+"""
+import json
+import os
+from os.path import dirname, exists, join, realpath
+from apex import amp
+from easydict import EasyDict as edict
+from .basic_utils import is_jsonable, save_json, make_zipfile
+
+import torch
+from .logger import LOGGER
+
+
+def save_training_meta(args):
+ # args is an EasyDict object, treat it the same as a normal dict
+ os.makedirs(join(args.output_dir, 'log'), exist_ok=True)
+ os.makedirs(join(args.output_dir, 'ckpt'), exist_ok=True)
+
+ # training args
+ save_args_path = join(args.output_dir, 'log', 'args.json')
+ save_json(args, save_args_path, save_pretty=True)
+
+ # model args
+ model_config = json.load(open(args.model_config))
+ save_model_config_path = join(args.output_dir, 'log', 'model_config.json')
+ save_json(model_config, save_model_config_path, save_pretty=True)
+
+ # save a copy of the codebase. !!!Do not store heavy file in your codebase when using it.
+ code_dir = dirname(dirname(dirname(realpath(__file__))))
+ code_zip_filename = os.path.join(args.output_dir, "code.zip")
+ LOGGER.info(f"Saving code from {code_dir} to {code_zip_filename}...")
+ make_zipfile(code_dir, code_zip_filename,
+ enclosing_dir="code",
+ exclude_dirs_substring="results",
+ exclude_dirs=["results", "debug_results", "__pycache__", "linjli"],
+ exclude_extensions=[".pyc", ".ipynb", ".swap"])
+ LOGGER.info(f"Saving code done.")
+
+
+class TrainingSaver(object):
+ def __init__(self, output_dir):
+ self.output_dir = output_dir
+ self.max_save_load_trial = 10
+
+ def save_tokenizer(self, tokenizer):
+ tokenizer_dir = join(self.output_dir, 'tokenizer')
+ os.makedirs(tokenizer_dir, exist_ok=True)
+ if tokenizer is not None:
+ tokenizer.save_pretrained(tokenizer_dir)
+
+ def save_args(self, args):
+ arg_dir = join(self.output_dir, 'log')
+ os.makedirs(arg_dir, exist_ok=True)
+ save_args_path = join(arg_dir, 'args.json')
+ LOGGER.info(f"Training/evaluation parameters: {args}")
+ LOGGER.info(f"saving args to {save_args_path}")
+ temp_args = edict(vars(args))
+ for key, value in temp_args.items():
+ if not is_jsonable(value):
+ value = f'{value}'
+ temp_args[key] = value
+ save_json(temp_args, save_args_path, save_pretty=True, sort_keys=True)
+
+ def save_model(self, checkpoint_dir, step, model, optimizer=None):
+ os.makedirs(checkpoint_dir, exist_ok=True)
+ model_path = join(checkpoint_dir, 'model.bin')
+ model_to_save = model.module if hasattr(model, 'module') else model
+ state_dict = {k: v.cpu() if isinstance(v, torch.Tensor) else v
+ for k, v in model_to_save.state_dict().items()}
+ # with retrial, as azure blob fails occasionally.
+ save_trial = 0
+ while save_trial < self.max_save_load_trial:
+ exception_msg = ''
+ try:
+ LOGGER.info(f"ModelSaver save trial NO. {save_trial}")
+ torch.save(state_dict, model_path)
+ if optimizer is not None:
+ optimizer_state_dict = {
+ k: v.cpu() if isinstance(v, torch.Tensor) else v
+ for k, v in optimizer.state_dict().items()}
+ dump = {'step': step, 'optimizer': optimizer_state_dict}
+ torch.save(
+ dump,
+ f'{checkpoint_dir}/optmizer_state.bin')
+ LOGGER.info(f"Save checkpoint to {checkpoint_dir}")
+ break
+ except Exception as e:
+ exception_msg = e
+ save_trial += 1
+ else:
+ LOGGER.info(
+ f"Failed to save checkpoint after {self.max_save_load_trial} trails, "
+ f"exception msg: {exception_msg}.")
+ return
+
+
+def load_state_dict_with_mismatch(model, loaded_state_dict_or_path):
+ """operated in-place, no need to return `model`"""
+
+ if isinstance(loaded_state_dict_or_path, str):
+ loaded_state_dict = torch.load(
+ loaded_state_dict_or_path, map_location="cpu")
+ else:
+ loaded_state_dict = loaded_state_dict_or_path
+ model_keys = set([k for k in list(model.state_dict().keys())])
+ load_keys = set(loaded_state_dict.keys())
+
+ toload = {}
+ mismatched_shape_keys = []
+ for k in model_keys:
+ if k in load_keys:
+ if model.state_dict()[k].shape != loaded_state_dict[k].shape:
+ mismatched_shape_keys.append(k)
+ else:
+ toload[k] = loaded_state_dict[k]
+
+ LOGGER.info("You can ignore the keys with `num_batches_tracked` or from task heads")
+ LOGGER.info("Keys in loaded but not in model:")
+ diff_keys = load_keys.difference(model_keys)
+ LOGGER.info(f"In total {len(diff_keys)}, {sorted(diff_keys)}")
+ LOGGER.info("Keys in model but not in loaded:")
+ diff_keys = model_keys.difference(load_keys)
+ LOGGER.info(f"In total {len(diff_keys)}, {sorted(diff_keys)}")
+ LOGGER.info("Keys in model and loaded, but shape mismatched:")
+ LOGGER.info(f"In total {len(mismatched_shape_keys)}, {sorted(mismatched_shape_keys)}")
+ model.load_state_dict(toload, strict=False)
+
+
+def compare_dict_difference(dict1, dict2, dict1_name="dict1",
+ dict2_name="dict2",
+ print_value_diff=True, verbose=False,
+ exclude_keys=()):
+ """
+ Args:
+ dict1:
+ dict2:
+ dict1_name:
+ dict2_name:
+ print_value_diff: bool, output dict value difference within shared keys
+ for dict1 and dict2. In effect only when verbose == True
+ verbose:
+ """
+ exclude_keys = set(exclude_keys)
+ keys1 = set(dict1.keys()).difference(exclude_keys)
+ keys2 = set(dict2.keys()).difference(exclude_keys)
+ shared_keys = keys1.intersection(keys2)
+ keys1_unique = keys1.difference(shared_keys)
+ keys2_unique = keys2.difference(shared_keys)
+ key_diff_list = list(keys1_unique) + list(keys2_unique)
+
+ # value difference in the shared keys in dict1 and dict2
+ value_diff_dict = {}
+ for k in shared_keys:
+ if dict1[k] != dict2[k]:
+ value_diff_dict[k] = [(dict1_name, dict1[k]), (dict2_name, dict2[k])]
+
+ if len(value_diff_dict) == 0 and len(key_diff_list) == 0:
+ return True
+
+ def print_value_diff():
+ if verbose and print_value_diff:
+ LOGGER.info("=" * 30 + "value difference")
+ LOGGER.info(f"{json.dumps(value_diff_dict, indent=4)}")
+
+ if len(value_diff_dict) > 0 and len(key_diff_list) == 0:
+ # OK
+ print_value_diff()
+ return True
+
+ if verbose:
+ LOGGER.info("=" * 30 + "key difference")
+ LOGGER.info(f"keys in {dict1_name} but not in {dict2_name}: "
+ f"total {len(keys1_unique)}, {sorted(keys1_unique)}")
+ LOGGER.info(f"keys in {dict2_name} but not in {dict1_name}: "
+ f"total {len(keys2_unique)}, {sorted(keys2_unique)}")
+ return False
+
+
+def _to_cuda(state):
+ """ usually load from cpu checkpoint but need to load to cuda """
+ if isinstance(state, torch.Tensor):
+ ret = state.cuda() # assume propoerly set py torch.cuda.set_device
+ if 'Half' in state.type():
+ ret = ret.float() # apex O2 requires it
+ return ret
+ elif isinstance(state, list):
+ new_state = [_to_cuda(t) for t in state]
+ elif isinstance(state, tuple):
+ new_state = tuple(_to_cuda(t) for t in state)
+ elif isinstance(state, dict):
+ new_state = {n: _to_cuda(t) for n, t in state.items()}
+ else:
+ return state
+ return new_state
+
+
+def _to_cpu(state):
+ """ store in cpu to avoid GPU0 device, fp16 to save space """
+ if isinstance(state, torch.Tensor):
+ ret = state.cpu()
+ if 'Float' in state.type():
+ ret = ret.half()
+ return ret
+ elif isinstance(state, list):
+ new_state = [_to_cpu(t) for t in state]
+ elif isinstance(state, tuple):
+ new_state = tuple(_to_cpu(t) for t in state)
+ elif isinstance(state, dict):
+ new_state = {n: _to_cpu(t) for n, t in state.items()}
+ else:
+ return state
+ return new_state
+
+
+
+class TrainingRestorer(object):
+ def __init__(self, args, model, optimizer):
+ if exists(f"{args.output_dir}/log/args.json"):
+ restore_args = json.load(
+ open(f'{args.output_dir}/log/args.json', 'r'))
+ restore_args_path = join(
+ args.output_dir, 'log',
+ 'restore_args.json')
+ temp_args = edict(vars(restore_args))
+ for key, value in temp_args.items():
+ if not is_jsonable(value):
+ value = f'{value}'
+ temp_args[key] = value
+ save_json(
+ temp_args, restore_args_path,
+ save_pretty=True, sort_keys=True)
+ assert compare_dict_difference(
+ args, restore_args, dict1_name="current_args",
+ dict2_name="restore_args",
+ print_value_diff=True, verbose=True,
+ exclude_keys=('local_rank'))
+ # keep 2 checkpoints in case of corrupted
+ self.save_path = f'{args.output_dir}/restore.pt'
+ self.backup_path = f'{args.output_dir}/restore_backup.pt'
+ self.model = model
+ self.optimizer = optimizer
+ self.min_restore_steps = 20
+ self.restorer_save_step = max(
+ self.min_restore_steps, int(args.restore_ratio * args.max_global_step))
+ # since saving to or loading from azure blob fails sometimes
+ self.max_save_load_trial = 10
+ self.amp = args.mixed_precision_method == "apex"
+ self.deepspeed = args.mixed_precision_method == "deepspeed" and args.restore_deepspeed_ckpt
+ if self.deepspeed:
+ self.save_path = f'{args.output_dir}/deepspeed_restore'
+ os.makedirs(self.save_path, exist_ok=True)
+ self.backup_path = f'{args.output_dir}/deepspeed_restore_backup'
+ os.makedirs(self.backup_path, exist_ok=True)
+ self.restore_at_init()
+
+ def restore_at_init(self):
+ if self.save_path.endswith(".pt"):
+ save_path = self.save_path
+ backup_path = self.backup_path
+ else:
+ # deepspeed
+ save_path = join(self.save_path, "restore_ckpt.pt")
+ backup_path = join(self.backup_path, "restore_ckpt.pt")
+ if exists(save_path) or exists(backup_path):
+ LOGGER.info('found previous checkpoint. try to resume...')
+ exception_msg = ''
+ # with retrial, as azure blob fails occasionally.
+ restore_trial = 0
+ while restore_trial < self.max_save_load_trial:
+ LOGGER.info(f"TrainingRestorer restore trial NO. {restore_trial}")
+ # try:
+ self.restore()
+ LOGGER.info(f"TrainingRestorer restore from global_step {self.global_step}")
+ break
+ # except Exception as e:
+ # exception_msg = e
+ # restore_trial += 1
+ # else:
+ # LOGGER.info(
+ # f"TrainingRestorer restore failed after {self.max_save_load_trial} trails, "
+ # f"exception msg: {exception_msg}.")
+ else:
+ self.global_step = 0
+
+ def step(self):
+ self.global_step += 1
+ if self.global_step % self.restorer_save_step == 0:
+ # with retrial, as azure blob fails occasionally.
+ save_trial = 0
+ while save_trial < self.max_save_load_trial:
+ LOGGER.info(f"TrainingRestorer save trial NO. {save_trial}")
+ try:
+ self.save()
+ break
+ except Exception as e:
+ save_trial += 1
+
+ def save(self):
+ checkpoint = {'global_step': self.global_step}
+ if not self.deepspeed:
+ # model_to_save = self.model.module if hasattr(self.model, 'module') else self.model
+ checkpoint['model_state_dict'] = _to_cpu(self.model.state_dict())
+ checkpoint['optim_state_dict'] = _to_cpu(self.optimizer.state_dict())
+ if self.amp:
+ checkpoint['amp_state_dict'] = amp.state_dict()
+ if exists(self.save_path):
+ os.rename(self.save_path, self.backup_path)
+ torch.save(checkpoint, self.save_path)
+ else:
+ # deepspeed, not efficient
+ if exists(self.save_path):
+ os.rename(self.save_path, self.backup_path)
+ else:
+ self.model.save_checkpoint(self.save_path)
+ torch.save(checkpoint, join(self.save_path, "restore_ckpt.pt"))
+
+ def restore(self):
+ if not self.deepspeed:
+ try:
+ checkpoint = torch.load(self.save_path)
+ except Exception:
+ checkpoint = torch.load(self.backup_path)
+ self.model.load_state_dict(_to_cuda(checkpoint['model_state_dict']))
+ self.optimizer.load_state_dict(
+ _to_cuda(checkpoint['optim_state_dict']))
+ if self.amp:
+ amp.load_state_dict(checkpoint['amp_state_dict'])
+ else:
+ # deepspeed, not efficient
+ try:
+ checkpoint = torch.load(join(self.save_path, "restore_ckpt.pt"))
+ self.model.load_checkpoint(self.save_path)
+ except Exception:
+ checkpoint = torch.load(join(self.backup_path, "restore_ckpt.pt"))
+ self.model.load_checkpoint(self.backup_path)
+ self.global_step = checkpoint['global_step']
+ LOGGER.info(f'resume training from step {self.global_step}')
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/logger.py b/One-to-All-Animation/benchmark/DisCo/utils/logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..1969082294bd3cf8021978821ba66bd3e11477b7
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/logger.py
@@ -0,0 +1,188 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+import logging
+import os
+from logging import StreamHandler, Handler, getLevelName
+
+
+# this class is a copy of logging.FileHandler except we end self.close()
+# at the end of each emit. While closing file and reopening file after each
+# write is not efficient, it allows us to see partial logs when writing to
+# fused Azure blobs, which is very convenient
+class FileHandler(StreamHandler):
+ """
+ A handler class which writes formatted logging records to disk files.
+ """
+ def __init__(self, filename, mode='a', encoding=None, delay=False):
+ """
+ Open the specified file and use it as the stream for logging.
+ """
+ # Issue #27493: add support for Path objects to be passed in
+ filename = os.fspath(filename)
+ #keep the absolute path, otherwise derived classes which use this
+ #may come a cropper when the current directory changes
+ self.baseFilename = os.path.abspath(filename)
+ self.mode = mode
+ self.encoding = encoding
+ self.delay = delay
+ if delay:
+ #We don't open the stream, but we still need to call the
+ #Handler constructor to set level, formatter, lock etc.
+ Handler.__init__(self)
+ self.stream = None
+ else:
+ StreamHandler.__init__(self, self._open())
+
+ def close(self):
+ """
+ Closes the stream.
+ """
+ self.acquire()
+ try:
+ try:
+ if self.stream:
+ try:
+ self.flush()
+ finally:
+ stream = self.stream
+ self.stream = None
+ if hasattr(stream, "close"):
+ stream.close()
+ finally:
+ # Issue #19523: call unconditionally to
+ # prevent a handler leak when delay is set
+ StreamHandler.close(self)
+ finally:
+ self.release()
+
+ def _open(self):
+ """
+ Open the current base file with the (original) mode and encoding.
+ Return the resulting stream.
+ """
+ return open(self.baseFilename, self.mode, encoding=self.encoding)
+
+ def emit(self, record):
+ """
+ Emit a record.
+
+ If the stream was not opened because 'delay' was specified in the
+ constructor, open it before calling the superclass's emit.
+ """
+ if self.stream is None:
+ self.stream = self._open()
+ StreamHandler.emit(self, record)
+ self.close()
+
+ def __repr__(self):
+ level = getLevelName(self.level)
+ return '<%s %s (%s)>' % (
+ self.__class__.__name__, self.baseFilename, level)
+
+
+_LOG_FMT = '%(asctime)s - %(levelname)s - %(name)s - %(message)s'
+_DATE_FMT = '%m/%d/%Y %H:%M:%S'
+logging.basicConfig(format=_LOG_FMT, datefmt=_DATE_FMT, level=logging.INFO)
+LOGGER = logging.getLogger('__main__') # this is the global logger
+logging.getLogger('matplotlib.font_manager').disabled = True # cclin
+from .common import init_logging
+init_logging()
+
+# def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
+# logger = logging.getLogger(name)
+# logger.setLevel(logging.INFO)
+# # don't log results for the non-master process
+# if distributed_rank > 0:
+# return logger
+# ch = logging.StreamHandler(stream=sys.stdout)
+# ch.setLevel(logging.INFO)
+# formatter = logging.Formatter(_LOG_FMT, datefmt=_DATE_FMT)
+# ch.setFormatter(formatter)
+# logger.addHandler(ch)
+
+# if save_dir:
+# fh = FileHandler(os.path.join(save_dir, filename))
+# fh.setLevel(logging.INFO)
+# fh.setFormatter(formatter)
+# logger.addHandler(fh)
+
+# logging.getLogger('matplotlib.font_manager').disabled = True # cclin
+# return logger
+
+
+def add_log_to_file(log_path):
+ fh = FileHandler(log_path)
+ formatter = logging.Formatter(_LOG_FMT, datefmt=_DATE_FMT)
+ fh.setFormatter(formatter)
+ LOGGER.addHandler(fh)
+
+
+from tensorboardX import SummaryWriter
+
+class TensorboardLogger(object):
+ def __init__(self):
+ self._logger = None
+ self._global_step = 0
+
+ def create(self, path):
+ self._logger = SummaryWriter(path)
+
+ def noop(self, *args, **kwargs):
+ return
+
+ def step(self):
+ self._global_step += 1
+
+ @property
+ def global_step(self):
+ return self._global_step
+
+ @global_step.setter
+ def global_step(self, step):
+ self._global_step = step
+
+ def log_scalar_dict(self, log_dict, prefix=''):
+ """ log a dictionary of scalar values"""
+ if self._logger is None:
+ return
+ if prefix:
+ prefix = f'{prefix}_'
+ for name, value in log_dict.items():
+ if isinstance(value, dict):
+ self.log_scalar_dict(value, self._global_step,
+ prefix=f'{prefix}{name}')
+ else:
+ self._logger.add_scalar(f'{prefix}{name}', value,
+ self._global_step)
+
+ def __getattr__(self, name):
+ if self._logger is None:
+ return self.noop
+ return self._logger.__getattribute__(name)
+
+
+TB_LOGGER = TensorboardLogger()
+
+
+class RunningMeter(object):
+ """ running meteor of a scalar value
+ (useful for monitoring training loss)
+ """
+ def __init__(self, name, val=None, smooth=0.99):
+ self._name = name
+ self._sm = smooth
+ self._val = val
+
+ def __call__(self, value):
+ self._val = (value if self._val is None
+ else value*(1-self._sm) + self._val*self._sm)
+
+ def __str__(self):
+ return f'{self._name}: {self._val:.4f}'
+
+ @property
+ def val(self):
+ return self._val
+
+ @property
+ def name(self):
+ return self._name
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/metric_logger.py b/One-to-All-Animation/benchmark/DisCo/utils/metric_logger.py
new file mode 100644
index 0000000000000000000000000000000000000000..8b829d0bfbd0816a451b509d74d45c9041244a04
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/metric_logger.py
@@ -0,0 +1,312 @@
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+from collections import defaultdict
+from collections import deque
+import os
+
+import torch
+
+from .dist import is_main_process
+try:
+ import wandb
+ WANDB_ENABLE = True
+except:
+ print("failed to load wandb")
+ WANDB_ENABLE = False
+# import torchaudio
+
+
+def log_dict_to_wandb(log_dict, step, prefix=""):
+ """include a separator `/` at the end of `prefix`"""
+ if not WANDB_ENABLE:
+ return
+ if not is_main_process():
+ return
+ if torch.distributed.get_rank() != 0:
+ return
+
+ log_dict = {f"{prefix}{k}": v for k, v in log_dict.items()}
+ wandb.log(log_dict, step)
+
+def log_img_to_wandb(img_dict, step):
+ """include a separator `/` at the end of `prefix`"""
+ if not WANDB_ENABLE:
+ return
+ if not is_main_process():
+ return
+ if torch.distributed.get_rank() != 0:
+ return
+
+ wandb.log(img_dict, step)
+
+def setup_wandb(args, project, name, entity=None):
+ if not (WANDB_ENABLE and is_main_process()):
+ return
+ if torch.distributed.get_rank() != 0:
+ return
+
+ print('init wandb for the main process')
+ run = wandb.init(
+ config=args,
+ project=project,
+ entity=entity,
+ name=name,
+ reinit=True
+ )
+ return run
+
+# class SmoothedValue(object):
+# """Track a series of values and provide access to smoothed values over a
+# window or the global series average.
+# """
+
+# def __init__(self, window_size=20):
+# self.deque = deque(maxlen=window_size)
+# # self.series = []
+# self.total = 0.0
+# self.count = 0
+
+# def update(self, value):
+# self.deque.append(value)
+# # self.series.append(value)
+# self.count += 1
+# self.total += value
+
+# @property
+# def median(self):
+# d = torch.tensor(list(self.deque))
+# return d.median().item()
+
+# @property
+# def avg(self):
+# d = torch.tensor(list(self.deque))
+# return d.mean().item()
+
+# @property
+# def global_avg(self):
+# return self.total / self.count
+
+# @property
+# def last_value(self):
+# return self.deque[-1]
+
+
+# class MetricLogger(object):
+# def __init__(self, delimiter="\t"):
+# self.meters = {}
+# self.params = {}
+# self.delimiter = delimiter
+
+# def update_params(self, update_dict):
+# for param_group, group_dict in update_dict.items():
+# if param_group not in self.params:
+# self.params[param_group] = {}
+# for param_name, param_value in group_dict.items():
+# # skipping parameters if they start with '_'
+# if param_name.startswith('_'):
+# continue
+# if isinstance(param_value, torch.Tensor):
+# param_value = param_value.item()
+# assert isinstance(param_value, (float, int))
+# self.params[param_group][param_name] = param_value
+
+# def update_metrics(self, update_dict):
+# for metric_group, group_dict in update_dict.items():
+# if metric_group not in self.meters:
+# self.meters[metric_group] = defaultdict(SmoothedValue)
+# for metric_name, metric_value in group_dict.items():
+# # skipping metrics if they start with '_'
+# if metric_name.startswith('_'):
+# continue
+# if isinstance(metric_value, torch.Tensor):
+# metric_value = metric_value.item()
+# assert isinstance(metric_value, (float, int))
+# self.meters[metric_group][metric_name].update(metric_value)
+
+# def get_logs(self, iteration):
+# return_str = []
+# if len(self.meters) > 0:
+# offset_m = max([len(group_name) for group_name in self.meters.keys()])
+# else:
+# offset_m = 0
+# if len(self.params) > 0:
+# offset_p = max([len(group_name) for group_name in self.params.keys()])
+# else:
+# offset_p = 0
+# offset = max(offset_m, offset_p)
+
+# for group_name, values in sorted(self.meters.items(),
+# key=lambda x: x[0]):
+# loss_str = []
+# for name, meter in values.items():
+# loss_str.append("{}: {:.4f} ({:.4f})".format(
+# name, meter.median, meter.global_avg,
+# ))
+# return_str.append(
+# "{:{offset}s} - {}".format(
+# group_name, self.delimiter.join(loss_str), offset=offset,
+# ),
+# )
+# for group_name, values in self.params.items():
+# loss_str = []
+# for name, param in values.items():
+# loss_str.append("{}: {:.2e}".format(name, param))
+# return_str.append(
+# "{:{offset}s} - {}".format(
+# group_name, self.delimiter.join(loss_str), offset=offset,
+# ),
+# )
+# return "\n ".join(return_str)
+
+class SmoothedValue(object):
+ def __init__(self, window_size=10):
+ self.deque = deque(maxlen=window_size)
+ self.total = 0.0
+ self.count = 0
+
+ def update(self, value):
+ self.deque.append(value)
+ self.count += 1
+ self.total += value
+
+ @property
+ def median(self):
+ d = torch.tensor(list(self.deque))
+ return d.median().item()
+
+ @property
+ def avg(self):
+ d = torch.tensor(list(self.deque))
+ return d.mean().item()
+
+ @property
+ def global_avg(self):
+ return self.total / self.count
+
+
+class MetricLogger(object):
+ def __init__(self, delimiter="\t", meter_creator=SmoothedValue):
+ self.meters = defaultdict(meter_creator)
+ self.delimiter = delimiter
+
+ def update(self, **kwargs):
+ for k, v in kwargs.items():
+ if isinstance(v, torch.Tensor):
+ v = v.item()
+ assert isinstance(v, (float, int))
+ self.meters[k].update(v)
+
+ def __getattr__(self, attr):
+ if attr in self.meters:
+ return self.meters[attr]
+ if attr in self.__dict__:
+ return self.__dict__[attr]
+ raise AttributeError("'{}' object has no attribute '{}'".format(
+ type(self).__name__, attr))
+
+ def __str__(self):
+ loss_str = []
+ for name, meter in self.meters.items():
+ loss_str.append(
+ "{}: {:.4f} ({:.4f})".format(name, meter.median, meter.global_avg)
+ )
+ return self.delimiter.join(loss_str)
+
+
+class TensorboardLogger(MetricLogger):
+ def __init__(self,
+ log_dir,
+ delimiter='\t',
+ philly_log_dir=None):
+ super(TensorboardLogger, self).__init__(delimiter)
+ try:
+ from tensorboardX import SummaryWriter
+ except ImportError:
+ raise ImportError(
+ 'To use tensorboard please install tensorboardX '
+ '[ pip install tensorboardx ].'
+ )
+ self.philly_tb_logger = None
+ self.philly_tb_logger_avg = None
+ self.philly_tb_logger_med = None
+ if is_main_process():
+ self.tb_logger = SummaryWriter(log_dir)
+ self.tb_logger_avg = SummaryWriter(os.path.join(log_dir, 'avg'))
+ self.tb_logger_med = SummaryWriter(os.path.join(log_dir, 'med'))
+ if philly_log_dir is not None:
+ self.philly_tb_logger = SummaryWriter(philly_log_dir)
+ self.philly_tb_logger_avg = SummaryWriter(os.path.join(philly_log_dir, 'avg'))
+ self.philly_tb_logger_med = SummaryWriter(os.path.join(philly_log_dir, 'med'))
+ else:
+ self.tb_logger = None
+ self.tb_logger_avg = None
+ self.tb_logger_med = None
+
+ def get_logs(self, iteration):
+ if self.tb_logger:
+ for group_name, values in self.meters.items():
+ for name, meter in values.items():
+ self.tb_logger.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.last_value, iteration,
+ )
+ self.tb_logger_avg.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.avg, iteration,
+ )
+ self.tb_logger_med.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.median, iteration,
+ )
+ if self.philly_tb_logger:
+ self.philly_tb_logger.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.last_value, iteration,
+ )
+ self.philly_tb_logger_avg.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.avg, iteration,
+ )
+ self.philly_tb_logger_med.add_scalar(
+ '{}/{}'.format(group_name, name),
+ meter.median, iteration,
+ )
+ for group_name, values in self.params.items():
+ for name, param in values.items():
+ self.tb_logger.add_scalar(
+ '{}/{}'.format(group_name, name),
+ param, iteration,
+ )
+ if self.philly_tb_logger:
+ self.philly_tb_logger.add_scalar(
+ '{}/{}'.format(group_name, name),
+ param, iteration,
+ )
+ return super(TensorboardLogger, self).get_logs(iteration)
+
+ def close(self):
+ if is_main_process():
+ self.tb_logger.close()
+ self.tb_logger_avg.close()
+ self.tb_logger_med.close()
+ if self.philly_tb_logger:
+ self.philly_tb_logger.close()
+ self.philly_tb_logger_avg.close()
+ self.philly_tb_logger_med.close()
+
+
+class AverageMeter(object):
+ """Computes and stores the average and current value"""
+ def __init__(self):
+ self.reset()
+
+ def reset(self):
+ self.val = 0
+ self.avg = 0
+ self.sum = 0
+ self.count = 0
+
+ def update(self, val, n=1):
+ self.val = val
+ self.sum += val * n
+ self.count += n
+ self.avg = self.sum / self.count
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/misc.py b/One-to-All-Animation/benchmark/DisCo/utils/misc.py
new file mode 100644
index 0000000000000000000000000000000000000000..1d8305fbbaaec4310f61e7165f495b201a386727
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/misc.py
@@ -0,0 +1,292 @@
+from utils.lib import *
+
+
+# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
+import errno
+import os
+import os.path as op
+import re
+import logging
+import numpy as np
+import torch
+import random
+import shutil
+from .dist import is_main_process
+import yaml
+from .logger import LOGGER as logger
+from pprint import pformat
+from .common import limited_retry_agent, exclusive_open_to_read
+
+
+def humanbytes(B):
+ 'Return the given bytes as a human friendly KB, MB, GB, or TB string'
+ B = float(B)
+ KB = float(1024)
+ MB = float(KB ** 2) # 1,048,576
+ GB = float(KB ** 3) # 1,073,741,824
+ TB = float(KB ** 4) # 1,099,511,627,776
+
+ if B < KB:
+ return '{0} {1}'.format(B, 'Bytes' if 0 == B > 1 else 'Byte')
+ elif KB <= B < MB:
+ return '{0:.2f} KB'.format(B/KB)
+ elif MB <= B < GB:
+ return '{0:.2f} MB'.format(B/MB)
+ elif GB <= B < TB:
+ return '{0:.2f} GB'.format(B/GB)
+ elif TB <= B:
+ return '{0:.2f} TB'.format(B/TB)
+
+
+def ensure_directory(path):
+ if path == '' or path == '.':
+ return
+ if path != None and len(path) > 0:
+ assert not op.isfile(path), '{} is a file'.format(path)
+ if not os.path.exists(path) and not op.islink(path):
+ try:
+ os.makedirs(path)
+ except:
+ if os.path.isdir(path):
+ # another process has done makedir
+ pass
+ else:
+ raise
+
+
+def get_user_name():
+ import getpass
+ return getpass.getuser()
+
+
+def acquireLock(lock_f='/tmp/lockfile.LOCK'):
+ ''' acquire exclusive lock file access '''
+ import fcntl
+ locked_file_descriptor = open(lock_f, 'w+')
+ fcntl.lockf(locked_file_descriptor, fcntl.LOCK_EX)
+ return locked_file_descriptor
+
+
+def releaseLock(locked_file_descriptor):
+ ''' release exclusive lock file access '''
+ locked_file_descriptor.close()
+
+
+def hash_sha1(s):
+ import hashlib
+ if type(s) is not str:
+ s = pformat(s)
+ return hashlib.sha1(s.encode('utf-8')).hexdigest()
+
+
+def print_trace():
+ import traceback
+ traceback.print_exc()
+
+
+class NoOp(object):
+ """ useful for distributed training No-Ops """
+ def __getattr__(self, name):
+ return self.noop
+
+ def noop(self, *args, **kwargs):
+ return
+
+
+def str_to_bool(value):
+ if value.lower() in {'false', 'f', '0', 'no', 'n'}:
+ return False
+ elif value.lower() in {'true', 't', '1', 'yes', 'y'}:
+ return True
+ raise ValueError(f'{value} is not a valid boolean value')
+
+
+def mkdir(path):
+ # if it is the current folder, skip.
+ # otherwise the original code will raise FileNotFoundError
+ if path == '':
+ return
+ try:
+ os.makedirs(path)
+ except OSError as e:
+ if e.errno != errno.EEXIST:
+ raise
+
+
+def save_config(cfg, path):
+ if is_main_process():
+ with open(path, 'w') as f:
+ f.write(cfg.dump())
+
+
+def config_iteration(output_dir, max_iter):
+ save_file = os.path.join(output_dir, 'last_checkpoint')
+ iteration = -1
+ if os.path.exists(save_file):
+ with open(save_file, 'r') as f:
+ fname = f.read().strip()
+ model_name = os.path.basename(fname)
+ model_path = os.path.dirname(fname)
+ if model_name.startswith('model_') and len(model_name) == 17:
+ iteration = int(model_name[-11:-4])
+ elif model_name == "model_final":
+ iteration = max_iter
+ elif model_path.startswith('checkpoint-') and len(model_path) == 18:
+ iteration = int(model_path.split('-')[-1])
+ return iteration
+
+
+def get_matching_parameters(model, regexp, none_on_empty=True):
+ """Returns parameters matching regular expression"""
+ if not regexp:
+ if none_on_empty:
+ return {}
+ else:
+ return dict(model.named_parameters())
+ compiled_pattern = re.compile(regexp)
+ params = {}
+ for weight_name, weight in model.named_parameters():
+ if compiled_pattern.match(weight_name):
+ params[weight_name] = weight
+ return params
+
+
+def freeze_weights(model, regexp):
+ """Freeze weights based on regular expression."""
+ for weight_name, weight in get_matching_parameters(model, regexp).items():
+ weight.requires_grad = False
+ logger.info("Disabled training of {}".format(weight_name))
+
+
+def unfreeze_weights(model, regexp, backbone_freeze_at=-1,
+ is_distributed=False):
+ """
+ WARNING: This is not fully tested and may have issues. Now it is not used
+ during training but keep it here for future reference.
+ Unfreeze weights based on regular expression.
+ This is helpful during training to unfreeze freezed weights after
+ other unfreezed weights have been trained for some iterations.
+ """
+ for weight_name, weight in get_matching_parameters(model, regexp).items():
+ weight.requires_grad = True
+ logger.info("Enabled training of {}".format(weight_name))
+ if backbone_freeze_at >= 0:
+ logger.info("Freeze backbone at stage: {}".format(backbone_freeze_at))
+ if is_distributed:
+ model.module.backbone.body._freeze_backbone(backbone_freeze_at)
+ else:
+ model.backbone.body._freeze_backbone(backbone_freeze_at)
+
+
+def delete_tsv_files(tsvs):
+ for t in tsvs:
+ if op.isfile(t):
+ try_delete(t)
+ line = op.splitext(t)[0] + '.lineidx'
+ if op.isfile(line):
+ try_delete(line)
+
+
+def concat_files(ins, out):
+ mkdir(op.dirname(out))
+ out_tmp = out + '.tmp'
+ with open(out_tmp, 'wb') as fp_out:
+ for i, f in enumerate(ins):
+ logging.info('concating {}/{} - {}'.format(i, len(ins), f))
+ with open(f, 'rb') as fp_in:
+ shutil.copyfileobj(fp_in, fp_out, 1024*1024*10)
+ os.rename(out_tmp, out)
+
+
+def concat_tsv_files(tsvs, out_tsv):
+ concat_files(tsvs, out_tsv)
+ sizes = [os.stat(t).st_size for t in tsvs]
+ sizes = np.cumsum(sizes)
+ all_idx = []
+ for i, t in enumerate(tsvs):
+ for idx in load_list_file(op.splitext(t)[0] + '.lineidx'):
+ if i == 0:
+ all_idx.append(idx)
+ else:
+ all_idx.append(str(int(idx) + sizes[i - 1]))
+ with open(op.splitext(out_tsv)[0] + '.lineidx', 'w') as f:
+ f.write('\n'.join(all_idx))
+
+
+def load_list_file(fname):
+ with open(fname, 'r') as fp:
+ lines = fp.readlines()
+ result = [line.strip() for line in lines]
+ if len(result) > 0 and result[-1] == '':
+ result = result[:-1]
+ return result
+
+
+def try_once(func):
+ def func_wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except Exception as e:
+ logging.info('ignore error \n{}'.format(str(e)))
+ return func_wrapper
+
+
+@try_once
+def try_delete(f):
+ os.remove(f)
+
+
+def set_seed(seed, n_gpu):
+ random.seed(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ if n_gpu > 0:
+ torch.cuda.manual_seed_all(seed)
+
+
+def print_and_run_cmd(cmd):
+ print(cmd)
+ os.system(cmd)
+
+
+def write_to_yaml_file(context, file_name):
+ with open(file_name, 'w') as fp:
+ yaml.dump(context, fp, encoding='utf-8')
+
+
+def load_from_yaml_file(yaml_file):
+ with open(yaml_file, 'r') as fp:
+ return yaml.load(fp, Loader=yaml.CLoader)
+
+
+def parse_yaml_file(yaml_file):
+ r = re.compile('.*fea.*lab.*.yaml')
+ temp = op.basename(yaml_file).split('.')
+ split_name = temp[0]
+ if r.match(yaml_file) is not None:
+ fea_folder = '.'.join(temp[temp.index('fea') + 1 : temp.index('lab')])
+ lab_folder = '.'.join(temp[temp.index('lab') + 1 : -1])
+ else:
+ fea_folder, lab_folder = None, None
+ return split_name, fea_folder, lab_folder
+
+
+def check_yaml_file(yaml_file):
+ # check yaml file, generate if possible
+ if not op.isfile(yaml_file):
+ try:
+ split_name, fea_folder, lab_folder = parse_yaml_file(yaml_file)
+ if fea_folder and lab_folder:
+ base_yaml_file = op.join(op.dirname(yaml_file), split_name + '.yaml')
+ if op.isfile(base_yaml_file):
+ data = load_from_yaml_file(base_yaml_file)
+ data['feature'] = op.join(fea_folder, split_name + '.feature.tsv')
+ data['label'] = op.join(lab_folder, split_name + '.label.tsv')
+ assert op.isfile(op.join(op.dirname(base_yaml_file), data['feature']))
+ assert op.isfile(op.join(op.dirname(base_yaml_file), data['label']))
+ if is_main_process():
+ write_to_yaml_file(data, yaml_file)
+ print("generate yaml file: {}".format(yaml_file))
+ except:
+ raise ValueError("yaml file: {} does not exist and cannot create it".format(yaml_file))
+
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/process_image.py b/One-to-All-Animation/benchmark/DisCo/utils/process_image.py
new file mode 100644
index 0000000000000000000000000000000000000000..5c0c05504d03ffc7bb1e83a3c23c67340b98ce88
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/process_image.py
@@ -0,0 +1,424 @@
+import numpy as np
+import base64
+import cv2
+import os
+from .common import ensure_directory
+from .common import network_input_to_image
+from .common import encoded_from_img
+import matplotlib.pyplot as plt
+from random import random
+import logging
+from .common import is_pil_image
+from PIL import Image
+
+
+def cvimg_to_pil(im):
+ im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
+ return Image.fromarray(im)
+
+def copy_make_border(im, top, bottom, left, right):
+ if is_pil_image(im):
+ w, h = im.size
+ w2 = w + left + right
+ h2 = top + bottom + h
+ im2 = Image.new('RGB', (w2, h2))
+ im2.paste(im, (left, top, left + w, top + h))
+ return im2
+ else:
+ im_squared = cv2.copyMakeBorder(im, top=top, bottom=bottom, left=left, right=right,
+ borderType=cv2.BORDER_CONSTANT, value=(0, 0, 0))
+ return im_squared
+
+def im_rescale(im, target_size):
+ if is_pil_image(im):
+ w, h = im.size
+ if w > h:
+ if w == target_size:
+ return im, 1
+ w2 = target_size
+ h2 = (w2 * h + w - 1) // w
+ im_scale = 1. * w2 / w
+ else:
+ if h == target_size:
+ return im, 1
+ h2 = target_size
+ w2 = (h2 * w + h - 1) // h
+ im_scale = 1. * h2 / h
+ #im_resized = im.resize((w2, h2), PIL.Image.BILINEAR)
+ im_resized = im.resize((w2, h2))
+ return im_resized, im_scale
+ else:
+ im_size_max = max(im.shape[0:2])
+ if target_size == im_size_max:
+ return im, 1
+ im_scale = float(target_size) / float(im_size_max)
+ im_resized = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,
+ interpolation=cv2.INTER_LINEAR)
+ return im_resized, im_scale
+
+def gen_colors(num_real_classes):
+ colors = []
+ for c in range(num_real_classes):
+ colors.append(np.random.rand(3))
+ return colors
+
+def draw_rects(rects, im=None, add_label=True, style=None):
+ if im is None:
+ im = np.zeros((1000, 1000, 3), dtype=np.uint8)
+ probs = None
+ if all('conf' in r for r in rects):
+ probs = [r['conf'] for r in rects]
+ draw_bb(im,
+ [r['rect'] for r in rects],
+ [r['class'] for r in rects],
+ probs=probs,
+ draw_label=add_label,
+ style=style)
+ return im
+
+def put_text(im, text, bottomleft=(0,100),
+ color=(255,255,255), font_scale=0.5,
+ font_thickness=1):
+ font = cv2.FONT_HERSHEY_SIMPLEX
+ if hasattr(cv2, 'UMat'):
+ im2 = cv2.putText(cv2.UMat(im),text,bottomleft,
+ font,font_scale, color,
+ thickness=font_thickness)
+ im[:] = im2.get()
+ else:
+ cv2.putText(im,text,bottomleft,
+ font,font_scale, color,
+ thickness=font_thickness)
+ return cv2.getTextSize(text, font, font_scale, font_thickness)[0]
+
+def show_net_input_image(data, mean_value=[104, 117, 123], std_value=[1, 1, 1],
+ save_to_file=None):
+ all_image = network_input_to_image(data, mean_value, std_value)
+ for i in range(len(all_image)):
+ if save_to_file:
+ save_image(all_image[i], save_to_file+'{}.jpg'.format(i))
+ else:
+ show_image(all_image[i])
+
+def show_net_input(data, label, max_image_to_show=None,
+ mean_value=[104, 117, 123], std_value=[1, 1, 1],
+ save_to_file=None, draw_label=True):
+ all_image = network_input_to_image(data, mean_value, std_value)
+ num_image = data.shape[0]
+ num_rect = label.shape[1] // 5
+ if max_image_to_show:
+ num_image = min(max_image_to_show, num_image)
+ im_height = all_image[0].shape[0]
+ im_width = all_image[0].shape[1]
+ for i in range(num_image):
+ rects = []
+ txts = []
+ for j in range(num_rect):
+ if label[i, j * 5] == 0:
+ break
+ cx, cy, w, h = label[i, (j * 5 + 0) : (j * 5 + 4)]
+ txt = str(label[i, j * 5 + 4])
+ cx = cx * (im_width - 1)
+ cy = cy * (im_height - 1)
+ w = w * (im_width - 1)
+ h = h * (im_height - 1)
+ rects.append((cx - 0.5 * w, cy - 0.5 * h, cx + 0.5 * w, cy + 0.5 *
+ h))
+ txts.append(txt)
+ draw_bb(all_image[i], rects, txts, draw_label=draw_label)
+ if save_to_file:
+ save_image(all_image[i], save_to_file+'{}.jpg'.format(i))
+ else:
+ show_image(all_image[i])
+
+def drawline(img,pt1,pt2,color,thickness=1,style='dotted',gap=None):
+ dist =((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2)**.5
+ if gap is None:
+ gap = thickness * 3
+ pts= []
+ for i in np.arange(0,dist,gap):
+ r=i/dist
+ x=int((pt1[0]*(1-r)+pt2[0]*r)+.5)
+ y=int((pt1[1]*(1-r)+pt2[1]*r)+.5)
+ p = (x,y)
+ pts.append(p)
+
+ if style=='dotted':
+ for p in pts:
+ cv2.circle(img,p,thickness,color,-1)
+ else:
+ s=pts[0]
+ e=pts[0]
+ i=0
+ for p in pts:
+ s=e
+ e=p
+ if i%2==1:
+ cv2.line(img,s,e,color,thickness)
+ i+=1
+
+def drawpoly(img,pts,color,thickness=1,style='dotted',):
+ s=pts[0]
+ e=pts[0]
+ pts.append(pts.pop(0))
+ for p in pts:
+ s=e
+ e=p
+ drawline(img,s,e,color,thickness,style)
+
+def draw_dotted_rect(img,pt1,pt2,color,thickness=1):
+ pts = [pt1,(pt2[0],pt1[1]),pt2,(pt1[0],pt2[1])]
+ drawpoly(img,pts,color,thickness,style='dotted')
+
+__label_to_color = {}
+__gold_colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255),
+ (0, 255, 255),
+ ]
+
+def rectangle(img, *args, **kwargs):
+ if hasattr(cv2, 'UMat'):
+ im2 = cv2.rectangle(cv2.UMat(img), *args, **kwargs)
+ img[:] = im2.get()
+ else:
+ cv2.rectangle(img, *args, **kwargs)
+
+def draw_bb(im, all_rect, all_label,
+ probs=None,
+ color=None,
+ font_scale=None,
+ font_thickness=None,
+ #rect_thickness=2,
+ draw_label=True,
+ style=None):
+ '''
+ all_rect: x0, y0, x1, y1
+ '''
+ ref = sum(im.shape[:2]) // 2
+
+ if font_scale is None:
+ font_scale = ref / 500.
+ if font_thickness is None:
+ font_thickness = max(ref // 300, 1)
+ rect_thickness = max(ref // 250, 1)
+ # in python3, it is float, and we need to convert it to integer
+ font_thickness = int(font_thickness)
+ rect_thickness = int(rect_thickness)
+
+ dist_label = set(all_label)
+ if color is None:
+ color = {}
+ color = __label_to_color
+ for l in dist_label:
+ if l in color:
+ continue
+ if len(__gold_colors) > 0:
+ color[l] = __gold_colors.pop()
+ for i, l in enumerate(dist_label):
+ if l in color:
+ continue
+ color[l] = (random() * 255., random() * 255, random() * 255)
+
+ if type(all_rect) is list:
+ assert len(all_rect) == len(all_label)
+ elif type(all_rect) is np.ndarray:
+ assert all_rect.shape[0] == len(all_label)
+ assert all_rect.shape[1] == 4
+ else:
+ assert False
+
+ all_filled_region = []
+ all_put_text = []
+ placed_position = {}
+ for i in range(len(all_label)):
+ rect = all_rect[i]
+ label = all_label[i]
+ if style == 'dotted':
+ draw_dotted_rect(im, (int(rect[0]), int(rect[1])),
+ (int(rect[2]), int(rect[3])),
+ color[label],
+ thickness=rect_thickness)
+ else:
+ assert style is None
+ rectangle(im, (int(rect[0]), int(rect[1])),
+ (int(rect[2]), int(rect[3])), color[label],
+ thickness=rect_thickness)
+ if probs is not None:
+ if draw_label:
+ label_in_image = '{}-{:.2f}'.format(label, probs[i])
+ else:
+ label_in_image = '{:.2f}'.format(probs[i])
+ else:
+ if draw_label:
+ label_in_image = '{}'.format(label)
+
+ if draw_label or probs is not None:
+ (text_width, text_height), _ = cv2.getTextSize(label_in_image, cv2.FONT_HERSHEY_SIMPLEX,
+ font_scale, font_thickness)
+ text_left = int(rect[0] + 2)
+ left_top = (int(rect[0]), int(rect[1]))
+ if left_top in placed_position:
+ text_bottom = placed_position[left_top][-1] + text_height
+ placed_position[left_top].append(text_bottom)
+ else:
+ text_bottom = int(rect[1]) + text_height
+ placed_position[left_top] = [text_bottom]
+
+ all_filled_region.append(((text_left, text_bottom - text_height),
+ (text_left + text_width, text_bottom + 5), (75, 75, 75)))
+ all_put_text.append((label_in_image, (text_left, text_bottom),
+ color[label]))
+
+ for left_top, right_bottom, c in all_filled_region:
+ rectangle(im, left_top, right_bottom,
+ c,
+ thickness=-1)
+ for label_in_image, (text_left, text_bottom), c in all_put_text:
+ put_text(im,
+ label_in_image,
+ (text_left, text_bottom),
+ c,
+ font_scale,
+ font_thickness)
+
+def save_image(im, file_name, quality=None):
+ ensure_directory(os.path.dirname(file_name))
+ if quality is None:
+ return cv2.imwrite(file_name, im)
+ else:
+ return cv2.imwrite(file_name, im, [int(cv2.IMWRITE_JPEG_QUALITY),
+ quality])
+
+
+def load_image(file_name):
+ return cv2.imread(file_name)
+
+def load_image_by_pil(file_name, respect_exif=False):
+ image = Image.open(file_name).convert('RGB')
+ if respect_exif:
+ from PIL import ImageOps
+ image = ImageOps.exif_transpose(image)
+ return image
+
+def pil_to_cvim(pil_image):
+ open_cv_image = np.array(pil_image)
+ open_cv_image = open_cv_image[:, :, ::-1]
+ return open_cv_image
+
+def show_image(im):
+ show_images([im], 1, 1)
+
+def show_images(all_image, num_rows=None, num_cols=None,
+ titles=None, out_fname=None):
+ plt.figure(1)
+ if num_rows is None and num_cols is None:
+ num_rows = 1
+ num_cols = len(all_image)
+
+ k = 0
+ for i in range(num_rows):
+ for j in range(num_cols):
+ if k >= len(all_image):
+ break
+ plt.subplot(num_rows, num_cols, k + 1)
+ if is_pil_image(all_image[k]):
+ plt.imshow(np.asarray(all_image[k]))
+ else:
+ if len(all_image[k].shape) == 3:
+ plt.imshow(cv2.cvtColor(all_image[k],
+ cv2.COLOR_BGR2RGB))
+ else:
+ # grey image
+ assert len(all_image[k].shape) == 2
+ plt.imshow(np.repeat(all_image[k][:, :, np.newaxis], 3, axis=2))
+ if titles is not None:
+ plt.title(titles[k])
+ k = k + 1
+ plt.subplots_adjust(wspace=0, hspace=0)
+ plt.tight_layout()
+ if out_fname is None:
+ plt.show()
+ else:
+ plt.savefig(out_fname)
+ plt.close()
+
+def bytes_to_img_array(img_bytes, check_channel=True):
+ """ Convert bytes to image array of shape h*w*c in BGR order
+ Ensure the image is valid with 3 channels if check_channel == True
+ NOTE: use > py3.5 to load webp image with OpenCV
+ """
+ import imghdr
+ import imageio
+ import sys
+
+ is_py2 = sys.version_info.major == 2
+ if is_py2:
+ from StringIO import StringIO as BytesIO
+ else:
+ from io import BytesIO
+
+ t = imghdr.what('', h = img_bytes)
+ imarr = None
+ if t == "gif":
+ gif = imageio.mimread(BytesIO(img_bytes))
+ imarr = gif[0]
+ else: # ["jpg", "jpeg", "png", "webp"]
+ try:
+ imarr = imageio.imread(BytesIO(img_bytes))
+ except (ValueError, SyntaxError) as e:
+ return None
+
+ if imarr is None:
+ return None
+ # ensure dtype is uint8
+ if imarr.dtype is not np.dtype('uint8'):
+ # NOTE: no easy way to convert other dtype to uint8 color scale
+ # info = np.iinfo(imarr.dtype) # Get the information of the incoming image type
+ # imarr = imarr.astype(np.float64) / info.max # normalize the imarr to 0 - 1
+ # imarr = 255 * imarr # Now scale by 255
+ # imarr = imarr.astype(np.uint8)
+ return None
+
+ # conver grayscale
+ if len(imarr.shape) == 2:
+ imarr = cv2.cvtColor(imarr, cv2.COLOR_GRAY2RGB)
+ if len(imarr.shape) != 3:
+ return None
+
+ h, w, c = imarr.shape
+ # convert form RGBA to BGRA
+ if c == 3:
+ imarr = imarr[:, :, (2, 1, 0)]
+ elif c == 4:
+ imarr = imarr[:, :, (2, 1, 0, 3)]
+ else:
+ return None
+
+ if check_channel and c == 4:
+ imarr = bgra_to_bgr_img_arr(imarr)
+
+ if imarr.max() - imarr.min() < 5:
+ return None
+
+ return imarr
+
+def file_to_base64_img(fpath, check_channel=True):
+ """ Read image file, converts to base64 encoded string
+ """
+ with open(fpath, 'rb') as fp:
+ img_bytes = fp.read()
+ imarr = bytes_to_img_array(img_bytes, check_channel=check_channel)
+ return encoded_from_img(imarr)
+
+def bgra_to_bgr_img_arr(img_arr):
+ """ Convert BGRA to BGR, and transparent part to white
+ if using opencv built-in cv2.cvtColor(img_arr, cv2.COLOR_RGBA2RGB),
+ transparent part can be any color
+ """
+ h, w, c = img_arr.shape
+ assert(c == 4)
+ alpha_channel = img_arr[:, :, 3]
+ trans_thres = max(alpha_channel.max() // 2, 1)
+ _, mask = cv2.threshold(alpha_channel, trans_thres, 255, cv2.THRESH_BINARY) # binarize mask
+ color = img_arr[:, :, :3]
+ new_img_arr = cv2.bitwise_not(cv2.bitwise_not(color, mask=mask))
+ return new_img_arr
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/process_tsv.py b/One-to-All-Animation/benchmark/DisCo/utils/process_tsv.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0f5f43cb000d7363128854a11833feab2d85344
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/process_tsv.py
@@ -0,0 +1,9373 @@
+# from .cloud_storage import create_cloud_fuse
+import argparse
+import base64
+import copy
+import cv2
+import glob
+import imghdr
+import inspect
+import json
+import logging
+import math
+import numpy as np
+import os
+import os.path as op
+import pymongo
+import random
+import re
+import shutil
+from collections import OrderedDict
+import sys
+import time
+import unicodedata
+import yaml
+from .tsv_io import TSVSplitProperty
+from .tsv_io import CompositeTSVFile
+from .common import pilimg_from_base64
+from .common import dict_get_all_path
+from .tsv_io import get_tsv_associates
+from .common import dict_get_path_value
+from .common import qd_tqdm
+from .common import qd_tqdm as tqdm
+from .common import parallel_map
+from .common import split_to_chunk_to_range
+from .common import ensure_remove_file
+from .common import get_tmp_folder
+
+from collections import defaultdict
+from deprecated import deprecated
+from pathos.multiprocessing import ProcessingPool as Pool
+from datetime import datetime
+from pprint import pformat
+try:
+ from StringIO import StringIO
+except ImportError:
+ from io import StringIO
+from future.utils import viewitems
+from .cloud_storage import CloudStorage
+from .process_image import draw_bb, show_image, save_image
+from .process_image import show_images
+from .process_image import draw_rects
+from .common import calculate_image_ap
+from .common import calculate_iou
+from .common import dict_to_list
+from .common import ensure_directory
+from .common import normalize_to_str
+from .common import generate_lineidx
+from .common import get_mpi_rank, get_mpi_size
+from .common import hash_sha1
+from .common import ensure_copy_file
+from .common import img_from_base64
+from .common import init_logging
+from .common import json_dump
+from .common import list_to_dict, list_to_dict_unique
+from .common import parse_test_data
+from .common import read_to_buffer
+from .tsv_io import load_list_file
+from .common import worth_create
+from .tsv_io import write_to_file
+from .common import write_to_yaml_file, load_from_yaml_file
+from .common import float_tolorance_equal
+from .common import is_positive_uhrs_verified, is_negative_uhrs_verified
+from .tsv_io import concat_files
+from .common import try_delete
+from .common import encoded_from_img
+from .common import get_frame_info
+from .common import calc_mean
+from .taxonomy import child_parent_print_tree2
+from .taxonomy import create_markdown_url
+from .taxonomy import disambibuity_noffsets
+from .taxonomy import gen_noffset
+from .taxonomy import gen_term_list
+from .taxonomy import get_nick_name
+from .taxonomy import is_noffset
+from .taxonomy import LabelToSynset, synset_to_noffset
+from .taxonomy import load_all_tax, merge_all_tax
+from .taxonomy import noffset_to_synset
+from .taxonomy import populate_cum_images
+from .taxonomy import populate_url_for_offset
+from .taxonomy import Taxonomy
+from .tsv_io import create_inverted_list
+from .tsv_io import create_inverted_list2
+from .tsv_io import extract_label
+from .tsv_io import get_meta_file
+from .tsv_io import load_labels
+from .tsv_io import TSVDataset, TSVFile
+from .tsv_io import tsv_reader, tsv_writer
+from .tsv_io import is_verified_rect
+from .tsv_io import tsv_copy
+from .tsv_io import tsv_writers
+from .tsv_io import get_default_splits
+from .db import create_mongodb_client
+from .db import create_bbverification_db
+from .tsv_io import get_tsv_lineidx_8b
+from .tsv_io import File
+import torch
+
+
+def delete_tsv_files(tsvs):
+ for t in tsvs:
+ if op.isfile(t):
+ try_delete(t)
+ line = op.splitext(t)[0] + '.lineidx'
+ if op.isfile(line):
+ try_delete(line)
+ line = get_tsv_lineidx_8b(t)
+ if op.isfile(line):
+ try_delete(line)
+
+def concat_tsv_files_mem_efficient(tsvs, out_tsv):
+ # prefer concat_tsv_files
+ if len(tsvs) == 1 and tsvs[0] == out_tsv:
+ return
+ concat_files(tsvs, out_tsv)
+ sizes = [os.stat(t).st_size for t in tsvs]
+ sizes = np.cumsum(sizes)
+ debug_check = {'n': 0, 'n8b': 0}
+ def gen_lineidx():
+ for i, t in enumerate(tsvs):
+ with File.open(op.splitext(t)[0] + '.lineidx') as fp:
+ for idx in fp:
+ debug_check['n'] += 1
+ if i == 0:
+ yield int(idx)
+ else:
+ yield int(idx) + sizes[i - 1]
+ with File.open(op.splitext(out_tsv)[0] + '.lineidx', 'w') as fp:
+ for x in tqdm(gen_lineidx()):
+ fp.write(str(x) + '\n')
+
+ def gen_lineidx_8b():
+ for i, t in enumerate(tsvs):
+ with File.open(op.splitext(t)[0] + '.lineidx.8b', 'rb') as fp:
+ while True:
+ x = fp.read(8)
+ if x != b'':
+ idx = int.from_bytes(x, 'little')
+ debug_check['n8b'] += 1
+ if i == 0:
+ yield idx
+ else:
+ yield int(idx) + sizes[i - 1]
+ else:
+ break
+ with File.open(op.splitext(out_tsv)[0] + '.lineidx.8b', 'wb') as fp:
+ for x in tqdm(gen_lineidx_8b()):
+ fp.write(int(x).to_bytes(8, 'little'))
+ assert debug_check['n'] == debug_check['n8b']
+
+def concat_tsv_files(tsvs, out_tsv, gen_lineidx=True):
+ if len(tsvs) == 1 and tsvs[0] == out_tsv:
+ return
+ File.prepare(tsvs)
+ concat_files(tsvs, out_tsv)
+ sizes = [File.get_file_size(t) for t in tsvs]
+ sizes = np.cumsum(sizes)
+ sizes = [0] + sizes[:-1].tolist()
+
+ if gen_lineidx:
+ # the generation process is much slower than that for lineidx.8b. As
+ # this format is going to be deprecated, we have a flag to disable this
+ # ggeneration proces
+ concate_lineidx(sizes, tsvs, out_tsv)
+ concate_lineidx_8b(sizes, tsvs, out_tsv)
+
+def concate_lineidx(sizes, tsvs, out_tsv):
+ File.prepare(tsvs)
+ def row_processor(row):
+ offset, in_tsv, out_tsv = row
+ fbar = qd_tqdm(unit_scale=True)
+ with File.open(in_tsv) as fp:
+ with File.open(out_tsv, 'w') as fpout:
+ for idx in fp:
+ fbar.update(1)
+ fpout.write(str(int(idx) + offset) + '\n')
+ all_info = [(sizes[i], op.splitext(t)[0] + '.lineidx') for i, t in enumerate(tsvs)]
+ folder = get_tmp_folder()
+ all_info = [(offset, in_tsv, op.join(folder, in_tsv)) for offset, in_tsv in all_info]
+ #for _, __, f in all_info:
+ #ensure_directory(op.dirname(f))
+ parallel_map(row_processor, all_info, 64)
+ concat_files([i[2] for i in all_info], op.splitext(out_tsv)[0] + '.lineidx')
+ for d in all_info:
+ ensure_remove_file(d[2])
+
+def concate_lineidx_8b(sizes, tsvs, out_tsv):
+ File.prepare(tsvs)
+ folder = get_tmp_folder()
+ def row_processor_8b(row):
+ offset, in_tsv, out_tsv = row
+ fbar = qd_tqdm(unit_scale=True)
+ bulk_size = 1024
+ with File.open(in_tsv, 'rb') as fp:
+ with File.open(out_tsv, 'wb') as fpout:
+ while True:
+ x = fp.read(8 * bulk_size)
+ fbar.update(len(x) // 8)
+ if x != b'':
+ import struct
+ fmt = '<{}q'.format(len(x) // 8)
+ x = [i + offset for i in struct.unpack(fmt, x)]
+ fpout.write(b''.join([i.to_bytes(8, 'little') for i in
+ x]))
+ else:
+ break
+ all_info_8b = [(sizes[i], op.splitext(t)[0] + '.lineidx.8b') for i, t in enumerate(tsvs)]
+ File.prepare([in_tsv for _, in_tsv in all_info_8b])
+ # op.join(folder, in_tsv) may also be equal to in_tsv, although it is fine
+ all_info_8b = [(offset, in_tsv, '{}/{}'.format(folder, in_tsv + '.lineidx.8b')) for offset, in_tsv
+ in all_info_8b]
+ parallel_map(row_processor_8b, all_info_8b, 64)
+ concat_files([i[2] for i in all_info_8b], op.splitext(out_tsv)[0] + '.lineidx.8b')
+ for d in all_info_8b:
+ ensure_remove_file(d[2])
+
+def concat_tsv_files_old(tsvs, out_tsv):
+ # prefer concat_tsv_files
+ if len(tsvs) == 1 and tsvs[0] == out_tsv:
+ return
+ concat_files(tsvs, out_tsv)
+ sizes = [os.stat(t).st_size for t in tsvs]
+ sizes = np.cumsum(sizes)
+ all_idx = []
+ for i, t in enumerate(tsvs):
+ for idx in load_list_file(op.splitext(t)[0] + '.lineidx'):
+ if i == 0:
+ all_idx.append(idx)
+ else:
+ all_idx.append(str(int(idx) + sizes[i - 1]))
+ write_to_file('\n'.join(all_idx), op.splitext(out_tsv)[0] + '.lineidx')
+ with File.open(get_tsv_lineidx_8b(out_tsv), 'wb') as fp:
+ for i in all_idx:
+ fp.write(int(i).to_bytes(8, 'little'))
+
+def merge_data_feature_tsv(from_data, to_data, feature_version):
+ assert from_data.startswith(to_data)
+ from_dataset = TSVDataset(from_data)
+ to_dataset = TSVDataset(to_data)
+ src_tsvs = load_list_file(from_dataset.get_data(
+ 'trainX', 'feature', feature_version))
+ dest_tsvs = load_list_file(to_dataset.get_data(
+ 'trainX',
+ 'feature',
+ feature_version))
+ assert len(dest_tsvs) == 1
+ dest_tsv = dest_tsvs[0]
+ logging.info(pformat(src_tsvs))
+ logging.info(pformat(dest_tsv))
+ if op.isfile(dest_tsv):
+ logging.info('skip to merge as exists')
+ else:
+ concat_tsv_files(src_tsvs, dest_tsv)
+
+def train_test_split(data_from, data_to, split_from='train', num_test=5000):
+ populate_dataset_details(data_from)
+ dataset_from = TSVDataset(data_from)
+ dataset_to = TSVDataset(data_to)
+
+ num_total_image = dataset_from.num_rows(split_from)
+ total_idx = list(range(num_total_image))
+ random.seed(666)
+ random.shuffle(total_idx)
+ split_names = ['test', 'train']
+ all_split_idx = [total_idx[: num_test], total_idx[num_test:]]
+ for split_idx, split_name in zip(all_split_idx, split_names):
+ dataset_to.write_data(dataset_from.iter_data(split_from,
+ filter_idx=split_idx), split_name)
+ # all label file
+ v = 0
+ while dataset_from.has(split_from, 'label', version=v):
+ dataset_to.write_data(dataset_from.iter_data(split_from,
+ t='label', version=v, filter_idx=split_idx),
+ split_name, t='label', version=v)
+ v = v + 1
+
+def find_best_matched_rect_idx(target, rects, check_class=True):
+ target_class_lower = target['class'].lower()
+ if check_class:
+ same_class_rects = [r for r in rects if r['class'].lower() == target_class_lower]
+ else:
+ same_class_rects = rects
+ idx_ious = [(i, calculate_iou(r['rect'], target['rect']))
+ for i, r in enumerate(same_class_rects)]
+ if len(idx_ious) == 0:
+ return None, -1
+ return max(idx_ious, key=lambda r: r[-1])
+
+def find_best_matched_rect(target, rects, check_class=True, check_iou=True):
+ target_class_lower = target['class'].lower()
+ if check_class:
+ same_class_rects = [r for r in rects if r['class'].lower() == target_class_lower]
+ else:
+ same_class_rects = rects
+ if check_iou:
+ rect_ious = [(r, calculate_iou(r['rect'], target['rect']))
+ for r in same_class_rects]
+ else:
+ rect_ious = [(r, 1) for r in same_class_rects]
+ if len(rect_ious) == 0:
+ return None, -1
+ return max(rect_ious, key=lambda r: r[-1])
+
+def create_tsvdataset_from_image_folder(root_folder, data):
+ from .process_image import load_image
+ dataset = TSVDataset(data)
+ all_full_file_name = [op.join(root, f) for root, dirnames, filenames in os.walk(root_folder)
+ for f in filenames]
+ def row_processor(full_file_name):
+ im = load_image(full_file_name)
+ if im is not None:
+ key = full_file_name.replace(root_folder, '')
+ return key, base64.b64encode(read_to_buffer(full_file_name))
+ parallel_tsv_process(
+ row_processor,
+ all_full_file_name,
+ dataset.get_data('train'),
+ 64
+ )
+
+def create_new_image_tsv_if_exif_rotated(data, split):
+ dataset = TSVDataset(data)
+ key_no_rotate_in_image = 'no_rotate_in_image'
+ if dataset.has(split, key_no_rotate_in_image):
+ return
+ info = {'changed': 0, 'total': 0}
+ def gen_rows():
+ logging.info('{}-{}'.format(data, split))
+ for key, str_rects, str_im in tqdm(dataset.iter_data(split)):
+ info['total'] = info['total'] + 1
+ im = img_from_base64(str_im)
+ from .common import img_from_base64_ignore_rotation
+ im2 = img_from_base64_ignore_rotation(str_im)
+ if im.shape[0] != im2.shape[0] or im.shape[1] != im2.shape[1]:
+ assert im.shape[0] == im2.shape[1]
+ assert im.shape[1] == im2.shape[0]
+ info['changed'] = info['changed'] + 1
+ yield key, str_rects, encoded_from_img(im)
+ else:
+ yield key, str_rects, str_im
+ tmp_tsv = dataset.get_data(split, 'tmp')
+ tsv_writer(gen_rows(), tmp_tsv)
+ logging.info(pformat(info))
+ if info['changed'] != 0:
+ from .tsv_io import tsv_mv
+ tsv_mv(tmp_tsv, dataset.get_data(split))
+ else:
+ from .tsv_io import tsv_rm
+ tsv_rm(tmp_tsv)
+ dataset.write_data([], split, key_no_rotate_in_image)
+
+def get_data_distribution(data, split, version):
+ # return a dictionary to represent the distribution of the data
+ # only composite dataset requires the following two information
+ result = {}
+
+ populate_dataset_details(data)
+ dataset = TSVDataset(data)
+ tsvsource_to_imageratio = {src[5:]:
+ (float(numdestimages) / float(numsrcimages))
+ for src, numdestimages, numsrcimages in
+ dataset.iter_data(split + 'X', 'tsvsource.numdestimages.numsrcimages')}
+ result['tsvsource_to_imageratio'] = tsvsource_to_imageratio
+
+ tsvsource_to_boxratio = {src[5:]:
+ (float(numdest) / float(numsrc))
+ for src, numdest, numsrc in
+ dataset.iter_data(split + 'X', 'tsvsource.numdestbbs.numsrcbbs')}
+ result['tsvsource_to_boxratio'] = tsvsource_to_boxratio
+
+ tsvsource_to_num_image = {source[5:]: int(num_image) for source, num_image in dataset.iter_data(split + 'X', 'numImagesPerSource')}
+ result['tsvsource_to_num_image'] = tsvsource_to_num_image
+
+ tsvsource_to_num_category = {source[5:]: int(num_image) for source, num_image
+ in dataset.iter_data(split + 'X', 'numCategoriesPerSource')}
+ result['tsvsource_to_num_category'] = tsvsource_to_num_category
+
+ label_to_count = {l: int(c) for l, c in dataset.iter_data(split, 'inverted.label.count', version=version)}
+ unique_labels = set([l if not l.startswith('-') else l[1:] for l in label_to_count])
+ import math
+ all_label_pos_negs = [[l, [label_to_count.get(l, 0), -label_to_count.get('-' + l, 0)]] for l in unique_labels]
+ all_label_pos_negs = [[l, [math.log10(label_to_count.get(l, 0) + 1),
+ -math.log10(label_to_count.get('-' + l, 0) + 1)]] for l in unique_labels]
+ all_label_pos_negs = sorted(all_label_pos_negs, key=lambda x: x[1][0])
+ result['all_label_pos_negs'] = all_label_pos_negs
+
+ result['num_labels_with_neg'] = len([l for l, (pos, neg) in all_label_pos_negs if neg != 0])
+ result['num_labels_with_pos'] = len([l for l, (pos, neg) in all_label_pos_negs if pos != 0])
+
+ label_to_count = {l: int(c) for l, c in dataset.iter_data(split, 'inverted.label.count',
+ version=version)}
+ _, c = next(dataset.iter_data(split, 'inverted.background.count',
+ version=version))
+ label_to_count['__background'] = int(c)
+ result['label_to_count'] = label_to_count
+
+ return result
+
+def convert_pred_to_dataset_label(full_expid, predict_file,
+ th_file, min_value):
+ pred_file = op.join('output',
+ full_expid,
+ 'snapshot',
+ predict_file)
+
+ from .common import parse_test_data
+ data, split = parse_test_data(predict_file)
+
+ from process_tsv import load_key_rects
+
+ dataset = TSVDataset(data)
+ populate_dataset_details(data)
+ latest_version = dataset.get_latest_version(split, 'label')
+ gt_key_rects = load_key_rects(dataset.iter_data(split, 'label',
+ latest_version))
+ pred_key_rects = load_key_rects(tsv_reader(pred_file))
+ pred_key_to_rects = {key: rects for key, rects in pred_key_rects}
+ if th_file:
+ th_file = op.join('output', full_expid, 'snapshot', th_file)
+ per_cat_th = {l: max(float(th), min_value) for l, th, _ in tsv_reader(th_file)}
+ else:
+ per_cat_th = {}
+ def gen_rows():
+ for key, rects in gt_key_rects:
+ pred_rects = pred_key_to_rects.get(key, [])
+ pred_rects = [r for r in pred_rects
+ if r['conf'] >= per_cat_th.get(r['class'], 0)]
+ yield key, json.dumps(pred_rects)
+ info = [('full_expid', full_expid),
+ ('predict_file', pred_file),
+ ('th_file', th_file),
+ ('min_value', min_value)]
+ dataset.update_data(gen_rows(), split, 'label',
+ generate_info=info)
+
+ populate_dataset_details(data)
+
+def ensure_inject_expid(full_expid):
+ all_predict = []
+ all_predict.extend(glob.glob(op.join('output', full_expid, 'snapshot',
+ '*.predict')))
+ all_predict.extend(glob.glob(op.join('output', full_expid, 'snapshot',
+ '*.predict.tsv')))
+ for p in all_predict:
+ ensure_inject_expid_pred(full_expid, op.basename(p))
+
+def ensure_inject_dataset(data, **kwargs):
+ for split in get_default_splits():
+ ensure_upload_image_to_blob(data, split)
+ ensure_inject_image(data, split)
+ ensure_inject_gt(data, split, **kwargs)
+
+def ensure_inject_decorate(func):
+ def func_wrapper(*args, **kwargs):
+ client = create_mongodb_client()
+ db = client['qd']
+ task = db['task']
+ # .func_name is ok for python2, but not for python3. .__name__ is ok
+ # for both
+ func_name = func.__name__
+ if func_name.startswith('ensure_'):
+ func_name = func_name[len('ensure_'): ]
+ argnames, ins_varargs, ins_kwargs, ins_defaults = inspect.getargspec(func)
+ # we have not supported if other paramseters is not None
+ assert ins_varargs is None and ins_kwargs is None
+ query = {'task_type': func_name}
+ for n, v in zip(argnames[: len(args)], args):
+ assert n not in query
+ query[n] = v
+ for k in kwargs:
+ assert k not in query
+ query[k] = kwargs[k]
+
+ # create the unique index to make the update_one atomic
+ logging.info('make sure the index is created: {}'.format(
+ ', '.join(query.keys())))
+ task.create_index([(k, pymongo.ASCENDING) for k in query])
+
+ while True:
+ result = task.update_one(filter=query,
+ update={'$setOnInsert': query},
+ upsert=True)
+ if result.matched_count == 0:
+ task.update_one(filter=query,
+ update={'$set': {'status': 'started',
+ 'create_time': datetime.now()}})
+ func(*args, **kwargs)
+ task.update_many(filter=query,
+ update={'$set': {'status': 'done'}})
+ return True
+ else:
+ assert result.matched_count == 1
+ existing_entries = list(task.find(query))
+ if any(e for e in existing_entries if e['status'] == 'done'):
+ logging.info('ignore to inject since it is done: \n{}'.format(query))
+ break
+ else:
+ logging.info('waiting to finish \n{}'.format(
+ pformat(existing_entries)))
+ time.sleep(10)
+ # return False if not done
+ return func_wrapper
+
+def ensure_composite_key_url(data, split):
+ dataset = TSVDataset(data)
+ if not dataset.has(split):
+ logging.info('data tsv does not exist')
+ return
+ if dataset.has(split, 'key.url'):
+ logging.info('it exists')
+ return
+ data_to_dataset = {}
+ uploaded_key_url = set()
+ def gen_rows():
+ for key, _ in dataset.iter_data(split, 'label'):
+ c_data, c_split, c_key = parse_combine(key)
+ if c_data in data_to_dataset:
+ c_dataset = data_to_dataset[c_data]
+ else:
+ c_dataset = TSVDataset(c_data)
+ data_to_dataset[c_data] = c_dataset
+ if (c_data, c_split) not in uploaded_key_url:
+ ensure_upload_image_to_blob(c_data, c_split)
+ uploaded_key_url.add((c_data, c_split))
+ _, url = c_dataset.seek_by_key(c_key, c_split, 'key.url')
+ yield key, url
+ dataset.write_data(gen_rows(), split, 'key.url')
+
+def upload_image_to_blob(data, split, config=None):
+ dataset = TSVDataset(data)
+ if not dataset.has(split):
+ logging.info('{} - {} does not exist'.format(data, split))
+ return
+ logging.info('{} - {}'.format(data, split))
+ if op.isfile(dataset.get_data(split + 'X')):
+ ensure_composite_key_url(data, split)
+ logging.info('ignore to upload images for composite dataset')
+ return
+ parallel = True
+ if not parallel:
+ s = CloudStorage(config=config)
+ def gen_rows():
+ for key, _, str_im in tqdm(dataset.iter_data(split)):
+ url_key = map_image_key_to_url_key(data, split, key)
+ if sys.version_info.major == 3:
+ url = s.upload_stream(base64.b64decode(str_im),
+ 'images/' + url_key + '.jpg')
+ else:
+ url = s.upload_stream(StringIO(base64.b64decode(str_im)),
+ 'images/' + url_key)
+ yield key, url
+ dataset.write_data(gen_rows(), split, 'key.url')
+ else:
+ from .common import split_to_chunk
+ from .tsv_io import rm_tsv
+ num_rows = dataset.num_rows(split)
+ num_chunk = num_rows // 1000
+ num_chunk = max(1, num_chunk)
+ tasks = split_to_chunk(range(num_rows), num_chunk)
+ tasks = [(data, split, t, i, len(tasks), config) for i, t in enumerate(tasks)]
+ parallel_map(upload_image_to_blob_by_idx, tasks)
+ # merge the result
+ def gen_rows():
+ for idx_task in range(len(tasks)):
+ for key, url in dataset.iter_data(split,
+ 'key.url.{}.{}'.format(idx_task, len(tasks))):
+ yield key, url
+ dataset.write_data(gen_rows(), split, 'key.url')
+ # remove intermediate files
+ for idx_task in range(len(tasks)):
+ rm_tsv(dataset.get_data(split, 'key.url.{}.{}'.format(idx_task, len(tasks))))
+
+def upload_image_to_blob_by_idx(args):
+ data, split, idxes, idx_task, num_task, config = args
+ t = 'key.url.{}.{}'.format(idx_task, num_task)
+ dataset = TSVDataset(data)
+ if dataset.has(split, t):
+ logging.info('return since exist')
+ return
+ s = CloudStorage(config=config)
+ def gen_rows():
+ for key, _, str_im in tqdm(dataset.iter_data(split, filter_idx=idxes)):
+ url_key = map_image_key_to_url_key(data, split, key)
+ if sys.version_info.major == 3:
+ url = s.upload_stream(base64.b64decode(str_im),
+ 'images/' + url_key + '.jpg')
+ else:
+ url = s.upload_stream(StringIO(base64.b64decode(str_im)),
+ 'images/' + url_key)
+ if s.sas_token:
+ url += s.sas_token
+ yield key, url
+ dataset.write_data(gen_rows(), split, t)
+
+@ensure_inject_decorate
+def ensure_upload_image_to_blob(data, split, config=None):
+ upload_image_to_blob(data, split, config=config)
+
+@ensure_inject_decorate
+def ensure_inject_image(data, split):
+ dataset = TSVDataset(data)
+ if not dataset.has(split):
+ return
+
+ client = create_mongodb_client()
+ db = client['qd']
+ images = db['image']
+ images.delete_many(filter={'data': data, 'split': split})
+ images.create_index([
+ ('data', pymongo.ASCENDING),
+ ('split', pymongo.ASCENDING),
+ ('key', pymongo.ASCENDING),
+ ],
+ unique=True)
+ all_data = []
+
+ logging.info('injecting {} - {}'.format(data, split))
+ injected = set()
+ key_to_hw = None
+ if dataset.has(split, 'hw'):
+ key_to_hw = {key: [int(x) for x in hw.split(' ')] for key, hw in
+ dataset.iter_data(split, 'hw')}
+ assert dataset.has(split, 'key.url')
+ key_to_url = {key: url for key, url in dataset.iter_data(split, 'key.url')}
+ logging.info('injecting image for {} - {}'.format(data, split))
+ for i, (key, _) in tqdm(enumerate(dataset.iter_data(split,
+ 'label'))):
+ if key in injected:
+ continue
+ else:
+ injected.add(key)
+ url = key_to_url[key]
+ doc = {'data': data,
+ 'split': split,
+ 'key': key,
+ 'idx_in_split': i,
+ 'url': url,
+ 'create_time': datetime.now(),
+ }
+ if key_to_hw:
+ doc['height'], doc['width'] = key_to_hw[key]
+ all_data.append(doc)
+ if len(all_data) > 1000:
+ images.insert_many(all_data)
+ all_data = []
+ if len(all_data) > 0:
+ images.insert_many(all_data)
+ all_data = []
+
+@ensure_inject_decorate
+def ensure_update_pred_with_correctness(data, split,
+ full_expid, predict_file):
+ ensure_inject_gt(data, split)
+ ensure_inject_pred(full_expid, predict_file, data, split)
+
+ update_pred_with_correctness(data, split,
+ full_expid,
+ predict_file)
+
+
+def update_pred_with_correctness(test_data, test_split,
+ full_expid,
+ predict_file):
+ client = create_mongodb_client()
+ db = client['qd']
+ _pred = db['predict_result']
+
+ # get the latest version of the gt
+ pipeline = [{'$match': {'data': test_data,
+ 'split': test_split,
+ 'version': {'$lte': 0}}},
+ {'$group': {'_id': {'data': '$data',
+ 'split': '$split',
+ 'key': '$key',
+ 'action_target_id': '$action_target_id'},
+ 'contribution': {'$sum': '$contribution'},
+ 'class': {'$first': '$class'},
+ 'rect': {'$first': '$rect'}}},
+ {'$match': {'contribution': {'$gte': 1}}}, # if it is 0, it means we removed the box
+ {'$addFields': {'data': '$_id.data',
+ 'split': '$_id.split',
+ 'key': '$_id.key'}},
+ ]
+ def get_query_pipeline(data, split, key, class_name):
+ return [{'$match': {'$expr': {'$and': [{'$eq': ['$data', '$${}'.format(data)]},
+ {'$eq': ['$split', '$${}'.format(split)]},
+ {'$eq': ['$key', '$${}'.format(key)]},
+ {'$eq': ['$class', '$${}'.format(class_name)]}]}}},
+ {'$group': {'_id': '$action_target_id',
+ 'contribution': {'$sum': '$contribution'},
+ 'create_time': {'$max': '$create_time'},
+ 'rect': {'$first': '$rect'}}},
+ {'$match': {'contribution': {'$gte': 1}}},
+ ]
+
+ # get the target prediction bounding boxes
+ pipeline = [{'$match': {'full_expid': full_expid,
+ 'pred_file': predict_file}},
+ {'$group': {'_id': {'data': '$data',
+ 'split': '$split',
+ 'key': '$key',
+ 'class': '$class'},
+ 'pred_box': {'$push': {'rect': '$rect',
+ 'conf': '$conf',
+ 'pred_box_id': '$_id'}}}},
+ {'$lookup': {'from': 'ground_truth',
+ 'let': {'target_data': '$_id.data',
+ 'target_split': '$_id.split',
+ 'target_key': '$_id.key',
+ 'target_class': '$_id.class'},
+ 'pipeline': get_query_pipeline('target_data',
+ 'target_split',
+ 'target_key',
+ 'target_class'),
+ 'as': 'gt_box'}},
+ ]
+ all_correct_box, all_wrong_box = [], []
+ for row in tqdm(_pred.aggregate(pipeline, allowDiskUse=True)):
+ curr_pred = row['pred_box']
+ curr_gt = row['gt_box']
+ curr_pred = sorted(curr_pred, key=lambda x: -x['conf'])
+ for p in curr_pred:
+ matched = [g for g in curr_gt if
+ not g.get('used', False) and
+ ('rect' not in p or
+ not p['rect'] or
+ 'rect' not in g or
+ not g['rect'] or
+ calculate_iou(g['rect'], p['rect']) > 0.3)]
+ if len(matched) == 0:
+ all_wrong_box.append(p['pred_box_id'])
+ else:
+ all_correct_box.append(p['pred_box_id'])
+ matched[0]['used'] = True
+ if len(all_correct_box) > 1000:
+ _pred.update_many({'_id': {'$in': all_correct_box}},
+ {'$set': {'correct': 1}})
+ all_correct_box = []
+ if len(all_wrong_box) > 1000:
+ _pred.update_many({'_id': {'$in': all_wrong_box}},
+ {'$set': {'correct': 0}})
+ all_wrong_box = []
+ if len(all_correct_box) > 0:
+ _pred.update_many({'_id': {'$in': all_correct_box}},
+ {'$set': {'correct': 1}})
+ all_correct_box = []
+ if len(all_wrong_box) > 0:
+ _pred.update_many({'_id': {'$in': all_wrong_box}},
+ {'$set': {'correct': 0}})
+ all_wrong_box = []
+
+def ensure_inject_expid_pred(full_expid, predict_file):
+ try:
+ data, split = parse_test_data(predict_file)
+ except:
+ logging.info('ignore to inject {} - {}'.format(full_expid, predict_file))
+ return
+ ensure_upload_image_to_blob(data, split)
+ ensure_inject_image(data, split)
+ ensure_inject_gt(data, split)
+ ensure_inject_pred(full_expid,
+ predict_file,
+ data,
+ split)
+ ensure_update_pred_with_correctness(data, split,
+ full_expid, predict_file)
+
+@ensure_inject_decorate
+def ensure_inject_pred(full_expid, pred_file, test_data, test_split):
+ client = create_mongodb_client()
+ db = client['qd']
+ pred_collection = db['predict_result']
+ logging.info('cleaning {} - {}'.format(full_expid, pred_file))
+ pred_collection.delete_many({'full_expid': full_expid, 'pred_file': pred_file})
+ pred_file = op.join('output', full_expid, 'snapshot', pred_file)
+ all_rect = []
+ for key, label_str in tqdm(tsv_reader(pred_file)):
+ rects = json.loads(label_str)
+ rects = [r for r in rects if r['conf'] > 0.05]
+ for i, r in enumerate(rects):
+ r['full_expid'] = full_expid
+ r['pred_file'] = op.basename(pred_file)
+ r['data'] = test_data
+ r['split'] = test_split
+ r['key'] = key
+ all_rect.extend(rects)
+ if len(all_rect) > 10000:
+ pred_collection.insert_many(all_rect)
+ all_rect = []
+ if len(all_rect) > 0:
+ pred_collection.insert_many(all_rect)
+
+def ensure_inject_gt(data, split, **kwargs):
+ client = create_mongodb_client()
+ db = client['qd']
+ task = db['task']
+ assert split is not None
+ dataset = TSVDataset(data)
+ version = 0
+ set_previous_key_rects = False
+ while dataset.has(split, 'label', version=version):
+ query = {'task_type': 'inject_gt',
+ 'data': data,
+ 'split': split,
+ 'version': version}
+ result = task.update_one(filter=query,
+ update={'$setOnInsert': query},
+ upsert=True)
+ if result.matched_count == 0:
+ logging.info('start to inserting {}-{}-{}'.format(data,
+ split, version))
+ # no process is working on inserting current version
+ task.update_one(filter=query,
+ update={'$set': {'status': 'started',
+ 'create_time': datetime.now()}})
+ if not set_previous_key_rects:
+ if version == 0:
+ previous_key_to_rects = {}
+ else:
+ key_rects = load_key_rects(dataset.iter_data(split, 'label',
+ version=version-1))
+ previous_key_to_rects = {key: rects for key, rects in key_rects}
+ set_previous_key_rects = True
+ inject_gt_version(data, split, version, previous_key_to_rects,
+ **kwargs)
+ task.update_many(filter={'task_type': 'inject_gt',
+ 'data': data,
+ 'split': split,
+ 'version': version}, update={'$set': {'status': 'done'}})
+ else:
+ # it is done or it is started by anohter process. let's skip
+ # this version
+ assert result.matched_count == 1
+ while True:
+ existing_entries = list(task.find(query))
+ if any(e for e in existing_entries if e['status'] == 'done'):
+ logging.info('ignore to inject since it is done: \n{}'.format(query))
+ break
+ elif len(existing_entries) == 0:
+ logging.info('we will do it')
+ version = version - 1
+ break
+ else:
+ logging.info('waiting to finish \n{}'.format(
+ pformat(existing_entries)))
+ time.sleep(10)
+ set_previous_key_rects = False
+ version = version + 1
+
+def inject_gt_version(data, split, version, previous_key_to_rects,
+ delete_existing=True):
+ client = create_mongodb_client()
+ db = client['qd']
+ gt = db['ground_truth']
+ dataset = TSVDataset(data)
+ if delete_existing:
+ logging.info('deleting data={}, split={}, version={}'.format(
+ data, split, version))
+ gt.delete_many({'data': data, 'split': split, 'version': version})
+ dataset = TSVDataset(data)
+
+ if not dataset.has(split, 'label', version):
+ return False
+ all_rect = []
+ logging.info('{}-{}-{}'.format(data, split, version))
+ total_inserted = 0
+ for idx_in_split, (key, label_str) in tqdm(enumerate(dataset.iter_data(
+ split, 'label', version=version))):
+ rects = json.loads(label_str)
+ def add_to_all_rect(r, extra_info):
+ r2 = copy.deepcopy(r)
+ r2.update(extra_info)
+ r2['idx_in_split'] = idx_in_split
+ r2['data'] = data
+ r2['split'] = split
+ r2['key'] = key
+ r2['action_target_id'] = hash_sha1([data, split, key, r['class'],
+ r.get('rect', [])])
+ r2['version'] = version
+ r2['create_time'] = datetime.now()
+ all_rect.append(r2)
+ if version == 0:
+ assert key not in previous_key_to_rects
+ for r in rects:
+ add_to_all_rect(r, {'contribution': 1})
+ else:
+ previous_rects = previous_key_to_rects[key]
+ # use strict_rect_in_rects rather than rect_in_rects: if the higher
+ # version contains more properies, we want to have the properies in
+ # teh database also.
+ previous_not_in_current = copy.deepcopy([r for r in previous_rects if
+ not strict_rect_in_rects(r, rects)])
+ current_not_in_previous = copy.deepcopy([r for r in rects if
+ not strict_rect_in_rects(r, previous_rects)])
+ for r in previous_not_in_current:
+ add_to_all_rect(r, {'contribution': -1})
+ for r in current_not_in_previous:
+ add_to_all_rect(r, {'contribution': 1})
+ previous_key_to_rects[key] = rects
+ if len(all_rect) > 1000:
+ db_insert_many(gt, all_rect)
+ total_inserted = total_inserted + len(all_rect)
+ logging.info('inserting data={}, split={}, version={}, curr_insert={}, total={}'.format(
+ data, split, version, len(all_rect), total_inserted))
+ all_rect = []
+
+ if len(all_rect) > 0:
+ total_inserted = total_inserted + len(all_rect)
+ logging.info('inserting data={}, split={}, version={}, curr_insert={}, total={}'.format(
+ data, split, version, len(all_rect), total_inserted))
+ db_insert_many(gt, all_rect)
+ all_rect = []
+ return True
+
+def db_insert_many(collection, all_info):
+ for a in all_info:
+ if '_id' in a:
+ del a['_id']
+ collection.insert_many(all_info)
+
+class VisualizationDatabaseByMongoDB():
+ def __init__(self):
+ self._client = create_mongodb_client()
+ self._db = self._client['qd']
+ self._pred = self._db['predict_result']
+ self._gt = self._db['ground_truth']
+
+ def _get_positive_start(self, start_id, max_item):
+ if start_id < 0:
+ rank = pymongo.DESCENDING
+ start_id = min(0, start_id + max_item)
+ start_id = abs(start_id)
+ else:
+ rank = pymongo.ASCENDING
+ return rank, start_id
+
+ def query_pipeline(self, pipeline, collection, db_name):
+ image_info = list(self._client[db_name][collection].aggregate(
+ pipeline, allowDiskUse=True))
+ logging.info(len(image_info))
+ if len(image_info) > 0:
+ logging.info(pformat(image_info[0]))
+ image_info = [{'key': x['key'],
+ 'url': x.get('url', ''),
+ 'gt': x.get('gt', []),
+ 'pred': x.get('pred', [])} for x in image_info]
+ return image_info
+
+ def insert(self, dic, collection, db_name):
+ return self._client[db_name][collection].insert(dic)
+
+ def query_by_id(self, _id, collection, db_name):
+ from bson.objectid import ObjectId
+ return list(self._client[db_name][collection].find({'_id':
+ ObjectId(_id)}))[0]
+
+ def query_predict_recall(self, full_expid, pred_file, class_name, threshold, start_id, max_item):
+ rank, start_id = self._get_positive_start(start_id, max_item)
+ # from the predict file
+ row = self._pred.find_one({'full_expid': full_expid, 'pred_file':
+ pred_file})
+ if row is None:
+ logging.info('no prediction data in db')
+ return []
+ data = row['data']
+ split = row['split']
+ logging.info(data)
+ logging.info(split)
+ pipeline = [{'$match': {'data': data, 'split': split, 'class': class_name}},
+ {'$group': {'_id': {'key': '$key', 'target_action_id': '$target_action_id'},
+ 'contribution': {'$sum': '$contribution'},
+ 'num_target_label': {'$sum': 1}}},
+ {'$match': {'contribution': {'$gte': 1}}},
+ {'$group': {'_id': {'key': '$_id.key'},
+ 'num_contribution': {'$sum': 1}}},
+ ## add the number of correct predicted
+ {'$lookup': {
+ 'from': 'predict_result',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'full_expid': full_expid,
+ 'pred_file': pred_file,
+ 'class': class_name,
+ 'conf': {'$gte': threshold}}},
+ {'$group': {'_id': {'key': '$key'},
+ 'correct': {'$sum': '$correct'}}},
+ {'$match': {'$expr': {'$and': [{'$eq': ['$_id.key', '$$key']}]}}},
+ ],
+ 'as': 'recall',
+ }},
+ {'$unwind': {'path': '$recall', 'preserveNullAndEmptyArrays': True}},
+ {'$addFields': {'recall': {'$divide': ['$recall.correct', '$num_target_label']}}},
+ {'$sort': {'recall': rank}},
+ {'$skip': start_id},
+ {'$limit': max_item},
+ # add the field of url
+ {'$lookup': {
+ 'from': 'image',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$data', data]},
+ {'$eq': ['$split', split]},
+ {'$eq': ['$key', '$$key']},],}}},
+ {'$project': {'url': True, '_id': 0}}],
+ 'as': 'url',
+ }},
+ {'$addFields': {'url': {'$arrayElemAt': ['$url', 0]}}},
+ {'$addFields': {'url': '$url.url'}},
+ ## add the field of pred
+ {'$lookup': {
+ 'from': 'predict_result',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$full_expid', full_expid]},
+ {'$eq': ['$pred_file', pred_file]},
+ {'$eq': ['$key', '$$key']},
+ {'$gte': ['$conf', threshold]}]}}},
+ {'$project': {'conf': True, 'rect': True, 'class': True, '_id': 0}}],
+ 'as': 'pred',
+ }
+ },
+ ## add the gt field
+ {'$lookup': {
+ 'from': 'ground_truth',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$data', data]},
+ {'$eq': ['$split', split]},
+ {'$eq': ['$key', '$$key']},],}}},
+ {'$group': {'_id': {'action_target_id': '$action_target_id'},
+ 'contribution': {'$sum': '$contribution'},
+ 'rect': {'$first': '$rect'},
+ 'class': {'$first': '$class'},
+ 'conf': {'$first': '$conf'}}, },
+ {'$match': {'contribution': {'$gte': 1}}},
+ ],
+ 'as': 'gt',
+ }}
+ ]
+ image_info = list(self._gt.aggregate(pipeline))
+ logging.info(len(image_info))
+ image_info = [{'key': x['_id']['key'],
+ 'url': x['url'],
+ 'gt': x['gt'],
+ 'pred': x['pred']} for x in image_info]
+ return image_info
+
+ def query_predict_precision(self, full_expid, pred_file, class_name, threshold, start_id, max_item):
+ rank, start_id = self._get_positive_start(start_id, max_item)
+ filter_pred = {'full_expid': full_expid,
+ 'pred_file': pred_file,
+ 'conf': {'$gte': threshold}}
+ if class_name != 'None' and class_name:
+ filter_pred['class'] = class_name
+ pipeline = [
+ {'$match': filter_pred},
+ {'$group': {'_id': {'data': '$data',
+ 'split': '$split',
+ 'key': '$key'},
+ 'correct': {'$sum': '$correct'},
+ 'total': {'$sum': 1}}},
+ {'$addFields': {'precision': {'$divide': ['$correct', '$total']}}},
+ {'$sort': {'precision': rank}},
+ {'$skip': start_id},
+ {'$limit': max_item},
+ # add the field of url
+ {'$lookup': {
+ 'from': 'image',
+ 'let': {'data': '$_id.data',
+ 'split': '$_id.split',
+ 'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$data', '$$data']},
+ {'$eq': ['$split', '$$split']},
+ {'$eq': ['$key', '$$key']},],}}},
+ {'$project': {'url': True, '_id': 0}}],
+ 'as': 'url',
+ }},
+ {'$unwind': '$url'},
+ {'$addFields': {'url': '$url.url'}},
+ ## add the field of pred
+ {'$lookup': {
+ 'from': 'predict_result',
+ 'let': {'data': '$_id.data',
+ 'split': '$_id.split',
+ 'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$full_expid', full_expid]},
+ {'$eq': ['$pred_file', pred_file]},
+ {'$eq': ['$key', '$$key']},
+ {'$gte': ['$conf', threshold]}]}}},
+ {'$project': {'conf': True, 'rect': True, 'class': True, '_id': 0}}],
+ 'as': 'pred',
+ }
+ },
+ ## add the gt field
+ {'$lookup': {
+ 'from': 'ground_truth',
+ 'let': {'data': '$_id.data',
+ 'split': '$_id.split',
+ 'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': [{'$eq': ['$data', '$$data']},
+ {'$eq': ['$split', '$$split']},
+ {'$eq': ['$key', '$$key']},],}}},
+ {'$group': {'_id': {'action_target_id': '$action_target_id'},
+ 'contribution': {'$sum': '$contribution'},
+ 'rect': {'$first': '$rect'},
+ 'class': {'$first': '$class'},
+ 'conf': {'$first': '$conf'}}, },
+ {'$match': {'contribution': {'$gte': 1}}},
+ ],
+ 'as': 'gt',
+ }}
+ ]
+
+ logging.info(pformat(pipeline))
+ image_info = list(self._pred.aggregate(pipeline))
+ image_info = [{'key': x['_id']['key'],
+ 'url': x['url'],
+ 'gt': x['gt'],
+ 'pred': x['pred']} for x in image_info]
+ return image_info
+
+ def query_ground_truth(self, data, split, version, label, start_id, max_item):
+ pipeline = self.get_ground_truth_pipeline(data, split, version, label, start_id, max_item)
+ image_info = list(self._gt.aggregate(pipeline['pipeline']))
+ logging.info(len(image_info))
+ image_info = [{'key': x['key'],
+ 'url': x['url'],
+ 'gt': x['gt']} for x in image_info]
+ return pipeline, image_info
+
+ def get_ground_truth_pipeline(self, data, split, version, label, start_id, max_item):
+ rank, start_id = self._get_positive_start(start_id, max_item)
+
+ match_pairs = {'data': data}
+ gt_match = []
+ gt_match.append({'$eq': ['$data', data]})
+ url_match = []
+ url_match.append({'$eq': ['$data', data]})
+ if split is not None:
+ match_pairs['split'] = split
+ gt_match.append({'$eq': ['$split', split]})
+ url_match.append({'$eq': ['$split', split]})
+ if label is not None:
+ match_pairs['class'] = label
+ if version is not None:
+ match_pairs['version'] = {'$lte': version}
+ gt_match.append({'$lte': ['$version', version]})
+ gt_match.append({'$eq': ['$key', '$$key']})
+ url_match.append({'$eq': ['$key', '$$key']})
+ pipeline = [{'$match': match_pairs},
+ {'$group': {'_id': {'key': '$key'},
+ 'contribution': {'$sum': '$contribution'}}},
+ {'$match': {'contribution': {'$gte': 1}}},
+ {'$sort': {'_id.key': rank}},
+ {'$skip': start_id},
+ {'$limit': max_item},
+ # add gt boxes
+ {'$lookup': {
+ 'from': 'ground_truth',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': gt_match}}},
+ {'$group': {'_id': {'action_target_id': '$action_target_id'},
+ 'contribution': {'$sum': '$contribution'},
+ 'rect': {'$first': '$rect'},
+ 'class': {'$first': '$class'},
+ 'conf': {'$first': '$conf'}}, },
+ {'$match': {'contribution': {'$gte': 1}}},
+ ],
+ 'as': 'gt',
+ }},
+ # add url
+ {'$lookup': {
+ 'from': 'image',
+ 'let': {'key': '$_id.key'},
+ 'pipeline': [{'$match': {'$expr': {'$and': url_match}}},
+ {'$project': {'url': True, '_id': 0}}],
+ 'as': 'url',
+ }},
+ {'$unwind': '$url'},
+ {'$addFields': {'url': '$url.url',
+ 'key': '$_id.key'}},
+ ]
+
+ return {'pipeline': pipeline,
+ 'database': 'qd',
+ 'collection': 'ground_truth'}
+
+def get_class_count(data, splits):
+ dataset = TSVDataset(data)
+ result = {}
+ for split in splits:
+ result[split] = {row[0]: int(row[1])
+ for row in dataset.iter_data(
+ split, 'inverted.label.count', -1)}
+ return result
+
+def get_colored_name(node, colors):
+ name = node.name
+ if hasattr(node, 'sub_group'):
+ sub_group = node.sub_group
+ else:
+ sub_group = -1
+ idx = sub_group + 1
+ while idx >= len(colors):
+ colors.append('rgb({},{},{})'.format(
+ int(random.random() * 255),
+ int(random.random() * 255),
+ int(random.random() * 255)))
+ return "{}".format(colors[idx],
+ name)
+
+def get_vis_url(data, l, split=None):
+ if split is None:
+ return '/detection/view_image?data={}&label={}&start_id=0'.format(
+ data, l)
+ else:
+ return '/detection/view_image?data={}&split={}&label={}&start_id=0'.format(
+ data, split, l)
+
+
+def get_readable_label(l):
+ if is_noffset(l):
+ return '{}({})'.format(l, get_nick_name(noffset_to_synset(l)))
+ else:
+ return l
+
+def get_node_key(node, k, default_value=-1):
+ r = default_value
+ if hasattr(node, k):
+ r = node.__getattribute__(k)
+ return r
+
+def get_node_info(data, node, colors, all_data):
+ ss = []
+ if hasattr(node, 'ap'):
+ ss.append('ap({0:.2f})'.format(node.ap))
+ if hasattr(node, 'images_with_bb') and \
+ hasattr(node, 'images_no_bb'):
+ keys = ['with_bb', 'no_bb']
+ for k in keys:
+ ss.append("{}({},{},{})".format(
+ k,
+ get_node_key(node, 'images_' + k, -1),
+ get_vis_url(data + '_' + k, node.name, split='train'),
+ get_node_key(node, k + '_train', -1),
+ get_vis_url(data + '_' + k, node.name, split='test'),
+ get_node_key(node, k + '_test', -1)))
+ ignore_keys = ['support', 'dist', 'name', 'url',
+ 'with_bb_train',
+ 'with_bb_test',
+ 'no_bb_train',
+ 'no_bb_test',
+ 'ap',
+ 'images_with_bb',
+ 'images_no_bb',
+ 'noffset',
+ 'sub_group',
+ 'cum_images_with_bb',
+ 'cum_images_no_bb']
+ for key in node.features:
+ if any(x == key for x in ignore_keys):
+ continue
+ if key.endswith('_readable') or \
+ key.endswith('_toTrain') or \
+ key.endswith('_toTest') or \
+ key.endswith('_total'):
+ continue
+ value = node.__getattribute__(key)
+ if key in all_data and value != None:
+ total = get_node_key(node, '{}_total'.format(key))
+ toTrain = get_node_key(node, '{}_toTrain'.format(key))
+ toTest = get_node_key(node, '{}_toTest'.format(key))
+ extra_info = '({},{},{})'.format(total, toTrain, toTest)
+ labels = value.split(',')
+ value = ','.join(["{}".format(get_vis_url(key, l),
+ get_readable_label(l)) for l in labels])
+ value = '{}{}'.format(value, extra_info)
+ ss.append('{}[{}]'.format(key, value))
+ if len(ss) > 0:
+ return "{}: {}".format(
+ get_colored_name(node, colors),
+ '; '.join(ss))
+ else:
+ return get_colored_name(node, colors)
+
+def gen_html_tree_view(data, full_expid=None,
+ predict_file=None):
+ colors=['rgb(0,0,0)',
+ 'rgb(255,0,0)',
+ 'rgb(0,0,255)']
+ dataset = TSVDataset(data)
+ all_data = os.listdir('./data')
+ file_name = op.join(dataset._data_root, 'root_enriched.yaml')
+ logging.info('loading {}'.format(file_name))
+ with open(file_name, 'r') as fp:
+ config_tax = yaml.load(fp)
+ tax = Taxonomy(config_tax)
+ if full_expid is not None and \
+ predict_file is not None:
+ map_file = op.join('output',full_expid, 'snapshot',
+ op.splitext(predict_file)[0] + '.report.class_ap.json')
+ if op.isfile(map_file):
+ class_ap = json.loads(read_to_buffer(map_file))
+ class_ap = class_ap['overall']['0.3']['class_ap']
+ for node in tax.root.iter_search_nodes():
+ node.add_feature('ap',
+ class_ap.get(node.name, -1))
+
+ def gen_html_tree_view_rec(root):
+ '''
+ include itself
+ '''
+ if len(root.children) == 0:
+ s = u"{}".format(
+ get_node_info(data, root, colors, all_data))
+ return s
+ else:
+ result = []
+ # we cannot remove span tag here
+ result.append("{}".format(
+ get_node_info(data, root, colors, all_data)))
+ result.append('')
+ all_child = sorted(root.children, key=lambda c: c.sub_group)
+ for c in all_child:
+ r = gen_html_tree_view_rec(c)
+ result.append(r)
+ result.append('
')
+ result.append('')
+ return '\n'.join(result)
+ s = gen_html_tree_view_rec(tax.root)
+ return s
+
+
+def gt_predict_images(predicts, gts, test_data, target_images, label, start_id, threshold,
+ label_to_idx, image_aps, test_data_split='test'):
+ test_dataset = TSVDataset(test_data)
+ test_tsv = TSVFile(test_dataset.get_data(test_data_split))
+ for i in xrange(start_id, len(target_images)):
+ key = target_images[i]
+ logging.info('key = {}, ap = {}'.format(key, image_aps[i][1]))
+ idx = label_to_idx[key]
+ row = test_tsv.seek(idx)
+ origin = img_from_base64(row[2])
+ im_gt = np.copy(origin)
+ draw_bb(im_gt, [g['rect'] for g in gts[key]],
+ [g['class'] for g in gts[key]])
+ im_gt_target = np.copy(origin)
+ gts_target = [g for g in gts[key] if g['class'] == label]
+ draw_bb(im_gt_target, [g['rect'] for g in gts_target],
+ [g['class'] for g in gts_target])
+ im_pred = np.copy(origin)
+ rects = [p for p in predicts[key] if p['conf'] > threshold]
+ draw_bb(im_pred, [r['rect'] for r in rects],
+ [r['class'] for r in rects],
+ [r['conf'] for r in rects])
+ im_pred_target = np.copy(origin)
+ rects = [p for p in rects if p['class'] == label]
+ draw_bb(im_pred_target, [r['rect'] for r in rects],
+ [r['class'] for r in rects],
+ [r['conf'] for r in rects])
+ yield key, origin, im_gt_target, im_pred_target, im_gt, im_pred, image_aps[i][1]
+
+def get_confusion_matrix_by_predict_file_label(full_expid,
+ predict_file, label, threshold):
+ '''
+ get confusion matrix for specific label
+ '''
+ test_data, test_data_split = parse_test_data(predict_file)
+
+ # load the gt
+ logging.info('loading {} - {}'.format(test_data, test_data_split))
+ test_dataset = TSVDataset(test_data)
+ rows = test_dataset.iter_data(test_data_split, 'label', -1)
+ gts = {}
+ label_to_idx = {}
+ keys_with_label = []
+ for i, row in enumerate(rows):
+ rects = json.loads(row[1])
+ gts[row[0]] = rects
+ label_to_idx[row[0]] = i
+ if any(r['class'] == label for r in rects):
+ keys_with_label.append(row[0])
+
+ predict_full_path = op.join('output', full_expid, 'snapshot', predict_file)
+ if not full_expid.startswith('Tax'):
+ logging.info('loading {}'.format(predict_file))
+ predicts, _ = load_labels(predict_full_path)
+ else:
+ # create the inverted index
+ pred_label_file = '{}.labelmap.tsv'.format(predict_full_path)
+ pred_inverted_file = '{}.inverted.tsv'.format(predict_full_path)
+ pred_key_file = '{}.key.tsv'.format(predict_full_path)
+ if not op.isfile(pred_label_file) or \
+ not op.isfile(pred_inverted_file) or \
+ not op.isfile(pred_key_file):
+ pred_inverted = {}
+ pred_keys = []
+ rows = tsv_reader(predict_full_path)
+ logging.info('loading data and creating index')
+ inverted, pred_keys = create_inverted_list2(
+ tsv_reader(predict_full_path))
+ logging.info('done loading data and creating index')
+ pred_labels = inverted.keys()
+ tsv_writer(([l] for l in pred_labels), pred_label_file)
+ tsv_writer(((l, ' '.join(map(str, inverted[l]))) for l in
+ pred_labels), pred_inverted_file)
+ tsv_writer([[k] for k in pred_keys], pred_key_file)
+ # find out data whose prediction has the target label
+ all_labels = load_list_file(pred_label_file)
+ if label in all_labels:
+ row = TSVFile(pred_inverted_file).seek(all_labels.index(label))
+ assert row[0] == label
+ idx = map(int, row[1].split(' '))
+ else:
+ idx = []
+ # find out the index from the ground truth
+ key_to_predidx = {k: i for i, k in enumerate(load_list_file(pred_key_file))}
+ idx.extend([key_to_predidx[k] for k in keys_with_label])
+ idx = set(idx)
+ tsv = TSVFile(predict_full_path)
+ predicts = {}
+ logging.info('loading')
+ for i in idx:
+ row = tsv.seek(i)
+ assert len(row) == 2
+ predicts[row[0]] = json.loads(row[1])
+ logging.info('done')
+ # load data from the inverted index
+ logging.info('done loading {}'.format(predict_file))
+
+ return {'predicts': predicts,
+ 'gts': gts,
+ 'label_to_idx': label_to_idx}
+
+def get_confusion_matrix_by_predict_file(full_expid,
+ predict_file, threshold):
+ '''
+ get confusion matrix for all classes
+ '''
+
+ test_data, test_data_split = parse_test_data(predict_file)
+
+ # load the gt
+ logging.info('loading {} - {}'.format(test_data, test_data_split))
+ test_dataset = TSVDataset(test_data)
+ rows = test_dataset.iter_data(test_data_split, 'label', -1)
+ gts = {}
+ label_to_idx = {}
+ for i, row in enumerate(rows):
+ gts[row[0]] = json.loads(row[1])
+ label_to_idx[row[0]] = i
+
+ logging.info('loading {}'.format(predict_file))
+ predicts, _ = load_labels(op.join('output', full_expid, 'snapshot', predict_file))
+ logging.info('done loading {}'.format(predict_file))
+
+ # calculate the confusion matrix
+ confusion_pred_gt = {}
+ confusion_gt_pred = {}
+ update_confusion_matrix(predicts, gts, threshold,
+ confusion_pred_gt,
+ confusion_gt_pred)
+
+ return {'predicts': predicts,
+ 'gts': gts,
+ 'confusion_pred_gt': confusion_pred_gt,
+ 'confusion_gt_pred': confusion_gt_pred,
+ 'label_to_idx': label_to_idx}
+
+def inc_one_dic_dic(dic, c1, c2):
+ if c1 not in dic:
+ dic[c1] = {}
+ if c2 not in dic[c1]:
+ dic[c1][c2] = 0
+ dic[c1][c2] = dic[c1][c2] + 1
+
+def update_confusion_matrix(predicts, gts, threshold,
+ confusion_pred_gt,
+ confusion_gt_pred):
+ for key in predicts:
+ curr_pred = [p for p in predicts[key] if p['conf'] > threshold]
+ if key not in gts:
+ continue
+ curr_gt = gts[key]
+ if len(curr_pred) == 0 and len(curr_gt) > 0:
+ for g in curr_gt:
+ inc_one_dic_dic(confusion_gt_pred, g['class'], 'None')
+ continue
+ elif len(curr_pred) > 0 and len(curr_gt) == 0:
+ for p in curr_pred:
+ inc_one_dic_dic(confusion_pred_gt, p['class'], 'None')
+ continue
+ elif len(curr_pred) == 0 and len(curr_gt) == 0:
+ continue
+ ious = np.zeros((len(curr_pred), len(curr_gt)))
+ for i, p in enumerate(curr_pred):
+ for j, g in enumerate(curr_gt):
+ iou = calculate_iou(p['rect'], g['rect'])
+ ious[i, j] = iou
+ gt_idx = np.argmax(ious, axis=1)
+ for i, p in enumerate(curr_pred):
+ j = gt_idx[i]
+ predict_class = p['class']
+ gt_class = curr_gt[j]['class']
+ if ious[i, j] > 0.3:
+ inc_one_dic_dic(confusion_pred_gt,
+ predict_class, gt_class)
+ else:
+ inc_one_dic_dic(confusion_pred_gt,
+ predict_class, 'None')
+ pred_idx = np.argmax(ious, axis=0)
+ for j, g in enumerate(curr_gt):
+ i = pred_idx[j]
+ predict_class = curr_pred[i]['class']
+ gt_class = g['class']
+ if ious[i, j] > 0.3:
+ inc_one_dic_dic(confusion_gt_pred,
+ gt_class, predict_class)
+ else:
+ inc_one_dic_dic(confusion_gt_pred,
+ gt_class, 'None')
+
+def normalize_str_in_rects(data, out_data):
+ '''
+ normalize all the unicode to string
+ '''
+ dataset = TSVDataset(data)
+ dest_dataset = TSVDataset(out_data)
+ splits = get_default_splits()
+ for split in splits:
+ if not op.isfile(dataset.get_data(split)):
+ continue
+ def gen_rows():
+ for key, label_str, im_str in tsv_reader(dataset.get_data(split)):
+ rects = json.loads(label_str)
+ for rect in rects:
+ s = rect['class']
+ rect['class'] = normalize_to_str(s)
+ if s != rect['class']:
+ logging.info(u'{}->{}'.format(s, rect['class']))
+ label_str = json.dumps(rects)
+ yield key, label_str, im_str
+ tsv_writer(gen_rows(), dest_dataset.get_data(split))
+
+def tsv_details(row_hw, row_label, num_rows):
+ label_count = {}
+ sizes = []
+ logging.info('tsv details...')
+ for r_hw, r_label in tqdm(zip(row_hw, row_label), total=num_rows):
+ if r_label[1] == 'd':
+ # this is the deleted label
+ rects = []
+ else:
+ rects = json.loads(r_label[1])
+ assert r_hw[0] == r_label[0]
+ height, width = map(int, r_hw[1].split(' '))
+ if type(rects) is list:
+ # this is the detection dataset
+ # convert it to str. if it is unicode, in yaml, there will be some
+ # special tags, which is annoying
+ curr_labels = set(normalize_to_str(rect['class']) for rect in rects)
+ for rect in rects:
+ if 'rect' not in rect or all(x == 0 for x in rect['rect']):
+ # it is image-level annotation
+ continue
+ r = rect['rect']
+ # this should be a valid bounding box
+ cx, cy = (r[0] + r[2]) / 2., (r[1] + r[3]) / 2.
+ rw, rh = r[2] - r[0], r[3] - r[1]
+ #assert cx >= 0 and cx < width \
+ #and cy >= 0 and cy < height
+ if rw < 1 or rh < 1:
+ logging.warn('rw or rh too small: {} - {}'.format(r_label[0],
+ ','.join(map(str, r))))
+ else:
+ # this is classification dataset
+ assert type(rects) is int
+ curr_labels = [rects]
+ for c in curr_labels:
+ if c in label_count:
+ label_count[c] = label_count[c] + 1
+ else:
+ label_count[c] = 1
+ sizes.append((height, width))
+ size_counts = [s[0] * s[1] for s in sizes]
+ min_size = sizes[np.argmin(size_counts)]
+ max_size = sizes[np.argmax(size_counts)]
+ min_size = map(float, min_size)
+ max_size = map(float, max_size)
+ mean_size = (np.mean([s[0] for s in sizes]),
+ np.mean([s[1] for s in sizes]))
+ mean_size = map(float, mean_size)
+
+ return {'label_count': label_count,
+ 'min_image_size': min_size,
+ 'max_image_size': max_size,
+ 'mean_image_size': mean_size}
+
+
+def detect_duplicate_key(tsv, duplicate_tsv):
+ rows = tsv_reader(tsv)
+ key_to_idx = {}
+ for i, row in enumerate(rows):
+ key = row[0]
+ if key in key_to_idx:
+ key_to_idx[key].append(i)
+ else:
+ key_to_idx[key] = [i]
+ def gen_rows():
+ for key in key_to_idx:
+ idxs = key_to_idx[key]
+ if len(idxs) > 1:
+ logging.info('duplicate key: {}: {}'.format(key, ', '.join(map(str,
+ idxs))))
+ yield key, ','.join(map(str, idxs))
+ tsv_writer(gen_rows(), duplicate_tsv)
+ return TSVFile(duplicate_tsv).num_rows()
+
+def populate_all_dataset_details():
+ all_data = os.listdir('data/')
+ for data in all_data:
+ try:
+ populate_dataset_details(data)
+ except:
+ continue
+
+def update_labelmap(rows, num_rows, labelmap):
+ '''
+ labelmap is a hashset and can be added
+ '''
+ logging.info('updating labelmap')
+ for row in tqdm(rows, total=num_rows):
+ assert len(row) == 2
+ try:
+ labelmap.update(set([rect['class'] for rect in
+ json.loads(row[1])]))
+ except:
+ labelmap.add(row[1])
+ logging.info('done')
+
+def derive_composite_meta_data(data, split, t):
+ data_to_dataset = {}
+ dataset = TSVDataset(data)
+ all_source_data_split = dataset.load_composite_source_data_split(split)
+ def gen_rows():
+ assert dataset.has(split, 'label')
+ iter_label = dataset.iter_data(split, 'label')
+ iter_shuffle = tsv_reader(dataset.get_shuffle_file(split))
+ for (idx_source, idx_row), (label_row) in zip(iter_shuffle,
+ iter_label):
+ idx_source = int(idx_source)
+ idx_row = int(idx_row)
+ c_data, c_split = all_source_data_split[idx_source]
+ if c_data in data_to_dataset:
+ c_dataset = data_to_dataset[c_data]
+ else:
+ c_dataset = TSVDataset(c_data)
+ data_to_dataset[c_data] = c_dataset
+ assert c_dataset.has(c_split, t)
+ key, t_data = c_dataset.seek_by_idx(idx_row, c_split, t)
+ yield label_row[0], t_data
+ assert not dataset.has(split, t)
+ dataset.write_data(gen_rows(), split, t)
+
+def ensure_create_inverted_tsvs(dataset, splits):
+ # for each data tsv, generate the inverted file, and the labelmap
+ is_parallel = True
+ for split in splits:
+ if not dataset.has(split):
+ continue
+ latest = dataset.get_latest_version(split, 'label')
+ if not is_parallel:
+ for v in range(latest + 1):
+ assert dataset.has(split, 'label', v)
+ ensure_create_inverted_tsv_for_each((dataset, split, v))
+ else:
+ params = [(dataset, split, v) for v in range(latest + 1)]
+ params = [param for param in params if
+ not has_inverted(param)]
+ if len(params) > 0:
+ p = Pool()
+ p.map(ensure_create_inverted_tsv_for_each, params)
+
+ # generate the inverted tsv for background images without any labels
+ for split in splits:
+ if not dataset.has(split):
+ continue
+ latest = dataset.get_latest_version(split, 'label')
+ if not is_parallel:
+ for v in range(latest + 1):
+ assert dataset.has(split, 'label', v)
+ ensure_create_inverted_tsv_background_for_each((dataset, split, v))
+ else:
+ params = [(dataset, split, v) for v in range(latest + 1)]
+ params = [param for param in params if
+ not has_inverted_background(param)]
+ if len(params) > 0:
+ p = Pool()
+ p.map(ensure_create_inverted_tsv_background_for_each, params)
+
+def has_inverted(param):
+ dataset, split, v = param
+ inverted_keys = ['inverted.label',
+ 'inverted.label.with_bb',
+ 'inverted.label.no_bb',
+ 'inverted.label.with_bb.verified',
+ 'inverted.label.with_bb.noverified',]
+ return all(dataset.has(split, k, v) for k in inverted_keys)
+
+def has_inverted_background(args):
+ dataset, split, v = args
+ if dataset.has(split, 'inverted.background', version=v) and \
+ dataset.has(split, 'inverted.background.count'):
+ return True
+ else:
+ return False
+
+def ensure_create_inverted_tsv_background_for_each(args):
+ dataset, split, v = args
+ if dataset.has(split, 'inverted.background', version=v) and \
+ dataset.has(split, 'inverted.background.count'):
+ return
+ label_to_indices = dataset.load_inverted_label(split, version=v)
+ all_idx = [i for l in label_to_indices for i in label_to_indices[l]]
+ all_idx = set(all_idx)
+ num = dataset.num_rows(split)
+ background_idx = set(range(num)).difference(all_idx)
+
+ def gen_rows():
+ yield 'background', ' '.join(map(str, background_idx))
+ dataset.write_data(gen_rows(), split, 'inverted.background', version=v)
+
+ def gen_row_count():
+ yield 'background', len(background_idx)
+ dataset.write_data(gen_row_count(), split, 'inverted.background.count',
+ version=v)
+
+def ensure_create_inverted_tsv_for_each(args):
+ dataset, split, v = args
+ if not dataset.has(split, 'labelmap', v) or \
+ dataset.last_update_time(split, 'labelmap', v) < dataset.last_update_time(split, 'label', v):
+ curr_labelmap = set()
+ update_labelmap(dataset.iter_data(split, 'label', v),
+ dataset.num_rows(split),
+ curr_labelmap)
+ curr_labelmap = sorted(list(curr_labelmap))
+ dataset.write_data([[l] for l in curr_labelmap], split, 'labelmap', v)
+ else:
+ curr_labelmap = None
+ inverted_keys = ['inverted.label',
+ 'inverted.label.with_bb',
+ 'inverted.label.no_bb',
+ 'inverted.label.with_bb.verified',
+ 'inverted.label.with_bb.noverified',]
+ if any(not dataset.has(split, k, v) for k in inverted_keys):
+ logging.info('version = {}'.format(v))
+ if curr_labelmap is None:
+ curr_labelmap = []
+ for row in dataset.iter_data(split, 'labelmap', v):
+ assert len(row) == 1
+ curr_labelmap.append(row[0])
+ def gen_inverted_rows(inv):
+ logging.info('re-orderring')
+ set_labelmap = set(curr_labelmap)
+ for label in tqdm(inv):
+ assert label in set_labelmap
+ for label in tqdm(curr_labelmap):
+ i = inv[label] if label in inv else []
+ yield label, ' '.join(map(str, i))
+ inverted_result = create_inverted_list(
+ dataset.iter_data(split, 'label', v))
+ for k in inverted_keys:
+ dataset.write_data(gen_inverted_rows(inverted_result[k]),
+ split, k, v)
+
+def ensure_extract_from_data_source(data, split, t):
+ assert t != 'label'
+ dataset = TSVDataset(data)
+ if dataset.has(split, t):
+ logging.info('ignore to generate {}, {}, {}'.format(data, split, t))
+ return
+ all_data_split = dataset.load_composite_source_data_split(split)
+ source_data_to_dataset = {}
+ label_iter = dataset.iter_data(split, 'label')
+ shuffle_iter = tsv_reader(dataset.get_shuffle_file(split))
+ def gen_rows():
+ for (idx_source, idx_row), label_row in zip(shuffle_iter, label_iter):
+ idx_source, idx_row = int(idx_source), int(idx_row)
+ source_data, source_split = all_data_split[idx_source]
+ if source_data not in source_data_to_dataset:
+ source_data_to_dataset[source_data] = TSVDataset(source_data)
+ source_dataset = source_data_to_dataset[source_data]
+ source_key, str_t = source_dataset.seek_by_idx(idx_row, source_split, t)
+ assert label_row[0] == '_'.join([source_data, source_split, source_key])
+ yield label_row[0], str_t
+ dataset.write_data(gen_rows(), split, t)
+
+def populate_dataset_hw(data,
+ splits=('train', 'trainval', 'test', 'val'),
+ img_t=None,
+ multi_thread=True,
+ ):
+ dataset = TSVDataset(data)
+ for split in splits:
+ if dataset.has(split, img_t) and not dataset.has(split, 'hw'):
+ success = False
+ if op.isfile(dataset.get_data(split + 'X', img_t)):
+ try:
+ derive_composite_meta_data(data, split, 'hw')
+ success = True
+ except:
+ pass
+ if not success:
+ if not multi_thread:
+ logging.info('generating hw')
+ rows = dataset.iter_data(split, img_t, progress=True)
+ dataset.write_data(((row[0], ' '.join(map(str,
+ img_from_base64(row[-1]).shape[:2]))) for
+ row in rows), split, 'hw')
+ else:
+ num_images = dataset.num_rows(split, img_t)
+ num_tasks = min(num_images, 128 * 3)
+ num_worker = (num_tasks + 2) // 3
+ num_image_per_worker = (num_images + num_tasks - 1) // num_tasks
+ assert num_image_per_worker > 0
+ all_idx = []
+ for i in range(num_tasks):
+ curr_idx_start = i * num_image_per_worker
+ if curr_idx_start >= num_images:
+ break
+ curr_idx_end = curr_idx_start + num_image_per_worker
+ curr_idx_end = min(curr_idx_end, num_images)
+ if curr_idx_end > curr_idx_start:
+ all_idx.append(range(curr_idx_start, curr_idx_end))
+ logging.info('creating pool')
+ m = Pool(num_worker)
+ def get_hw(filter_idx):
+ dataset = TSVDataset(data)
+ rows = dataset.iter_data(split, img_t, progress=True,
+ filter_idx=filter_idx)
+ return [(row[0], ' '.join(map(str,
+ img_from_base64(row[-1]).shape[:2])))
+ for row in rows]
+ all_result = m.map(get_hw, all_idx)
+ x = []
+ for r in all_result:
+ x.extend(r)
+ dataset.write_data(x, split, 'hw')
+
+def ensure_label_extract(data, splits):
+ dataset = TSVDataset(data)
+ for split in splits:
+ if (not dataset.has(split, 'label')) and \
+ dataset.has(split):
+ def gen_rows():
+ if op.isfile(dataset.get_data(split)):
+ iter_row = dataset.iter_data(split)
+ else:
+ iter_row = dataset.iter_composite(split, t=None, version=0)
+ for row in tqdm(iter_row):
+ if len(row) == 3:
+ str_rects = row[1]
+ else:
+ assert len(row) == 2
+ str_rects = json_dump([])
+ yield row[0], str_rects
+ dataset.write_data(gen_rows(), split, 'label')
+
+def ensure_labelmap_extract(data):
+ splits = get_default_splits()
+ dataset = TSVDataset(data)
+ # generate the label map if there is no
+ if not op.isfile(dataset.get_labelmap_file()) and \
+ not op.islink(dataset.get_labelmap_file()):
+ logging.info('no labelmap, generating...')
+ labelmap = []
+ for split in splits:
+ label_tsv = dataset.get_data(split, 'label', version=0)
+ if not op.isfile(label_tsv):
+ continue
+ for row in tqdm(tsv_reader(label_tsv)):
+ try:
+ labelmap.extend(set([rect['class'] for rect in
+ json.loads(row[1])]))
+ except:
+ labelmap.append(row[1])
+ if len(labelmap) == 0:
+ logging.warning('there are no labels!')
+ labelmap = sorted(list(set(labelmap)))
+ logging.info('find {} labels'.format(len(labelmap)))
+ need_update = False
+ if op.isfile(dataset.get_labelmap_file()):
+ origin_labelmap = dataset.load_labelmap()
+ if len(origin_labelmap) == len(labelmap):
+ for o in origin_labelmap:
+ if o not in labelmap:
+ need_update = True
+ break
+ else:
+ need_update = True
+ else:
+ need_update = True
+ if need_update:
+ logging.info('updating {}'.format(dataset.get_labelmap_file()))
+ write_to_file('\n'.join(labelmap), dataset.get_labelmap_file())
+
+def populate_dataset_details(data, check_image_details=False,
+ splits=None, check_box=False, data_root=None):
+ logging.info(data)
+ dataset = TSVDataset(data)
+
+ if not splits:
+ splits = get_default_splits()
+
+ # populate the height and with
+ if check_image_details:
+ populate_dataset_hw(data, splits)
+
+ ensure_label_extract(data, splits)
+
+ for split in splits:
+ tsv_file = dataset.get_data(split)
+ out_file = get_meta_file(tsv_file)
+ if not op.isfile(out_file) and \
+ dataset.has(split, 'hw') and \
+ dataset.has(split):
+ row_hw = dataset.iter_data(split, 'hw')
+ row_label = dataset.iter_data(split, 'label')
+ num_rows = dataset.num_rows(split)
+ if check_image_details:
+ details = tsv_details(row_hw, row_label, num_rows)
+ write_to_yaml_file(details, out_file)
+
+ ensure_labelmap_extract(data)
+
+ labelmap = []
+ if not op.isfile(dataset.get_pos_labelmap_file()):
+ ls = dataset.load_labelmap()
+ write_to_file('\n'.join([l for l in ls if not l.startswith('-')]),
+ dataset.get_pos_labelmap_file())
+
+ # generate the rows with duplicate keys
+ for split in splits:
+ label_tsv = dataset.get_data(split, 'label')
+ duplicate_tsv = dataset.get_data(split, 'key_duplicate')
+ if op.isfile(label_tsv) and not op.isfile(duplicate_tsv):
+ detect_duplicate_key(label_tsv, duplicate_tsv)
+
+ # generate lineidx if it is not generated
+ for split in splits:
+ lineidx = dataset.get_lineidx(split)
+ full_tsv = dataset.get_data(split)
+ if not op.isfile(lineidx) and op.isfile(full_tsv):
+ logging.info('no lineidx for {}. generating...'.format(split))
+ generate_lineidx(full_tsv, lineidx)
+
+ ensure_create_inverted_tsvs(dataset, splits)
+ # check if the number of rows from the label tsv are equal to the number of rows in image tsv
+ for split in splits:
+ v = 0
+ num_rows = None
+ while True:
+ if not dataset.has(split, 'label', v):
+ break
+ if dataset.has(split, 'check_count', v):
+ v = v + 1
+ continue
+ if num_rows is None:
+ num_rows = dataset.num_rows(split)
+ num_rows_in_label = dataset.num_rows(split, 'label', v)
+ # we can remove the assert
+ assert num_rows == num_rows_in_label
+ if num_rows != num_rows_in_label:
+ dataset.write_data([['num_rows', num_rows], ['num_rows_in_label', num_rows_in_label]],
+ split, 'check_count', v)
+ else:
+ dataset.write_data([], split, 'check_count', v)
+ v = v + 1
+
+ if not op.isfile(dataset.get_noffsets_file()):
+ logging.info('no noffset file. generating...')
+ labelmap = dataset.load_labelmap()
+ mapper = LabelToSynset(True)
+ ambigous = []
+ ss = [mapper.convert(l) for l in labelmap]
+ for l, (success, s) in zip(labelmap, ss):
+ if not success and len(s) > 1:
+ d = create_info_for_ambigous_noffset(l, [synset_to_noffset(s1)
+ for s1 in s])
+ ambigous.append(d)
+ if len(ambigous) > 0:
+ logging.info('ambigous term which has no exact noffset: {}'.format(
+ dataset.name))
+ write_to_yaml_file(ambigous, dataset.get_noffsets_file() +
+ '.ambigous.yaml')
+ noffsets = []
+ for success, s in ss:
+ if not success:
+ noffsets.append('')
+ else:
+ noffsets.append(','.join([synset_to_noffset(o) for o in s]))
+ write_to_file('\n'.join(noffsets), dataset.get_noffsets_file())
+
+ if not op.isfile(dataset.get_labelmap_of_noffset_file()):
+ noffsets = dataset.load_noffsets()
+ all_line = []
+ for noffset in noffsets:
+ if len(noffset) == 0:
+ all_line.append('unkown')
+ else:
+ ss = [noffset_to_synset(n) for n in noffset.split(',')]
+ all_line.append(','.join([get_nick_name(s) for s in ss]))
+ write_to_file('\n'.join(all_line),
+ dataset.get_labelmap_of_noffset_file())
+
+ # generate the label -> count tsv
+ for split in splits:
+ v = 0
+ while True:
+ label_idx_file = dataset.get_data(split, 'inverted.label', v)
+ label_count_file = dataset.get_data(split, 'inverted.label.count', v)
+ if op.isfile(label_idx_file):
+ if not op.isfile(label_count_file):
+ label_idx = dataset.load_inverted_label_as_list(split, v)
+ tsv_writer(((l, str(len(i))) for l, i in label_idx), label_count_file)
+ else:
+ break
+ v = v + 1
+
+ if op.isfile(dataset.get_data('trainX')):
+ # composite dataset.
+ create_index_composite_dataset(dataset)
+
+ populate_num_images_composite(dataset)
+
+ add_node_to_ancestors(dataset)
+
+ populate_all_label_counts(dataset)
+
+ if check_box:
+ populate_bbcount(dataset)
+
+def create_label_bbcount(dataset, split, v):
+ class_to_bbcount = defaultdict(int)
+ logging.info('reading {}, {}, {}'.format(split, 'label', v))
+ for key, str_rects in dataset.iter_data(split, 'label',
+ v, progress=True):
+ rects = json.loads(str_rects)
+ for r in rects:
+ if 'rect' in r and not all(x == 0 for x in r['rect']):
+ c = r['class']
+ class_to_bbcount[c] = class_to_bbcount[c] + 1
+ labelmap = [l for l, in dataset.iter_data(split, 'labelmap',
+ v)]
+ dataset.write_data(((l, class_to_bbcount.get(l, 0)) for l in labelmap),
+ split, 'label.bbcount', v)
+
+def create_label_verifiedbbcount(dataset, split, v):
+ class_to_bbcount = defaultdict(int)
+ logging.info('reading {}, {}, {}'.format(split, 'label', v))
+ for key, str_rects in dataset.iter_data(split, 'label',
+ v, progress=True):
+ rects = json.loads(str_rects)
+ for r in rects:
+ if 'rect' in r and \
+ not all(x == 0 for x in r['rect']) and \
+ is_verified_rect(r):
+ c = r['class']
+ class_to_bbcount[c] = class_to_bbcount[c] + 1
+ labelmap = [l for l, in dataset.iter_data(split, 'labelmap',
+ v)]
+ dataset.write_data(((l, class_to_bbcount.get(l, 0)) for l in labelmap),
+ split, 'label.verifiedbbcount', v)
+
+def populate_bbcount(dataset):
+ for split in get_default_splits():
+ v = 0
+ while True:
+ if dataset.has(split, 'label', v):
+ if not dataset.has(split, 'label.verifiedbbcount', v):
+ create_label_verifiedbbcount(dataset, split, v)
+ if not dataset.has(split, 'label.bbcount', v):
+ create_label_bbcount(dataset, split, v)
+ v = v + 1
+ else:
+ break
+
+def populate_all_label_counts(dataset):
+ for split in get_default_splits():
+ v = 0
+ while True:
+ if dataset.has(split, 'inverted.label.count', v):
+ if not dataset.has(split, 'inverted.label.count.total', v):
+ count = sum([int(count) for _, count in dataset.iter_data(split,
+ 'inverted.label.count', v)])
+ dataset.write_data([(str(count),)],
+ split,
+ 'inverted.label.count.total', v)
+ v = v + 1
+ else:
+ break
+
+def add_node_to_ancestors(dataset):
+ tree_file = op.join(dataset._data_root, 'root.yaml')
+ out_file = op.join(dataset._data_root, 'treenode_to_ancestors.tsv')
+ if op.isfile(tree_file) and worth_create(tree_file, out_file):
+ tax = Taxonomy(load_from_yaml_file(tree_file))
+ tax.update()
+ tsv_writer([[name, ','.join(tax.name_to_ancestors_list[name])] for name in
+ tax.name_to_ancestors_list], out_file)
+
+def populate_num_images_composite(dataset):
+ data_with_bb = dataset.name + '_with_bb'
+ data_no_bb = dataset.name + '_no_bb'
+ datas = [data_with_bb, data_no_bb]
+ datasets = [TSVDataset(d) for d in datas]
+ suffixes = ['with_bb', 'no_bb']
+ splits = ['train', 'test']
+ dest_tree_file = op.join(dataset._data_root, 'root_enriched.yaml')
+ src_tree_file = op.join(dataset._data_root, 'root.yaml')
+ if op.isfile(dest_tree_file) or not op.isfile(src_tree_file):
+ return
+ tax = Taxonomy(load_from_yaml_file(src_tree_file))
+ for split in splits:
+ for suffix, d in zip(suffixes, datasets):
+ if not d.has(split, 'inverted.label.count'):
+ continue
+ label_to_count_with_bb = {label: int(count) for label, count in d.iter_data(split,
+ 'inverted.label.count')}
+ for label in label_to_count_with_bb:
+ count = label_to_count_with_bb[label]
+ if not label.startswith('-'):
+ nodes = tax.root.search_nodes(name=label)
+ else:
+ nodes = tax.root.search_nodes(name=label[1:])
+ assert len(nodes) == 1, label
+ node = nodes[0]
+ if not label.startswith('-'):
+ node.add_feature('{}_{}'.format(suffix, split), count)
+ else:
+ node.add_feature('{}_{}_neg'.format(suffix, split), count)
+ write_to_yaml_file(tax.dump(), dest_tree_file)
+
+def create_index_composite_dataset(dataset):
+ split = 'train'
+ splitx = split + 'X'
+ fname_numImagesPerSource = dataset.get_data(splitx,
+ 'numImagesPerSource')
+ if op.isfile(fname_numImagesPerSource):
+ return
+ # how many images are contributed from each data source
+ trainX_file = dataset.get_data(splitx)
+ source_tsvs = load_list_file(trainX_file)
+
+ shuffle_file = dataset.get_shuffle_file(split)
+ if not op.isfile(shuffle_file):
+ return
+ rows = tsv_reader(shuffle_file)
+ all_idxSource_idxRow = []
+ for idx_source, idx_row in rows:
+ all_idxSource_idxRow.append((int(idx_source), int(idx_row)))
+ # note, the data may be duplicated.
+ all_idxSource_idxRow = list(set(all_idxSource_idxRow))
+
+ idxSource_to_idxRows = list_to_dict(all_idxSource_idxRow, 0)
+ num_images_per_datasource = [None] * len(source_tsvs)
+ num_srcimages_per_datasource = [TSVFile(s).num_rows() for s in source_tsvs]
+ for idxSource in idxSource_to_idxRows:
+ assert num_images_per_datasource[idxSource] is None
+ num_images_per_datasource[idxSource] = len(idxSource_to_idxRows[idxSource])
+ tsv_writer([(name, str(num)) for name, num in zip(source_tsvs,
+ num_images_per_datasource)], fname_numImagesPerSource)
+ dataset.write_data([(source_tsvs[i], num_images_per_datasource[i], num_srcimages_per_datasource[i])
+ for i in range(len(source_tsvs))], splitx,
+ 'tsvsource.numdestimages.numsrcimages')
+
+ # for each data source, how many labels are contributed and how many are
+ # not
+ if op.isfile(dataset.get_data(splitx, 'origin.label')):
+ source_tsv_label_files = load_list_file(dataset.get_data(splitx,
+ 'origin.label'))
+ source_tsv_labels = [TSVFile(t) for t in source_tsv_label_files]
+ trainX_label_file = dataset.get_data(splitx, 'label')
+ all_dest_label_file = load_list_file(trainX_label_file)
+ dest_labels = [TSVFile(f) for f in all_dest_label_file]
+ all_idxSource_sourceLabel_destLabel = []
+ logging.info('each datasource and each idx row')
+ idxSource_to_numRect = {}
+ all_idxSource_numSourceRects_numDestRects = []
+ for idx_source, idx_row in tqdm(all_idxSource_idxRow):
+ source_rects = json.loads(source_tsv_labels[idx_source].seek(idx_row)[-1])
+ dest_rects = json.loads(dest_labels[idx_source].seek(idx_row)[-1])
+ if idx_source not in idxSource_to_numRect:
+ idxSource_to_numRect[idx_source] = 0
+ idxSource_to_numRect[idx_source] = idxSource_to_numRect[idx_source] + \
+ len(dest_rects)
+ all_idxSource_numSourceRects_numDestRects.append((
+ idx_source, len(source_rects), len(dest_rects)))
+ for r in dest_rects:
+ all_idxSource_sourceLabel_destLabel.append((idx_source,
+ r.get('class_from', r['class']), r['class']))
+ idxSource_to_numSourceRects_numDestRects = list_to_dict(
+ all_idxSource_numSourceRects_numDestRects, 0)
+ idxSource_to_numSourceRects_numDestRect = {idxSource: [sum(x1 for x1, x2 in idxSource_to_numSourceRects_numDestRects[idxSource]),
+ sum(x2 for x1, x2 in idxSource_to_numSourceRects_numDestRects[idxSource])]
+ for idxSource in idxSource_to_numSourceRects_numDestRects}
+
+ dataset.write_data([(source_tsvs[idxSource],
+ idxSource_to_numSourceRects_numDestRect[idxSource][1],
+ idxSource_to_numSourceRects_numDestRect[idxSource][0])
+ for idxSource in range(len(source_tsvs))],
+ splitx, 'tsvsource.numdestbbs.numsrcbbs')
+
+ sourcetsv_to_num_rect = {source_tsvs[idx_source]: idxSource_to_numRect[idx_source]
+ for idx_source in idxSource_to_numRect}
+ dataset.write_data([(s, sourcetsv_to_num_rect[s]) for s in source_tsvs],
+ splitx, 'numRectsPerSource')
+
+ idxSource_to_sourceLabel_destLabels = list_to_dict(
+ all_idxSource_sourceLabel_destLabel, 0)
+ source_numSourceLabels = [(s, 0) for s in source_tsvs]
+ source_includedSourceLabels = [(s, []) for s in source_tsvs]
+ for idxSource in idxSource_to_sourceLabel_destLabels:
+ sourceLabel_destLabels = idxSource_to_sourceLabel_destLabels[idxSource]
+ sourceLabel_to_destLabels = list_to_dict(sourceLabel_destLabels, 0)
+ source_numSourceLabels[idxSource] = (source_tsvs[idxSource],
+ len(sourceLabel_to_destLabels))
+ source_includedSourceLabels[idxSource][1].extend(
+ sourceLabel_to_destLabels.keys())
+
+ dataset.write_data([(n, str(i)) for (n, i) in source_numSourceLabels],
+ splitx, 'numCategoriesPerSource')
+
+ # save teh list of included labels
+ sourceDataset_to_includedSourceLabels = {}
+ for source, sourceLabels in source_includedSourceLabels:
+ source_dataset_name = op.basename(op.dirname(source))
+ if source_dataset_name not in sourceDataset_to_includedSourceLabels:
+ sourceDataset_to_includedSourceLabels[source_dataset_name] = []
+ sourceDataset_to_includedSourceLabels[source_dataset_name].extend(sourceLabels)
+ for source_dataset_name in sourceDataset_to_includedSourceLabels:
+ sourceDataset_to_includedSourceLabels[source_dataset_name] = \
+ set(sourceDataset_to_includedSourceLabels[source_dataset_name])
+
+ tsv_writer([(n, ','.join(sourceDataset_to_includedSourceLabels[n])) for n in
+ sourceDataset_to_includedSourceLabels], op.join(dataset._data_root,
+ 'trainX.includeCategoriesPerSourceDataset.tsv'))
+
+ tsv_writer([(n, get_nick_name(noffset_to_synset(s)) if is_noffset(s) else
+ s) for n in sourceDataset_to_includedSourceLabels
+ for s in sourceDataset_to_includedSourceLabels[n]],
+ op.join(dataset._data_root, 'trainX.includeCategoriesPerSourceDatasetReadable.tsv'))
+
+class TSVTransformer(object):
+ def __init__(self):
+ self._total_rows = 0
+ self._row_processor = None
+
+ def ReadProcess(self, source_tsv, row_processor):
+ self._row_processor = row_processor
+ self._total_rows = 0
+
+ rows = tsv_reader(source_tsv)
+ x = [self._over_row_processor(row) for row in rows]
+
+ logging.info('total rows = {}; total_processed = {}'.format(self._total_rows,
+ len(x)))
+
+ def Process(self, source_tsv, dst_tsv, row_processor):
+ '''
+ row_processor: a function whose input should be a list of tsv cols and
+ whose return is also a list of tsv colums (will be saved into dst_tsv)
+ '''
+ self._row_processor = row_processor
+ self._total_rows = 0
+
+ rows = tsv_reader(source_tsv)
+ result = (self._over_row_processor(row) for row in rows)
+ tsv_writer(result, dst_tsv)
+
+ logging.info('total rows = {}'.format(self._total_rows))
+
+ def _over_row_processor(self, row):
+ out = self._row_processor(row)
+ self._total_rows = self._total_rows + 1
+ if self._total_rows % 500 == 0:
+ logging.info('processed = {}'.format(self._total_rows))
+ return out
+
+def randomize_tsv_file(tsv_file):
+ prefix = os.path.splitext(tsv_file)[0]
+ shuffle_file = prefix + '.shuffle'
+ if os.path.exists(shuffle_file):
+ return shuffle_file
+ idx_file = prefix + '.lineidx'
+ with open(idx_file, 'r') as fp:
+ num = len([line for line in fp.readlines() if len(line.strip()) > 0])
+ np.random.seed(777)
+ nums = np.random.permutation(num)
+ result = '\n'.join(map(str, nums))
+ with open(shuffle_file, 'w') as fp:
+ fp.write(result)
+ return shuffle_file
+
+def gen_tsv_from_labeling(input_folder, output_folder):
+ fs = glob.glob(op.join(input_folder, '*'))
+ labels = set()
+ def gen_rows():
+ for f in fs:
+ im = cv2.imread(f, cv2.IMREAD_COLOR)
+ if im is None:
+ continue
+ yaml_file = op.splitext(f)[0] + '.yaml'
+ if not op.isfile(yaml_file):
+ logging.info('{} not exist'.format(yaml_file))
+ with open(yaml_file, 'r') as fp:
+ bb_labels = yaml.loads(fp.read())
+ for bb_label in bb_labels:
+ labels.add(bb_label['class'])
+ with open(f, 'r') as fp:
+ encoded_im = base64.b64encode(fp.read())
+ yield op.basename(f), json.dumps(bb_labels), encoded_im
+
+ tsv_writer(gen_rows(), op.join(output_folder, 'train.tsv'))
+ write_to_file('\n'.join(labels), op.join(output_folder, 'labelmap.txt'))
+
+def try_json_parse(s):
+ try:
+ return json.loads(s)
+ except ValueError:
+ return s
+
+def get_label_type(full_expid, predict_file):
+ label_type = 'label'
+ for row in tsv_reader(
+ op.join('output', full_expid, 'snapshot', predict_file)):
+ rects = json.loads(row[-1])
+ if len(rects) > 0:
+ if 'caption' in rects[0]:
+ label_type = 'caption'
+ break
+ return label_type
+
+def iter_full_expid_pred(
+ full_expid, predict_file, start_id, threshold,
+ label_type, label_version=None):
+ test_data, test_data_split = parse_test_data(predict_file)
+ pred_tsv = TSVFile(op.join('output', full_expid, 'snapshot', predict_file))
+ num_total = len(pred_tsv)
+ while start_id < 0:
+ start_id += num_total
+ test_dataset = TSVDataset(test_data)
+ iter_image = test_dataset.iter_data(
+ test_data_split,
+ filter_idx=range(start_id, num_total))
+ has_gt = test_dataset.has(test_data_split, t=label_type, version=label_version)
+ if has_gt:
+ iter_gt = test_dataset.iter_data(test_data_split, t=label_type,
+ version=label_version,
+ filter_idx=range(start_id, num_total))
+ for i, row_image in enumerate(iter_image):
+ key = row_image[0]
+ if has_gt:
+ row_gt = next(iter_gt)
+ str_gt = row_gt[-1]
+ key = row_gt[0]
+ rects_gt = json.loads(str_gt)
+ if not isinstance(rects_gt, list):
+ rects_gt = [{'class': str(rects_gt)}]
+ else:
+ rects_gt = []
+ str_im = row_image[-1]
+ pred_key, str_pred = pred_tsv[i + start_id]
+ assert pred_key == key, (i,pred_key,key)
+ im = img_from_base64(str_im)
+ rects_pred = [r for r in json.loads(str_pred) if r['conf'] > threshold]
+ yield {
+ 'key': key,
+ 'im': im,
+ 'rects_gt': rects_gt,
+ 'rects_pred': rects_pred,
+ }
+
+def visualize_predict_no_draw(full_expid, predict_file, label, start_id,
+ threshold):
+ test_data, test_data_split = parse_test_data(predict_file)
+ logging.info('{}->{}/{}'.format(predict_file, test_data, test_data_split))
+ pred_full_path = op.join('output', full_expid, 'snapshot', predict_file)
+ pred_key_path = '{}.key.tsv'.format(pred_full_path)
+ pred_label_path = '{}.labelmap.th{}.tsv'.format(pred_full_path,
+ threshold)
+ pred_inverted_path = '{}.inverted.th{}.tsv'.format(pred_full_path,
+ threshold)
+ pred_sorted_cache_path = '{}.key_idxGT_idxPred_ap.th{}.{}.tsv'.format(
+ pred_full_path, threshold, label)
+
+ test_dataset = TSVDataset(test_data)
+ if not op.isfile(pred_sorted_cache_path):
+ if not op.isfile(pred_key_path) or \
+ not op.isfile(pred_label_path) or \
+ not op.isfile(pred_inverted_path):
+ logging.info('loading {}'.format(pred_full_path))
+ inverted, pred_keys = create_inverted_list2(
+ tsv_reader(pred_full_path), threshold)
+ pred_labels = inverted.keys()
+ logging.info('writing {}'.format(pred_key_path))
+ tsv_writer([[k] for k in pred_keys], pred_key_path)
+ tsv_writer(([l] for l in pred_labels), pred_label_path)
+ tsv_writer(((l, ' '.join(map(str, inverted[l]))) for l in
+ pred_labels), pred_inverted_path)
+ keys_from_pred = []
+ labelmap = load_list_file(pred_label_path)
+ pred_keys = load_list_file(pred_key_path)
+ if label in labelmap:
+ inverted_row = TSVFile(pred_inverted_path).seek(labelmap.index(label))
+ assert inverted_row[0] == label
+ assert len(inverted_row) == 2
+ idx_from_pred = map(int, inverted_row[1].split(' '))
+ keys_from_pred = [pred_keys[i] for i in idx_from_pred]
+ else:
+ keys_from_pred = []
+ inverted_test_split = test_dataset.load_inverted_label(test_data_split, version=-1,
+ label=label)
+ if label in inverted_test_split:
+ idx_from_gt = inverted_test_split[label]
+ else:
+ idx_from_gt = []
+ rows = test_dataset.iter_data(test_data_split, t='label', version=-1,
+ filter_idx=idx_from_gt, unique=True)
+ keys_from_gt = [row[0] for row in rows]
+ target_keys = list(set(keys_from_pred + keys_from_gt))
+ target_keys = [k for k in target_keys if k in pred_keys]
+ target_idx_in_pred = [pred_keys.index(k) for k in target_keys]
+ gt_keys = test_dataset.load_keys(test_data_split)
+ target_idx_in_gt = [gt_keys.index(k) for k in target_keys]
+ rows_in_gt = test_dataset.iter_data(test_data_split, t='label', version=-1,
+ filter_idx=target_idx_in_gt)
+ pred_tsv = TSVFile(pred_full_path)
+ rows_in_pred = (pred_tsv.seek(i) for i in target_idx_in_pred)
+ target_aps = []
+ for row_in_gt, row_in_pred in zip(rows_in_gt, rows_in_pred):
+ assert row_in_gt[0] == row_in_pred[0]
+ assert len(row_in_gt) == 2
+ assert len(row_in_pred) == 2
+ rects_gt = json.loads(row_in_gt[1])
+ rects_pred = json.loads(row_in_pred[1])
+ rects_gt = [r for r in rects_gt if r['class'] == label]
+ rects_pred = [r for r in rects_pred if r['class'] == label]
+ ap = calculate_image_ap([r['rect'] for r in rects_gt if 'rect' in r],
+ [r['rect'] for r in rects_pred])
+ target_aps.append(ap)
+ key_idxGT_idxPred_aps = zip(target_keys, target_idx_in_gt,
+ target_idx_in_pred, target_aps)
+ key_idxGT_idxPred_aps = sorted(key_idxGT_idxPred_aps, key=lambda x:
+ x[-1])
+ tsv_writer(key_idxGT_idxPred_aps, pred_sorted_cache_path)
+
+ tsv = TSVFile(pred_sorted_cache_path)
+ total_num = tsv.num_rows()
+ if total_num == 0:
+ return
+ while start_id < 0:
+ start_id = start_id + total_num
+ while start_id >= total_num:
+ start_id = start_id - total_num
+ i = start_id
+ tsv_pred = TSVFile(pred_full_path)
+ for i in range(start_id, total_num):
+ key, idx_gt, idx_pred, ap = tsv.seek(i)
+ idx_gt, idx_pred, ap = int(idx_gt), int(idx_pred), float(ap)
+ row_gt = next(test_dataset.iter_data(test_data_split,
+ filter_idx=[idx_gt]))
+ row_pred = tsv_pred.seek(idx_pred)
+ assert row_gt[0] == row_pred[0], (row_gt[0], row_pred[0])
+
+ rects_gt = json.loads(next(test_dataset.iter_data(test_data_split, 'label',
+ filter_idx=[idx_gt], version=-1))[1])
+
+ rects_pred = json.loads(row_pred[1])
+ rects_pred = [r for r in rects_pred if r['conf'] > threshold]
+ im_origin = img_from_base64(row_gt[-1])
+ yield key, im_origin, rects_gt, rects_pred, ap
+
+def visualize_predict(full_expid, predict_file, label, start_id, threshold):
+ test_data, test_data_split = parse_test_data(predict_file)
+ pred_full_path = op.join('output', full_expid, 'snapshot', predict_file)
+ pred_key_path = '{}.key.tsv'.format(pred_full_path)
+ pred_label_path = '{}.labelmap.th{}.tsv'.format(pred_full_path,
+ threshold)
+ pred_inverted_path = '{}.inverted.th{}.tsv'.format(pred_full_path,
+ threshold)
+ pred_sorted_cache_path = '{}.key_idxGT_idxPred_ap.th{}.{}.tsv'.format(
+ pred_full_path, threshold, label)
+
+ test_dataset = TSVDataset(test_data)
+ if not op.isfile(pred_sorted_cache_path):
+ if not op.isfile(pred_key_path) or \
+ not op.isfile(pred_label_path) or \
+ not op.isfile(pred_inverted_path):
+ logging.info('loading {}'.format(pred_full_path))
+ inverted, pred_keys = create_inverted_list2(
+ tsv_reader(pred_full_path), threshold)
+ pred_labels = inverted.keys()
+ logging.info('writing {}'.format(pred_key_path))
+ tsv_writer([[k] for k in pred_keys], pred_key_path)
+ tsv_writer(([l] for l in pred_labels), pred_label_path)
+ tsv_writer(((l, ' '.join(map(str, inverted[l]))) for l in
+ pred_labels), pred_inverted_path)
+ keys_from_pred = []
+ labelmap = load_list_file(pred_label_path)
+ pred_keys = load_list_file(pred_key_path)
+ if label in labelmap:
+ inverted_row = TSVFile(pred_inverted_path).seek(labelmap.index(label))
+ assert inverted_row[0] == label
+ assert len(inverted_row) == 2
+ idx_from_pred = map(int, inverted_row[1].split(' '))
+ keys_from_pred = [pred_keys[i] for i in idx_from_pred]
+ else:
+ keys_from_pred = []
+ inverted_test_split = test_dataset.load_inverted_label(test_data_split, version=-1,
+ label=label)
+ if label in inverted_test_split:
+ idx_from_gt = inverted_test_split[label]
+ else:
+ idx_from_gt = []
+ rows = test_dataset.iter_data(test_data_split, t='label', version=-1,
+ filter_idx=idx_from_gt, unique=True)
+ keys_from_gt = [row[0] for row in rows]
+ target_keys = list(set(keys_from_pred + keys_from_gt))
+ target_keys = [k for k in target_keys if k in pred_keys]
+ target_idx_in_pred = [pred_keys.index(k) for k in target_keys]
+ gt_keys = test_dataset.load_keys(test_data_split)
+ target_idx_in_gt = [gt_keys.index(k) for k in target_keys]
+ rows_in_gt = test_dataset.iter_data(test_data_split, t='label', version=-1,
+ filter_idx=target_idx_in_gt)
+ pred_tsv = TSVFile(pred_full_path)
+ rows_in_pred = (pred_tsv.seek(i) for i in target_idx_in_pred)
+ target_aps = []
+ for row_in_gt, row_in_pred in zip(rows_in_gt, rows_in_pred):
+ assert row_in_gt[0] == row_in_pred[0]
+ assert len(row_in_gt) == 2
+ assert len(row_in_pred) == 2
+ rects_gt = json.loads(row_in_gt[1])
+ rects_pred = json.loads(row_in_pred[1])
+ rects_gt = [r for r in rects_gt if r['class'] == label]
+ rects_pred = [r for r in rects_pred if r['class'] == label]
+ ap = calculate_image_ap([r['rect'] for r in rects_gt],
+ [r['rect'] for r in rects_pred])
+ target_aps.append(ap)
+ key_idxGT_idxPred_aps = zip(target_keys, target_idx_in_gt,
+ target_idx_in_pred, target_aps)
+ key_idxGT_idxPred_aps = sorted(key_idxGT_idxPred_aps, key=lambda x:
+ x[-1])
+ tsv_writer(key_idxGT_idxPred_aps, pred_sorted_cache_path)
+
+ tsv = TSVFile(pred_sorted_cache_path)
+ total_num = tsv.num_rows()
+ if total_num == 0:
+ return
+ while start_id < 0:
+ start_id = start_id + total_num
+ while start_id >= total_num:
+ start_id = start_id - total_num
+ i = start_id
+ tsv_pred = TSVFile(pred_full_path)
+ for i in range(start_id, total_num):
+ key, idx_gt, idx_pred, ap = tsv.seek(i)
+ idx_gt, idx_pred, ap = int(idx_gt), int(idx_pred), float(ap)
+ row_gt = next(test_dataset.iter_data(test_data_split,
+ filter_idx=[idx_gt]))
+ row_pred = tsv_pred.seek(idx_pred)
+ assert row_gt[0] == row_pred[0], (row_gt[0], row_pred[0])
+
+ rects_gt = json.loads(row_gt[1])
+ rects_pred = json.loads(row_pred[1])
+ rects_pred = [r for r in rects_pred if r['conf'] > threshold]
+ rects_gt_target = [r for r in rects_gt if r['class'] == label]
+ rects_pred_target = [r for r in rects_pred if r['class'] == label]
+ if len(rects_gt_target) == 0 and len(rects_pred_target) == 0:
+ logging.info('skipping to next')
+ continue
+ im_origin = img_from_base64(row_gt[-1])
+ im_gt_target = np.copy(im_origin)
+ draw_bb(im_gt_target, [r['rect'] for r in rects_gt_target],
+ [r['class'] for r in rects_gt_target])
+ im_pred_target = np.copy(im_origin)
+ draw_bb(im_pred_target, [r['rect'] for r in rects_pred_target],
+ [r['class'] for r in rects_pred_target])
+ im_gt = np.copy(im_origin)
+ draw_bb(im_gt, [r['rect'] for r in rects_gt],
+ [r['class'] for r in rects_gt])
+ im_pred = np.copy(im_origin)
+ draw_bb(im_pred, [r['rect'] for r in rects_pred],
+ [r['class'] for r in rects_pred])
+ yield key, im_origin, im_gt_target, im_pred_target, im_gt, im_pred, ap
+
+def visualize_box_no_draw(data, split, version, label, start_id, color_map={},
+ split_type='label',
+ min_conf=-1, max_conf=2):
+ dataset = TSVDataset(data)
+ if split is None:
+ # guess which split should be used. only support non-composite tsv
+ candidate_split = get_default_splits()
+ for c in candidate_split:
+ if not op.isfile(dataset.get_data(c)):
+ continue
+ inverted = dataset.load_inverted_label(c, version, label)
+ if label not in inverted:
+ continue
+ n = len(inverted[label])
+ if n <= start_id:
+ start_id = start_id - n
+ else:
+ logging.info('split = {}'.format(split))
+ split = c
+ break
+ if not split:
+ logging.info('cannot find the valid')
+ return
+ if label is not None:
+ logging.info('loading inverted label')
+ idx = dataset.load_inverted_label(split, version, label)[label]
+ curr_num_image = len(idx)
+ else:
+ curr_num_image = dataset.num_rows(split, t=split_type, version=version)
+ if curr_num_image == 0:
+ logging.info('there is no image')
+ return
+ while start_id > curr_num_image:
+ start_id = start_id - curr_num_image
+ while start_id < 0:
+ start_id = start_id + curr_num_image
+ if label is not None:
+ filter_idx = idx[start_id:]
+ else:
+ filter_idx = range(start_id, curr_num_image)
+ logging.info('start to read')
+ rows_image = dataset.iter_data(split, filter_idx=filter_idx)
+ rows_label = dataset.iter_data(split, split_type, version=version,
+ filter_idx=filter_idx)
+ for idx_row, (row_image, row_label) in enumerate(zip(rows_image, rows_label)):
+ key = row_image[0]
+ assert key == row_label[0], (key, row_label[0], idx_row)
+ assert len(row_label) == 2
+ label_str = row_label[-1]
+ img_str = row_image[-1]
+ im = img_from_base64(img_str)
+ assert im is not None
+ origin = np.copy(im)
+ rects = try_json_parse(label_str)
+ if type(rects) is list:
+ if label is not None:
+ rects = [r for r in rects if \
+ r['class'] == label and \
+ r.get('conf', 1) >= min_conf and \
+ r.get('conf', 1) <= max_conf or r['class'] != label]
+ if all(r['class'] != label for r in rects):
+ continue
+ yield (key, origin, rects)
+ else:
+ yield key, origin, [{'class': label_str, 'rect': [0, 0, 0, 0]}]
+
+def visualize_box(data, split, version, label, start_id, color_map={}):
+ dataset = TSVDataset(data)
+ logging.info('loading inverted label')
+ if split is None:
+ # guess which split should be used. only support non-composite tsv
+ candidate_split = get_default_splits()
+ for c in candidate_split:
+ if not op.isfile(dataset.get_data(c)):
+ continue
+ inverted = dataset.load_inverted_label(c, version, label)
+ if label not in inverted:
+ continue
+ n = len(inverted[label])
+ if n <= start_id:
+ start_id = start_id - n
+ else:
+ logging.info('split = {}'.format(split))
+ split = c
+ break
+ if not split:
+ logging.info('cannot find the valid')
+ return
+ else:
+ inverted = dataset.load_inverted_label(split, version, label)
+ logging.info('inverted label loaded')
+ logging.info('keys: {}'.format(inverted.keys()))
+ if label not in inverted:
+ return
+ idx = inverted[label]
+ if len(idx) == 0:
+ return
+ while start_id > len(idx):
+ start_id = start_id - len(idx)
+ while start_id < 0:
+ start_id = start_id + len(idx)
+ logging.info('start to read')
+ rows_image = dataset.iter_data(split, filter_idx=idx[start_id:])
+ rows_label = dataset.iter_data(split, 'label', version=version,
+ filter_idx=idx[start_id:])
+ for row_image, row_label in zip(rows_image, rows_label):
+ key = row_image[0]
+ assert key == row_label[0]
+ assert len(row_image) == 3
+ assert len(row_label) == 2
+ label_str = row_label[-1]
+ img_str = row_image[-1]
+ im = img_from_base64(img_str)
+ origin = np.copy(im)
+ rects = try_json_parse(label_str)
+ new_name = key.replace('/', '_').replace(':', '')
+ if type(rects) is list:
+ #rects = [l for l in rects if 'conf' not in l or l['conf'] > 0.3]
+ def get_rect_class(rects):
+ all_class = []
+ all_rect = []
+ for rect in rects:
+ label_class = rect['class']
+ rect = rect['rect']
+ all_class.append(label_class)
+ if not (rect[0] == 0 and rect[1] == 0
+ and rect[2] == 0 and rect[3] == 0):
+ all_rect.append(rect)
+ else:
+ all_rect.append((0, 0, im.shape[1] - 1, im.shape[0] - 1))
+ return all_rect, all_class
+ all_rect, all_class = get_rect_class(rects)
+ draw_bb(im, all_rect, all_class)
+ target_rects = [l for l in rects if l['class']
+ == label]
+ all_rect, all_class = get_rect_class(target_rects)
+ im_label = np.copy(origin)
+ draw_bb(im_label, all_rect, all_class)
+ yield new_name, origin, im_label, im, pformat(target_rects)
+ else:
+ yield new_name, origin, im, im, ''
+
+
+def visualize_tsv2(data, split, label):
+ '''
+ by default, pass split as 'train'
+ TODO: try to refactor it with visualize_box
+ '''
+ dataset = TSVDataset(data)
+ logging.info('loading inverted label')
+ inverted = dataset.load_inverted_label(split)
+ logging.info('inverted label loaded')
+ logging.info('keys: {}'.format(inverted.keys()))
+ assert label in inverted
+ idx = inverted[label]
+ is_composite = False
+ if split == 'train' and not op.isfile(dataset.get_data(split)):
+ is_composite = True
+ tsvs = [TSVFile(f) for f in dataset.get_train_tsvs()]
+ shuffle_tsv_rows = tsv_reader(dataset.get_shuffle_file(split))
+ shuffle = []
+ for row in shuffle_tsv_rows:
+ shuffle.append([int(row[0]), int(row[1])])
+ else:
+ tsv = TSVFile(dataset.get_data(split))
+ num_image = 0
+ num_rows = 2
+ num_cols = 2
+ num_image_one_fig = num_rows * num_cols
+ idx.extend([0] * (num_image_one_fig - len(idx) % num_image_one_fig))
+ idx = np.asarray(idx)
+ idx = idx.reshape((-1, num_image_one_fig))
+ logging.info('start to read')
+ color_map = {}
+ for i in idx:
+ all_image = []
+ for j in i:
+ logging.info(j)
+ if is_composite:
+ row_image = tsvs[shuffle[j][0]].seek(shuffle[j][1])
+ else:
+ row_image = tsv.seek(j)
+ im = img_from_base64(row_image[-1])
+ labels = try_json_parse(row_image[1])
+ num_image = num_image + 1
+ if type(labels) is list:
+ labels = [l for l in labels if 'conf' not in l or l['conf'] > 0.3]
+ all_class = []
+ all_rect = []
+ for label in labels:
+ label_class = label['class']
+ rect = label['rect']
+ all_class.append(label_class)
+ if not (rect[0] == 0 and rect[1] == 0
+ and rect[2] == 0 and rect[3] == 0):
+ all_rect.append(rect)
+ else:
+ all_rect.append((0, 0, im.shape[1] - 1, im.shape[0] - 1))
+ new_name = row_image[0].replace('/', '_').replace(':', '')
+ draw_bb(im, all_rect, all_class, color=color_map)
+ all_image.append(im)
+ logging.info('start to show')
+ show_images(all_image, num_rows, num_cols)
+
+ logging.info('#image: {}'.format(num_image))
+
+def visualize_tsv(tsv_image, tsv_label, out_folder=None, label_idx=1):
+ '''
+ deprecated, use visualize_tsv2
+ '''
+ rows_image = tsv_reader(tsv_image)
+ rows_label = tsv_reader(tsv_label)
+ assert out_folder == None or not op.exists(out_folder)
+ source_folder = op.dirname(tsv_image)
+ num_image = 0
+ for row_image, row_label in zip(rows_image, rows_label):
+ assert row_image[0] == row_label[0]
+ im = img_from_base64(row_image[-1])
+ labels = try_json_parse(row_label[label_idx])
+ num_image = num_image + 1
+ if type(labels) is list:
+ labels = [l for l in labels if 'conf' not in l or l['conf'] > 0.3]
+ all_class = []
+ all_rect = []
+ for label in labels:
+ label_class = label['class']
+ rect = label['rect']
+ all_class.append(label_class)
+ if not (rect[0] == 0 and rect[1] == 0
+ and rect[2] == 0 and rect[3] == 0):
+ all_rect.append(rect)
+ else:
+ all_rect.append((0, 0, im.shape[1] - 1, im.shape[0] - 1))
+ new_name = row_image[0].replace('/', '_').replace(':', '')
+ draw_bb(im, all_rect, all_class)
+ if out_folder:
+ fname = os.path.join(out_folder,
+ '_'.join(set(c.replace(' ', '_') for c in all_class)),
+ new_name +'.png')
+ else:
+ fname = op.join(out_folder, row_image[0],
+ '{}_{}_{}.png'.format(num_image, labels, row_image[0]))
+ if out_folder:
+ save_image(im, fname)
+ else:
+ show_image(im)
+
+ logging.info('#image: {}'.format(num_image))
+
+def iou(wh1, wh2):
+ w1, h1 = wh1
+ w2, h2 = wh2
+ return min(w1, w2) * min(h1, h2) / max(w1, w2) / max(h1, h2)
+
+class ImageTypeParser(object):
+ def __init__(self):
+ self.m = None
+ pass
+
+ def parse_type(self, im_binary):
+ return imghdr.what('', im_binary)
+ self._ensure_init()
+ mime_type = self.m.buffer(im_binary)
+ t = op.basename(mime_type)
+ return t
+
+ def _ensure_init(self):
+ if self.m is None:
+ import magic
+ #m = magic.open(magic.MAGIC_MIME_TYPE)
+ m = magic.from_file(magic.MAGIC_MIME_TYPE)
+ m.load()
+ self.m = m
+
+def collect_label(row, stat, **kwargs):
+ labels = json.loads(row[1])
+ labels = [label['class'] for label in labels]
+ remove_labels = kwargs['remove_image'].split(',')
+ is_remove = False
+ for label in labels:
+ if label in remove_labels or remove_labels == 'all':
+ if random.random() <= kwargs['remove_image_prob']:
+ is_remove = True
+ break
+
+ stat.append((is_remove, labels))
+
+class TSVDatasetSource(TSVDataset):
+ def __init__(self, name, root=None,
+ split_infos=None,
+ cleaness=10,
+ use_all=False,
+ use_negative_label=False,
+ select_by_verified=False):
+ super(TSVDatasetSource, self).__init__(name)
+ self._noffset_count = {}
+ self._type = None
+ self._root = root
+ # the list of
+ self._sourcelabel_to_targetlabels = None
+ self._targetlabel_to_sourcelabels = None
+ self._initialized = False
+ self._type_to_datasetlabel_to_split_idx = None
+ self._type_to_datasetlabel_to_count = None
+ self._type_to_split_label_idx = None
+ if split_infos is not None:
+ self._split_infos = split_infos
+ else:
+ self._split_infos = [{'split': s, 'version': -1}
+ for s in get_default_splits()]
+ assert len(set([split_info['split'] for split_info in
+ self._split_infos])) == len(self._split_infos)
+ self._use_all = use_all
+ self._select_by_verified = select_by_verified
+ self.cleaness = cleaness
+ self.use_negative_label = use_negative_label
+
+ def get_version_by_split(self, split_name):
+ for split_info in self._split_infos:
+ if split_info['split'] == split_name:
+ return split_info['version']
+ return -1
+
+ def get_label_tsv(self, split_name):
+ version_by_config = self.get_version_by_split(split_name)
+ return super(TSVDatasetSource, self).get_data(split_name, 'label',
+ version_by_config)
+
+ def populate_info(self, root):
+ self._ensure_initialized()
+ for node in root.iter_search_nodes():
+ if root == node:
+ continue
+ if node.name in self._targetlabel_to_sourcelabels:
+ sourcelabels = self._targetlabel_to_sourcelabels[node.name]
+ node.add_feature(self.name, ','.join(sourcelabels))
+ if any(is_noffset(l) for l in sourcelabels):
+ node.add_feature(self.name + '_readable',
+ ','.join(get_nick_name(noffset_to_synset(l)) if
+ is_noffset(l) else l for l in sourcelabels))
+ total = 0
+ for sourcelabel in sourcelabels:
+ for t in self._type_to_datasetlabel_to_count:
+ datasetlabel_to_count = self._type_to_datasetlabel_to_count[t]
+ c = datasetlabel_to_count.get(sourcelabel, 0)
+ total = total + c
+ key = 'images_{}'.format(t)
+ node.add_feature(key,
+ node.__getattribute__(key) + c)
+ node.add_feature('{}_total'.format(self.name), total)
+
+ def _ensure_initialized(self):
+ if self._initialized:
+ return
+ populate_dataset_details(self.name)
+
+ self.update_label_mapper()
+
+ self._load_inverted()
+
+ self._initialized = True
+
+ def _load_inverted(self):
+ # make sure self.update_label_mapper() is called
+ types = ['with_bb', 'no_bb']
+ self._type_split_label_idx = []
+ for split_info in self._split_infos:
+ split = split_info['split']
+ version = split_info['version']
+ logging.info('loading the inverted file: {}-{}'.format(self.name,
+ split))
+ if not self.has(split, 'label', version=version):
+ continue
+ # load inverted list
+ type_to_inverted = {}
+ for i, t in enumerate(types):
+ if self._select_by_verified:
+ inverted_label_type = 'inverted.label.{}.verified'.format(t)
+ else:
+ inverted_label_type = 'inverted.label.{}'.format(t)
+ rows = self.iter_data(split, inverted_label_type,
+ version=version)
+ type_to_inverted[t] = {r[0]: map(int, r[1].split(' '))
+ for r in tqdm(rows) if
+ r[0] in self._sourcelabel_to_targetlabels and
+ len(r[1]) > 0}
+
+ # register the positive labels
+ for i, t in enumerate(types):
+ inverted = type_to_inverted[t]
+ inverted = {l: inverted[l] for l in inverted if not l.startswith('-')}
+ label_idx = dict_to_list(inverted, 0)
+ for label, idx in label_idx:
+ self._type_split_label_idx.append((t, split, label, idx))
+ # for no_bb, we need to add the with_bb into the list
+ if t == 'with_bb':
+ self._type_split_label_idx.append(('no_bb', split, label, idx))
+
+ if self.use_negative_label:
+ # currently, we only have a scenario where we have negative
+ # annotations in the no_bb data source and the need to apply it
+ # to no_bb target set.
+ inverted = type_to_inverted['no_bb']
+ inverted = {l: inverted[l] for l in inverted if l.startswith('-')}
+ label_idx = dict_to_list(inverted, 0)
+ for label, idx in label_idx:
+ #self._type_split_label_idx.append(('with_bb', split, label, idx))
+ self._type_split_label_idx.append(('no_bb', split, label, idx))
+
+ self._type_split_label_idx = list(set(self._type_split_label_idx))
+ self._type_to_split_label_idx = list_to_dict(
+ self._type_split_label_idx, 0)
+ self._type_to_datasetlabel_to_split_idx = {}
+ for t in self._type_to_split_label_idx:
+ split_label_idx = self._type_to_split_label_idx[t]
+ label_to_split_idx = list_to_dict(split_label_idx, 1)
+ self._type_to_datasetlabel_to_split_idx[t] = label_to_split_idx
+ self._type_to_datasetlabel_to_count = {}
+ for t in self._type_to_datasetlabel_to_split_idx:
+ datasetlabel_to_split_idx = self._type_to_datasetlabel_to_split_idx[t]
+ datasetlabel_to_count = {l: len(datasetlabel_to_split_idx[l]) for l in
+ datasetlabel_to_split_idx}
+ self._type_to_datasetlabel_to_count[t] = datasetlabel_to_count
+
+ self._split_to_num_image = {split_info['split']: self.num_rows(split_info['split']) for split_info in
+ self._split_infos if self.has(split_info['split'])}
+
+ def update_label_mapper(self):
+ root = self._root
+ # load the labelmap for all splits, self.load_labelmap is not correct,
+ # since we will update the label and will not update the labelmap
+ labelmap = []
+ for split_info in self._split_infos:
+ split, version = split_info['split'], split_info['version']
+ if self.has(split, 'labelmap', version):
+ for row in self.iter_data(split, 'labelmap', version):
+ labelmap.append(row[0])
+ # if it has a prefix of -, it means it has no that tag.
+ labelmap = [l for l in labelmap if not l.startswith('-')]
+ hash_labelmap = set(labelmap)
+ labelmap = list(hash_labelmap)
+
+ tree_noffsets = {}
+ for node in root.iter_search_nodes():
+ if node == root or not node.noffset:
+ continue
+ for s in node.noffset.split(','):
+ tree_noffsets[s] = node.name
+ name_to_targetlabels = {}
+ targetlabel_has_whitelist = set()
+ invalid_list = []
+ any_source_key = 'label_names_in_all_dataset_source'
+ for node in root.iter_search_nodes():
+ if node == root:
+ continue
+ if hasattr(node, self.name) or hasattr(node, any_source_key):
+ if hasattr(node, self.name):
+ # this is like a white-list
+ values = node.__getattribute__(self.name)
+ else:
+ values = node.__getattribute__(any_source_key)
+ if values is not None:
+ source_terms = values.split(',')
+ for t in source_terms:
+ t = t.strip()
+ if t not in name_to_targetlabels:
+ name_to_targetlabels[t] = set()
+ if t not in hash_labelmap:
+ invalid_list.append((t, self.name, node.name))
+ continue
+ name_to_targetlabels[t].add(node.name)
+ # even if it is None, we will also add it to white-list so that
+ # we will not automatically match the term.
+ targetlabel_has_whitelist.add(node.name)
+ else:
+ # we will keep the lower case always for case-insensitive
+ # comparison
+ all_candidate_src_names = [node.name.lower()]
+ if hasattr(node, 'alias_names'):
+ all_candidate_src_names.extend([s.strip() for s in
+ node.alias_names.split(',')])
+ for t in set(all_candidate_src_names):
+ if t not in name_to_targetlabels:
+ name_to_targetlabels[t] = set()
+ name_to_targetlabels[t].add(node.name)
+
+ sourcelabel_targetlabel = []
+ if len(invalid_list) != 0:
+ logging.warn('invalid white list information: {}'.format(pformat(invalid_list)))
+
+ #result = {}
+ label_to_synset = LabelToSynset()
+ for l in labelmap:
+ matched = False
+ if l.lower() in name_to_targetlabels:
+ matched = True
+ for t in name_to_targetlabels[l.lower()]:
+ sourcelabel_targetlabel.append((l, t))
+ if l in name_to_targetlabels:
+ for t in name_to_targetlabels[l]:
+ sourcelabel_targetlabel.append((l, t))
+ matched = True
+ if not matched:
+ succeed, ns = label_to_synset.convert(l)
+ if not succeed:
+ continue
+ for n in ns:
+ n = synset_to_noffset(n)
+ if n in tree_noffsets:
+ t = tree_noffsets[n]
+ if t in targetlabel_has_whitelist:
+ # if it has white list, we will not respect the
+ # noffset to do the autmatic matching
+ continue
+ sourcelabel_targetlabel.append((l, t))
+ #result[l] = t
+ if self.use_negative_label:
+ # we just add the mapping here. no need to check if -s is in the
+ # source label list
+ sourcelabel_targetlabel.extend([('-' + s, '-' + t) for s, t in
+ sourcelabel_targetlabel])
+
+ self._sourcelabel_to_targetlabels = list_to_dict_unique(sourcelabel_targetlabel,
+ 0)
+ self._targetlabel_to_sourcelabels = list_to_dict_unique(sourcelabel_targetlabel,
+ 1)
+
+ return self._sourcelabel_to_targetlabels
+
+ def select_tsv_rows(self, label_type):
+ self._ensure_initialized()
+ result = []
+ if label_type in self._type_to_split_label_idx:
+ split_label_idx = self._type_to_split_label_idx[label_type]
+ datasetlabel_to_splitidx = list_to_dict(split_label_idx, 1)
+ for datasetlabel in datasetlabel_to_splitidx:
+ if datasetlabel in self._sourcelabel_to_targetlabels:
+ split_idxes = datasetlabel_to_splitidx[datasetlabel]
+ targetlabels = self._sourcelabel_to_targetlabels[datasetlabel]
+ for targetlabel in targetlabels:
+ result.extend([(targetlabel, split, idx) for split, idx in
+ split_idxes])
+ # must_have_indices
+ for split_info in self._split_infos:
+ split = split_info['split']
+ must_have_indices = split_info.get('must_have_indices', [])
+ # we set the target label here as None so that the post-processing
+ # will not ignore it. The real labels will also be converted
+ # corrected since we do not depend on this target label only.
+ result.extend((None, split, i) for i in must_have_indices)
+ if self._use_all:
+ split_to_targetlabel_idx = list_to_dict(result, 1)
+ for s in split_to_targetlabel_idx:
+ rootlabel_idxes = split_to_targetlabel_idx[s]
+ idx_to_rootlabel = list_to_dict(rootlabel_idxes, 1)
+ num_image = self._split_to_num_image[s]
+ idxes = set(range(num_image)).difference(set(idx_to_rootlabel.keys()))
+ for i in idxes:
+ # for these images, the root label is hard-coded as None
+ result.append((None, s, i))
+ for split_info in self._split_infos:
+ s = split_info['split']
+ if s in split_to_targetlabel_idx:
+ continue
+ if s not in self._split_to_num_image:
+ continue
+ result.extend([(None, s, i) for i in
+ range(self._split_to_num_image[s])])
+ return result
+
+def initialize_images_count(root):
+ for node in root.iter_search_nodes():
+ node.add_feature('images_with_bb', 0)
+ node.add_feature('images_no_bb', 0)
+
+def trainval_split(dataset, num_test_each_label):
+ if op.isfile(dataset.get_train_tsv()):
+ logging.info('skip to run trainval split for {} because it has been done'.format(
+ dataset.name))
+ return
+ random.seed(777)
+ label_to_idx = {}
+ for i, row in enumerate(tsv_reader(dataset.get_trainval_tsv('label'))):
+ rects = json.loads(row[1])
+ if len(rects) == 0:
+ logging.info('{} has empty label for {}'.format(dataset.name, i))
+ continue
+ random.shuffle(rects)
+ label = rects[0]['class']
+ if label in label_to_idx:
+ label_to_idx[label].append(i)
+ else:
+ label_to_idx[label] = [i]
+
+ test_idx = []
+ train_idx = []
+ for label in label_to_idx:
+ if len(label_to_idx[label]) < num_test_each_label:
+ logging.fatal('dataset {} has less than {} images for label {}'.
+ format(dataset.name, num_test_each_label, label))
+ random.shuffle(label_to_idx[label])
+ test_idx.extend(label_to_idx[label][: num_test_each_label])
+ train_idx.extend(label_to_idx[label][num_test_each_label: ])
+
+ trainval = TSVFile(dataset.get_trainval_tsv())
+
+ def gen_train():
+ for i in train_idx:
+ row = trainval.seek(i)
+ yield row
+ tsv_writer(gen_train(), dataset.get_train_tsv())
+
+ def gen_test():
+ for i in test_idx:
+ yield trainval.seek(i)
+ tsv_writer(gen_test(), dataset.get_test_tsv_file())
+
+def convert_one_label(rects, label_mapper):
+ to_remove = []
+ rects2 = []
+ for rect in rects:
+ if rect['class'] in label_mapper:
+ for t in label_mapper[rect['class']]:
+ r2 = copy.deepcopy(rect)
+ assert type(t) is str or type(t) is unicode
+ r2['class'] = t
+ rects2.append(r2)
+ rects[:] = []
+ rects.extend(rects2)
+
+def convert_label_by_dataset(dataset, split, version, idx, label_mapper, with_bb):
+ result = None
+ for i, row in zip(idx, dataset.iter_data(split, 'label', version=version,
+ filter_idx=idx)):
+ assert len(row) == 2
+ rects = json.loads(row[1])
+ def eval_with_bb(r):
+ if not r['class'].startswith('-'):
+ return 'rect' in r and any(x != 0 for x in r['rect'])
+ else:
+ return 'rect' not in r or all(x == 0 for x in r['rect'])
+ if with_bb:
+ # in the case with -, we will not add rect
+ # with all zeros, thus, no need to check if it is all zeros
+ # when it is negative samples
+ rects = [r for r in rects if eval_with_bb(r)]
+ # all annotations if eval_with_bb(r) is valid for no_bb. Thus, disable
+ # the following
+ #else:
+ #rects = [r for r in rects if not eval_with_bb(r)]
+ if result is None:
+ # don't use this, because all list will be shared
+ #result = [len(row) * ['d']] * tsv.num_rows()
+ result = [None] * dataset.num_rows(split)
+ for _ in range(len(result)):
+ result[_] = ['d'] * len(row)
+ rects2 = []
+ # the following code should use convert_one_label
+ for rect in rects:
+ if rect['class'] in label_mapper:
+ for t in label_mapper[rect['class']]:
+ r2 = copy.deepcopy(rect)
+ r2['class'] = t
+ if rect['class'] != t:
+ # keep this for logging
+ r2['class_from'] = rect['class']
+ rects2.append(r2)
+ row[1] = rects2
+ result[i] = row
+ return result
+
+def convert_label(label_tsv, idx, label_mapper, with_bb):
+ tsv = TSVFile(label_tsv)
+ result = None
+ for i in tqdm(idx):
+ row = tsv.seek(i)
+ assert len(row) == 2
+ rects = json.loads(row[1])
+ def eval_with_bb(r):
+ if not r['class'].startswith('-'):
+ return 'rect' in r and any(x != 0 for x in r['rect'])
+ else:
+ return 'rect' not in r or all(x == 0 for x in r['rect'])
+ if with_bb:
+ # in the case with -, we will not add rect
+ # with all zeros, thus, no need to check if it is all zeros
+ # when it is negative samples
+ rects = [r for r in rects if eval_with_bb(r)]
+ # all annotations if eval_with_bb(r) is valid for no_bb. Thus, disable
+ # the following
+ #else:
+ #rects = [r for r in rects if not eval_with_bb(r)]
+ if result is None:
+ # don't use this, because all list will be shared
+ #result = [len(row) * ['d']] * tsv.num_rows()
+ result = [None] * tsv.num_rows()
+ for _ in range(len(result)):
+ result[_] = ['d'] * len(row)
+ rects2 = []
+ # the following code should use convert_one_label
+ for rect in rects:
+ if rect['class'] in label_mapper:
+ for t in label_mapper[rect['class']]:
+ r2 = copy.deepcopy(rect)
+ r2['class'] = t
+ if rect['class'] != t:
+ # keep this for logging
+ r2['class_from'] = rect['class']
+ rects2.append(r2)
+ row[1] = rects2
+ result[i] = row
+ return result
+
+def create_info_for_ambigous_noffset(name, noffsets):
+ definitions = [str(noffset_to_synset(n).definition()) for n in noffsets]
+ de = [{'noffset': n,
+ 'definition': d.replace("`", '').replace("'", ''),
+ 'nick_name': str(get_nick_name(noffset_to_synset(n)))}
+ for n, d in zip(noffsets, definitions)]
+ d = {'name': name,
+ 'definitions': de,
+ 'noffset': None,
+ 'markdown_url': create_markdown_url(noffsets)}
+ return d
+
+def node_should_have_images(root, th, fname):
+ enough = True
+ few_training_with_bb = []
+ for node in root.iter_search_nodes():
+ if node == root:
+ continue
+ if node.cum_images_with_bb < th:
+ few_training_with_bb.append({'name': node.name,
+ 'cum_images_with_bb': node.cum_images_with_bb,
+ 'parent list': [p.name for p in node.get_ancestors()[:-1]]})
+ enough = False
+ logging.warn('less images: {} ({})'.format(
+ node.name.encode('utf-8'),
+ node.cum_images_with_bb))
+ if enough:
+ logging.info('con. every node has at least {} images'.format(th))
+ else:
+ write_to_yaml_file(few_training_with_bb, fname)
+
+def clean_dataset2(source_dataset_name, dest_dataset_name):
+ source_dataset = TSVDataset(source_dataset_name)
+ dest_dataset = TSVDataset(dest_dataset_name)
+ splits = get_default_splits()
+ for split in splits:
+ src_tsv = source_dataset.get_data(split)
+ if op.isfile(src_tsv):
+ valid_idxs = []
+ dest_tsv = dest_dataset.get_data(split)
+ def gen_rows():
+ rows = tsv_reader(src_tsv)
+ num_removed_images = 0
+ num_removed_rects = 0
+ for i, row in enumerate(tqdm(rows)):
+ if (i % 1000) == 0:
+ logging.info('{} - #removedImages={};#removedRects={}'.format(
+ i, num_removed_images, num_removed_rects))
+ im = img_from_base64(row[-1])
+ if im is None:
+ num_removed_images = num_removed_images + 1
+ continue
+ height, width = im.shape[:2]
+ rects = json.loads(row[1])
+ invalid = False
+ to_remove = []
+ for rect in rects:
+ r = rect['rect']
+ if all(s == 0 for s in r):
+ continue
+ changed = False
+ origin = copy.deepcopy(rect)
+ for j in range(4):
+ if r[j] < 0:
+ r[j] = 0
+ changed = True
+ for j in range(2):
+ if r[2 * j] >= width -1:
+ changed = True
+ r[2 * j] = width - 1
+ if [2 * j + 1] >= height - 1:
+ changed = True
+ r[2 * j + 1] = height - 1
+ if changed:
+ rect['changed_from_rect'] = origin
+ cx, cy = (r[0] + r[2]) / 2., (r[1] + r[3]) / 2.
+ w, h = r[2] - r[0], r[3] - r[1]
+ if cx < 0 or cy < 0 or cx >= width or \
+ cy >= height or w <= 1 or h <= 1 or \
+ w >= width or h >= height:
+ to_remove.append(rect)
+ if len(to_remove) > 0:
+ num_removed_rects = num_removed_rects + len(to_remove)
+ for rect in to_remove:
+ rects.remove(rect)
+ valid_idxs.append(i)
+ if len(to_remove) > 0:
+ yield row[0], json.dumps(rects), row[2]
+ else:
+ yield row
+ tsv_writer(gen_rows(), dest_tsv)
+ dest_dataset.write_data(source_dataset.iter_data(split, 'label',
+ filter_idx=valid_idxs), split, 'label')
+
+def clean_dataset(source_dataset_name, dest_dataset_name):
+ '''
+ use version 2
+ '''
+ source_dataset = TSVDataset(source_dataset_name)
+ dest_dataset = TSVDataset(dest_dataset_name)
+ splits = get_default_splits()
+ for split in splits:
+ src_tsv = source_dataset.get_data(split)
+ if op.isfile(src_tsv):
+ dest_tsv = dest_dataset.get_data(split)
+ def gen_rows():
+ rows = tsv_reader(src_tsv)
+ num_removed_images = 0
+ num_removed_rects = 0
+ for i, row in enumerate(rows):
+ if (i % 1000) == 0:
+ logging.info('{} - #removedImages={};#removedRects={}'.format(
+ i, num_removed_images, num_removed_rects))
+ im = img_from_base64(row[-1])
+ height, width = im.shape[:2]
+ rects = json.loads(row[1])
+ invalid = False
+ to_remove = []
+ for rect in rects:
+ r = rect['rect']
+ if all(s == 0 for s in r):
+ continue
+ cx, cy = (r[0] + r[2]) / 2., (r[1] + r[3]) / 2.
+ w, h = r[2] - r[0], r[3] - r[1]
+ if cx < 0 or cy < 0 or cx >= width or \
+ cy >= height or w <= 1 or h <= 1 or \
+ w >= width or h >= height:
+ to_remove.append(rect)
+ if len(to_remove) > 0:
+ logging.info('before removing {}'.format(len(rects)))
+ num_removed_rects = num_removed_rects + len(to_remove)
+ for rect in to_remove:
+ rects.remove(rect)
+ r = rect['rect']
+ logging.info('removing {}'.format(','.join(map(str,
+ r))))
+ if len(to_remove) > 0:
+ logging.info('after removing {}'.format(len(rects)))
+ if len(rects) > 0:
+ yield row[0], json.dumps(rects), row[2]
+ else:
+ num_removed_images = num_removed_images + 1
+ logging.info('removing image {}'.format(row[0]))
+ else:
+ yield row
+ tsv_writer(gen_rows(), dest_tsv)
+
+def parallel_convert_label(func, all_task, num_worker=128):
+ num_split = num_worker
+ num_task_each_split = (len(all_task) + num_split - 1) / num_split
+ all_sub_tasks = []
+ for i in range(num_split):
+ start_idx = i * num_task_each_split
+ if start_idx >= len(all_task):
+ break
+ end_idx = start_idx + num_task_each_split
+ if end_idx > len(all_task):
+ end_idx = len(all_task)
+ all_sub_tasks.append(all_task[start_idx:end_idx])
+ m = Pool(num_worker)
+ all_sub_results = m.map(func, all_sub_tasks)
+ result = all_sub_results[0]
+ for s in all_sub_results[1:]:
+ assert len(result) == len(s)
+ for i in range(len(result)):
+ assert len(result[i]) == 2
+ assert len(s[i]) == 2
+ if result[i][1] == 'd' and s[i][1] != 'd':
+ result[i][0] = s[i][0]
+ result[i][1] = s[i][1]
+ else:
+ assert not (result[i][1] != 'd' and s[i][1] != 'd')
+ return result
+
+def parallel_map_to_array(func, all_task, num_worker=128):
+ num_split = num_worker * 2
+ num_task_each_split = (len(all_task) + num_split - 1) / num_split
+ all_sub_tasks = []
+ for i in range(num_split):
+ start_idx = i * num_task_each_split
+ if start_idx > len(all_task):
+ break
+ end_idx = start_idx + num_task_each_split
+ if end_idx > len(all_task):
+ end_idx = len(all_task)
+ all_sub_tasks.append(all_task[start_idx:end_idx])
+ m = Pool(num_worker)
+ all_sub_results = m.map(func, all_sub_tasks)
+ result = []
+ for s in all_sub_results:
+ result.extend(s)
+ return result
+
+def convert_label_db(dataset, split, idx, with_bb):
+ result = None
+ label_mapper = dataset._sourcelabel_to_targetlabels
+ queried = []
+ for row_with_idx in tqdm(dataset.iter_gt(split, idx=idx)):
+ i = row_with_idx[0]
+ queried.append(i)
+ row = list(row_with_idx[1:])
+ rects = row[1]
+ def eval_with_bb(r):
+ if not r['class'].startswith('-'):
+ return 'rect' in r and any(x != 0 for x in r['rect'])
+ else:
+ return 'rect' not in r or all(x == 0 for x in r['rect'])
+ if with_bb:
+ # in the case with -, we will not add rect
+ # with all zeros, thus, no need to check if it is all zeros
+ # when it is negative samples
+ rects = [r for r in rects if eval_with_bb(r)]
+ # all annotations if eval_with_bb(r) is valid for no_bb. Thus, disable
+ # the following
+ #else:
+ #rects = [r for r in rects if not eval_with_bb(r)]
+ if result is None:
+ result = [None] * dataset.num_rows(split)
+ for _ in range(len(result)):
+ result[_] = ['d'] * len(row)
+ rects2 = []
+ # the following code should use convert_one_label
+ for rect in rects:
+ if rect['class'] in label_mapper:
+ for t in label_mapper[rect['class']]:
+ r2 = copy.deepcopy(rect)
+ r2['class'] = t
+ if rect['class'] != t:
+ # keep this for logging
+ r2['class_from'] = rect['class']
+ rects2.append(r2)
+ row[1] = rects2
+ result[i] = row
+ not_coverred = set(idx).difference(queried)
+ assert len(not_coverred) == 0
+ return result
+
+def create_trainX_db(train_ldtsi, extra_dtsi, tax, out_dataset,
+ lift_train=False):
+ t_to_ldsi = list_to_dict(train_ldtsi, 2)
+ extra_t_to_dsi = list_to_dict(extra_dtsi, 1)
+ train_ldtsik = []
+ extra_dtsik = []
+ for label_type in t_to_ldsi:
+ ldsi = t_to_ldsi[label_type]
+ extra_dsi = extra_t_to_dsi.get(label_type, [])
+ d_to_lsi = list_to_dict(ldsi, 1)
+ extra_d_to_si = list_to_dict(extra_dsi, 0)
+ k = 0
+ sources = []
+ sources_label = []
+ with_bb = label_type == 'with_bb'
+ for dataset in d_to_lsi:
+ lsi = d_to_lsi[dataset]
+ extra_si = extra_d_to_si.get(dataset, [])
+ s_li = list_to_dict(lsi, 1)
+ extra_s_to_i = list_to_dict(extra_si, 0)
+ for split in s_li:
+ li = s_li[split]
+ idx_to_l = list_to_dict(li, 1)
+ idx = idx_to_l.keys()
+ extra_i = extra_s_to_i.get(split, [])
+ # link the data tsv
+ source = dataset.get_data(split)
+ out_split = 'train{}'.format(k)
+ train_ldtsik.extend([(l, dataset, label_type, split, i,
+ k) for l, i in li])
+ extra_dtsik.extend([(dataset, label_type, split, i, k)
+ for i in extra_i])
+ k = k + 1
+ sources.append(source)
+ logging.info('converting labels: {}-{}'.format(
+ dataset.name, split))
+
+ converted_label = convert_label_db(dataset,
+ split, idx, with_bb=with_bb)
+ # convert the file name
+ logging.info('delifting the labels')
+ for i in tqdm(idx):
+ l = converted_label[i]
+ if lift_train:
+ l[1] = json.dumps(lift_one_image(l[1], tax))
+ else:
+ l[1] = json.dumps(delift_one_image(l[1], tax))
+ l[0] = '{}_{}_{}'.format(dataset.name, split, l[0])
+ label_file = out_dataset[label_type].get_data(out_split, 'label')
+ logging.info('writing the label file {}'.format(label_file))
+ tsv_writer(converted_label, label_file)
+ sources_label.append(label_file)
+ write_to_file('\n'.join(sources),
+ out_dataset[label_type].get_data('trainX'))
+ write_to_file('\n'.join(sources_label),
+ out_dataset[label_type].get_data('trainX', 'label'))
+
+ logging.info('saving the shuffle file')
+ type_to_ldsik = list_to_dict(train_ldtsik, 2)
+ extra_type_to_dsik = list_to_dict(extra_dtsik, 1)
+ for label_type in type_to_ldsik:
+ ldsik = type_to_ldsik[label_type]
+ shuffle_info = [(str(k), str(i)) for l, d, s, i, k in ldsik]
+ shuffle_info = list(set(shuffle_info))
+ if label_type in extra_type_to_dsik:
+ dsik = extra_type_to_dsik[label_type]
+ # we should not de-duplicate it because it comes from the duplicate
+ # policy
+ extra_shuffle_info = [(str(k), str(i) ) for d, s, i, k in dsik]
+ shuffle_info.extend(extra_shuffle_info)
+ random.shuffle(shuffle_info)
+ tsv_writer(shuffle_info,
+ out_dataset[label_type].get_shuffle_file('train'))
+
+ populate_output_num_images(train_ldtsik, 'toTrain', tax.root)
+
+def create_trainX(train_ldtsi, extra_dtsi, tax, out_dataset,
+ lift_train=False, use_original_label=False):
+ t_to_ldsi = list_to_dict(train_ldtsi, 2)
+ extra_t_to_dsi = list_to_dict(extra_dtsi, 1)
+ train_ldtsik = []
+ extra_dtsik = []
+ for label_type in t_to_ldsi:
+ ldsi = t_to_ldsi[label_type]
+ extra_dsi = extra_t_to_dsi.get(label_type, [])
+ d_to_lsi = list_to_dict(ldsi, 1)
+ extra_d_to_si = list_to_dict(extra_dsi, 0)
+ k = 0
+ sources = []
+ sources_origin_label = []
+ sources_label = []
+ with_bb = label_type == 'with_bb'
+ for dataset in d_to_lsi:
+ lsi = d_to_lsi[dataset]
+ extra_si = extra_d_to_si.get(dataset, [])
+ s_li = list_to_dict(lsi, 1)
+ extra_s_to_i = list_to_dict(extra_si, 0)
+ for split in s_li:
+ li = s_li[split]
+ idx_to_l = list_to_dict(li, 1)
+ idx = idx_to_l.keys()
+ extra_i = extra_s_to_i.get(split, [])
+ # link the data tsv
+ source = dataset.get_data(split)
+ out_split = 'train{}'.format(k)
+ train_ldtsik.extend([(l, dataset, label_type, split, i,
+ k) for l, i in li])
+ extra_dtsik.extend([(dataset, label_type, split, i, k)
+ for i in extra_i])
+ k = k + 1
+ sources.append(source)
+ logging.info('converting labels: {}-{}'.format(
+ dataset.name, split))
+ source_origin_label = dataset.get_label_tsv(split)
+ if not use_original_label:
+ #converted_label = convert_label(source_origin_label,
+ #idx, dataset._sourcelabel_to_targetlabels,
+ #with_bb=with_bb)
+ converted_label = convert_label_by_dataset(
+ dataset, split,
+ dataset.get_version_by_split(split),
+ idx, dataset._sourcelabel_to_targetlabels,
+ with_bb=with_bb)
+ sources_origin_label.append(source_origin_label)
+ # convert the file name
+ logging.info('delifting the labels')
+ for i in tqdm(idx):
+ l = converted_label[i]
+ if lift_train:
+ l[1] = json.dumps(lift_one_image(l[1], tax))
+ else:
+ l[1] = json.dumps(delift_one_image(l[1], tax))
+ l[0] = '{}_{}_{}'.format(dataset.name, split, l[0])
+ label_file = out_dataset[label_type].get_data(out_split, 'label')
+ logging.info('writing the label file {}'.format(label_file))
+ tsv_writer(converted_label, label_file)
+ else:
+ label_file = source_origin_label
+ sources_label.append(label_file)
+ write_to_file('\n'.join(sources),
+ out_dataset[label_type].get_data('trainX'))
+ write_to_file('\n'.join(sources_label),
+ out_dataset[label_type].get_data('trainX', 'label'))
+ write_to_file('\n'.join(sources_origin_label),
+ out_dataset[label_type].get_data('trainX', 'origin.label'))
+ logging.info('saving the shuffle file')
+ type_to_ldsik = list_to_dict(train_ldtsik, 2)
+ extra_type_to_dsik = list_to_dict(extra_dtsik, 1)
+ for label_type in type_to_ldsik:
+ ldsik = type_to_ldsik[label_type]
+ shuffle_info = [(str(k), str(i)) for l, d, s, i, k in ldsik]
+ shuffle_info = list(set(shuffle_info))
+ if label_type in extra_type_to_dsik:
+ dsik = extra_type_to_dsik[label_type]
+ # we should not de-duplicate it because it comes from the duplicate
+ # policy
+ extra_shuffle_info = [(str(k), str(i) ) for d, s, i, k in dsik]
+ shuffle_info.extend(extra_shuffle_info)
+ random.shuffle(shuffle_info)
+ tsv_writer(shuffle_info,
+ out_dataset[label_type].get_shuffle_file('train'))
+
+ # expand nested trainX if needed
+ expand_nested_splitX(out_dataset[label_type].name, 'train')
+
+ populate_output_num_images(train_ldtsik, 'toTrain', tax.root)
+
+def expand_nested_splitX(data, split):
+ dataset = TSVDataset(data)
+ if not dataset.has(split):
+ logging.info('{}-{} does not exist'.format(data, split))
+ return
+ if op.isfile(dataset.get_data(split)):
+ logging.info('{}/{}.tsv already exists'.format(data, split))
+ return
+ assert op.isfile(dataset.get_data(split + 'X'))
+
+ need_to_expand = False
+ src_data_splits = dataset.load_composite_source_data_split(split)
+ for src_data, src_split in src_data_splits:
+ src_dataset = TSVDataset(src_data)
+ if not op.isfile(src_dataset.get_data(src_split)):
+ assert op.isfile(src_dataset.get_data(src_split + 'X'))
+ need_to_expand = True
+ break
+ if not need_to_expand:
+ logging.info('no need to expand')
+ return
+
+ if not op.isfile(dataset.get_data(split, 'label')):
+ convertcomposite_to_standard(data, split, ignore_image=True)
+
+ cache_shuffle = {}
+ def get_shuffle(d, s):
+ if (d, s) in cache_shuffle:
+ return cache_shuffle[(d, s)]
+ else:
+ shuffle = [(int(i), int(j)) for i, j in
+ tsv_reader(TSVDataset(d).get_shuffle_file(s))]
+ cache_shuffle[(d, s)] = shuffle
+ return shuffle
+
+ cache_src_data_splits = {}
+ def get_src_data_splits(d, s):
+ if (d, s) in cache_src_data_splits:
+ return cache_src_data_splits[(d, s)]
+ else:
+ ssrc_data_splits = TSVDataset(d).load_composite_source_data_split(s)
+ cache_src_data_splits[(d, s)] = ssrc_data_splits
+ return ssrc_data_splits
+
+ cache_single_tsv = {}
+ def get_single(d, s):
+ if (d, s) in cache_single_tsv:
+ return cache_single_tsv[(d, s)]
+ else:
+ single = TSVDataset(d).get_data(s)
+ cache_single_tsv[(d, s)] = single
+ return single
+
+ cache_is_single = {}
+ def get_is_single(d, s):
+ if (d, s) in cache_is_single:
+ return cache_is_single[(d, s)]
+ else:
+ is_single = op.isfile(TSVDataset(d).get_data(s))
+ cache_is_single[(d, s)] = is_single
+ return is_single
+
+ def get_tsv_line(d, s, i):
+ single_tsv = get_is_single(d, s)
+ if single_tsv:
+ return get_single(d, s), i
+ else:
+ ssrc_data_splits = get_src_data_splits(d, s)
+ shuffle = get_shuffle(d, s)
+ idx_src, idx_row = shuffle[i]
+ src_d, src_s = ssrc_data_splits[idx_src]
+ return get_tsv_line(src_d, src_s, idx_row)
+
+ shuffle = get_shuffle(data, split)
+ all_tsv_idx = []
+ for idx_src, idx_row in shuffle:
+ ss_data, ss_split = src_data_splits[idx_src]
+ tsv, i = get_tsv_line(ss_data, ss_split, idx_row)
+ all_tsv_idx.append((tsv, i))
+ unique_tsvs = list(list_to_dict(all_tsv_idx, 0).keys())
+ tsv_to_idx = {t: i for i, t in enumerate(unique_tsvs)}
+ shuffle_result = [(tsv_to_idx[t], i) for t, i in all_tsv_idx]
+ tsv_writer(shuffle_result, dataset.get_shuffle_file(split))
+ write_to_file('\n'.join(unique_tsvs), dataset.get_data(split + 'X'))
+
+def create_testX_db(test_ldtsi, tax, out_dataset):
+ t_to_ldsi = list_to_dict(test_ldtsi, 2)
+ for label_type in t_to_ldsi:
+ sources = []
+ sources_label = []
+ ldsi = t_to_ldsi[label_type]
+ d_to_lsi = list_to_dict(ldsi, 1)
+ k = 0
+ all_ki = []
+ with_bb = label_type == 'with_bb'
+ for dataset in d_to_lsi:
+ lsi = d_to_lsi[dataset]
+ s_to_li = list_to_dict(lsi, 1)
+ for split in s_to_li:
+ li = s_to_li[split]
+ idx = list_to_dict(li, 1).keys()
+ out_split = 'test{}'.format(k)
+ s_file = dataset.get_data(split)
+ sources.append(s_file)
+ converted_label = convert_label_db(dataset,
+ split, idx, with_bb=with_bb)
+ for i in tqdm(idx):
+ l = converted_label[i]
+ l[1] = json.dumps(lift_one_image(l[1], tax))
+ l[0] = '{}_{}_{}'.format(dataset.name, split, l[0])
+ all_ki.extend([(str(k), str(i)) for i in idx])
+ label_file = out_dataset[label_type].get_data(out_split, 'label')
+ tsv_writer(converted_label, label_file)
+ sources_label.append(label_file)
+ k = k + 1
+ write_to_file('\n'.join(sources),
+ out_dataset[label_type].get_data('testX'))
+ write_to_file('\n'.join(sources_label),
+ out_dataset[label_type].get_data('testX', 'label'))
+ tsv_writer(all_ki, out_dataset[label_type].get_shuffle_file('test'))
+
+def create_testX(test_ldtsi, tax, out_dataset):
+ t_to_ldsi = list_to_dict(test_ldtsi, 2)
+ for label_type in t_to_ldsi:
+ sources = []
+ sources_origin_label = []
+ sources_label = []
+ ldsi = t_to_ldsi[label_type]
+ d_to_lsi = list_to_dict(ldsi, 1)
+ k = 0
+ all_ki = []
+ with_bb = label_type == 'with_bb'
+ for dataset in d_to_lsi:
+ lsi = d_to_lsi[dataset]
+ s_to_li = list_to_dict(lsi, 1)
+ for split in s_to_li:
+ li = s_to_li[split]
+ idx = list_to_dict(li, 1).keys()
+ out_split = 'test{}'.format(k)
+ s_file = dataset.get_data(split)
+ sources.append(s_file)
+ source_origin_label = dataset.get_label_tsv(split)
+ sources_origin_label.append(source_origin_label)
+ #converted_label = convert_label(source_origin_label,
+ #idx, dataset._sourcelabel_to_targetlabels,
+ #with_bb=with_bb)
+ converted_label = convert_label_by_dataset(
+ dataset, split, dataset.get_version_by_split(split),
+ idx, dataset._sourcelabel_to_targetlabels,
+ with_bb=with_bb)
+ for i in tqdm(idx):
+ l = converted_label[i]
+ l[1] = json.dumps(lift_one_image(l[1], tax))
+ l[0] = '{}_{}_{}'.format(dataset.name, split, l[0])
+ all_ki.extend([(str(k), str(i)) for i in idx])
+ label_file = out_dataset[label_type].get_data(out_split, 'label')
+ tsv_writer(converted_label, label_file)
+ sources_label.append(label_file)
+ k = k + 1
+ write_to_file('\n'.join(sources),
+ out_dataset[label_type].get_data('testX'))
+ write_to_file('\n'.join(sources_label),
+ out_dataset[label_type].get_data('testX', 'label'))
+ write_to_file('\n'.join(sources_origin_label),
+ out_dataset[label_type].get_data('testX', 'origin.label'))
+ tsv_writer(all_ki, out_dataset[label_type].get_shuffle_file('test'))
+ expand_nested_splitX(out_dataset[label_type].name, 'test')
+
+def remove_or_duplicate_each_type(train_ldtsi, label_to_min_image, label_to_max_image):
+ label_to_dtsi = list_to_dict(train_ldtsi, 0)
+ extra_dtsi = []
+ for label in label_to_dtsi:
+ if label is None:
+ continue
+ dtsi = label_to_dtsi[label]
+ max_image = label_to_max_image[label]
+ t_to_dsi = list_to_dict(dtsi, 1)
+ if isinstance(label_to_min_image, dict):
+ min_image = label_to_min_image[label]
+ else:
+ # label_to_min_image is an integer
+ min_image = label_to_min_image
+ for t in t_to_dsi:
+ dsi = t_to_dsi[t]
+ if len(dsi) > max_image:
+ # first remove the images with no bounding box
+ num_remove = len(dsi) - max_image
+ random.seed(9999)
+ random.shuffle(dsi)
+ dsi = sorted(dsi, key=lambda x: -x[0].cleaness)
+ assert len(dsi) > num_remove
+ dsi = dsi[: len(dsi) - num_remove]
+ t_to_dsi[t] = dsi
+ elif len(dsi) < min_image:
+ num_duplicate = int(np.ceil(float(min_image) / len(dsi)))
+ logging.info('duplicate images for {}/{}: {}->{}, {}'.format(
+ t, label, len(dsi), min_image, num_duplicate))
+ # we already has 1 copy of dsi, thus we should subtract 1
+ extra_dsi = (num_duplicate - 1) * dsi
+ extra_dtsi.extend([[d, t, s, i] for d, s, i in extra_dsi])
+ dtsi = dict_to_list(t_to_dsi, 1)
+ label_to_dtsi[label] = dtsi
+ logging.info('# train instances before duplication: {}'.format(len(train_ldtsi)))
+ train_ldtsi = dict_to_list(label_to_dtsi, 0)
+ logging.info('# train instances after duplication: {}'.format(len(train_ldtsi)))
+ return train_ldtsi, extra_dtsi
+
+def remove_or_duplicate(train_ldtsi, min_image, label_to_max_image):
+ # min_image is for the sum of with_bb and no_bb
+ # prefer to use _each_type version, which interpret min_image as the value
+ # for each type
+ label_to_dtsi = list_to_dict(train_ldtsi, 0)
+ extra_dtsi = []
+ for label in label_to_dtsi:
+ dtsi = label_to_dtsi[label]
+ max_image = label_to_max_image[label]
+ if len(dtsi) > max_image:
+ # first remove the images with no bounding box
+ num_remove = len(dtsi) - max_image
+ type_to_dsi = list_to_dict(dtsi, 1)
+ if 'no_bb' in type_to_dsi:
+ dsi = type_to_dsi['no_bb']
+ if num_remove >= len(dsi):
+ # remove all this images
+ del type_to_dsi['no_bb']
+ num_remove = num_remove - len(dsi)
+ else:
+ random.seed(9999)
+ random.shuffle(dsi)
+ type_to_dsi['no_bb'] = dsi[: len(dsi) - num_remove]
+ num_remove = 0
+ if num_remove > 0:
+ assert 'with_bb' in type_to_dsi
+ dsi = type_to_dsi['with_bb']
+ random.seed(9999)
+ random.shuffle(dsi)
+ dsi = sorted(dsi, key=lambda x: -x[0].cleaness)
+ assert len(dsi) > num_remove
+ type_to_dsi['with_bb'] = dsi[: len(dsi) - num_remove]
+ num_remove = 0
+ dtsi = dict_to_list(type_to_dsi, 1)
+ elif len(dtsi) < min_image:
+ num_duplicate = int(np.ceil(float(min_image) / len(dtsi)))
+ logging.info('duplicate images for label of {}: {}->{}, {}'.format(
+ label, len(dtsi), min_image, num_duplicate))
+ extra_dtsi.extend((num_duplicate - 1) * dtsi)
+ label_to_dtsi[label] = dtsi
+ logging.info('# train instances before duplication: {}'.format(len(train_ldtsi)))
+ train_ldtsi = dict_to_list(label_to_dtsi, 0)
+ logging.info('# train instances after duplication: {}'.format(len(train_ldtsi)))
+ return train_ldtsi, extra_dtsi
+
+def remove_test_in_train(train_ldtsi, test_ldtsi):
+ logging.info('before len(train_ldtsi) = {}'.format(len(train_ldtsi)))
+ set_train_dtsi = set((d, t, s, i) for l, d, t, s, i in train_ldtsi)
+ if len(train_ldtsi) > 0 and type(train_ldtsi[0]) is list:
+ # we need to convert it to immutable tuple since list is not hashable
+ train_ldtsi = [(l, d, t, s, i) for l, d, t, s, i in train_ldtsi]
+ set_train_ldtsi = set(train_ldtsi)
+ #assert len(set_train_ldtsi) == len(train_ldtsi)
+ set_test_dtsi = set((d, t, s, i) for l, d, t, s, i in test_ldtsi)
+ result = [(l, d, t, s, i) for l, d, t, s, i in train_ldtsi
+ if (d, t, s, i) not in set_test_dtsi]
+ logging.info('after len(train_ldtsi) = {}'.format(len(result)))
+ return result
+
+def split_train_test(ldtsi, num_test):
+ # group by label_type
+ t_to_ldsi = list_to_dict(ldtsi, 2)
+ train_ldtsi = []
+ test_ldtsi = []
+ for label_type in sorted(t_to_ldsi.keys()):
+ ldsi= t_to_ldsi[label_type]
+ l_to_dsi = list_to_dict(ldsi, 0)
+ for rootlabel in sorted(l_to_dsi.keys()):
+ dsi = l_to_dsi[rootlabel]
+ if len(dsi) < num_test:
+ logging.info('rootlabel={}; label_type={}->less than {} images'.format(
+ rootlabel, label_type, len(dsi)))
+ curr_num_test = min(num_test, int(len(dsi) / 2))
+ random.shuffle(dsi)
+ test_ldtsi.extend([(rootlabel, d, label_type, s, i) for d, s, i
+ in dsi[:curr_num_test]])
+ train_ldtsi.extend([(rootlabel, d, label_type, s, i) for d, s, i
+ in dsi[curr_num_test:]])
+ return train_ldtsi, test_ldtsi
+
+def regularize_data_sources(data_infos):
+ result = []
+ default_splits = get_default_splits()
+ for data_info in data_infos:
+ if type(data_info) is str:
+ r = {'name': data_info,
+ 'cleaness': 10,
+ 'valid_splits': default_splits,
+ 'use_all': False}
+ result.append(r)
+ elif type(data_info) is tuple or type(data_info) is list:
+ assert len(data_info) > 0
+ r = {'name': data_info[0],
+ 'cleaness': data_info[1] if len(data_info) > 1 else 10,
+ 'valid_splits': data_info[2] if len(data_info) > 2 else
+ default_splits,
+ 'use_all': data_info[3] if len(data_info) > 3 else False,
+ }
+ assert len(data_info) < 5
+ result.append(r)
+ elif type(data_info) is dict:
+ r = data_info
+ result.append(r)
+ else:
+ raise Exception('unkwown data_info = {}'.format(data_info))
+ for r in result:
+ if 'data' in r:
+ assert 'name' not in r
+ r['name'] = r['data']
+ del r['data']
+ return result
+
+def parse_data_clean_splits(data_infos):
+ '''
+ use regularize_data_sources
+ '''
+ datas, cleaness, all_valid_splits = [], [], []
+ default_splits = get_default_splits()
+ for data_info in data_infos:
+ if type(data_info) is str:
+ datas.append(data_info)
+ cleaness.append(10)
+ all_valid_splits.append(default_splits)
+ elif type(data_info) is tuple or type(data_info) is list:
+ assert len(data_info) > 0
+ datas.append(data_info[0])
+ cleaness.append(data_info[1] if len(data_info) > 1 else 10)
+ all_valid_splits.append(data_info[2] if len(data_info) > 2 else default_splits)
+ elif type(data_info) is dict:
+ datas.append(data_info['data'])
+ cleaness.append(data_info.get('cleaness', 10))
+ all_valid_splits.append(data_info.get('valid_splits', default_splits))
+ else:
+ raise Exception('unkwown data_info = {}'.format(data_info))
+ return datas, cleaness, all_valid_splits
+
+def attach_properties(src_nodes, dst_tree):
+ name_to_dst_node = {n.name: n for n in dst_tree.iter_search_nodes() if
+ n != dst_tree}
+ confusings = []
+ for src_node in src_nodes:
+ if src_node.name not in name_to_dst_node:
+ continue
+ dst_node = name_to_dst_node[src_node.name]
+ for f in src_node.features:
+ if f in ['support', 'name', 'dist', 'sub_group']:
+ continue
+ if f in dst_node.features:
+ if dst_node.__getattribute__(f) == src_node.__getattribute__(f):
+ continue
+ else:
+ confusings.append({'name': src_node.name,
+ 'feature': f,
+ 'value in tree': dst_node.__getattribute__(f),
+ 'value in property list': src_node.__getattribute__(f)})
+ else:
+ dst_node.add_feature(f, src_node.__getattribute__(f))
+ assert len(confusings) == 0, pformat(confusings)
+
+def update_taxonomy_by_latest(ref_data, target_data):
+ lift_train = False
+ from .common import ensure_copy_folder
+ # copy everything from ref_data to target_data and _no_bb
+ ensure_copy_folder(op.join('data', ref_data),
+ op.join('data', target_data))
+ ensure_copy_folder(op.join('data', ref_data + '_no_bb'),
+ op.join('data', target_data + '_no_bb'))
+
+ # _with_bb
+ ref_data = ref_data + '_with_bb'
+ target_data = target_data + '_with_bb'
+ update_bb_taxonomy_by_latest(ref_data, target_data)
+
+def update_bb_taxonomy_by_latest(ref_data, target_data):
+ ref_dataset = TSVDataset(ref_data)
+ out_dataset = TSVDataset(target_data)
+
+ split = 'train'
+ splitX = '{}X'.format(split)
+ all_idxsource_idxrow = [(int(s_idx_source), int(s_idx_row)) for s_idx_source, s_idx_row in
+ tsv_reader(ref_dataset.get_shuffle_file(split))]
+ pattern = 'data/(.*)/(train|trainval|test)\.label.*\.tsv'
+ # e.g. source_origin_label = 'data/SeeingAISplit/train.label.tsv'
+ source_data_splits = [re.match(pattern, source_origin_label).groups()
+ for source_origin_label, in ref_dataset.iter_data(splitX, 'origin.label')]
+ source_data_split_versions = [(d, s, -1) for d, s in source_data_splits]
+
+ lift_train = False
+ dump_to_taxonomy_dataset(ref_dataset, all_idxsource_idxrow,
+ source_data_split_versions, lift_train, split, out_dataset)
+
+def dump_to_taxonomy_dataset(ref_dataset, all_idxsource_idxrow,
+ source_data_split_versions, lift_train, split, out_dataset):
+ splitX = split + 'X'
+ tax = Taxonomy(load_from_yaml_file(op.join(ref_dataset._data_root, 'root.yaml')))
+ sources_label = []
+ sources_origin_label = []
+ for idxsource, (source_data, source_split, source_version) in enumerate(source_data_split_versions):
+ idx = [idx_r for idx_s, idx_r in all_idxsource_idxrow if idxsource == idx_s]
+ for n in tax.root.iter_search_nodes():
+ if source_data in n.features:
+ n.add_feature(source_data,
+ n.__getattribute__(source_data) + ',{}'.format(n.name))
+ source_dataset = TSVDatasetSource(source_data, root=tax.root,
+ split_infos=[{'split': source_split, 'version': -1}])
+ source_dataset._ensure_initialized()
+ source_origin_label = source_dataset.get_data(source_split, 'label',
+ source_version)
+ sources_origin_label.append(source_origin_label)
+ converted_label = convert_label(source_origin_label,
+ idx, source_dataset._sourcelabel_to_targetlabels,
+ with_bb=True)
+ for i in tqdm(idx):
+ l = converted_label[i]
+ if lift_train:
+ l[1] = json.dumps(lift_one_image(l[1], tax))
+ else:
+ l[1] = json.dumps(delift_one_image(l[1], tax))
+ l[0] = '{}_{}_{}'.format(source_dataset.name, source_split, l[0])
+ out_split = '{}{}'.format(split, idxsource)
+ label_file = out_dataset.get_data(out_split, 'label')
+ tsv_writer(converted_label, label_file)
+ sources_label.append(label_file)
+
+ # the label version might be updated. Thus, the sources_label could be
+ # different from the reference dataset
+ write_to_file('\n'.join(sources_label),
+ out_dataset.get_data(splitX, 'label'))
+
+ write_to_file('\n'.join(sources_origin_label),
+ out_dataset.get_data(splitX, 'origin.label'))
+
+ # copy the image source file
+ ensure_copy_file(ref_dataset.get_data(splitX),
+ out_dataset.get_data(splitX))
+
+ # copy the labelmap
+ ensure_copy_file(ref_dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+
+ # copy the shuffle file
+ # the idx could be different since we might add more images here
+ tsv_writer(all_idxsource_idxrow,
+ out_dataset.get_shuffle_file(split))
+
+def test():
+ data = 'LogosInTheWild-v2Clean'
+ idx = 1237
+ dataset = TSVDataset(data)
+ tsv = TSVFile(dataset.get_data('train', 'label', 3))
+ key, str_rects = tsv.seek(idx)
+ key, _, str_im = dataset.seek_by_key(key, 'train')
+
+ #im = img_from_base64(str_im)
+ jpgbytestring = base64.b64decode(str_im)
+ nparr = np.frombuffer(jpgbytestring, np.uint8)
+ im = cv2.imdecode(nparr, cv2.IMREAD_IGNORE_ORIENTATION);
+
+ rects = json.loads(str_rects)
+ draw_rects(im, rects)
+ save_image(im, '/mnt/jianfw_desk/a.png')
+
+def trim_rects_from_db(rects):
+ keys = ['_id', 'create_time', 'idx_in_split',
+ 'key', 'split', 'data']
+ for rect in rects:
+ for k in keys:
+ if k in rect:
+ del rect[k]
+
+class TSVDatasetDB(object):
+ def __init__(self, name):
+ self.name = name
+ self._db = create_mongodb_client()
+ self._gt = self._db['qd']['ground_truth']
+ self._image = self._db['qd']['image']
+
+ def iter_gt(self, split, version=None, version_by_time=None,
+ idx=None, bb_type='with_bb'):
+ # query the image db first and then attach the gt information
+ match = {'data': self.name,
+ 'split': split}
+ if idx:
+ match['idx_in_split'] = {'$in': list(idx)}
+ lookup_pipeline = self._get_gt_rect_pipeline(
+ split, version, version_by_time, bb_type,
+ extra_filter={'$eq': ['$key', '$$key']},
+ in_lookup=True)
+ pipeline = [{'$match': match},
+ {'$lookup': {'from': 'ground_truth',
+ 'let': {'key': '$key'},
+ 'pipeline': lookup_pipeline,
+ 'as': 'rects'
+ }}]
+ for row in self._image.aggregate(pipeline, allowDiskUse=True):
+ trim_rects_from_db(row['rects'])
+ yield row['idx_in_split'], row['key'], row['rects']
+
+ @deprecated('use iter_gt since this function will not return the image with no bb')
+ def iter_gt_image(self, split, version=None, version_by_time=None,
+ idx=None, bb_type='with_bb'):
+ # deprecated. use iter_gt since this function will not return anything
+ # if the image in idx has no box
+ # if idx is not none, here we do not guarrentee the order is kept.
+ # Thus, we also return the index of the image
+ if idx:
+ extra_filter = {'idx_in_split': {'$in': list(idx)}}
+ else:
+ extra_filter = None
+ pipeline = self._get_gt_rect_pipeline(split,
+ version, version_by_time, bb_type,
+ extra_filter)
+ pipeline.append({'$group': {'_id': '$idx_in_split',
+ 'key': {'$first': '$key'},
+ 'rects': {'$push': '$$ROOT'}}})
+ logging.info(pformat(pipeline))
+ for result in self._gt.aggregate(pipeline, allowDiskUse=True):
+ for rect in result['rects']:
+ if '_id' in rect:
+ del rect['_id']
+ if 'create_time' in rect:
+ del rect['create_time']
+ yield result['_id'], result['key'], result['rects']
+
+ def _get_gt_rect_pipeline(self, split, version, version_by_time,
+ bb_type, extra_filter, in_lookup=False):
+ if not in_lookup:
+ match = {'data': self.name,
+ 'split': split}
+ else:
+ match_condition = []
+ match_condition.append({'$eq': ['$data', self.name]})
+ match_condition.append({'$eq': ['$split', split]})
+ if extra_filter:
+ if not in_lookup:
+ match.update(extra_filter)
+ else:
+ match_condition.append(extra_filter)
+ if version_by_time:
+ if not in_lookup:
+ match['create_time'] = {'$lte': version_by_time}
+ else:
+ match_condition.append({'$lte': ['$create_time', version_by_time]})
+ sort_by = 'create_time'
+ else:
+ if version is None:
+ version = 0
+ if version != -1:
+ if not in_lookup:
+ match['version'] = {'$lte': version}
+ else:
+ match_condition.append({'$lte': ['$version', version]})
+ sort_by = 'version'
+ if in_lookup:
+ match = {'$expr': {'$and': match_condition}}
+ sort_value = OrderedDict() # use ordered since dict is non-ordered
+ sort_value[sort_by] = -1
+ sort_value['contribution'] = -1
+ pipeline = [{'$match': match},
+ # we may change some properties at the same version or
+ # time. In this case, we prefer contribution=1
+ {'$sort': sort_value},
+ {'$group': {'_id': '$action_target_id',
+ 'rect_info': {'$first': '$$ROOT'}}},
+ {'$replaceRoot': {'newRoot': '$rect_info'}},
+ {'$match': {'contribution': 1}},
+ ]
+ if bb_type == 'with_bb':
+ cond1 = {'rect': {'$ne': None}}
+ cond2_or = []
+ for i in range(4):
+ cond2_or.append({'rect.{}'.format(i): {'$ne': 0}})
+ cond2 = {'$or': cond2_or}
+ match_with_bb = {'$and': [cond1, cond2]}
+ pipeline.append({'$match': match_with_bb})
+ else:
+ assert bb_type == 'no_bb'
+ return pipeline
+
+ def iter_gt_rect(self, split, version=None, version_by_time=None,
+ bb_type='with_bb',
+ extra_filter=None):
+ # we do not add any filter here. Thus it is no_bb + with_bb
+ pipeline = self._get_gt_rect_pipeline(split, version, version_by_time,
+ bb_type, extra_filter)
+ return self._gt.aggregate(pipeline, allowDiskUse=True)
+
+ def num_rows(self, split):
+ pipeline = [{'$match': {'data': self.name, 'split': split}},
+ {'$group': {'_id': 1, 'm': {'$max': '$idx_in_split'}}}]
+ result = next(self._image.aggregate(pipeline))
+ return result['m'] + 1
+
+ def get_data(self, split):
+ return op.join('data', self.name, '{}.tsv'.format(split))
+
+ def _get_unique_labels(self):
+ # we ignore the version to make it simplier. it should cover all labels
+ splits = [split_info['split'] for split_info in self._split_infos]
+ pipeline = [{'$match': {'data': self.name,
+ 'split': {'$in': splits}}},
+ {'$group': {'_id': '$class'}}]
+ labelmap = sorted([r['_id'] for r in self._gt.aggregate(pipeline)])
+ return labelmap
+
+class TSVDatasetSourceDB(TSVDatasetDB):
+ def __init__(self, name, root=None,
+ split_infos=None,
+ cleaness=10,
+ use_all=False,
+ use_negative_label=False,
+ select_by_verified=False):
+ super(TSVDatasetSourceDB, self).__init__(name)
+ self._noffset_count = {}
+ self._type = None
+ self._root = root
+ # the list of
+ self._sourcelabel_to_targetlabels = None
+ self._targetlabel_to_sourcelabels = None
+ self._initialized = False
+ self._type_to_datasetlabel_to_split_idx = None
+ self._type_to_datasetlabel_to_count = None
+ self._type_to_split_label_idx = None
+ if split_infos is not None:
+ self._split_infos = split_infos
+ else:
+ self._split_infos = [{'split': s, 'version': -1}
+ for s in get_default_splits()]
+ self._split_to_info = {s['split']: s for s in self._split_infos}
+ assert len(set([split_info['split'] for split_info in
+ self._split_infos])) == len(self._split_infos)
+ self._use_all = use_all
+ self._select_by_verified = select_by_verified
+ self.cleaness = cleaness
+ self.use_negative_label = use_negative_label
+
+ def populate_info(self, root):
+ self._ensure_initialized()
+ for node in root.iter_search_nodes():
+ if root == node:
+ continue
+ if node.name in self._targetlabel_to_sourcelabels:
+ sourcelabels = self._targetlabel_to_sourcelabels[node.name]
+ node.add_feature(self.name, ','.join(sourcelabels))
+ if any(is_noffset(l) for l in sourcelabels):
+ node.add_feature(self.name + '_readable',
+ ','.join(get_nick_name(noffset_to_synset(l)) if
+ is_noffset(l) else l for l in sourcelabels))
+ total = 0
+ for sourcelabel in sourcelabels:
+ for t in self._type_to_datasetlabel_to_count:
+ datasetlabel_to_count = self._type_to_datasetlabel_to_count[t]
+ c = datasetlabel_to_count.get(sourcelabel, 0)
+ total = total + c
+ key = 'images_{}'.format(t)
+ node.add_feature(key,
+ node.__getattribute__(key) + c)
+ node.add_feature('{}_total'.format(self.name), total)
+
+ def _ensure_initialized(self):
+ if self._initialized:
+ return
+
+ self.update_label_mapper()
+
+ self._load_inverted()
+
+ self._initialized = True
+
+ def _load_inverted(self):
+ # make sure self.update_label_mapper() is called
+ types = ['with_bb', 'no_bb']
+ self._type_split_label_idx = []
+
+ usefull_dataset_labels = self._sourcelabel_to_targetlabels.keys()
+ usefull_dataset_labels = [l for l in usefull_dataset_labels if not l.startswith('-')]
+ for split_info in self._split_infos:
+ for bb_type in types:
+ iter_merged = self.iter_gt_rect(split=split_info['split'],
+ version=split_info.get('version'),
+ version_by_time=split_info.get('version_by_time'),
+ bb_type=bb_type,
+ extra_filter={'class': {'$in': usefull_dataset_labels}})
+ type_split_label_idx = ((bb_type, rect_info['split'],
+ rect_info['class'], rect_info['idx_in_split'])
+ for rect_info in iter_merged)
+ self._type_split_label_idx.extend(type_split_label_idx)
+
+ assert not self.use_negative_label, 'not supported'
+
+ self._type_split_label_idx = list(set(self._type_split_label_idx))
+ self._type_to_split_label_idx = list_to_dict(
+ self._type_split_label_idx, 0)
+ self._type_to_datasetlabel_to_split_idx = {}
+ for t in self._type_to_split_label_idx:
+ split_label_idx = self._type_to_split_label_idx[t]
+ label_to_split_idx = list_to_dict(split_label_idx, 1)
+ self._type_to_datasetlabel_to_split_idx[t] = label_to_split_idx
+ self._type_to_datasetlabel_to_count = {}
+ for t in self._type_to_datasetlabel_to_split_idx:
+ datasetlabel_to_split_idx = self._type_to_datasetlabel_to_split_idx[t]
+ datasetlabel_to_count = {l: len(datasetlabel_to_split_idx[l]) for l in
+ datasetlabel_to_split_idx}
+ self._type_to_datasetlabel_to_count[t] = datasetlabel_to_count
+
+ self._split_to_num_image = {split_info['split']: self.num_rows(split_info['split']) for split_info in
+ self._split_infos}
+
+ def update_label_mapper(self):
+ root = self._root
+
+ labelmap = self._get_unique_labels()
+ hash_labelmap = set(labelmap)
+
+ tree_noffsets = {}
+ for node in root.iter_search_nodes():
+ if node == root or not node.noffset:
+ continue
+ for s in node.noffset.split(','):
+ tree_noffsets[s] = node.name
+ name_to_targetlabels = {}
+ targetlabel_has_whitelist = set()
+ invalid_list = []
+ any_source_key = 'label_names_in_all_dataset_source'
+ for node in root.iter_search_nodes():
+ if node == root:
+ continue
+ if hasattr(node, self.name) or hasattr(node, any_source_key):
+ if hasattr(node, self.name):
+ # this is like a white-list
+ values = node.__getattribute__(self.name)
+ else:
+ values = node.__getattribute__(any_source_key)
+ if values is not None:
+ source_terms = values.split(',')
+ for t in source_terms:
+ t = t.strip()
+ if t not in name_to_targetlabels:
+ name_to_targetlabels[t] = set()
+ if t not in hash_labelmap:
+ invalid_list.append((t, self.name, node.name))
+ continue
+ name_to_targetlabels[t].add(node.name)
+ # even if it is None, we will also add it to white-list so that
+ # we will not automatically match the term.
+ targetlabel_has_whitelist.add(node.name)
+ else:
+ # we will keep the lower case always for case-insensitive
+ # comparison
+ all_candidate_src_names = [node.name.lower()]
+ if hasattr(node, 'alias_names'):
+ all_candidate_src_names.extend([s.strip() for s in
+ node.alias_names.split(',')])
+ for t in set(all_candidate_src_names):
+ if t not in name_to_targetlabels:
+ name_to_targetlabels[t] = set()
+ name_to_targetlabels[t].add(node.name)
+
+ sourcelabel_targetlabel = []
+ if len(invalid_list) != 0:
+ logging.warn('invalid white list information: {}'.format(pformat(invalid_list)))
+
+ #result = {}
+ label_to_synset = LabelToSynset()
+ for l in labelmap:
+ matched = False
+ if l.lower() in name_to_targetlabels:
+ matched = True
+ for t in name_to_targetlabels[l.lower()]:
+ sourcelabel_targetlabel.append((l, t))
+ if l in name_to_targetlabels:
+ for t in name_to_targetlabels[l]:
+ sourcelabel_targetlabel.append((l, t))
+ matched = True
+ if not matched:
+ succeed, ns = label_to_synset.convert(l)
+ if not succeed:
+ continue
+ for n in ns:
+ n = synset_to_noffset(n)
+ if n in tree_noffsets:
+ t = tree_noffsets[n]
+ if t in targetlabel_has_whitelist:
+ # if it has white list, we will not respect the
+ # noffset to do the autmatic matching
+ continue
+ sourcelabel_targetlabel.append((l, t))
+ #result[l] = t
+ if self.use_negative_label:
+ # we just add the mapping here. no need to check if -s is in the
+ # source label list
+ sourcelabel_targetlabel.extend([('-' + s, '-' + t) for s, t in
+ sourcelabel_targetlabel])
+
+ self._sourcelabel_to_targetlabels = list_to_dict_unique(sourcelabel_targetlabel,
+ 0)
+ self._targetlabel_to_sourcelabels = list_to_dict_unique(sourcelabel_targetlabel,
+ 1)
+
+ return self._sourcelabel_to_targetlabels
+
+ def iter_gt_image(self, split, idx=None, bb_type='with_bb'):
+ split_info = self._split_to_info[split]
+
+ return super(TSVDatasetSourceDB, self).iter_gt_image(split,
+ version=split_info.get('version'),
+ version_by_time=split_info.get('version_by_time'),
+ idx=idx, bb_type=bb_type)
+
+ def select_tsv_rows(self, label_type):
+ self._ensure_initialized()
+ result = []
+ if label_type in self._type_to_split_label_idx:
+ split_label_idx = self._type_to_split_label_idx[label_type]
+ datasetlabel_to_splitidx = list_to_dict(split_label_idx, 1)
+ for datasetlabel in datasetlabel_to_splitidx:
+ if datasetlabel in self._sourcelabel_to_targetlabels:
+ split_idxes = datasetlabel_to_splitidx[datasetlabel]
+ targetlabels = self._sourcelabel_to_targetlabels[datasetlabel]
+ for targetlabel in targetlabels:
+ result.extend([(targetlabel, split, idx) for split, idx in
+ split_idxes])
+ # must_have_indices
+ for split_info in self._split_infos:
+ split = split_info['split']
+ must_have_indices = split_info.get('must_have_indices', [])
+ # we set the target label here as None so that the post-processing
+ # will not ignore it. The real labels will also be converted
+ # corrected since we do not depend on this target label only.
+ result.extend((None, split, i) for i in must_have_indices)
+ if self._use_all:
+ split_to_targetlabel_idx = list_to_dict(result, 1)
+ for s in split_to_targetlabel_idx:
+ rootlabel_idxes = split_to_targetlabel_idx[s]
+ idx_to_rootlabel = list_to_dict(rootlabel_idxes, 1)
+ num_image = self._split_to_num_image[s]
+ idxes = set(range(num_image)).difference(set(idx_to_rootlabel.keys()))
+ for i in idxes:
+ # for these images, the root label is hard-coded as None
+ result.append((None, s, i))
+ for split_info in self._split_infos:
+ s = split_info['split']
+ if s in split_to_targetlabel_idx:
+ continue
+ if s not in self._split_to_num_image:
+ continue
+ result.extend([(None, s, i) for i in
+ range(self._split_to_num_image[s])])
+ return result
+
+def build_tax_dataset_from_db(taxonomy_folder, **kwargs):
+ random.seed(777)
+ dataset_name = kwargs.get('data',
+ op.basename(taxonomy_folder))
+ overall_dataset = TSVDataset(dataset_name)
+ if op.isfile(overall_dataset.get_labelmap_file()):
+ logging.info('ignore to build taxonomy since {} exists'.format(
+ overall_dataset.get_labelmap_file()))
+ return
+ init_logging()
+ logging.info('building {}'.format(dataset_name))
+ all_tax = load_all_tax(taxonomy_folder)
+ tax = merge_all_tax(all_tax)
+ tax.update()
+ initialize_images_count(tax.root)
+ mapper = LabelToSynset()
+ mapper.populate_noffset(tax.root)
+ imagenet22k = TSVDatasetSource('imagenet22k_448', tax.root)
+ if op.isfile(imagenet22k.get_labelmap_file()):
+ disambibuity_noffsets(tax.root, imagenet22k.load_noffsets())
+ else:
+ logging.info('there is no imagenet22k_448 dataset to help identify the noffset')
+ populate_url_for_offset(tax.root)
+
+ ambigous_noffset_file = op.join(overall_dataset._data_root,
+ 'ambigous_noffsets.yaml')
+ output_ambigous_noffsets(tax.root, ambigous_noffset_file)
+
+ data_infos = regularize_data_sources(kwargs['datas'])
+
+ data_sources = [TSVDatasetSourceDB(root=tax.root, **d)
+ for d in data_infos]
+
+ for s in data_sources:
+ s.populate_info(tax.root)
+
+ populate_cum_images(tax.root)
+
+ labels, child_parent_sgs = child_parent_print_tree2(tax.root, 'name')
+
+ label_map_file = overall_dataset.get_labelmap_file()
+ write_to_file('\n'.join(labels), label_map_file)
+ # save the parameter
+ write_to_yaml_file((taxonomy_folder, kwargs), op.join(overall_dataset._data_root,
+ 'generate_parameters.yaml'))
+ dest_taxonomy_folder = op.join(overall_dataset._data_root,
+ 'taxonomy_folder')
+ if op.isdir(dest_taxonomy_folder):
+ shutil.rmtree(dest_taxonomy_folder)
+ shutil.copytree(taxonomy_folder, dest_taxonomy_folder)
+
+ out_dataset = {'with_bb': TSVDataset(dataset_name + '_with_bb'),
+ 'no_bb': TSVDataset(dataset_name + '_no_bb')}
+
+ for label_type in out_dataset:
+ target_file = out_dataset[label_type].get_labelmap_file()
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(label_map_file, target_file)
+
+ logging.info('cum_images_with_bb: {}'.format(tax.root.cum_images_with_bb))
+ logging.info('cum_images_no_bb: {}'.format(tax.root.cum_images_no_bb))
+
+ # write the simplified version of the tree
+ dest = op.join(overall_dataset._data_root, 'root.simple.yaml')
+ write_to_yaml_file(tax.dump(['images_with_bb']), dest)
+
+ tree_file = overall_dataset.get_tree_file()
+ write_to_file('\n'.join(['{} {}{}'.format(c, p, '' if sg < 0 else ' {}'.format(sg))
+ for c, p, sg in child_parent_sgs]),
+ tree_file)
+ for label_type in out_dataset:
+ target_file = out_dataset[label_type].get_tree_file()
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(tree_file, target_file)
+
+ node_should_have_images(tax.root, 200,
+ op.join(overall_dataset._data_root, 'labels_with_few_images.yaml'))
+
+ # get the information of all train val
+ ldtsi = []
+ logging.info('collecting all candidate images')
+ for label_type in out_dataset:
+ for dataset in data_sources:
+ targetlabel_split_idxes = dataset.select_tsv_rows(label_type)
+ for rootlabel, split, idx in targetlabel_split_idxes:
+ ldtsi.append((rootlabel, dataset, label_type, split, idx))
+ # we need to remove the duplicates. the duplicates could come from such
+ # cases: for example, we have Laptop and laptop in the image. Both of the
+ # labels are mapped to laptop, which is in the target domain. In this case,
+ # the image could be in the list twice
+ ldtsi = list(set(ldtsi))
+
+ num_test = kwargs.get('num_test', 50)
+
+ # for each label, let's duplicate the image or remove the image
+ default_max_image = kwargs.get('max_image_per_label', 1000)
+ label_to_max_image = {n.name: n.__getattribute__('max_image_extract_for_train')
+ if 'max_image_extract_for_train' in n.features and n.__getattribute__('max_image_extract_for_train') > default_max_image
+ else default_max_image for n in tax.root.iter_search_nodes() if n != tax.root}
+ label_to_max_image = {l: max(label_to_max_image[l], num_test) for l in label_to_max_image}
+ # negative images constraint
+ labels = list(label_to_max_image.keys())
+ for l in labels:
+ label_to_max_image['-' + l] = label_to_max_image[l]
+ label_to_max_image[None] = 10000000000
+ min_image = kwargs.get('min_image_per_label', 200)
+
+ logging.info('keep a small image pool to split')
+ label_to_max_augmented_images = {l: label_to_max_image[l] * 3 for l in label_to_max_image}
+ # reduce the computing cost
+ ldtsi, extra_dtsi = remove_or_duplicate_each_type(ldtsi, 0,
+ label_to_max_augmented_images)
+ assert len(extra_dtsi) == 0
+
+ logging.info('select the best test image')
+ if num_test == 0:
+ test_ldtsi = []
+ else:
+ # generate the test set from the best data source
+ label_to_max_images_for_test = {l: num_test for l in
+ label_to_max_image}
+ test_ldtsi, extra_dtsi = remove_or_duplicate_each_type(ldtsi, 0,
+ label_to_max_images_for_test)
+ assert len(extra_dtsi) == 0
+
+ logging.info('removing test images from image pool')
+ train_ldtsi = remove_test_in_train(ldtsi, test_ldtsi)
+
+ logging.info('select the final training images')
+ train_ldtsi, extra_dtsi = remove_or_duplicate_each_type(train_ldtsi, min_image,
+ label_to_max_image)
+
+ logging.info('creating the train data')
+ create_trainX_db(train_ldtsi, extra_dtsi, tax, out_dataset,
+ lift_train=kwargs.get('lift_train', False))
+
+ populate_output_num_images(test_ldtsi, 'toTest', tax.root)
+
+ # dump the tree to yaml format
+ dest = op.join(overall_dataset._data_root, 'root.yaml')
+ d = tax.dump()
+ write_to_yaml_file(d, dest)
+ for label_type in out_dataset:
+ target_file = op.join(out_dataset[label_type]._data_root, 'root.yaml')
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(dest, target_file)
+
+ create_testX_db(test_ldtsi, tax, out_dataset)
+
+ logging.info('done')
+
+def build_taxonomy_from_single_composite_source(source_data,
+ source_split, source_version,
+ min_image_per_label,
+ out_data):
+ info = get_frame_info()
+ out_dataset = TSVDataset(out_data)
+ if op.isdir(out_dataset._data_root):
+ logging.info('ignore to build since exists')
+ return
+ populate_dataset_details(source_data)
+ dataset = TSVDataset(source_data)
+ label_to_idx = dataset.load_inverted_label(source_split,
+ version=source_version)
+ if min_image_per_label < 1:
+ # this is the ratio beteen the real value and the average
+ mean_count = calc_mean([len(idx) for _, idx in label_to_idx.items()])
+ min_image_per_label = int(mean_count * min_image_per_label)
+ all_idx = list(range(dataset.num_rows(source_split)))
+ idx_to_labels = list_to_dict(dict_to_list(label_to_idx, 0), 1)
+
+ while len(label_to_idx) > 0:
+ # remove the labels if the len(idx) >= min_image_per_label
+ to_remove = [l for l in label_to_idx if len(label_to_idx[l]) >= min_image_per_label]
+ for l in to_remove:
+ del label_to_idx[l]
+ if len(label_to_idx) == 0:
+ break
+ min_label = min(label_to_idx, key=lambda x: len(label_to_idx[x]))
+ min_idx = copy.deepcopy(label_to_idx[min_label])
+ min_count = len(min_idx)
+ copies = (min_image_per_label + min_count - 1) // min_count - 1
+ info['duplicate_info${}'.format(min_label)] = copies
+ assert copies > 0
+ # add these extra images
+ all_idx.extend(copies * min_idx)
+ for i in min_idx:
+ for l in idx_to_labels[i]:
+ if l in label_to_idx:
+ # otherwise, it means that label is enough
+ for _ in range(copies):
+ label_to_idx[l].append(i)
+ random.seed(6)
+ random.shuffle(all_idx)
+ ensure_copy_file(dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+
+ shuffle = TSVFile(dataset.get_shuffle_file(source_split))
+ tsv_writer((shuffle[i] for i in all_idx), out_dataset.get_shuffle_file('train'))
+ tsv_copy(dataset.get_data(source_split + 'X'),
+ out_dataset.get_data('trainX'))
+
+ out_dataset.write_data(
+ dataset.iter_data('train', 'hw', filter_idx=all_idx),
+ 'train', 'hw')
+ out_dataset.write_data(
+ dataset.iter_data('train', 'label', version=source_version,
+ filter_idx=all_idx),
+ 'train', 'label')
+ out_dataset.write_data(list(info.items()), 'train', 'generate_info')
+
+def build_taxonomy_from_single_source(source_data,
+ source_split, source_version,
+ min_image_per_label,
+ out_data):
+ populate_dataset_details(source_data)
+ populate_dataset_hw(source_data, ['train'])
+ dataset = TSVDataset(source_data)
+ label_to_idx = dataset.load_inverted_label(source_split,
+ version=source_version)
+ all_idx = list(range(dataset.num_rows(source_split)))
+ idx_to_labels = list_to_dict(dict_to_list(label_to_idx, 0), 1)
+
+ while len(label_to_idx) > 0:
+ # remove the labels if the len(idx) >= min_image_per_label
+ to_remove = [l for l in label_to_idx if len(label_to_idx[l]) >= min_image_per_label]
+ for l in to_remove:
+ del label_to_idx[l]
+ if len(label_to_idx) == 0:
+ break
+ min_label = min(label_to_idx, key=lambda x: len(label_to_idx[x]))
+ min_idx = copy.deepcopy(label_to_idx[min_label])
+ min_count = len(min_idx)
+ copies = (min_image_per_label + min_count - 1) // min_count - 1
+ assert copies > 0
+ # add these extra images
+ all_idx.extend(copies * min_idx)
+ for i in min_idx:
+ for l in idx_to_labels[i]:
+ if l in label_to_idx:
+ # otherwise, it means that label is enough
+ for _ in range(copies):
+ label_to_idx[l].append(i)
+ random.seed(6)
+ random.shuffle(all_idx)
+ out_dataset = TSVDataset(out_data)
+ shuffle = [(0, r) for r in all_idx]
+ tsv_writer(shuffle, out_dataset.get_train_shuffle_file())
+ ensure_copy_file(dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+
+ write_to_file(dataset.get_data('train'),
+ out_dataset.get_data('trainX'))
+ write_to_file(dataset.get_data('train', 'hw'),
+ out_dataset.get_data('trainX', 'hw'))
+ write_to_file(dataset.get_data('train', 'label', version=source_version),
+ out_dataset.get_data('trainX', 'label'))
+
+def build_taxonomy_impl(taxonomy_folder,
+ data, datas,
+ taxonomy=None,
+ num_test=50, max_image_per_label=1000,
+ min_image_per_label=200,
+ lift_train=False,
+ use_original_label=False,
+ **kwargs):
+ random.seed(777)
+ dataset_name = data
+ overall_dataset = TSVDataset(dataset_name)
+ if op.isfile(overall_dataset.get_labelmap_file()):
+ logging.info('ignore to build taxonomy since {} exists'.format(
+ overall_dataset.get_labelmap_file()))
+ return
+ init_logging()
+ logging.info('building {}'.format(dataset_name))
+ if taxonomy_folder is not None:
+ all_tax = load_all_tax(taxonomy_folder)
+ tax = merge_all_tax(all_tax)
+ else:
+ tax = Taxonomy(taxonomy)
+ tax.update()
+ initialize_images_count(tax.root)
+ mapper = LabelToSynset()
+ mapper.populate_noffset(tax.root)
+ imagenet22k = TSVDatasetSource('imagenet22k_448', tax.root)
+ if op.isfile(imagenet22k.get_labelmap_file()):
+ disambibuity_noffsets(tax.root, imagenet22k.load_noffsets())
+ else:
+ logging.info('there is no imagenet22k_448 dataset to help identify the noffset')
+ populate_url_for_offset(tax.root)
+
+ ambigous_noffset_file = op.join(overall_dataset._data_root,
+ 'ambigous_noffsets.yaml')
+ output_ambigous_noffsets(tax.root, ambigous_noffset_file)
+
+ if isinstance(datas, str):
+ datas = load_from_yaml_file(datas)
+ data_infos = regularize_data_sources(datas)
+
+ data_sources = [TSVDatasetSource(root=tax.root, **d)
+ for d in data_infos]
+
+ for s in data_sources:
+ s.populate_info(tax.root)
+
+ populate_cum_images(tax.root)
+
+ labels, child_parent_sgs = child_parent_print_tree2(tax.root, 'name')
+
+ label_map_file = overall_dataset.get_labelmap_file()
+ write_to_file('\n'.join(labels), label_map_file)
+ # save the parameter
+ write_to_yaml_file(get_frame_info(),
+ op.join(overall_dataset._data_root,
+ 'generate_parameters.yaml'))
+ dest_taxonomy_folder = op.join(overall_dataset._data_root,
+ 'taxonomy_folder')
+ if op.isdir(dest_taxonomy_folder):
+ shutil.rmtree(dest_taxonomy_folder)
+ if taxonomy_folder is not None:
+ shutil.copytree(taxonomy_folder, dest_taxonomy_folder)
+ else:
+ write_to_yaml_file(taxonomy, op.join(dest_taxonomy_folder, 'root.yaml'))
+
+ out_dataset = {'with_bb': TSVDataset(dataset_name + '_with_bb'),
+ 'no_bb': TSVDataset(dataset_name + '_no_bb')}
+
+ for label_type in out_dataset:
+ target_file = out_dataset[label_type].get_labelmap_file()
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(label_map_file, target_file)
+
+ logging.info('cum_images_with_bb: {}'.format(tax.root.cum_images_with_bb))
+ logging.info('cum_images_no_bb: {}'.format(tax.root.cum_images_no_bb))
+
+ # write the simplified version of the tree
+ dest = op.join(overall_dataset._data_root, 'root.simple.yaml')
+ write_to_yaml_file(tax.dump(['images_with_bb']), dest)
+
+ tree_file = overall_dataset.get_tree_file()
+ write_to_file('\n'.join(['{} {}{}'.format(c, p, '' if sg < 0 else ' {}'.format(sg))
+ for c, p, sg in child_parent_sgs]),
+ tree_file)
+ for label_type in out_dataset:
+ target_file = out_dataset[label_type].get_tree_file()
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(tree_file, target_file)
+
+ node_should_have_images(tax.root, 200,
+ op.join(overall_dataset._data_root, 'labels_with_few_images.yaml'))
+
+ # get the information of all train val
+ ldtsi = []
+ logging.info('collecting all candidate images')
+ for label_type in out_dataset:
+ for dataset in data_sources:
+ targetlabel_split_idxes = dataset.select_tsv_rows(label_type)
+ for rootlabel, split, idx in targetlabel_split_idxes:
+ ldtsi.append((rootlabel, dataset, label_type, split, idx))
+ # we need to remove the duplicates. the duplicates could come from such
+ # cases: for example, we have Laptop and laptop in the image. Both of the
+ # labels are mapped to laptop, which is in the target domain. In this case,
+ # the image could be in the list twice
+ ldtsi = list(set(ldtsi))
+
+ # for each label, let's duplicate the image or remove the image
+ default_max_image = max_image_per_label
+ label_to_max_image = {n.name: n.__getattribute__('max_image_extract_for_train')
+ if 'max_image_extract_for_train' in n.features and n.__getattribute__('max_image_extract_for_train') > default_max_image
+ else default_max_image for n in tax.root.iter_search_nodes() if n != tax.root}
+ label_to_max_image = {l: max(label_to_max_image[l], num_test) for l in label_to_max_image}
+ # negative images constraint
+ labels = list(label_to_max_image.keys())
+ for l in labels:
+ label_to_max_image['-' + l] = label_to_max_image[l]
+ label_to_max_image[None] = 10000000000
+
+ label_to_min_image = {n.name: n.__getattribute__('min_image_extract_for_train')
+ if 'min_image_extract_for_train' in n.features
+ else min_image_per_label for n in tax.root.iter_search_nodes() if n != tax.root}
+
+ logging.info('keep a small image pool to split')
+ label_to_max_augmented_images = {l: label_to_max_image[l] * 3 for l in label_to_max_image}
+ # reduce the computing cost
+ ldtsi, extra_dtsi = remove_or_duplicate_each_type(ldtsi, 0,
+ label_to_max_augmented_images)
+ assert len(extra_dtsi) == 0
+
+ logging.info('select the best test image')
+ if num_test == 0:
+ test_ldtsi = []
+ else:
+ # generate the test set from the best data source
+ label_to_max_images_for_test = {l: num_test for l in
+ label_to_max_image}
+ test_ldtsi, extra_dtsi = remove_or_duplicate_each_type(ldtsi, 0,
+ label_to_max_images_for_test)
+ assert len(extra_dtsi) == 0
+
+ logging.info('removing test images from image pool')
+ train_ldtsi = remove_test_in_train(ldtsi, test_ldtsi)
+
+ logging.info('select the final training images')
+ train_ldtsi, extra_dtsi = remove_or_duplicate_each_type(
+ train_ldtsi,
+ label_to_min_image,
+ label_to_max_image)
+
+ logging.info('creating the train data')
+ create_trainX(train_ldtsi, extra_dtsi, tax, out_dataset,
+ lift_train=lift_train,
+ use_original_label=use_original_label)
+
+ populate_output_num_images(test_ldtsi, 'toTest', tax.root)
+
+ # dump the tree to yaml format
+ dest = op.join(overall_dataset._data_root, 'root.yaml')
+ d = tax.dump()
+ write_to_yaml_file(d, dest)
+ for label_type in out_dataset:
+ target_file = op.join(out_dataset[label_type]._data_root, 'root.yaml')
+ ensure_directory(op.dirname(target_file))
+ shutil.copy(dest, target_file)
+
+ create_testX(test_ldtsi, tax, out_dataset)
+
+ logging.info('done')
+
+def delift_one_image(rects, tax):
+ # currently, for the training, we need to delift the label. That is, if it
+ # is man, we should remove the person label
+ rects2 = []
+ for curr_r in rects:
+ if curr_r['class'].startswith('-'):
+ # if it is a background, we do nothing here. In the future, we
+ # might change this logic
+ rects2.append(curr_r)
+ continue
+ curr_label = curr_r['class']
+ if 'rect' not in curr_r:
+ same_place_rects = rects2
+ else:
+ ious = [calculate_iou(r['rect'], curr_r['rect']) for r in rects2]
+ same_place_rects = [r for i, r in zip(ious, rects2) if i > 0.9]
+ # if current label is one of parent of the same_place rects, ignore it
+ ignore = False
+ for same_place_r in same_place_rects:
+ ancestors = tax.name_to_ancestors[same_place_r['class']]
+ if curr_label in ancestors or same_place_r['class'] == curr_label:
+ ignore = True
+ break
+ if ignore:
+ continue
+ ancestors = tax.name_to_ancestors[curr_label]
+ to_removed = []
+ for same_place_r in same_place_rects:
+ if same_place_r['class'] in ancestors:
+ to_removed.append(same_place_r)
+ for t in to_removed:
+ rects2.remove(t)
+ rects2.append(curr_r)
+ return rects2
+
+def lift_one_image(rects, tax):
+ rects2 = []
+ for curr_r in rects:
+ if curr_r['class'].startswith('-'):
+ rects2.append(curr_r)
+ continue
+ label = curr_r['class']
+ all_label = tax.name_to_ancestors[label]
+ all_label.add(label)
+ for l in all_label:
+ same_label_rects = [r for r in rects2 if r['class'] == l]
+ if 'rect' in curr_r:
+ ious = [calculate_iou(r['rect'], curr_r['rect']) for r in
+ same_label_rects if 'rect' in r]
+ if len(ious) > 0 and max(ious) > 0.9:
+ continue
+ else:
+ r = copy.deepcopy(curr_r)
+ r['class'] = l
+ rects2.append(r)
+ else:
+ if len(same_label_rects) == 0:
+ r = copy.deepcopy(curr_r)
+ r['class'] = l
+ rects2.append(r)
+ return rects2
+
+def populate_output_num_images(ldtX, suffix, root):
+ label_to_node = {n.name: n for n in root.iter_search_nodes() if n != root}
+ targetlabel_to_dX = list_to_dict(ldtX, 0)
+ for targetlabel in targetlabel_to_dX:
+ if not targetlabel or targetlabel.startswith('-'):
+ # currently, we ignore this background case. In the future, we
+ # might change this logic
+ continue
+ if not targetlabel:
+ # it means background images
+ continue
+ dtX = targetlabel_to_dX[targetlabel]
+ dataset_to_X = list_to_dict(dtX, 0)
+ for dataset in dataset_to_X:
+ X = dataset_to_X[dataset]
+ if len(X) == 0:
+ continue
+ key = '{}_{}'.format(dataset.name, suffix)
+ value = len(X)
+ label_to_node[targetlabel].add_feature(key, value)
+ labeltype_to_dX = list_to_dict(dtX, 1)
+ for labeltype in labeltype_to_dX:
+ dX = labeltype_to_dX[labeltype]
+ key = '{}_{}'.format(labeltype, suffix)
+ value = len(dX)
+ label_to_node[targetlabel].add_feature(key, value)
+
+def output_ambigous_noffsets(root, ambigous_noffset_file):
+ ambigous = []
+ for node in root.iter_search_nodes():
+ if hasattr(node, 'noffsets') and node.noffset is None:
+ noffsets = node.noffsets.split(',')
+ d = create_info_for_ambigous_noffset(node.name, noffsets)
+ d['parent_name'] = ','.join([n.name for n in
+ node.get_ancestors()[:-1]])
+ ambigous.append(d)
+ if len(ambigous) > 0:
+ logging.info('output ambigous terms to {}'.format(ambigous_noffset_file))
+ write_to_yaml_file(ambigous, ambigous_noffset_file)
+ else:
+ logging.info('Congratulations on no ambigous terms.')
+
+def output_ambigous_noffsets_main(tax_input_folder, ambigous_file_out):
+ all_tax = load_all_tax(tax_input_folder)
+ tax = merge_all_tax(all_tax)
+ mapper = LabelToSynset()
+ mapper.populate_noffset(tax.root)
+ imagenet22k = TSVDatasetSource('imagenet22k')
+ if op.isfile(imagenet22k.get_labelmap_file()):
+ logging.info('remove the noffset if it is not in imagenet22k')
+ disambibuity_noffsets(tax.root, imagenet22k.load_noffsets())
+ else:
+ logging.info('no imagenet22k data used to help remove noffset ambiguities')
+
+ populate_url_for_offset(tax.root)
+
+ output_ambigous_noffsets(tax.root, ambigous_file_out)
+
+def convert_inverted_file(name):
+ d = TSVDataset(name)
+ splits = get_default_splits()
+ for split in splits:
+ logging.info('loading {}-{}'.format(name, split))
+ x = d.load_inverted_label(split)
+ def gen_rows():
+ for label in x:
+ idx = x[label]
+ yield label, ' '.join(map(str, idx))
+
+ inverted_file = d.get_data(split, 'inverted.label')
+ target_file = op.splitext(inverted_file)[0] + '.tsv'
+ if not op.isfile(inverted_file):
+ if op.isfile(target_file):
+ os.remove(target_file)
+ continue
+ if op.isfile(target_file):
+ continue
+ tsv_writer(gen_rows(), target_file)
+
+def standarize_crawled(tsv_input, tsv_output):
+ rows = tsv_reader(tsv_input)
+ def gen_rows():
+ for i, row in enumerate(rows):
+ if (i % 1000) == 0:
+ logging.info(i)
+ image_str = row[-1]
+ image_label = row[0]
+ rects = [{'rect': [0, 0, 0, 0], 'class': image_label}]
+ image_name = '{}_{}'.format(op.basename(tsv_input), i)
+ yield image_name, json.dumps(rects), image_str
+ tsv_writer(gen_rows(), tsv_output)
+
+def get_data_sources(version):
+ return load_from_yaml_file('./aux_data/data_sources/{}.yaml'.format(version))
+
+def get_img_url2(img_key):
+ # don't use get_image_url
+ clean_name = _map_img_key_to_name2(img_key)
+ url = _get_url_from_name(clean_name)
+ return url
+
+def get_img_url(img_key):
+ # use version 2
+ clean_name = _map_img_key_to_name(img_key)
+ url = _get_url_from_name(clean_name)
+ return url
+
+def map_image_key_to_url_key(data, split, key):
+ return hash_sha1(str((data, split, key)))
+
+@deprecated(reason='need to incoroprate the data split info')
+def _map_img_key_to_name2(key):
+ assert len(key) > 0
+ ext = '.jpg'
+ pattern = '^([0-9]|-|[a-z]|[A-Z]|\.|_)*$'
+ if not re.match(pattern, key):
+ key = hash_sha1(key)
+ key = key.lower()
+ if key.endswith(ext):
+ return key
+ else:
+ return key + ext
+
+def _map_img_key_to_name(key):
+ # use version 2
+ _EXT = ".jpg"
+ if key.startswith("brand"):
+ return "brand" + str(hash(key)) + _EXT
+ else:
+ key = key.lower()
+ if key.endswith(_EXT):
+ return key
+ else:
+ return key + _EXT
+
+def _get_url_from_name(name):
+ _SITE = 'https://cogsimagestorage.blob.core.windows.net/'
+ _CONTAINER_NAME = "detectortrain"
+ return _SITE + _CONTAINER_NAME + "/" + name
+
+def parse_combine(key):
+ pattern = '(.*?)_(train|trainval|test)_(.*)'
+ result = re.match(pattern, key)
+ if result is None:
+ return None, None, key
+ else:
+ return result.groups()
+
+def convert_to_uhrs_with_url(data):
+ dataset = TSVDataset(data)
+ for split in get_default_splits():
+ if not dataset.has(split, 'label'):
+ continue
+ v = dataset.get_latest_version(split, 'label')
+ def gen_rows():
+ for row in dataset.iter_data(split, 'label', version=v):
+ key = row[0]
+ _, _, key = parse_combine(key)
+ row.append(get_img_url(key))
+ yield row
+ dataset.write_data(gen_rows(), split,
+ 'url', version=v)
+
+def find_same_location_rects(target, rects, iou=0.95):
+ return [r for r in rects if
+ calculate_iou(target['rect'], r['rect']) > iou]
+
+def find_same_rects(target, rects, iou=0.95):
+ same_class_rects = [r for r in rects if r['class'] == target['class']]
+ return [r for r in same_class_rects if
+ calculate_iou(target['rect'], r['rect']) > iou]
+
+def rects_diff(lefts, rights, iou=0.95):
+ result = []
+ for l in lefts:
+ if len(find_same_rects(l, rights, iou)) == 0:
+ result.append(l)
+ return result
+
+def rects_inter(lefts, rights, iou=0.95):
+ result = []
+ for l in lefts:
+ if len(find_same_rects(l, rights, iou)) > 0:
+ result.append(l)
+ return result
+
+
+def rect_in_rects(target, rects, iou=0.95):
+ same_class_rects = [r for r in rects if r['class'] == target['class']]
+ if 'rect' not in target:
+ return len(same_class_rects) > 0
+ else:
+ return any(r for r in same_class_rects if 'rect' in r and
+ calculate_iou(target['rect'], r['rect']) > iou)
+
+def strict_rect_in_rects(target, rects):
+ return any(float_tolorance_equal(target, r) for r in rects)
+
+def load_key_rects(iter_data):
+ assert type(iter_data) is not str
+ result = []
+ logging.info('loading key rects')
+ for row in tqdm(iter_data):
+ assert len(row) == 2
+ rects = json.loads(row[1])
+ if isinstance(rects, int):
+ # in this case, it is imagenet2012 dataset, which is the class
+ # index.
+ rects = [{'class': str(rects)}]
+ result.append([row[0], rects])
+ return result
+
+def convert_uhrs_result_back_to_sources(in_tsv, debug=True, tree_file=None):
+ rows = tsv_reader(in_tsv)
+ key_rects3 = []
+ num_yes, num_no, num_un = 0, 0, 0
+ for row in rows:
+ # key, yes, no, uncertain
+ assert len(row) == 4
+ rects_yes = json.loads(row[1])
+ rects_no = json.loads(row[2])
+ rects_un = json.loads(row[3])
+ num_yes = num_yes + len(rects_yes)
+ num_no = num_no + len(rects_no)
+ num_un = num_un + len(rects_un)
+ key_rects3.append([row[0], [rects_yes, rects_no, rects_un]])
+
+ logging.info('#yes={}; #no={}; #un={}; #yes/(#yes+#no+#un)={}'.format(
+ num_yes, num_no, num_un, 1.*num_yes/(num_yes+num_no+num_un)))
+
+ if tree_file:
+ tax = Taxonomy(load_from_yaml_file(tree_file))
+ mapper = LabelToSynset()
+ mapper.populate_noffset(tax.root)
+
+ datas = get_data_sources()
+ datas = [data for data, _ in datas]
+ datasplitkey_rects3 = [[parse_combine(key), rects3]
+ for key, rects3 in key_rects3]
+ data_split_key_rects3 = [(data, split, key, rects3)
+ for (data, split, key), rects3 in datasplitkey_rects3]
+
+ data_to_split_key_rects3 = list_to_dict(data_split_key_rects3, 0)
+
+ for data in data_to_split_key_rects3:
+ logging.info(data)
+ if tree_file:
+ source_dataset = TSVDatasetSource(data, tax.root)
+ source_dataset._ensure_initialized()
+ else:
+ source_dataset = TSVDataset(data)
+ split_key_rects3 = data_to_split_key_rects3[data]
+ split_to_key_rects3 = list_to_dict(split_key_rects3, 0)
+ for split in split_to_key_rects3:
+ logging.info(split)
+ key_rects3 = split_to_key_rects3[split]
+ key_to_rects3 = list_to_dict(key_rects3, 0)
+ v = source_dataset.get_latest_version(split, 'label')
+ logging.info('{} - {}'.format(data, split))
+ source_key_rects = load_key_rects(source_dataset.iter_data(split, 'label', version=v))
+ is_equal = True
+ num_added, num_removed = 0, 0
+ meta = {'in_tsv': in_tsv}
+ for i, (key, origin_rects) in tqdm(enumerate(source_key_rects)):
+ if debug:
+ old_origin_rects = copy.deepcopy(origin_rects)
+ yes_rects, no_rects, un_rects = key_to_rects3.get(key, [[[], [], []]])[0]
+ # if no_rects are in original, remove it. remove first
+ for r in no_rects:
+ delete_rects = find_same_rects(r, origin_rects)
+ if tree_file:
+ if r['class'] in source_dataset._targetlabel_to_sourcelabels:
+ for reverse_class in source_dataset._targetlabel_to_sourcelabels[r['class']]:
+ r2 = copy.deepcopy(r)
+ r2['class'] = reverse_class
+ delete_rects2 = find_same_rects(r2, origin_rects)
+ delete_rects.extend(delete_rects2)
+ if 'class_from' in r:
+ r2 = copy.deepcopy(r)
+ r2['class'] = r2['class_from']
+ delete_rects2 = find_same_rects(r2, origin_rects)
+ delete_rects.extend(delete_rects2)
+ for d in delete_rects:
+ # delete rects may include duplicate terms
+ if d in origin_rects:
+ origin_rects.remove(d)
+ num_removed = num_removed + 1
+ is_equal = False
+ # if yes_rects are not in original, add it
+ for r in yes_rects:
+ same_rects = find_same_rects(r, origin_rects)
+ if len(same_rects) > 0:
+ for s in same_rects:
+ if s.get('uhrs_confirm', 0) == 0:
+ is_equal = False
+ s['uhrs_confirm'] = s.get('uhrs_confirm', 0) + 1
+ else:
+ r['uhrs_confirm'] = r.get('uhrs_confirm', 0) + 1
+ origin_rects.append(copy.deepcopy(r))
+ is_equal = False
+ num_added = num_added + 1
+ for r in un_rects:
+ same_rects = find_same_rects(r, origin_rects)
+ for s in same_rects:
+ if s.get('uhrs_uncertain', 0) == 0:
+ is_equal = True
+ s['uhrs_uncertain'] = s.get('uhrs_uncertain', 0) + 1
+ if debug:
+ if len(origin_rects) != len(old_origin_rects):
+ for _, _, im_str in source_dataset.iter_data(split, filter_idx=[i]):
+ im = img_from_base64(im_str)
+ old_im = im.copy()
+ draw_bb(old_im, [r['rect'] for r in old_origin_rects],
+ [r['class'] for r in old_origin_rects])
+ new_im = im.copy()
+ draw_bb(new_im, [r['rect'] for r in origin_rects],
+ [r['class'] for r in origin_rects])
+ yes_im = im.copy()
+ draw_bb(yes_im, [r['rect'] for r in yes_rects],
+ [r['class'] for r in yes_rects])
+ no_im = im.copy()
+ draw_bb(no_im, [r['rect'] for r in no_rects],
+ [r['class'] for r in no_rects])
+
+ logging.info(pformat(old_origin_rects))
+ logging.info(pformat(origin_rects))
+ logging.info(pformat(yes_rects))
+ logging.info(pformat(no_rects))
+ show_images([old_im, new_im, yes_im, no_im], 2, 2)
+
+ assert not source_dataset.has(split, 'label', v + 1)
+ if not is_equal:
+ source_dataset.write_data(((key, json.dumps(rects)) for key, rects in source_key_rects),
+ split, 'label', version=v+1)
+ meta_file = source_dataset.get_data(split, 'label.metadata', version=v+1) + '.yaml'
+ meta['num_added_rects'] = num_added
+ meta['num_removed_rects'] = num_removed
+ meta['total_number_images'] = len(source_key_rects)
+
+ meta['avg_added_rects'] = 1. * num_added / meta['total_number_images']
+ meta['avg_removed_rects'] = 1. * num_removed / meta['total_number_images']
+ write_to_yaml_file(meta, meta_file)
+ logging.info(pformat(meta))
+ else:
+ logging.info('equal - {} - {}'.format(data, split))
+ populate_dataset_details(data)
+
+def merge_multi_by_key(tsv_file1, all_tsv_file2, out_tsv,
+ from_flag1, all_from_flag2):
+ files = [tsv_file1]
+ files.extend(all_tsv_file2)
+ all_key_rects = [load_key_rects(tsv_reader(f)) for f in files]
+ all_key_to_rects = [{key: rects for key, rects in key_rects}
+ for key_rects in all_key_rects]
+ keys = [key for key, _ in all_key_rects[0]]
+ flags = [from_flag1]
+ flags.extend(all_from_flag2)
+ def gen_rows():
+ for key in keys:
+ all_rects = [key_to_rects[key] for key_to_rects in all_key_to_rects if key in key_to_rects]
+ for rects, f in zip(all_rects, flags):
+ for r in rects:
+ r['from'] = f
+ rects = all_rects[0]
+ for r in all_rects[1:]:
+ rects.extend(r)
+ yield key, json_dump(rects)
+ tsv_writer(gen_rows(), out_tsv)
+
+def merge_by_key(tsv_file1, tsv_file2, out_tsv,
+ from_flag1='', from_flag2=''):
+ files = [tsv_file1, tsv_file2]
+ all_key_rects = [load_key_rects(tsv_reader(f)) for f in files]
+ all_key_to_rects = [{key: rects for key, rects in key_rects}
+ for key_rects in all_key_rects]
+ keys = [key for key, _ in all_key_rects[0]]
+ flags = [from_flag1, from_flag2]
+ def gen_rows():
+ for key in keys:
+ all_rects = [key_to_rects[key] for key_to_rects in all_key_to_rects if key in key_to_rects]
+ for rects, f in zip(all_rects, flags):
+ for r in rects:
+ r['from'] = f
+ rects = all_rects[0]
+ for r in all_rects[1:]:
+ rects.extend(r)
+ yield key, json_dump(rects)
+ tsv_writer(gen_rows(), out_tsv)
+
+def threshold_merged_prediction(pred_tsv_file, from_to_class_to_threshold,
+ output_file):
+ def gen_rows():
+ for key, str_rects in tsv_reader(pred_tsv_file):
+ rects = json.loads(str_rects)
+ all_rect = []
+ for r in rects:
+ if type(from_to_class_to_threshold[r['from']]) is dict:
+ th = from_to_class_to_threshold[r['from']][r['class']]
+ else:
+ th = from_to_class_to_threshold[r['from']]
+ assert type(th) is float or type(th) is int
+ if r['conf'] > th:
+ all_rect.append(r)
+ yield key, json_dump(all_rect)
+ tsv_writer(gen_rows(), output_file)
+
+def remove_has_confirmed_colocation_labels(all_data, iou_threshold=0.75):
+ all_split = get_default_splits()
+ debug = False
+ for data in all_data:
+ dataset = TSVDataset(data)
+ for split in all_split:
+ if not dataset.has(split):
+ continue
+ logging.info('{} -> {}'.format(data, split))
+ info = {'total': 0, 'removed': 0}
+ def gen_rows():
+ for i, (key, en_rects) in tqdm(enumerate(dataset.iter_data(split,
+ 'label', version=-1))):
+ rects = json.loads(en_rects)
+ info['total'] = info['total'] + len(rects)
+ if debug:
+ _, _, im = next(dataset.iter_data(split, filter_idx=[i]))
+ im = img_from_base64(im)
+ im_origin = np.copy(im)
+ draw_bb(im_origin, [r['rect'] for r in rects], [r['class'] for r in rects])
+ all_removed = []
+ # some labels has no rect
+ good_rects = [r for r in rects if 'rect' in r and
+ ('conf' not in r or ('conf' in r and 'uhrs_confirm' in r))]
+ pro_no_verify = [r for r in rects if 'conf' in r and
+ 'uhrs_confirm' not in r and 'rect' in r]
+ no_rects = [r for r in rects if 'rect' not in r]
+ assert len(good_rects) + len(pro_no_verify) + len(no_rects)==len(rects)
+ to_remove = []
+ for r in pro_no_verify:
+ if any((s for s in good_rects if
+ calculate_iou(r['rect'], s['rect']) >
+ iou_threshold)):
+ to_remove.append(r)
+ for t in to_remove:
+ rects.remove(t)
+ info['removed'] = info['removed'] + len(to_remove)
+ all_removed.extend(to_remove)
+ if debug and len(all_removed) > 0:
+ logging.info(len(all_removed))
+ im_removed = np.copy(im)
+ logging.info(pformat(all_removed))
+ draw_bb(im_removed, [r['rect'] for r in all_removed],
+ [r['class'] for r in all_removed])
+ show_images([im_origin, im_removed], 1, 2)
+ yield key, json_dump(rects)
+ def gen_info():
+ yield 'remove auto-pro and has good labels in same locatoin', iou_threshold
+ yield 'total', info['total']
+ yield 'removed', info['removed']
+ ratio = 1. * info['removed'] / info['total']
+ yield 'ratio', ratio
+ logging.info(pformat(info))
+ logging.info(ratio)
+
+ dataset.update_data(gen_rows(), split, 'label', generate_info=gen_info())
+
+def get_taxonomy_path(data):
+ pattern = 'Tax(.*)V([0-9]*)_(.*)'
+ result = re.match(pattern, data)
+ assert result is not None
+ major, minor, revision = result.groups()
+ return './aux_data/taxonomy10k/Tax{0}/Tax{0}V{1}'.format(major, minor)
+
+def uhrs_verify_db_merge_to_tsv(collection_name='uhrs_logo_verification',
+ extra_match=None):
+ set_interpretation_result_for_uhrs_result(collection_name)
+ c = create_bbverification_db(collection_name=collection_name)
+ data_split_to_key_rects, all_id = c.get_completed_uhrs_result(
+ extra_match=extra_match)
+ merge_uhrs_result_to_dataset(data_split_to_key_rects)
+ size = 1000
+ i = 0
+ while True:
+ start = i * size
+ end = i * size + size
+ if start >= len(all_id):
+ break
+ if end >= len(all_id):
+ end = len(all_id)
+ c.set_status_as_merged(all_id[start:end])
+ i += 1
+ y = [c.set_status_as_merged([i]) for i in tqdm(all_id)]
+ y = list(map(lambda i: c.set_status_as_merged([i]), all_id))
+
+def uhrs_merge_one(uhrs_rect, target_rects, tag_only=False):
+ info = {'num_added': 0,
+ 'num_removed': 0,
+ 'verified_confirmed': 0,
+ 'verified_removed': 0,
+ 'non_verified_confirmed': 0,
+ 'non_verified_removed': 0}
+ same_rect, iou = find_best_matched_rect(uhrs_rect, target_rects, check_iou=(not tag_only))
+ if iou < 0.8:
+ if is_positive_uhrs_verified(uhrs_rect):
+ target_rects.append(uhrs_rect)
+ info['num_added'] = 1
+ return info
+
+ if is_verified_rect(same_rect):
+ if is_positive_uhrs_verified(uhrs_rect):
+ info['verified_confirmed'] = 1
+ elif is_negative_uhrs_verified(uhrs_rect):
+ info['verified_removed'] = 1
+ target_rects.remove(same_rect)
+ else:
+ if is_positive_uhrs_verified(uhrs_rect):
+ info['non_verified_confirmed'] = 1
+ elif is_negative_uhrs_verified(uhrs_rect):
+ info['non_verified_removed'] = 1
+ target_rects.remove(same_rect)
+
+ same_rect['uhrs'] = {}
+ for t, v in viewitems(uhrs_rect['uhrs']):
+ same_rect['uhrs'][t] = v
+
+ return info
+
+def merge_uhrs_result_to_dataset(data_split_to_key_rects, tag_only=False):
+ from .common import list_to_dict
+ from .common import json_dump
+ for (data, split), uhrs_key_rects in viewitems(data_split_to_key_rects):
+ logging.info((data, split))
+ dataset = TSVDataset(data)
+ uhrs_key_to_rects = list_to_dict(uhrs_key_rects, 0)
+ logging.info('number of image will be affected: {}'.format(len(uhrs_key_rects)))
+ info = {}
+ def gen_rows():
+ for key, str_rects in dataset.iter_data(split, 'label', -1,
+ progress=True):
+ rects = json.loads(str_rects)
+ if key in uhrs_key_to_rects:
+ uhrs_rects = uhrs_key_to_rects[key]
+ del uhrs_key_to_rects[key]
+ else:
+ uhrs_rects = []
+ for uhrs_rect in uhrs_rects:
+ sub_info = uhrs_merge_one(uhrs_rect, rects, tag_only=tag_only)
+ for k, v in viewitems(sub_info):
+ info[k] = v + info.get(k, 0)
+ yield key, json_dump(rects)
+ assert len(uhrs_key_to_rects) == 0
+ def generate_info():
+ for k, v in viewitems(info):
+ yield k, v
+ for key, rects in viewitems(uhrs_key_to_rects):
+ yield key, json_dump(rects)
+ dataset.update_data(gen_rows(), split, 'label',
+ generate_info=generate_info())
+
+def set_interpretation_result_for_uhrs_result(collection_name='uhrs_logo_verification'):
+ c = create_bbverification_db(collection_name=collection_name)
+ query = {'status': {'$in': [c.status_merged, c.status_completed]},
+ 'interpretation_result': None}
+ positive_ids, negative_ids, uncertain_ids = [], [], []
+ pos, neg, un = 0, 0, 0
+ for rect_info in tqdm(c.collection.find(query)):
+ rect = rect_info['rect']
+ rect.update({'uhrs': rect_info['uhrs_completed_result']})
+ if is_positive_uhrs_verified(rect):
+ positive_ids.append(rect_info['_id'])
+ if len(positive_ids) > 1000:
+ logging.info('positive = {}'.format(pos))
+ q = {'_id': {'$in': positive_ids}}
+ c.collection.update_many(filter=q,
+ update={'$set': {'interpretation_result': 1}})
+ pos += len(positive_ids)
+ positive_ids.clear()
+ elif is_negative_uhrs_verified(rect):
+ negative_ids.append(rect_info['_id'])
+ if len(negative_ids) > 1000:
+ logging.info('neg = {}'.format(neg))
+ q = {'_id': {'$in': negative_ids}}
+ c.collection.update_many(filter=q,
+ update={'$set': {'interpretation_result': -1}})
+ neg += len(negative_ids)
+ negative_ids.clear()
+ else:
+ uncertain_ids.append(rect_info['_id'])
+ if len(uncertain_ids) > 1000:
+ logging.info('un = {}'.format(un))
+ query = {'_id': {'$in': uncertain_ids}}
+ c.collection.update_many(filter=query,
+ update={'$set': {'interpretation_result': 0}})
+ un += len(uncertain_ids)
+ uncertain_ids.clear()
+
+
+ if len(positive_ids) > 0:
+ query = {'_id': {'$in': positive_ids}}
+ c.collection.update_many(filter=query,
+ update={'$set': {'interpretation_result': 1}})
+ if len(negative_ids) > 0:
+ query = {'_id': {'$in': negative_ids}}
+ c.collection.update_many(filter=query,
+ update={'$set': {'interpretation_result': -1}})
+ if len(uncertain_ids) > 0:
+ query = {'_id': {'$in': uncertain_ids}}
+ c.collection.update_many(filter=query,
+ update={'$set': {'interpretation_result': 0}})
+
+def uhrs_verify_db_closest_rect(collection, test_data, test_split, gt_key, p):
+ rect_infos = list(collection.find({'data': test_data,
+ 'split': test_split,
+ 'key': gt_key}))
+ rects = [rect_info['rect'] for rect_info in rect_infos]
+ best_idx, best_iou = find_best_matched_rect_idx(p, rects, check_class=True)
+
+ if best_idx is not None:
+ rect_info = rect_infos[best_idx]
+ else:
+ rect_info = None
+
+ return rect_info, best_iou
+
+def verify_prediction_by_db(pred_file, test_data, test_split, conf_th=0.3,
+ priority_tier=1, collection_name='uhrs_bounding_box_verification'):
+ from qd.process_tsv import ensure_upload_image_to_blob
+ from qd.process_tsv import parse_combine
+ ensure_upload_image_to_blob(test_data, test_split)
+
+ dataset = TSVDataset(test_data)
+ gt_iter = dataset.iter_data(test_split, 'label', version=-1)
+ pred_iter = tsv_reader(pred_file)
+ key_url_iter = dataset.iter_data(test_split, 'key.url')
+
+ db_task = []
+ num_task, num_exists, num_matched_gt, num_change_pri = 0, 0, 0, 0
+ c = create_bbverification_db(collection_name=collection_name)
+ for gt_row, pred_row, url_row in tqdm(zip(gt_iter, pred_iter,
+ key_url_iter)):
+ gt_key, gt_str_rects = gt_row
+ pred_key, pred_str_rects = pred_row
+ assert gt_key == pred_key == url_row[0]
+ source_data, source_split, source_key = parse_combine(gt_key)
+ if source_data is None and source_split is None:
+ source_data = test_data
+ source_split = test_split
+ gt_rects = json.loads(gt_str_rects)
+ pred_rects = json.loads(pred_str_rects)
+ for p in pred_rects:
+ if p['conf'] < conf_th:
+ continue
+ # check with the gt
+ _, best_iou = find_best_matched_rect(p, gt_rects)
+ if best_iou > 0.7:
+ num_matched_gt = 0
+ continue
+ best_rect_info, best_iou = uhrs_verify_db_closest_rect(c.collection, source_data,
+ source_split, source_key, p)
+ if best_iou > 0.95:
+ num_exists = num_exists + 1
+ if best_rect_info['priority_tier'] != c.urgent_priority_tier and \
+ best_rect_info['status'] == c.status_requested:
+ c.collection.update_one(
+ {'_id': best_rect_info['_id']},
+ update={'$set': {'priority_tier': c.urgent_priority_tier}})
+ num_change_pri = num_change_pri + 1
+ continue
+ p['from'] = pred_file
+ url = url_row[1]
+ task = {'url': url,
+ 'data': source_data,
+ 'split': source_split,
+ 'key': source_key,
+ 'rect': p,
+ 'priority_tier': priority_tier,
+ 'priority': 0.5}
+ num_task = num_task + 1
+ db_task.append(task)
+ if len(db_task) > 1000:
+ c.request_by_insert(db_task)
+ db_task = []
+ if len(db_task) > 0:
+ c.request_by_insert(db_task)
+ db_task = []
+ logging.info('#task = {}; #exists in db = {}; #matched gt = {}; #num pri change = {}'.format(
+ num_task, num_exists, num_matched_gt, num_change_pri))
+
+def convertcomposite_to_standard(data,
+ split='train', ignore_image=False, **kwargs):
+ dataset = TSVDataset(data)
+ if op.isfile(dataset.get_data(split, t='label')) and \
+ op.isfile(dataset.get_data(split)):
+ logging.info('file exists')
+ return
+ rows_image = dataset.iter_composite(split, t=None, version=None)
+ num_image = dataset.num_rows(split)
+ out_tsv = dataset.get_data(split)
+ if not ignore_image:
+ logging.info('writing image tsv: {}'.format(out_tsv))
+ rows_label = dataset.iter_data(split, t='label', version=None)
+ tsv_writer(((row_label[0], row_label[1], row_image[2]) for row_image, row_label
+ in tqdm(zip(rows_image, rows_label), total=num_image)),
+ out_tsv)
+ if not op.isfile(dataset.get_data(split, t='label')):
+ logging.info('writing image label tsv')
+ rows = dataset.iter_composite(split, t='label', version=None)
+ tsv_writer(tqdm(rows), dataset.get_data(split, t='label'))
+
+def gen_merged_candidate(prediction_file,
+ gts, srclabel_to_destlabel=None, **kwargs):
+ # we will only consider the bounding box if the prob is larger than 0.7
+ prob_th = kwargs['merge_min_prob']
+ prob_th_max = kwargs['merge_max_prob']
+ # we will add the bounding box only if the iou is lower than 0.7 to avoid
+ # duplicate addition
+ iou_th = kwargs['merge_max_iou']
+ aug_labels = kwargs['aug_labels']
+ prediction = tsv_reader(prediction_file)
+ is_aligned = kwargs.get('is_aligned', False)
+ logging.info('loading prediction: {}'.format(prediction_file))
+ if not is_aligned:
+ key_to_pred = {}
+ for p in tqdm(prediction):
+ assert len(p) == 2
+ key = p[0]
+ rects = json.loads(p[1])
+ key_to_pred[key] = rects
+ num_image = 0
+ num_added = 0
+ for gt in tqdm(gts):
+ assert len(gt) == 2
+ num_image = num_image + 1
+ key = gt[0]
+ g_rects = json.loads(gt[1])
+ origin_g_rects = copy.deepcopy(g_rects)
+ add_rects = []
+ if not is_aligned:
+ if key not in key_to_pred:
+ yield key, origin_g_rects, add_rects, g_rects
+ continue
+ p_rects = key_to_pred[key]
+ else:
+ p_key, p_rects = next(prediction)
+ p_rects = json.loads(p_rects)
+ assert key == p_key
+ p_rects = [r for r in p_rects if r['conf'] > prob_th and
+ r['conf'] <= prob_th_max]
+ if aug_labels is not None:
+ p_rects = [r for r in p_rects if r['class'] in aug_labels]
+ if srclabel_to_destlabel:
+ p_rects = [r for r in p_rects if r['class'] in srclabel_to_destlabel]
+ for r in p_rects:
+ r['class'] = srclabel_to_destlabel[r['class']]
+ p_rects = sorted(p_rects, key=lambda x: -x['conf'])
+ for p_rect in p_rects:
+ is_add = True
+ ious = [calculate_iou(p_rect['rect'], g_rect['rect'])
+ for g_rect in g_rects]
+ if len(ious) > 0 and max(ious) > iou_th:
+ is_add = False
+ if is_add:
+ num_added = num_added + 1
+ p_rect['from'] = prediction_file
+ # add p_rect
+ add_rects.append(p_rect)
+ g_rects.append(p_rect)
+ yield key, origin_g_rects, add_rects, g_rects
+ logging.info('num_image = {}'.format(num_image))
+ logging.info('num_added = {}'.format(num_added))
+
+
+def merge_prediction_to_gt(prediction_file, gts, im_rows, dataset, split,
+ **param):
+ dataset.iter_data(split, 'label')
+ gts2 = gen_merged_candidate(prediction_file, gts, **param)
+ if im_rows is not None:
+ if False:
+ # show image
+ for gt2, im_row in zip(gts2, im_rows):
+ assert gt2[0] == im_row[0]
+ im = img_from_base64(im_row[-1])
+ origin_rects = gt2[1]
+ add_rects = gt2[2]
+ merged_rects = gt2[3]
+ if len(add_rects) == 0:
+ continue
+ im_origin_gt = np.copy(im)
+ draw_bb(im_origin_gt, [r['rect'] for r in origin_rects],
+ [r['class'] for r in origin_rects])
+ im_add = np.copy(im)
+ draw_bb(im_add, [r['rect'] for r in add_rects],
+ [r['class'] for r in add_rects],
+ [r['conf'] for r in add_rects])
+ im_merged = np.copy(im)
+ draw_bb(im_merged, [r['rect'] for r in merged_rects],
+ [r['class'] for r in merged_rects])
+ logging.info(pformat(add_rects))
+ show_images([im_origin_gt, im_add, im_merged], 1, 3)
+ else:
+ # save image
+ for i, (gt2, im_row) in enumerate(zip(gts2, im_rows)):
+ assert gt2[0] == im_row[0]
+ im = img_from_base64(im_row[-1])
+ origin_rects = gt2[1]
+ add_rects = gt2[2]
+ merged_rects = gt2[3]
+ if len(add_rects) == 0:
+ continue
+ add_class = list(set([r['class'] for r in add_rects]))
+ for c in add_class:
+ c_rects = [r for r in add_rects if r['class'] == c]
+ im_add = np.copy(im)
+ draw_rects(c_rects, im_add, add_label=False)
+ im_origin = np.copy(im)
+ draw_rects([x for x in origin_rects if x['class'] == c], im_origin)
+ im_merged = np.copy(im)
+ draw_rects([x for x in merged_rects if x['class'] == c], im_merged)
+ top = np.concatenate((im, im_add), 1)
+ bottom = np.concatenate((im_origin, im_merged), 1)
+ x = np.concatenate((top, bottom), 0)
+ save_image(x, './output/add_image/{}_{}.jpg'.format(
+ c, im_row[0]))
+ else:
+ meta = {'num_image': 0,
+ 'num_added_total': 0,
+ 'from': prediction_file}
+ all_added = []
+ def gen_rows():
+ for key, origin_rects, add_rects, merged_rects in gts2:
+ all_added.append((key, add_rects))
+ meta['num_added_total'] = meta['num_added_total']+len(add_rects)
+ meta['num_image'] = meta['num_image'] + 1
+ yield key, json_dump(merged_rects)
+ # we will not change the files if they are the same
+ def gen_info():
+ meta['num_added_each'] = 1. * meta['num_added_total'] / meta['num_image']
+ for k, v in viewitems(meta):
+ yield k, v
+ for k, rects in all_added:
+ yield k, json_dump(rects)
+ dataset.update_data(gen_rows(), split, 'label',
+ generate_info=gen_info())
+
+def generate_labels_to_verify(predict_file, data, split, th,
+ pred_to_gt, output_file):
+ dataset = TSVDataset(data)
+ if op.isfile(op.join(dataset._data_root, 'root.yaml')):
+ tax = Taxonomy(load_from_yaml_file(op.join(dataset._data_root, 'root.yaml')))
+ else:
+ tax = None
+ gt_key_rects = [(row[0], json.loads(row[1])) for row in tqdm(dataset.iter_data(split,
+ 'label', version=-1))]
+ logging.info('loading pred')
+ pred_key_to_rects = {}
+ for row in tqdm(tsv_reader(predict_file)):
+ key = row[0]
+ rects = json.loads(row[1])
+ pred_key_to_rects[key] = [r for r in rects if r['conf'] > th]
+
+ def gen_rows(pred_to_gt=True):
+ logging.info('start to writting')
+ for key, gt_rects in tqdm(gt_key_rects):
+ if tax is not None:
+ rects2 = lift_one_image(gt_rects, tax)
+ del gt_rects[:]
+ gt_rects.extend(rects2)
+ pred_rects = pred_key_to_rects.get(key)
+ if pred_rects is None:
+ continue
+ need_confirm = []
+ if pred_to_gt:
+ for pr in pred_rects:
+ if not onebb_in_list_of_bb(pr, gt_rects):
+ need_confirm.append(pr)
+ else:
+ for g in gt_rects:
+ if len(g) == 2:
+ assert 'class' in g and 'rect' in g
+ continue
+ if not onebb_in_list_of_bb(g, pred_rects):
+ need_confirm.append(g)
+ yield key, json.dumps(need_confirm)
+
+ tsv_writer(gen_rows(pred_to_gt=pred_to_gt), output_file)
+
+def onebb_in_list_of_bb(bb, bbs):
+ bbs = [b for b in bbs if b['class'] == bb['class']]
+ return any(calculate_iou(b['rect'], bb['rect']) > 0.5 for b in bbs)
+
+def inject_accuracy():
+ all_full_expid = os.listdir('./output')
+ for full_expid in tqdm(all_full_expid):
+ inject_accuracy_one(full_expid)
+
+def inject_accuracy_one(full_expid):
+ from qd.db import create_annotation_db
+ c = create_annotation_db()
+ all_predict = glob.glob(op.join('output', full_expid, 'snapshot',
+ '*.predict'))
+ all_predict.extend(glob.glob(op.join('output', full_expid, 'snapshot',
+ '*.predict.tsv')))
+
+ all_report = glob.glob(op.join('output', full_expid, 'snapshot', '*.report'))
+ for report_file in all_report:
+ from .common import parse_test_data_with_version
+ try:
+ test_data, test_split, test_version = parse_test_data_with_version(op.basename(report_file))
+ except:
+ continue
+ info = {'full_expid': full_expid,
+ 'report_file': op.basename(report_file),
+ 'test_data': test_data,
+ 'test_split': test_split,
+ 'test_version': test_version,
+ }
+ if 'coco_box' in report_file or '.randomness.' in report_file:
+ acc = load_from_yaml_file(report_file)
+ elif '.neg_aware_gmap.' in report_file:
+ acc = load_from_yaml_file(report_file)
+ if 'neg_aware_gmap.noNMSGt.noNMSDet.noExpandDet.report' in report_file:
+ key = 'nngmAP'
+ elif '.neg_aware_gmap.noNMSGt.report' in report_file:
+ key = 'ngmAP'
+ else:
+ key = 'gmAP'
+ acc = {key: acc['map']}
+ elif '.top1.' in report_file:
+ acc = load_from_yaml_file(report_file)
+ elif report_file.endswith('predict.tsv.speed.yaml'):
+ all_meter = load_from_yaml_file(report_file)['meters']
+ all_meter = [m for m in all_meter if m['name'] == '']
+ assert len(all_meter) == 1
+ acc = all_meter[0]
+ del acc['name']
+ elif report_file.endswith('caption.report'):
+ acc = json.loads(read_to_buffer(report_file))
+ elif any(report_file.endswith(k) for k in [
+ 'ir_acc.report',
+ 'cap_acc.report',
+ 'cap_acc.nospace.report',
+ 'vqa_acc.report',
+ 'vqa2.report',
+ 'stvqa_acc.report',
+ 'stvqa_nopro_acc',
+ 'stvqa_anls.report',
+ 'nlvr2.report',
+ 'acc.report',
+ 'vizwiz_vqa.report',
+ 'textvqa_acc.report',
+ ]):
+ acc = load_from_yaml_file(report_file)
+ from .common import get_all_path, dict_get_path_value
+ all_path = get_all_path(acc)
+ acc = {p: dict_get_path_value(acc, p) for p in all_path}
+ elif report_file.endswith('attr.report'):
+ x = json.loads(read_to_buffer(report_file))
+ acc = {'attr': x['overall']['0.5']['map']}
+ else:
+ map_json_file = report_file + '.map.json'
+ if op.isfile(map_json_file):
+ x = json.loads(read_to_buffer(map_json_file))
+ acc = {}
+ for k1 in x:
+ for k2 in x[k1]:
+ for k3 in x[k1][k2]:
+ k = '{}${}${}'.format(k1, k2, k3)
+ acc[k] = x[k1][k2][k3]
+ else:
+ continue
+ for k in list(acc.keys()):
+ curr = copy.deepcopy(info)
+ curr['metric_name'] = k
+ exist = False
+ for found in c.iter_acc(**curr):
+ exist = True
+ if found['metric_value'] == acc[k]:
+ continue
+ else:
+ # the newer one will overwrite the old one. Sometimes, the
+ # code has issues and the experiment results are not
+ # correct
+ c.update_one_acc(query=curr,
+ update={'$set': {'metric_value': acc[k]}})
+ if not exist:
+ curr['metric_value'] = acc[k]
+ c.insert_acc(**curr)
+
+def find_predict_file(report_file, all_predict):
+ for k in ['.ir_acc.report',
+ '.vqa_acc.report',
+ '.stvqa_acc.report',
+ '.stvqa_anls.report',
+ '.caption.report',
+ '.attr.report'
+ ]:
+ if report_file.endswith(k):
+ pred = report_file[:-len(k)] + '.tsv'
+ if pred in all_predict:
+ return pred
+ #model_iter_0200182.pt.TaxImageNet2012CapDef.test.max_token100.vphoto_def.predict.top1.vphoto_def.report
+ #model_iter_0200182.pt.TaxImageNet2012CapDef.test.max_token100.vphoto_def.predict.tsv
+ r_pattern = '.*\.(v[^\.]*)\..*(v[^\.]*)\..*'
+ result = re.match(r_pattern, op.basename(report_file))
+ if result is not None:
+ v1, v2 = result.groups()
+ if v1 == v2:
+ pattern = '(.*)\.top1\.{}\.report'.format(v1)
+ result = re.match(pattern, op.basename(report_file))
+ if result is not None:
+ prefix, = result.groups()
+ p = prefix + '.tsv'
+ p = op.join(op.dirname(report_file), p)
+ for p1 in all_predict:
+ if p1 == p:
+ return p
+
+
+ found = False
+ for p in all_predict:
+ if p + '.report' == report_file:
+ assert not found
+ found = True
+ result = p
+ return result
+ for p in all_predict:
+ if p.endswith('.predict.tsv'):
+ ps = p[: -len('.predict.tsv')]
+ elif p.endswith('.predict'):
+ ps = p[: -len('.predict')]
+ else:
+ continue
+ if report_file.startswith(ps):
+ rs = report_file[len(ps):]
+ logging.info(rs)
+ eval_keys = ['predict', 'tsv', 'coco_box', 'neg_aware_gmap', 'top1',
+ 'noNMSGt', 'noNMSDet', 'noExpandDet', 'speed', 'MaxDet.*']
+ p0 = ''.join(['(\.{})?'.format(k) for k in eval_keys])
+ pattern = '{}(\.v[0-9]*)?(\.0)?\.(report|yaml)'.format(p0)
+ if re.match(pattern, rs):
+ assert not found
+ found = True
+ result = p
+ if not found:
+ matched = [p for p in all_predict if report_file.startswith(p)]
+ if len(matched) > 0:
+ result = sorted(matched, key=lambda x: -len(x))[0]
+ found = True
+ assert found
+ return result
+
+def softnms_row_process(row, sigma=0.5, method=2, Nt=0.5):
+ from .common import softnms_c
+ key, str_rects = row
+ rects = json.loads(str_rects)
+ all_class_rect = [(r['class'], r) for r in rects]
+ class_to_rects = list_to_dict(all_class_rect, 0)
+ rects2 = []
+ for c, rs in class_to_rects.items():
+ rs = softnms_c(rs, sigma=sigma, method=method, Nt=Nt)
+ for r in rs:
+ r['class'] = c
+ rects2.extend(rs)
+ return key, json_dump(rects2)
+
+def tsv_subset_process_NtoN(info):
+ row_processor = info['row_processor']
+ idx_process = info['idx_process']
+ tmp_out = info['tmp_out']
+ idx_range_start = info['idx_range_start']
+ idx_range_end = info['idx_range_end']
+ head = info['head']
+ sep = info['out_sep']
+ if all(op.isfile(t) and all(op.isfile(s) for s in get_tsv_associates(t)) for t in tmp_out):
+ logging.info('skip since exist: {}'.format(tmp_out))
+ return
+ if 'in_tsvs' in info:
+ tsvs = info['in_tsvs']
+ else:
+ tsvs = [TSVFile(t) for t in info['in_tsv_files']]
+ def gen_rows():
+ if idx_process == 0 and head is not None:
+ yield head
+ for i in tqdm(range(idx_range_start, idx_range_end)):
+ r = row_processor([t[i] for t in tsvs])
+ if r is None:
+ continue
+ yield r
+ tsv_writers(gen_rows(), tmp_out, sep=sep)
+ logging.info('done to generate {}'.format(tmp_out))
+
+def tsv_subset_process_1toN(info, with_row_idx):
+ row_processor = info['row_processor']
+ idx_process = info['idx_process']
+ tmp_out = info['tmp_out']
+ idx_range_start = info['idx_range_start']
+ idx_range_end = info['idx_range_end']
+ head = info['head']
+ sep = info['out_sep']
+ if all(op.isfile(t) for t in tmp_out):
+ logging.info('skip since exist: {}'.format(tmp_out))
+ return
+ if 'in_tsv' in info:
+ tsv = info['in_tsv']
+ else:
+ in_tsv_file = info['in_tsv_file']
+ tsv = TSVFile(in_tsv_file)
+ def gen_rows():
+ if idx_process == 0 and head is not None:
+ yield head
+ for i in tqdm(range(idx_range_start, idx_range_end)):
+ try:
+ if with_row_idx:
+ r = row_processor(tsv[i], i)
+ else:
+ r = row_processor(tsv[i])
+ if r is None:
+ continue
+ if isinstance(r, (list, tuple)):
+ yield r
+ else:
+ while True:
+ try:
+ x = next(r)
+ yield x
+ except StopIteration:
+ break
+ except:
+ logging.info(f'{tsv}-{i}')
+ raise
+ tsv_writers(gen_rows(), tmp_out, sep=sep)
+
+def tsv_subset_process(info, with_row_idx=False):
+ row_processor = info['row_processor']
+ idx_process = info['idx_process']
+ tmp_out = info['tmp_out']
+ idx_range_start = info['idx_range_start']
+ idx_range_end = info['idx_range_end']
+ head = info['head']
+ sep = info['out_sep']
+ if op.isfile(tmp_out):
+ logging.info('skip since exist: {}'.format(tmp_out))
+ return
+ if 'in_tsv' in info:
+ tsv = info['in_tsv']
+ else:
+ in_tsv_file = info['in_tsv_file']
+ tsv = TSVFile(in_tsv_file)
+ def gen_rows():
+ if idx_process == 0 and head is not None:
+ yield head
+ for i in tqdm(range(idx_range_start, idx_range_end)):
+ # this is a breaking change to add i as option, but we have to do
+ # this as row_processor has no way to figure it out which row it is
+ try:
+ if with_row_idx:
+ r = row_processor(tsv[i], i)
+ else:
+ r = row_processor(tsv[i])
+ if r is None:
+ continue
+ if isinstance(r, (list, tuple)):
+ yield r
+ else:
+ while True:
+ try:
+ x = next(r)
+ yield x
+ except StopIteration:
+ break
+ except:
+ logging.info(f'{tsv}/{i}')
+ raise
+ tsv_writer(gen_rows(), tmp_out, sep=sep)
+
+def tsv_subset_aggregator(info, with_row_idx=False):
+ row_processor = info['row_processor']
+ tmp_out = info['tmp_out']
+ idx_range_start = info['idx_range_start']
+ idx_range_end = info['idx_range_end']
+ if File.isfile(tmp_out):
+ return load_from_yaml_file(tmp_out)
+ if 'in_tsv' in info:
+ tsv = info['in_tsv']
+ else:
+ in_tsv_file = info['in_tsv_file']
+ tsv = TSVFile(in_tsv_file)
+ ret = {}
+ for i in tqdm(range(idx_range_start, idx_range_end)):
+ # this is a breaking change to add i as option, but we have to do
+ # this as row_processor has no way to figure it out which row it is
+ try:
+ if with_row_idx:
+ row_processor(ret, tsv[i], i)
+ else:
+ row_processor(ret, tsv[i])
+ except:
+ logging.info(f'{tsv}/{i}')
+ raise
+ write_to_yaml_file(ret, tmp_out)
+ return ret
+
+def multi_tsv_subset_process(info):
+ row_processor = info['row_processor']
+ idx_process = info['idx_process']
+ in_tsv_files = info['in_tsv_files']
+ tmp_out = info['tmp_out']
+ idx_range = info['idx_range']
+ head = info['head']
+ out_sep = info['out_sep']
+ if op.isfile(tmp_out):
+ logging.info('skip to create {}'.format(tmp_out))
+ return
+ def gen_rows():
+ if idx_process == 0 and head is not None:
+ yield head
+ tsvs = [TSVFile(f) for f in in_tsv_files]
+ for i in tqdm(idx_range):
+ row_result = row_processor([tsv[i] for tsv in tsvs])
+ if row_result is not None:
+ # we can return None to remove rows
+ yield row_result
+ tsv_writer(gen_rows(), tmp_out, sep=out_sep)
+
+def multi_tsv_row_merger(rows):
+ all_key = [row[0] for row in rows]
+ assert all(all_key[0] == key for key in all_key[1:])
+ all_rect = [json.loads(row[1]) for row in rows]
+ str_rect = json_dump([r for rs in all_rect for r in rs])
+ return all_key[0], str_rect
+
+def parallel_tsv_process_NtoN(row_processor, in_tsv_files,
+ out_tsv_files, num_process, num_jobs=None, head=None, out_sep='\t'):
+ in_tsvs = [TSVFile(in_tsv_file) if isinstance(in_tsv_file, str) else
+ in_tsv_file for in_tsv_file in in_tsv_files]
+ total = len(in_tsvs[0])
+ assert all(len(t) == total for t in in_tsvs[1:])
+ for t in in_tsvs:
+ t.close()
+ if num_jobs is None:
+ num_jobs = max(1, num_process)
+ rows_each_rank = (total + num_jobs - 1) // num_jobs
+ all_task = []
+ folder = get_tmp_folder()
+ for i in range(num_jobs):
+ start = i * rows_each_rank
+ end = start + rows_each_rank
+ end = min(end, total)
+ tmp_out = ['{}/{}'.format(folder, out_tsv_file) + '.{}.{}.tsv'.format(i, num_jobs)
+ for out_tsv_file in out_tsv_files]
+ info = {
+ 'row_processor': row_processor,
+ 'idx_process': i,
+ #'in_tsv_files': in_tsv_files,
+ 'in_tsvs': in_tsvs,
+ 'tmp_out': tmp_out,
+ 'idx_range_start': start,
+ 'idx_range_end': end,
+ 'head': head,
+ 'out_sep': out_sep,
+ }
+ all_task.append(info)
+ from .common import parallel_map
+ parallel_map(tsv_subset_process_NtoN, all_task,
+ num_worker=num_process)
+ all_out = [task['tmp_out'] for task in all_task]
+ for i, out_tsv_file in enumerate(out_tsv_files):
+ tmp_out = [out[i] for out in all_out]
+ concat_tsv_files(tmp_out, out_tsv_file, gen_lineidx=False)
+ delete_tsv_files(tmp_out)
+
+def parallel_multi_tsv_process(row_processor, in_tsv_files,
+ out_tsv_file, num_process, num_jobs=None, head=None, out_sep='\t'):
+ in_tsvs = [TSVFile(in_tsv_file) for in_tsv_file in in_tsv_files]
+ total = len(in_tsvs[0])
+ assert all(len(t) == total for t in in_tsvs[1:])
+ if num_jobs is None:
+ num_jobs = max(1, num_process)
+ rows_each_rank = (total + num_jobs - 1) // num_jobs
+ all_task = []
+ for i in range(num_jobs):
+ start = i * rows_each_rank
+ end = start + rows_each_rank
+ end = min(end, total)
+ if num_jobs == 1:
+ tmp_out = out_tsv_file
+ else:
+ tmp_out = out_tsv_file + '.{}.{}.tsv'.format(i, num_jobs)
+ info = {'row_processor': row_processor,
+ 'idx_process': i,
+ 'in_tsv_files': in_tsv_files,
+ 'tmp_out': tmp_out,
+ 'idx_range': list(range(start, end)),
+ 'head': head,
+ 'out_sep': out_sep
+ }
+ all_task.append(info)
+ from .common import parallel_map
+ parallel_map(multi_tsv_subset_process, all_task,
+ num_worker=num_process)
+ if num_jobs > 1:
+ all_out = [task['tmp_out'] for task in all_task]
+ concat_tsv_files(all_out, out_tsv_file, gen_lineidx=False)
+ delete_tsv_files(all_out)
+
+def parallel_tsv_process_1toN(row_processor, in_tsv_file,
+ out_tsv_files, num_process, num_jobs=None, head=None, out_sep='\t',
+ with_row_idx=False,
+ ):
+ # in_tsv_file can be a string, interpreted as a tsv file
+ # or a list
+ if isinstance(in_tsv_file, str):
+ in_tsv = TSVFile(in_tsv_file)
+ else:
+ in_tsv = in_tsv_file
+ total = len(in_tsv)
+ if num_jobs is None:
+ if num_process == 0:
+ num_jobs = 1
+ else:
+ num_jobs = num_process
+ rows_each_rank = (total + num_jobs - 1) // num_jobs
+ all_task = []
+ if isinstance(in_tsv, (TSVFile, CompositeTSVFile)):
+ # we need to clear all the cache in TSVFile. otherwise, the process
+ # might need a lot of time to copy the cache in in_tsv, e.g. lineidx
+ # when the number of data are huge.
+ in_tsv.close()
+ folder = get_tmp_folder()
+ for i in range(num_jobs):
+ start = i * rows_each_rank
+ end = start + rows_each_rank
+ end = min(end, total)
+ tmp_out = ['{}/{}'.format(folder, out_tsv_file) + '.{}.{}.tsv'.format(i, num_jobs)
+ for out_tsv_file in out_tsv_files]
+ info = {'row_processor': row_processor,
+ 'idx_process': i,
+ #'in_tsv_file': in_tsv_file,
+ 'in_tsv': in_tsv,
+ 'tmp_out': tmp_out,
+ 'idx_range_start': start,
+ 'idx_range_end': end,
+ 'head': head,
+ 'out_sep': out_sep
+ }
+ all_task.append(info)
+ from .common import parallel_map
+ parallel_map(lambda x: tsv_subset_process_1toN(x, with_row_idx), all_task,
+ num_worker=num_process)
+ all_out = [task['tmp_out'] for task in all_task]
+ if isinstance(in_tsv, TSVFile):
+ # explicitly close the file
+ in_tsv.close()
+ for i, out_tsv_file in enumerate(out_tsv_files):
+ tmp_out = [out[i] for out in all_out]
+ concat_tsv_files(tmp_out, out_tsv_file, gen_lineidx=False)
+ delete_tsv_files(tmp_out)
+
+def parallel_tsv_process(row_processor, in_tsv_file,
+ out_tsv_file,
+ num_process=64,
+ num_jobs=None,
+ head=None,
+ out_sep='\t',
+ with_row_idx=False,
+ ):
+ if isinstance(in_tsv_file, str):
+ in_tsv = TSVFile(in_tsv_file)
+ else:
+ in_tsv = in_tsv_file
+ total = len(in_tsv)
+ if num_jobs is None:
+ if num_process == 0:
+ num_jobs = 1
+ else:
+ num_jobs = num_process
+ rows_each_rank = (total + num_jobs - 1) // num_jobs
+ all_task = []
+ if isinstance(in_tsv, TSVFile):
+ # we need to clear all the cache in TSVFile. otherwise, the process
+ # might need a lot of time to copy the cache in in_tsv, e.g. lineidx
+ # when the number of data are huge.
+ in_tsv.close()
+ folder = get_tmp_folder()
+ for i in range(num_jobs):
+ start = i * rows_each_rank
+ end = start + rows_each_rank
+ end = min(end, total)
+ #tmp_out = out_tsv_file + '.{}.{}.tsv'.format(i, num_jobs)
+ tmp_out = '{}/{}'.format(folder, out_tsv_file) + '.{}.{}.tsv'.format(i, num_jobs)
+ info = {'row_processor': row_processor,
+ 'idx_process': i,
+ #'in_tsv_file': in_tsv_file,
+ 'in_tsv': in_tsv,
+ 'tmp_out': tmp_out,
+ 'idx_range_start': start,
+ 'idx_range_end': end,
+ 'head': head,
+ 'out_sep': out_sep
+ }
+ all_task.append(info)
+ from .common import parallel_map
+ parallel_map(lambda x: tsv_subset_process(x, with_row_idx), all_task,
+ num_worker=num_process)
+ all_out = [task['tmp_out'] for task in all_task]
+ concat_tsv_files(all_out, out_tsv_file, gen_lineidx=False)
+ delete_tsv_files(all_out)
+
+def parallel_tsv_aggregator(
+ mapper,
+ reducer,
+ in_tsv_file,
+ num_process=64,
+ num_jobs=None,
+ head=None,
+ out_sep='\t',
+ with_row_idx=False,
+):
+ if isinstance(in_tsv_file, str):
+ in_tsv = TSVFile(in_tsv_file)
+ else:
+ in_tsv = in_tsv_file
+ total = len(in_tsv)
+ if num_jobs is None:
+ if num_process == 0:
+ num_jobs = 1
+ else:
+ num_jobs = num_process
+ rows_each_rank = (total + num_jobs - 1) // num_jobs
+ all_task = []
+ if isinstance(in_tsv, TSVFile):
+ # we need to clear all the cache in TSVFile. otherwise, the process
+ # might need a lot of time to copy the cache in in_tsv, e.g. lineidx
+ # when the number of data are huge.
+ in_tsv.close()
+ folder = get_tmp_folder()
+ basename = datetime.now().strftime('%Y_%m_%d_%H_%M_%S') + '_' + str(hash(in_tsv_file))
+ for i in range(num_jobs):
+ start = i * rows_each_rank
+ end = start + rows_each_rank
+ end = min(end, total)
+ #tmp_out = out_tsv_file + '.{}.{}.tsv'.format(i, num_jobs)
+ tmp_out = '{}/{}'.format(folder, basename) + '.{}.{}.yaml'.format(i, num_jobs)
+ info = {'row_processor': mapper,
+ 'idx_process': i,
+ #'in_tsv_file': in_tsv_file,
+ 'in_tsv': in_tsv,
+ 'tmp_out': tmp_out,
+ 'idx_range_start': start,
+ 'idx_range_end': end,
+ 'head': head,
+ 'out_sep': out_sep
+ }
+ all_task.append(info)
+ from .common import parallel_map
+ rets = parallel_map(lambda x: tsv_subset_aggregator(x, with_row_idx), all_task,
+ num_worker=num_process)
+ rets = reducer(rets)
+ all_out = [task['tmp_out'] for task in all_task]
+ for f in all_out:
+ ensure_remove_file(f)
+ return rets
+
+def mpi_tsv_process(row_processor, in_tsv_file, out_tsv_file):
+ mpi_size = get_mpi_size()
+ mpi_rank = get_mpi_rank()
+ in_tsv = TSVFile(in_tsv_file)
+ total = len(in_tsv)
+ rows_each_rank = (total + mpi_size - 1) // mpi_size
+ logging.info('size for each rank = {}'.format(rows_each_rank))
+ start = mpi_rank * rows_each_rank
+ end = min(start + rows_each_rank, total)
+ logging.info('rank = {}; start = {}; end = {}'.format(mpi_rank,
+ start, end))
+ out_tsv_rank = out_tsv_file + '.{}.{}.tsv'.format(mpi_rank, mpi_size)
+ def gen_rows():
+ for i in tqdm(range(start, end)):
+ row = in_tsv[i]
+ row = row_processor(row)
+ yield row
+ tsv_writer(gen_rows(), out_tsv_rank)
+
+ all_out = [out_tsv_file + '.{}.{}.tsv'.format(i, mpi_size) for i in
+ range(mpi_size)]
+
+ while True:
+ if all(op.isfile(f) for f in all_out):
+ break
+ logging.info('waiting {}'.format('; '.join(f for f in all_out if not
+ op.isfile(f))))
+ time.sleep(5)
+
+ if mpi_rank == 0:
+ concat_tsv_files(all_out, out_tsv_file)
+ delete_tsv_files(all_out)
+ else:
+ while not op.isfile(out_tsv_file):
+ logging.info('waiting {}'.format(out_tsv_file))
+ time.sleep(5)
+
+def create_focus_dataset(data, source_version, target_labels, out_data):
+ out_dataset = TSVDataset(out_data)
+ write_to_file('\n'.join(target_labels),
+ out_dataset.get_labelmap_file())
+
+ # train
+ dataset = TSVDataset(data)
+ write_to_file(dataset.get_data('train'), out_dataset.get_data('trainX'))
+ write_to_file(dataset.get_data('train', t='hw'),
+ out_dataset.get_data('trainX', t='hw'))
+
+ def gen_rows():
+ target_label_set = set(target_labels)
+ for key, str_rects in dataset.iter_data('train', t='label',
+ version=source_version, progress=True):
+ rects = json.loads(str_rects)
+ rects = [r for r in rects if r['class'] in target_label_set]
+ yield '_'.join([data, 'train', key]), json_dump(rects)
+ out_dataset.write_data(gen_rows(), 'train', t='label')
+ num_rows = dataset.num_rows('train')
+ tsv_writer(((0, i) for i in range(num_rows)),
+ op.join(out_dataset._data_root, 'train.shuffle.txt'))
+
+class CogAPI(object):
+ def __init__(self):
+ self.remote_image_features = ['adult']
+ self.run_ocr = False
+ self.computervision_client = None
+
+ def ensure_init(self):
+ from msrest.authentication import CognitiveServicesCredentials
+ from azure.cognitiveservices.vision.computervision import ComputerVisionClient
+ if self.computervision_client is None:
+ x = load_from_yaml_file('aux_data/configs/cognitive_credential.yaml')
+ self.subscription_key = x['subscription_key']
+ self.endpoint = x['endpoint']
+ self.computervision_client = ComputerVisionClient(self.endpoint,
+ CognitiveServicesCredentials(self.subscription_key))
+
+ def call(self, image_url):
+ self.ensure_init()
+ result = {}
+ if self.remote_image_features:
+ remote_image_analysis = self.computervision_client.analyze_image(image_url,
+ self.remote_image_features)
+ from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
+ if 'adult' in self.remote_image_features:
+ result.update(self.parse_adult(remote_image_analysis))
+ if 'description' in self.remote_image_features:
+ result.update(self.parse_description(remote_image_analysis))
+ if VisualFeatureTypes.image_type in self.remote_image_features:
+ result.update(self.parse_type(remote_image_analysis))
+ if self.run_ocr:
+ recognize_printed_results = self.computervision_client.batch_read_file(image_url, raw=True)
+ result.update(self.parse_ocr(recognize_printed_results))
+
+ return result
+
+ def parse_ocr(self, recognize_printed_results):
+ from azure.cognitiveservices.vision.computervision.models import TextOperationStatusCodes
+ # Get the operation location (URL with an ID at the end) from the response
+ operation_location_remote = recognize_printed_results.headers["Operation-Location"]
+ # Grab the ID from the URL
+ operation_id = operation_location_remote.split("/")[-1]
+
+ # Call the "GET" API and wait for it to retrieve the results
+ while True:
+ get_printed_text_results = self.computervision_client.get_read_operation_result(operation_id)
+ if get_printed_text_results.status not in ['NotStarted', 'Running']:
+ break
+ time.sleep(1)
+
+ lines = []
+ if get_printed_text_results.status == TextOperationStatusCodes.succeeded:
+ for text_result in get_printed_text_results.recognition_results:
+ for line in text_result.lines:
+ lines.append({'text': line.text, 'bounding_box':
+ line.bounding_box})
+ return {'ocr': lines}
+
+ def parse_description(self, result):
+ return {'captions': [{'text': cap.text,
+ 'conf': cap.confidence}
+ for cap in result.description.captions]}
+
+ def parse_type(self, remote_image_analysis):
+ return {'clip_art_type': remote_image_analysis.image_type.clip_art_type,
+ 'line_drawing_type': remote_image_analysis.image_type.line_drawing_type,
+ }
+
+ def parse_adult(self, remote_image_analysis):
+ result = {'is_adult': remote_image_analysis.adult.is_adult_content,
+ 'adult_score': remote_image_analysis.adult.adult_score,
+ 'is_racy': remote_image_analysis.adult.is_racy_content,
+ 'racy_score': remote_image_analysis.adult.racy_score}
+ return result
+
+def adult_filtering_by_cogapi(data, split):
+ dataset = TSVDataset(data)
+ api = CogAPI()
+ in_tsv = dataset.get_data(split, 'key.url')
+ out_tsv = dataset.get_data(split, 'key.adult')
+ def row_processor(row):
+ key, url = row
+ try:
+ result = api.call(url)
+ return key, json_dump(result)
+ except:
+ from .common import print_trace
+ print_trace()
+ return key, json_dump(-1)
+ if op.isfile(out_tsv):
+ return
+ parallel_tsv_process(row_processor, in_tsv,
+ out_tsv, num_process=16, num_jobs=1024)
+
+def scale_ocr_result(result, h_scale, w_scale):
+ for r in result:
+ r['rect'][::2] = [x * w_scale for x in r['rect'][::2]]
+ r['rect'][1::2] = [x * h_scale for x in r['rect'][1::2]]
+ r['lines'][::2] = [x * w_scale for x in r['lines'][::2]]
+ r['lines'][1::2] = [x * h_scale for x in r['lines'][1::2]]
+
+def ocr_engine_result_to_rects(lines):
+ rects = []
+ for info in lines:
+ r = {}
+ xs = info['boundingBox'][::2]
+ ys = info['boundingBox'][1::2]
+ r['rect'] = [min(xs), min(ys), max(xs), max(ys)]
+ r['class'] = 'text'
+ r['lines'] = info['boundingBox']
+ r['text'] = info['text']
+ rects.append(r)
+ return rects
+
+def run_ocr_on_content(input_file, urls):
+ headers = {
+ 'Content-Type':'image/jpg'
+ }
+ url = urls[int(random.random() * 9999) % len(urls)]
+ import requests
+ r = requests.post(url, headers=headers, data=input_file)
+
+ if (r.ok):
+ x = json.loads(r.text)
+ if 'analyzeResult' not in x or 'readResults' not in x['analyzeResult']:
+ return []
+ rects = ocr_engine_result_to_rects(x['analyzeResult']['readResults'][0]['lines'])
+ return rects
+
+class OCRRowProcessor(object):
+ def __init__(self, urls):
+ self.urls = urls
+
+ def __call__(self, row):
+ if len(row) == 3:
+ key, str_rects, str_im = row
+ else:
+ key, str_im = row
+ im = img_from_base64(str_im)
+ def proper_image_scale(im):
+ h, w = im.shape[:2]
+ if h <= w:
+ ratio = 800. / h
+ w = ratio * w
+ h = 800
+ if w > 8000:
+ w = 8000
+ else:
+ ratio = 800. / w
+ w = 800
+ h = ratio * h
+ if h > 8000:
+ h = 8000
+ im = cv2.resize(im, (int(w), int(h)))
+ return im
+
+ if max(im.shape[:2]) <= 200 or max(im.shape[:2]) > 8000:
+ im_scale = proper_image_scale(im)
+ h_scale, w_scale = (1. * im_scale.shape[0] / im.shape[0], 1. *
+ im_scale.shape[1] / im.shape[1])
+ else:
+ h_scale, w_scale = 1, 1
+ im_scale = im
+
+ content = cv2.imencode('.jpg', im_scale)[1]
+ try:
+ result = run_ocr_on_content(content.tobytes(), self.urls)
+ except:
+ logging.info(pformat(im_scale.shape))
+ raise
+ if result is None:
+ logging.info('unable to process {}'.format(key))
+ return key, -1
+ else:
+ scale_ocr_result(result, 1./h_scale, 1./w_scale)
+ return key, json_dump(result)
+
+def ocr_tsv(in_tsv, out_tsv, urls):
+ processor = OCRRowProcessor(urls)
+ parallel_tsv_process(processor, in_tsv, out_tsv,
+ num_process=5, num_jobs=10240)
+
+def create_dataset_from_pred(pred_tsv, conf_th, src_data, out_data):
+ # create label
+ def gen_rows():
+ for key, str_rects in tqdm(tsv_reader(pred_tsv)):
+ rects = json.loads(str_rects)
+ high_rects = [r for r in rects if r['conf'] > conf_th]
+ if len(high_rects) > 0:
+ yield '_'.join([src_data, 'train', key]), json_dump(high_rects)
+ tsv_writer(gen_rows(), './data/{}/train.label.tsv'.format(out_data))
+
+ create_image_X_by_key(out_data, 'train', 'label')
+ ensure_copy_file(TSVDataset('coco2017Full').get_labelmap_file(),
+ TSVDataset(out_data).get_labelmap_file())
+ populate_dataset_details(out_data)
+ populate_dataset_hw(out_data, ['train'])
+
+def create_image_X_by_key(target_data, target_split, t):
+ # given train.label.tsv where key is a composed key, we derive the
+ # trainX.tsv and the shuffle file
+ dataset = TSVDataset(target_data)
+ data_split_keys = [parse_combine(key) for key, _ in
+ dataset.iter_data(target_split, t)]
+ data_to_split_keys = list_to_dict(data_split_keys, 0)
+ data_splits = []
+ for data, split_keys in data_to_split_keys.items():
+ split_to_keys = list_to_dict(split_keys, 0)
+ for split in split_to_keys:
+ data_splits.append((data, split))
+ data_to_dataset = {}
+ def get_dataset(src_data):
+ if src_data not in data_to_dataset:
+ data_to_dataset[src_data] = TSVDataset(src_data)
+ return data_to_dataset[src_data]
+ src_tsv = [get_dataset(data).get_data(split) for data, split in data_splits]
+ data_split_to_idx = {data_split: i for i, data_split in
+ enumerate(data_splits)}
+ def gen_shuffle():
+ for src_data, src_split, src_key in data_split_keys:
+ idx_source = data_split_to_idx[(src_data, src_split)]
+ idx_key = get_dataset(src_data).get_idx_by_key(src_key,
+ src_split)
+ yield idx_source, idx_key
+
+ tsv_writer(gen_shuffle(),
+ get_dataset(target_data).get_shuffle_file(target_split))
+ write_to_file('\n'.join(src_tsv),
+ get_dataset(target_data).get_data(target_split + 'X'))
+
+def create_tiny_set(data, out_data):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+
+ num_image = dataset.num_rows('train')
+ all_idx = list(range(num_image))
+ random.shuffle(all_idx)
+
+ out_num_train = int(0.1 * len(all_idx))
+ out_num_test = int(0.05 * len(all_idx))
+ train_idx = all_idx[:out_num_train]
+ test_idx = all_idx[out_num_train: (out_num_train + out_num_test)]
+
+ ensure_copy_file(dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+
+ for t in [None, 'label']:
+ out_dataset.write_data(dataset.iter_data('train',
+ t=t,
+ filter_idx=train_idx,
+ progress=True),
+ split='train',
+ t=t)
+ out_dataset.write_data(dataset.iter_data('train',
+ t=t,
+ filter_idx=test_idx,
+ progress=True),
+ split='test',
+ t=t)
+
+def create_tsv_by_image_folder(folder, tsv_file,
+ max_short=1200, key_func=None):
+ from .common import is_valid_image
+ from .common import insensitive_glob
+ from .process_image import load_image
+ if key_func is None:
+ key_func = lambda f: op.basename(f)
+ def gen_rows():
+ for ext in ['png', 'jpg', 'jpeg', 'JPG']:
+ pattern = '*.{}'.format(ext)
+ pattern = op.join(folder, pattern)
+ im_files = insensitive_glob(pattern)
+ for f in tqdm(im_files):
+ im = load_image(f)
+ if not is_valid_image(im):
+ continue
+ if min(im.shape[:2]) > max_short:
+ ratio = 1. * max_short / min(im.shape[:2])
+ h = int(im.shape[0] * ratio)
+ w = int(im.shape[1] * ratio)
+ im = cv2.resize(im, (w, h))
+ yield key_func(f), encoded_from_img(im)
+ else:
+ yield key_func(f), base64.b64encode(read_to_buffer(f))
+ tsv_writer(gen_rows(), tsv_file)
+
+def create_versions_from_uncertain_label(data, split):
+ dataset = TSVDataset(data)
+ info = defaultdict(int)
+ assert not dataset.has(split, 'label', version=1)
+ assert not dataset.has(split, 'label', version=2)
+ def gen_rows():
+ iter_label = dataset.iter_data(split, 'label')
+ for key, str_rects in tqdm(iter_label):
+ rects = json.loads(str_rects)
+ for r in rects:
+ if r['class'].endswith('_?'):
+ r['class'] = r['class'][:-2]
+ info[r['class']] += 1
+ yield key, json_dump(rects)
+ def gen_info():
+ yield 'remove _? in class name', 'keep the boxes'
+ for k, v in info.items():
+ yield k, v
+ dataset.update_data(gen_rows(), split, 'label',
+ generate_info=gen_info())
+
+ info = defaultdict(int)
+ def gen_rows2():
+ iter_label = dataset.iter_data(split, 'label')
+ for key, str_rects in iter_label:
+ rects = json.loads(str_rects)
+ origin_num = len(rects)
+ info['original box'] += origin_num
+ if split == 'train':
+ rects = [r for r in rects if not r['class'].endswith('_?')]
+ info['removed'] += origin_num - len(rects)
+ else:
+ assert split == 'test'
+ for r in rects:
+ if r['class'].endswith('_?'):
+ r['class'] = r['class'][:-2]
+ r['diff'] = 1
+ info['new diff set'] += 1
+ yield key, json_dump(rects)
+ def gen_info2():
+ if split == 'train':
+ yield 'remove the box whose label ends with _?',
+ else:
+ assert split == 'test'
+ yield 'remove _? if the class ends with _?.', \
+ 'keep the box', \
+ 'add diff = 1'
+ for k, v in info.items():
+ yield k, v
+ dataset.update_data(gen_rows2(), split, 'label',
+ generate_info=gen_info2())
+
+def remove_size_in_label(data, split, version):
+ dataset = TSVDataset(data)
+ def gen_rows():
+ for key, str_rects in tqdm(dataset.iter_data(split, 'label',
+ version=version)):
+ rects = json.loads(str_rects)
+ assert len(rects) == 1
+ c = rects[0]['class']
+ assert not all(s in c for s in ['_s_', '_S_'])
+ for s in ['_s_', '_S_']:
+ parts = c.split('_s_')
+ assert len(parts) in [1, 2]
+ rects[0]['class'] = parts[0]
+ if len(parts) == 2:
+ break
+ yield key, json_dump(rects)
+ dataset.update_data(gen_rows(), split, 'label',
+ generate_info=[('remove size in the label', )])
+
+def crop_detbox(data, split, version, out_data=None, save_type=None):
+ dataset = TSVDataset(data)
+ iter_image = dataset.iter_data(split)
+ iter_label = dataset.iter_data(split, 'label', version=version)
+ labels = []
+ def gen_rows():
+ for (image_key, _, image_str), (label_key, str_rects) in tqdm(
+ zip(iter_image, iter_label)):
+ assert image_key == label_key
+ im = img_from_base64(image_str)
+ h, w = im.shape[:2]
+ rects = json.loads(str_rects)
+ for i, r in enumerate(rects):
+ x0, y0, x1, y1 = r['rect']
+ x0, y0 = int(x0), int(y0)
+ x1, y1 = math.ceil(x1), math.ceil(y1)
+ x0, y0 = max(0, x0), max(0, y0)
+ x1, y1 = min(x1, w), min(y1, h)
+ if x1 <= x0 or y1 <= y0:
+ continue
+ sub = im[y0:y1, x0:x1, :]
+ del r['rect']
+ res_key = image_key + '${}'.format(i)
+ str_label = json_dump([r])
+ labels.append((res_key, str_label))
+ yield res_key, str_label, encoded_from_img(sub,
+ save_type=save_type)
+ if out_data is None:
+ out_data = '{}_crop_{}{}'.format(data, split, version)
+ out_dataset = TSVDataset(out_data)
+ if out_dataset.has(split):
+ logging.info('{} - {} exists'.format(out_dataset.name,
+ split))
+ return out_data
+ #assert not out_dataset.has(split)
+ out_dataset.write_data(gen_rows(), split)
+ out_dataset.write_data(labels, split, 'label')
+ populate_dataset_details(out_data)
+ return out_data
+
+def create_single_class_detection_taxonomy(data, split, version, root_name,
+ excludes=None):
+ populate_dataset_details(data)
+ dataset = TSVDataset(data)
+ labels = [l for l, in dataset.iter_data(split, 'labelmap', version=version)]
+ if excludes is not None:
+ lower_label = [(l.lower(), l) for l in labels]
+ lower_to_labels = list_to_dict(lower_label, 0)
+ lower_excludes = [e.lower() for e in excludes]
+ for e in lower_excludes:
+ if e in lower_to_labels:
+ del lower_to_labels[e]
+ labels = [l for _, ls in lower_to_labels.items() for l in ls]
+ info = [{'name': root_name,
+ 'alias_names': ','.join(labels)}]
+ return info
+
+def unflatten_to_detection(data, split, pred, output,
+ threshold=0.01):
+ dataset = TSVDataset(data)
+ iter_label = dataset.iter_data(split, 'label')
+ iter_pred = tsv_reader(pred)
+ def gen_rows():
+ pre_key = None
+ pre_rects = []
+ for (key, str_rects), (pred_key, pred_rects) in tqdm(zip(
+ iter_label, iter_pred)):
+ assert key == pred_key
+ idx = key.rfind('$')
+ real_key = key[:idx]
+ if real_key != pre_key:
+ if pre_key is not None:
+ yield pre_key, json_dump(pre_rects)
+ pre_key = real_key
+ pre_rects = []
+ gt = json.loads(str_rects)
+ assert len(gt) == 1
+ gt = gt[0]
+ pred = json.loads(pred_rects)
+ for p in pred:
+ sub_gt = copy.deepcopy(gt)
+ sub_gt['class'] = p['class']
+ sub_gt['conf'] *= p['conf']
+ if sub_gt['conf'] > threshold:
+ pre_rects.append(sub_gt)
+ yield pre_key, json_dump(pre_rects)
+ tsv_writer(gen_rows(), output)
+
+def flatten_labels_for_classification(image_data, image_split, label_tsv,
+ out_data, out_split):
+ input_argument = get_frame_info()
+ input_argument['func'] = 'flatten_labels_for_classification'
+
+ dataset = TSVDataset(image_data)
+
+ populate_dataset_hw(image_data, [image_split])
+
+ iter_hw = dataset.iter_data(image_split, 'hw')
+ if label_tsv is not None:
+ iter_label = tsv_reader(label_tsv)
+ else:
+ iter_label = dataset.iter_data(image_split, 'label')
+
+ all_idx = []
+ def gen_rows():
+ for idx_image, ((label_key, str_rects), (hw_key, str_hw)) in enumerate(
+ zip(iter_label, iter_hw)):
+ assert label_key == hw_key
+ h, w = map(int, str_hw.split(' '))
+ rects = json.loads(str_rects)
+ for i, r in enumerate(rects):
+ x1, y1, x2, y2 = r['rect']
+
+ # since it is for classification, it has to be a valid box.
+ # Here we do the fewest pre-processing/filtering to have a
+ # valid box coordinates
+ x1 = int(x1)
+ y1 = int(y1)
+ x2 = math.ceil(x2)
+ y2 = math.ceil(y2)
+
+ x1 = min(w, max(0, x1))
+ x2 = min(w, max(0, x2))
+ y1 = min(h, max(0, y1))
+ y2 = min(h, max(0, y2))
+
+ if y2 <= y1 or x2 <= x1:
+ continue
+ r['rect'] = [x1, y1, x2, y2]
+ all_idx.append(idx_image)
+ yield label_key + '${}'.format(i), json_dump([r])
+ if out_data == None:
+ out_data = '{}_{}'.format(image_data,
+ hash_sha1(label_tsv)[-5:])
+ out_dataset = TSVDataset(out_data)
+ if op.isdir(out_dataset._data_root):
+ logging.info('{} exists'.format(out_dataset._data_root))
+ return out_data
+ out_dataset.write_data(gen_rows(), out_split, 'label')
+ tsv_writer(((0, i) for i in all_idx),
+ out_dataset.get_shuffle_file(out_split))
+ write_to_file(dataset.get_data(image_split), out_dataset.get_data(out_split
+ + 'X'))
+ readme_file = op.join(out_dataset._data_root, 'readme.yaml')
+
+ write_to_yaml_file(input_argument, readme_file)
+
+ expand_nested_splitX(out_data, out_split)
+
+ return out_data
+
+def download_images_to_tsv(info, tsv_file, key='key'):
+ from .common import url_to_bytes
+ from .common import bytes_to_image
+ def processor(i):
+ bs = url_to_bytes(i['url'])
+ if bs is None:
+ return None
+ try:
+ im = bytes_to_image(bs)
+ except:
+ return None
+ if im is None:
+ return None
+ return i[key], json_dump([]), base64.b64encode(bs)
+ parallel_tsv_process(processor, info, tsv_file, num_process=16,
+ num_jobs=1024)
+
+def smart_resize_dataset(data, input_size, out_data, resize_type='cv2',
+ save_type=None):
+ if resize_type is None:
+ resize_type = 'cv2'
+ assert resize_type in ['cv2', 'pil']
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+
+ for split in ['train', 'test']:
+ if not dataset.has(split):
+ continue
+ infos = []
+ def gen_rows():
+ if resize_type == 'cv2':
+ for key, str_rects, str_im in dataset.iter_data(split,
+ progress=True):
+ im = img_from_base64(str_im)
+ im2, left, top, scale = smart_resize(im, input_size)
+ im2 = im2.astype(np.uint8)
+ infos.append((left, top, scale))
+ yield key, json_dump([]), encoded_from_img(im2,
+ save_type=save_type)
+ else:
+ assert resize_type == 'pil'
+ for key, str_rects, str_im in dataset.iter_data(split,
+ progress=True):
+ im = pilimg_from_base64(str_im)
+ im2, left, top, scale = smart_resize(im, input_size)
+ infos.append((left, top, scale))
+ yield key, json_dump([]), encoded_from_img(im2,
+ save_type=save_type)
+ if not out_dataset.has(split):
+ out_dataset.write_data(gen_rows(), split)
+ v = 0
+ while dataset.has(split, 'label', version=v):
+ def gen_label_rows():
+ for i, (key, str_rects) in enumerate(dataset.iter_data(split, 'label',
+ version=v, progress=True)):
+ rects = json.loads(str_rects)
+ def transform_box(r, info):
+ left, top, scale = info
+ x1, y1, x2, y2 = r['rect']
+ out_x1 = x1 * scale + left
+ out_y1 = y1 * scale + top
+ out_x2 = x2 * scale + left
+ out_y2 = y2 * scale + top
+ r['rect'] = [out_x1, out_y1, out_x2, out_y2]
+ return r
+ rects = [transform_box(r, infos[i]) for r in rects]
+ yield key, json_dump(rects)
+ if not out_dataset.has(split, 'label', version=v):
+ out_dataset.write_data(gen_label_rows(), split, 'label', version=v)
+ v += 1
+ ensure_copy_file(dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+ populate_dataset_hw(out_data)
+
+def smart_resize_lefttop(im, target_size, lower=True):
+ from .process_image import is_pil_image
+ if is_pil_image(im):
+ w, h = im.size
+ else:
+ h, w, c = im.shape
+ alpha = target_size / np.sqrt(h * w)
+ if lower:
+ height2 = int(alpha * h)
+ width2 = int(alpha * w)
+ else:
+ height2 = int(np.round(alpha * h))
+ width2 = int(np.round(alpha * w))
+ if h > w:
+ if lower:
+ input_height = height2 // 32 * 32
+ input_width = (input_height * w) // h // 32 * 32
+ im_scale = input_width / w
+ else:
+ input_height = (height2 + 31) // 32 * 32
+ input_width = ((input_height * w + h - 1) // h +
+ 31) // 32 * 32
+ else:
+ if lower:
+ input_width = (width2) // 32 * 32
+ input_height = (input_width * h) // w // 32 * 32
+ im_scale = input_height / h
+ else:
+ input_width = (width2 + 31) // 32 * 32
+ input_height = ((input_width * h + w - 1) // w +
+ 31) // 32 * 32
+
+ im_resized = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,
+ interpolation=cv2.INTER_LINEAR)
+ if is_pil_image(im_resized):
+ new_w, new_h = im_resized.size
+ else:
+ new_h, new_w = im_resized.shape[0:2]
+ left = 0
+ right = input_width - new_w - left
+ top = 0
+ bottom = input_height - new_h - top
+ from .process_image import copy_make_border
+ im_squared = copy_make_border(im_resized, top=top,
+ bottom=bottom, left=left, right=right)
+ return im_squared, im_scale
+
+def smart_resize(im, target_size):
+ from .process_image import is_pil_image
+ if is_pil_image(im):
+ w, h = im.size
+ else:
+ h, w, c = im.shape
+ alpha = target_size / np.sqrt(h * w)
+ height2 = int(np.round(alpha * h))
+ width2 = int(np.round(alpha * w))
+ if h > w:
+ input_height = (height2 + 31) // 32 * 32
+ input_width = ((input_height * w + h - 1) // h +
+ 31) // 32 * 32
+ else:
+ input_width = (width2 + 31) // 32 * 32
+ input_height = ((input_width * h + w - 1) // w +
+ 31) // 32 * 32
+
+ if float(h) / input_height > float(w) / input_width:
+ rescale_size = input_height
+ else:
+ rescale_size = input_width
+ from .process_image import im_rescale
+ im_resized, im_scale = im_rescale(im, rescale_size)
+ if is_pil_image(im_resized):
+ new_w, new_h = im_resized.size
+ else:
+ new_h, new_w = im_resized.shape[0:2]
+ left = (input_width - new_w) // 2
+ right = input_width - new_w - left
+ top = (input_height - new_h) // 2
+ bottom = input_height - new_h - top
+ from .process_image import copy_make_border
+ im_squared = copy_make_border(im_resized, top=top,
+ bottom=bottom, left=left, right=right)
+ return im_squared, left, top, im_scale
+
+def kmeans(np_feature, k, seed=6):
+ from sklearn.preprocessing import normalize
+ from libKMCUDA import kmeans_cuda
+ np_feature = normalize(np_feature, axis=1)
+ init = 'kmeans++'
+ while True:
+ centroid, assignments = kmeans_cuda(np_feature,
+ k,
+ verbosity=1,
+ seed=seed,
+ device=1,
+ init=init,
+ metric='cos',
+ )
+ unique_assignment, cluster_count = np.unique(assignments, return_counts=True)
+ if len(unique_assignment) == k:
+ logging.info('reached non-empty')
+ break
+ num_new = k - len(unique_assignment)
+ logging.info('adding {}'.format(num_new))
+ new_from_cluster_idx = np.argsort(cluster_count)[-num_new:]
+ cluster_idx = unique_assignment[new_from_cluster_idx]
+ feat_idx = [np.where(assignments == i)[0] for i in cluster_idx]
+ feat_idx = np.concatenate(feat_idx)
+ np.random.seed(6)
+ feat_idx = np.random.permutation(feat_idx)
+ new_cluster = np_feature[feat_idx[:num_new]]
+ new_cluster_idx = 0
+ for c in range(len(centroid)):
+ if np.isnan(centroid[c][0]):
+ centroid[c] = new_cluster[new_cluster_idx]
+ new_cluster_idx += 1
+ assert new_cluster_idx == len(new_cluster)
+ init = centroid
+ return centroid, assignments
+
+def kmeans_pred_to_dataX(data, split, k, feature_fname, out_data,
+ num_kmeans=1):
+ out_dataset = TSVDataset(out_data)
+ if op.isfile(out_dataset.get_labelmap_file()) and \
+ op.isfile(out_dataset.get_data(split + 'X')):
+ return out_data
+ dataset = TSVDataset(data)
+ iter_label = dataset.iter_data(split, 'label')
+ iter_pred = tsv_reader(feature_fname)
+ np_feature = None
+ num_rows = dataset.num_rows(split)
+ for i, (label_row, pred_row) in tqdm(enumerate(zip(iter_label, iter_pred))):
+ assert label_row[0] == pred_row[0]
+ f = json.loads(pred_row[-1])[0]['feature']
+ if np_feature is None:
+ np_feature = np.zeros((num_rows, len(f)), dtype=np.float32)
+ np_feature[i] = f
+ # there are some issues with multi-gpu. Thus setting device=1 which means to use
+ # gpu 0
+ all_centroid, all_assignment = [], []
+ for i in range(num_kmeans):
+ centroid, assignments = kmeans(np_feature, k, seed=i + 9)
+ all_centroid.append(centroid)
+ all_assignment.append(assignments)
+ disk_assign = [int(i) for _, i in out_dataset.iter_data(split, 'label')]
+ for a, da in zip(assignments, disk_assign):
+ assert a == da
+ for i, centroid in zip(range(num_kmeans), all_centroid):
+ out_dataset.write_data(centroid, split, 'kmeans_center', version=i)
+ write_to_file(dataset.get_data(split),
+ out_dataset.get_data(split + 'X'))
+ tsv_writer(((0, i) for i in range(num_rows)),
+ out_dataset.get_shuffle_file(split))
+ if op.isfile(out_dataset.get_labelmap_file()):
+ labelmap = out_dataset.load_labelmap()
+ assert len(labelmap) == k
+ for i, l in enumerate(labelmap):
+ assert l == str(i)
+ else:
+ tsv_writer(((i,) for i in range(k)), out_dataset.get_labelmap_file())
+ iter_label = dataset.iter_data(split, 'label')
+ def gen_label():
+ for row in zip(iter_label, *all_assignment):
+ key = row[0][0]
+ label = '_'.join(map(str, [int(a) for a in row[1:]]))
+ yield key, json_dump([{'class': label}])
+ tsv_writer(gen_label(), out_dataset.get_data(split, 'label'))
+ tsv_writer([(feature_fname,)], out_dataset.get_data(split, 'feature_ptr'))
+ return out_data
+
+def create_compare_dataset(pred1, pred2, suffix1, suffix2, data, split, out_data):
+ out_dataset = TSVDataset(out_data)
+ dataset = TSVDataset(data)
+ tsv_writer([(dataset.get_data(split),)], out_dataset.get_data(split + 'X'))
+ tsv_writer(((0, i) for i in range(dataset.num_rows(split)) for _ in
+ range(2)),
+ out_dataset.get_shuffle_file(split))
+ iter_pred1 = tsv_reader(pred1)
+ iter_pred2 = tsv_reader(pred2)
+ iter_gt = dataset.iter_data(split, 'label')
+ def gen_label_rows():
+ for row_gt, row_pred1, row_pred2 in zip(iter_gt, iter_pred1, iter_pred2):
+ assert row_gt[0] == row_pred1[0] == row_pred2[0]
+ rects_pred1 = json.loads(row_pred1[1])
+ rects_pred1 = [r for r in rects_pred1 if r['conf'] > 0.2]
+ rects_pred2 = json.loads(row_pred2[1])
+ rects_pred2 = [r for r in rects_pred2 if r['conf'] > 0.2]
+ yield row_gt[0] + suffix1, json_dump(rects_pred1)
+ yield row_gt[0] + suffix2, json_dump(rects_pred2)
+ out_dataset.write_data(gen_label_rows(), split, 'label')
+ expand_nested_splitX(out_data, split)
+ populate_dataset_details(out_data)
+
+def duplicate_balance_fg_classes(
+ data, split, version,
+ bkg_class, fg_ratio, fg_rel_class_ratio, out_data):
+ # some recommendation: fg_ratio = 0.3
+ # fg_rel_class_ratio: 0.1
+ info = get_frame_info()
+ populate_dataset_details(data)
+ out_dataset = TSVDataset(out_data)
+ if op.isfile(out_dataset.get_labelmap_file()):
+ logging.info('{} exists'.format(out_dataset))
+ return
+ dataset = TSVDataset(data)
+
+ # {label: list_of_idx}
+ label_to_idx = dataset.load_inverted_label(split, version)
+ # the number of images with unknown categories
+ unknown_count = len(label_to_idx[bkg_class])
+ # total number of images with product categories
+ product_count = sum([len(idx) for l, idx in label_to_idx.items()
+ if l != bkg_class])
+ # current ratio
+ curr_ratio = 1. * product_count / (product_count + unknown_count)
+ # we need to duplicate product images by dup_factor times
+ dup_factor = int(math.ceil(fg_ratio / curr_ratio))
+ # duplicate operations by duplicating the index
+ dup_label_to_idx = {l: idx * dup_factor for l, idx in label_to_idx.items()
+ if l != bkg_class}
+ info['dup_factor'] = dup_factor
+ # calculate the average number of images for each category
+ avg_count = calc_mean([len(idx) for l, idx in dup_label_to_idx.items()])
+ # based on the parameters, each category should have at_least_count images.
+ at_least_count = int(avg_count * fg_rel_class_ratio)
+ for l, idx in dup_label_to_idx.items():
+ if len(idx) < at_least_count:
+ info[l] = (len(idx), at_least_count)
+ # duplicate the images by duplicating the index
+ dup_label_to_idx = {l: idx
+ if len(idx) >= at_least_count else idx * int(math.ceil(1. * at_least_count / len(idx)))
+ for l, idx in dup_label_to_idx.items()
+ }
+ # make the index as a list
+ final_idx = [i for _, idxs in dup_label_to_idx.items() for i in idxs]
+ final_idx.extend(label_to_idx[bkg_class])
+ # random shuffling
+ random.shuffle(final_idx)
+ # save it
+ tsv_writer(((0, i) for i in final_idx), out_dataset.get_shuffle_file(split))
+ assert op.isfile(dataset.get_data(split))
+ assert op.isfile(dataset.get_data(split, t='label', version=version))
+ tsv_writer([(dataset.get_data(split),)], out_dataset.get_data(split + 'X'))
+ tsv_writer([(dataset.get_data(split, t='label', version=version),)],
+ out_dataset.get_data(split + 'X', t='label'))
+ ensure_copy_file(dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file())
+ out_dataset.write_data(info.items(), split, t='generate_info')
+
+ populate_dataset_details(out_data)
+
+def split_dataset_one(
+ data, num_split, out_data,
+ split_type, split, version
+):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+ num_rows = dataset.num_rows(split, t=split_type, version=version)
+ each_size = (num_rows + num_split - 1) // num_split
+ shuffle = []
+ t_to_tsvs = defaultdict(list)
+ for i in range(num_split):
+ start = i * each_size
+ end = start + each_size
+ end = min(end, num_rows)
+ t = split_type
+ logging.info('split = {}; i = {}; t = {}'.format(
+ split, i, t))
+ def gen_rows():
+ for j, row in enumerate(dataset.iter_data(
+ split, t=t,
+ version=version,
+ filter_idx=range(start,
+ end),
+ progress=True)):
+ if t is None:
+ shuffle.append((i, j))
+ yield row
+ ssplit = '{}_{}_{}'.format(split, i, num_split)
+ if out_dataset.has(ssplit, t, version=version):
+ iter_in_file = out_dataset.iter_data(ssplit, t, version=version)
+ for in_file, curr in zip(iter_in_file, gen_rows()):
+ assert in_file == curr
+ else:
+ out_dataset.safe_write_data(
+ gen_rows(),
+ split=ssplit, t=t,
+ version=version)
+ t_to_tsvs[str(t)].append(out_dataset.get_data(ssplit, t, version))
+ if op.isfile(out_dataset.get_shuffle_file(split)):
+ iter_in_file = tsv_reader(out_dataset.get_shuffle_file(split))
+ for x, y in zip(iter_in_file, shuffle):
+ assert x == y
+ else:
+ tsv_writer(shuffle, out_dataset.get_shuffle_file(split))
+ t = split_type
+ split_x = '{}X'.format(split)
+ target_file = out_dataset.get_data(split_x, t=t, version=version)
+ if op.isfile(target_file):
+ assert '\n'.join(t_to_tsvs[str(t)]) == read_to_buffer(target_file).decode()
+ else:
+ write_to_file('\n'.join(t_to_tsvs[str(t)]), target_file)
+ ensure_copy_file(dataset.get_labelmap_file(), out_dataset.get_labelmap_file())
+
+def split_dataset(
+ data, num_split, out_data,
+ split_types=(None, 'label', 'hw', 'caption'),
+ splits=('train', 'trainval', 'test'),
+):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+ for split in splits:
+ num_rows = dataset.num_rows(split)
+ each_size = (num_rows + num_split - 1) // num_split
+ shuffle = []
+ t_to_tsvs = defaultdict(list)
+ for i in range(num_split):
+ start = i * each_size
+ end = start + each_size
+ end = min(end, num_rows)
+ for t in split_types:
+ logging.info('split = {}; i = {}; t = {}'.format(
+ split, i, t))
+ def gen_rows():
+ for j, row in enumerate(dataset.iter_data(
+ split, t=t,
+ filter_idx=range(start,
+ end),
+ progress=True)):
+ if t is None:
+ shuffle.append((i, j))
+ yield row
+ ssplit = '{}_{}_{}'.format(split, i, num_split)
+ if out_dataset.has(ssplit, t):
+ iter_in_file = out_dataset.iter_data(ssplit, t)
+ for in_file, curr in zip(iter_in_file, gen_rows()):
+ assert in_file == curr
+ else:
+ out_dataset.write_data(gen_rows(), split=ssplit, t=t)
+ t_to_tsvs[str(t)].append(out_dataset.get_data(ssplit, t))
+ if op.isfile(out_dataset.get_shuffle_file(split)):
+ iter_in_file = tsv_reader(out_dataset.get_shuffle_file(split))
+ for x, y in zip(iter_in_file, shuffle):
+ assert x == y
+ else:
+ tsv_writer(shuffle, out_dataset.get_shuffle_file(split))
+ for t in split_types:
+ split_x = '{}X'.format(split)
+ target_file = out_dataset.get_data(split_x, t=t)
+ if op.isfile(target_file):
+ assert '\n'.join(t_to_tsvs[str(t)]) == read_to_buffer(target_file).decode()
+ else:
+ write_to_file('\n'.join(t_to_tsvs[str(t)]), target_file)
+ ensure_copy_file(dataset.get_labelmap_file(), out_dataset.get_labelmap_file())
+
+def merge_dataset_parallel(*args, **kwargs):
+ merge_dataset(*args, **kwargs)
+
+#@deprecated('use merge_dataset_parallel')
+#def merge_dataset(source_infos, target_info, ps):
+ #target_dataset = TSVDataset(target_info['data'])
+ #for p in ps:
+ #tsv_list = []
+ #for source in source_infos:
+ #dataset = TSVDataset(source['data'])
+ #if 'version_info' in source and p['type'] in source['version_info']:
+ #version = source['version_info'][p['type']]
+ #elif 'version' in p:
+ #version = p['version']
+ #else:
+ #version = None
+ #tsv_file = dataset.get_data(source['split'], t=p['type'],
+ #version=version)
+ #if op.isfile(tsv_file):
+ #tsv_list.append(tsv_file)
+ #else:
+ #tsv_x = dataset.get_data(source['split'] + 'X', t=p['type'],
+ #version=version)
+ #curr_list = load_list_file(tsv_x)
+ #curr_shuffle = dataset.get_shuffle_file(source['split'])
+ #logging.info('loading {}'.format(curr_shuffle))
+ #tsv_list.extend(curr_list)
+ #out_tsvx = target_dataset.get_data(
+ #target_info['split'] + 'X', p['type'],
+ #version=target_info.get('version'))
+ #if not op.isfile(out_tsvx):
+ #write_to_file('\n'.join(tsv_list), out_tsvx)
+ #else:
+ #es = load_list_file(out_tsvx)
+ #assert len(tsv_list) == len(es)
+ #for e, c in zip(es, tsv_list):
+ #assert e == c, (e, c)
+
+ #for p in ps:
+ #if p.get('type') is not None:
+ #continue
+ #tsv_list = []
+ #def gen_shuffle():
+ #for source in source_infos:
+ #dataset = TSVDataset(source['data'])
+ #if 'version_info' in source and p['type'] in source['version_info']:
+ #version = source['version_info'][p['type']]
+ #elif 'version' in p:
+ #version = p['version']
+ #else:
+ #version = None
+ #tsv_file = dataset.get_data(source['split'], t=p['type'],
+ #version=version)
+ #tsv_offset = len(tsv_list)
+ #if op.isfile(tsv_file):
+ #num = dataset.num_rows(source['split'])
+ #for i in range(num):
+ #yield tsv_offset, i
+ #tsv_list.append(tsv_file)
+ #else:
+ #tsv_x = dataset.get_data(source['split'] + 'X', t=p['type'],
+ #version=version)
+ #curr_list = load_list_file(tsv_x)
+ #curr_shuffle = dataset.get_shuffle_file(source['split'])
+ #logging.info('loading {}'.format(curr_shuffle))
+ #for i, j in tqdm(tsv_reader(curr_shuffle)):
+ #yield int(i) + tsv_offset, j
+ #tsv_list.extend(curr_list)
+ #shuffle_f = target_dataset.get_shuffle_file(target_info['split'])
+ #if not op.isfile(shuffle_f):
+ #tsv_writer(gen_shuffle(), shuffle_f)
+ #else:
+ #for in_file, curr in zip(tsv_reader(shuffle_f), gen_shuffle()):
+ #assert in_file[0] == str(curr[0])
+ #assert in_file[1] == str(curr[1])
+
+
+
+#@deprecated('try to switch to merge_dataset2, tested once')
+#def merge_dataset(source_infos, target_info, ps):
+ #target_dataset = TSVDataset(target_info['data'])
+ #for p in ps:
+ #tsv_list = []
+ #shuffle = []
+ #for source in source_infos:
+ #dataset = TSVDataset(source['data'])
+ #if 'version_info' in source and p['type'] in source['version_info']:
+ #version = source['version_info'][p['type']]
+ #elif 'version' in p:
+ #version = p['version']
+ #else:
+ #version = None
+ #tsv_file = dataset.get_data(source['split'], t=p['type'],
+ #version=version)
+ #tsv_offset = len(tsv_list)
+ #if op.isfile(tsv_file):
+ #num = dataset.num_rows(source['split'])
+ #shuffle.extend([(tsv_offset, i) for i in range(num)])
+ #tsv_list.append(tsv_file)
+ #else:
+ #tsv_x = dataset.get_data(source['split'] + 'X', t=p['type'],
+ #version=version)
+ #curr_list = load_list_file(tsv_x)
+ #curr_shuffle = dataset.get_shuffle_file(source['split'])
+ #logging.info('loading {}'.format(curr_shuffle))
+ #shuffle.extend([(int(i) + tsv_offset, j) for i, j in
+ #tqdm(tsv_reader(curr_shuffle))])
+ #tsv_list.extend(curr_list)
+ #out_tsvx = target_dataset.get_data(
+ #target_info['split'] + 'X', p['type'],
+ #version=target_info.get('version'))
+ #if not op.isfile(out_tsvx):
+ #write_to_file('\n'.join(tsv_list), out_tsvx)
+ #else:
+ #es = load_list_file(out_tsvx)
+ #assert len(tsv_list) == len(es)
+ #for e, c in zip(es, tsv_list):
+ #assert e == c, (e, c)
+ #if p.get('type') is None:
+ #shuffle_f = target_dataset.get_shuffle_file(target_info['split'])
+ #if not op.isfile(shuffle_f):
+ #tsv_writer(shuffle, shuffle_f)
+ #else:
+ #for in_file, curr in zip(tsv_reader(shuffle_f), shuffle):
+ #assert in_file[0] == str(curr[0])
+ #assert in_file[1] == str(curr[1])
+
+ ## labelmap
+ ##target_labelmap = target_dataset.get_labelmap_file()
+ ##lss = [TSVDataset(source['data']).load_labelmap() for source in source_infos]
+ ##labelmap = list(set([l for ls in lss for l in ls]))
+ ##labelmap = sorted(labelmap)
+ ##if not op.isfile(target_labelmap):
+ ##write_to_file('\n'.join(labelmap), target_labelmap)
+ ##else:
+ ##existing = load_list_file(target_labelmap)
+ ##assert len(existing) == len(labelmap)
+ ##for e, l in zip(existing, labelmap):
+ ##assert e == l
+
+def merge_dataset_row_processor(row, offset):
+ i, j = row
+ return int(i) + offset, j
+
+def merge_dataset(source_infos, target_info, ps):
+ target_dataset = TSVDataset(target_info['data'])
+ for p in ps:
+ tsv_list = []
+ for source in source_infos:
+ dataset = TSVDataset(source['data'])
+ if 'version_info' in source and p['type'] in source['version_info']:
+ version = source['version_info'][p['type']]
+ elif 'version' in p:
+ version = p['version']
+ else:
+ version = None
+ tsv_file = dataset.get_data(source['split'], t=p['type'],
+ version=version)
+ if File.isfile(tsv_file):
+ tsv_list.append(tsv_file)
+ else:
+ tsv_x = dataset.get_data(source['split'] + 'X', t=p['type'],
+ version=version)
+ curr_list = load_list_file(tsv_x)
+ curr_shuffle = dataset.get_shuffle_file(source['split'])
+ logging.info('loading {}'.format(curr_shuffle))
+ tsv_list.extend(curr_list)
+ out_tsvx = target_dataset.get_data(
+ target_info['split'] + 'X', p['type'],
+ version=target_info.get('version'))
+ if not File.isfile(out_tsvx):
+ tsv_writer(((_t, ) for _t in tsv_list), out_tsvx)
+ #write_to_file('\n'.join(tsv_list), out_tsvx)
+ else:
+ es = load_list_file(out_tsvx)
+ assert len(tsv_list) == len(es)
+ for e, c in zip(es, tsv_list):
+ assert e == c, (e, c)
+
+ all_num_tsv = []
+ for source in source_infos:
+ dataset = TSVDataset(source['data'])
+ curr_shuffle = dataset.get_shuffle_file(source['split'])
+ if File.isfile(curr_shuffle):
+ tsv_x = dataset.get_data(source['split'] + 'X', t=p['type'],
+ version=version)
+ curr_list = load_list_file(tsv_x)
+ all_num_tsv.append(len(curr_list))
+ else:
+ assert File.isfile(dataset.get_data(source['split']))
+ all_num_tsv.append(1)
+
+ s = 0
+ tsv_offset = [0]
+ for n in all_num_tsv[:-1]:
+ s += n
+ tsv_offset.append(s)
+
+ all_shuffle = []
+ target_shuffle = target_dataset.get_shuffle_file(target_info['split'])
+ folder = get_tmp_folder()
+ for idxsource, source in enumerate(source_infos):
+ dataset = TSVDataset(source['data'])
+ out_shuffle = op.join(folder,
+ '{}'.format(target_shuffle) +
+ '.{}.{}.tsv'.format(idxsource, len(source_infos)),
+ )
+ src_shuffle_tsv = dataset.get_shuffle_file(source['split'])
+ parallel_tsv_process(lambda row: merge_dataset_row_processor(row, tsv_offset[idxsource]),
+ src_shuffle_tsv,
+ out_shuffle,
+ 64,
+ )
+ all_shuffle.append(out_shuffle)
+ concat_tsv_files(all_shuffle,
+ target_dataset.get_shuffle_file(target_info['split']),
+ gen_lineidx=False
+ )
+ delete_tsv_files(all_shuffle)
+
+def tuple_merge_pred_label_to_gt(x):
+ pred, data, split, in_version, out_version = x
+ merge_pred_label_to_gt(pred, data, split, in_version, out_version)
+
+def merge_pred_label_to_gt(pred, data, split, in_version, out_version):
+ dataset = TSVDataset(data)
+ def gen_rows():
+ iter_pred = tsv_reader(pred)
+ iter_gt = dataset.iter_data(split, 'label', version=in_version)
+ for row_pred, row_gt in tqdm(zip(iter_pred, iter_gt)):
+ assert row_pred[0] == row_gt[0]
+ pred_rects = json.loads(row_pred[1])
+ gt = json.loads(row_gt[1])
+ for p in pred_rects:
+ if 'zlib_feature' in p:
+ del p['zlib_feature']
+ if 'attr_labels' in p:
+ del p['attr_labels']
+ if 'attr_scores' in p:
+ del p['attr_scores']
+ gt.extend(pred_rects)
+ yield row_pred[0], json_dump(gt)
+ #assert not dataset.has(split, 'label', version=out_version)
+ dataset.write_data(gen_rows(), split, 'label', version=out_version)
+
+def generate_caption_linelist(data, split, version=None):
+ dataset = TSVDataset(data)
+ if not dataset.has(split, 'caption', version=None):
+ logging.info('caption does not exist')
+ return
+ iter_caption = dataset.iter_data(split, 'caption', version=version)
+ iter_shuffle = tsv_reader(dataset.get_shuffle_file(split))
+
+ def gen_rows():
+ for (idx_source, idx_row), (key, s) in tqdm(zip(iter_shuffle,
+ iter_caption)):
+ cs = json.loads(s)
+ for idx_caption in range(len(cs)):
+ yield idx_source, idx_row, idx_caption
+ if not dataset.has(split, 'caption_linelist', version=version):
+ dataset.safe_write_data(gen_rows(), split, 'caption_linelist',
+ version=version)
+
+def generate_key_idximage_idxcaption_from_num(data, split, version):
+ dataset = TSVDataset(data)
+ if not dataset.has(split, 'caption', version):
+ logging.info('ignore to generate as caption file does not exist')
+ return
+ iter_caption = dataset.iter_data(split, 'num_caption', version=version)
+
+ def gen_rows():
+ for idx_img, (key, n) in tqdm(enumerate(iter_caption)):
+ n = int(n)
+ for i in range(n):
+ yield key, idx_img, i
+
+ t = 'key_idximage_idxcaption'
+ if not dataset.has(split, t, version=version):
+ dataset.write_data(gen_rows(), split, t, version=version)
+
+def derive_key_idximage_idxcaption_from_merge_dataset(source_infos, target_info):
+ for s in source_infos:
+ assert s.get('version_info') is None
+ generate_key_idximage_idxcaption(s['data'], s['split'])
+
+ split = target_info['split']
+ def gen_rows():
+ offset = 0
+ for s in source_infos:
+ dataset = TSVDataset(s['data'])
+ for key, idximage, idxcaption in dataset.iter_data(s['split'],
+ t='key_idximage_idxcaption'):
+ yield key, int(idximage) + offset, idxcaption
+ added = False
+ for t in [None, 'caption', 'hw']:
+ if dataset.has(s['split'], t):
+ offset += dataset.num_rows(s['split'])
+ added = True
+ break
+ assert added
+ data = target_info['data']
+ out = TSVDataset(data)
+ if not out.has(split, 'key_idximage_idxcaption'):
+ out.write_data(gen_rows(), split, t='key_idximage_idxcaption')
+
+def derive_key_idximage_idxcaption_from_merge_dataset_parallel_multi_source(source_infos, target_info):
+ for s in source_infos:
+ assert s.get('version_info') is None
+ generate_key_idximage_idxcaption(s['data'], s['split'])
+
+ out = TSVDataset(target_info['data'])
+ if out.has(target_info['split'], 'key_idximage_idxcaption'):
+ return
+
+ all_size = [len(TSVSplitProperty(s['data'], s['split'], 'caption')) for s in
+ source_infos]
+ cum_size = 0
+ all_offset = [cum_size]
+ for s in all_size[:-1]:
+ cum_size += s
+ all_offset.append(cum_size)
+
+ in_tsvs = list(zip(all_offset, source_infos))
+ from .cloud_storage import create_cloud_fuse
+ c = create_cloud_fuse()
+ tsvs = [TSVDataset(s['data']).get_data(s['split'], 'key_idximage_idxcaption') for s
+ in source_infos]
+ c.ensure_cache(tsvs)
+ c.ensure_cache([get_tsv_associates(t)[0] for t in tsvs])
+
+ def row_processor(row):
+ offset, s = row
+ for key, idximage, idxcaption in TSVSplitProperty(s['data'],
+ s['split'],
+ 'key_idximage_idxcaption'):
+ yield key, int(idximage) + offset, idxcaption
+ out_tsv = out.get_data(target_info['split'], 'key_idximage_idxcaption')
+ parallel_tsv_process(
+ row_processor,
+ in_tsvs,
+ out_tsv,
+ 64
+ )
+
+def derive_key_idximage_idxcaption_from_merge_dataset_parallel_each(source_infos, target_info):
+ for s in source_infos:
+ assert s.get('version_info') is None
+ generate_key_idximage_idxcaption(s['data'], s['split'])
+
+ out = TSVDataset(target_info['data'])
+ if out.has(target_info['split'], 'key_idximage_idxcaption'):
+ return
+
+ all_size = [len(TSVSplitProperty(s['data'], s['split'], 'caption')) for s in
+ source_infos]
+ cum_size = 0
+ all_offset = [cum_size]
+ for s in all_size[:-1]:
+ cum_size += s
+ all_offset.append(cum_size)
+
+ from .cloud_storage import create_cloud_fuse
+ c = create_cloud_fuse()
+ tsvs = [TSVDataset(s['data']).get_data(s['split'], 'key_idximage_idxcaption') for s
+ in source_infos]
+ c.ensure_cache(tsvs)
+ c.ensure_cache([get_tsv_associates(t)[0] for t in tsvs])
+
+ tmp_folder = get_tmp_folder()
+ out_tsv = out.get_data(target_info['split'], 'key_idximage_idxcaption')
+ all_tmp = []
+ for offset, s in zip(all_offset, source_infos):
+ curr_in_tsv = TSVDataset(s['data']).get_data(s['split'], 'key_idximage_idxcaption')
+ curr_out_tsv = op.join(tmp_folder, out_tsv + f'.{offset}.tsv')
+
+ def row_processor(row):
+ key, idximage, idxcaption = row
+ return key, int(idximage) + offset, idxcaption
+ parallel_tsv_process(
+ row_processor,
+ curr_in_tsv,
+ curr_out_tsv,
+ 64
+ )
+ all_tmp.append(curr_out_tsv)
+ concat_tsv_files(all_tmp, out_tsv, gen_lineidx=False)
+ delete_tsv_files(all_tmp)
+
+def derive_key_idximage_idxcaption_idxsource_from_merge_dataset_parallel_multi_source(source_infos, target_info):
+ for s in source_infos:
+ assert s.get('version_info') is None
+ generate_key_idximage_idxcaption_idxsource(s['data'], s['split'])
+
+ out = TSVDataset(target_info['data'])
+ if out.has(target_info['split'], 'key_idximage_idxcaption_idxsource'):
+ return
+
+ all_size = [len(TSVSplitProperty(s['data'], s['split'], 'caption')) for s in
+ source_infos]
+ cum_size = 0
+ all_img_offset = [cum_size]
+ for s in all_size[:-1]:
+ cum_size += s
+ all_img_offset.append(cum_size)
+
+ all_source_offset = [0]
+ cum = 0
+ for s in source_infos[:-1]:
+ curr_dataset = TSVDataset(s['data'])
+ if File.isfile(curr_dataset.get_data(s['split'])):
+ num = 1
+ else:
+ num = len(load_list_file(curr_dataset.get_data(s['split'] + 'X')))
+ cum += num
+ all_source_offset.append(cum)
+
+ in_tsvs = list(zip(all_img_offset, all_source_offset, source_infos))
+ from .cloud_storage import create_cloud_fuse
+ c = create_cloud_fuse()
+ tsvs = [TSVDataset(s['data']).get_data(s['split'],
+ 'key_idximage_idxcaption_idxsource') for s
+ in source_infos]
+ c.ensure_cache(tsvs)
+ c.ensure_cache([get_tsv_associates(t)[0] for t in tsvs])
+
+ def row_processor(row):
+ img_offset, source_offset, s = row
+ for idxsource, in TSVSplitProperty(s['data'], s['split'], 'key_idximage_idxcaption_idxsource'):
+ yield int(idxsource) + source_offset,
+ out_tsv = out.get_data(target_info['split'], 'key_idximage_idxcaption_idxsource')
+ parallel_tsv_process(row_processor, in_tsvs, out_tsv, 64)
+
+def derive_key_idximage_idxcaption_idxsource_from_merge_dataset_parallel_each_source(source_infos, target_info):
+ for s in source_infos:
+ assert s.get('version_info') is None
+ generate_key_idximage_idxcaption_idxsource(s['data'], s['split'])
+
+ out = TSVDataset(target_info['data'])
+ if out.has(target_info['split'], 'key_idximage_idxcaption_idxsource'):
+ return
+
+ all_size = [len(TSVSplitProperty(s['data'], s['split'], 'caption')) for s in
+ source_infos]
+ cum_size = 0
+ all_img_offset = [cum_size]
+ for s in all_size[:-1]:
+ cum_size += s
+ all_img_offset.append(cum_size)
+
+ all_source_offset = [0]
+ cum = 0
+ for s in source_infos[:-1]:
+ curr_dataset = TSVDataset(s['data'])
+ if File.isfile(curr_dataset.get_data(s['split'])):
+ num = 1
+ else:
+ num = len(load_list_file(curr_dataset.get_data(s['split'] + 'X')))
+ cum += num
+ all_source_offset.append(cum)
+
+ c = create_cloud_fuse()
+ tsvs = [TSVDataset(s['data']).get_data(s['split'],
+ 'key_idximage_idxcaption_idxsource') for s
+ in source_infos]
+ c.ensure_cache(tsvs)
+ c.ensure_cache([get_tsv_associates(t)[0] for t in tsvs])
+
+ out_tsv = out.get_data(target_info['split'], 'key_idximage_idxcaption_idxsource')
+
+ tmp_folder = get_tmp_folder()
+ all_tmp = []
+ for img_offset, source_offset, s in zip(all_img_offset, all_source_offset, source_infos):
+ def row_processor(row):
+ idxsource, = row
+ return int(idxsource) + source_offset,
+ in_tsv = TSVDataset(s['data']).get_data(s['split'], 'key_idximage_idxcaption_idxsource')
+ curr_out = '{}/{}'.format(tmp_folder, out_tsv + '.{}.tsv'.format(img_offset))
+ parallel_tsv_process(row_processor, in_tsv, curr_out, 64)
+ all_tmp.append(curr_out)
+ concat_tsv_files(all_tmp, out_tsv, gen_lineidx=False)
+ delete_tsv_files(all_tmp)
+
+def assert_dataset_each_length_same(data):
+ dataset = TSVDataset(data)
+ img_tsvs = load_list_file(dataset.get_data('trainX'))
+ cap_tsvs = load_list_file(dataset.get_data('trainX', 'caption'))
+ assert len(img_tsvs) == len(cap_tsvs)
+ #c = create_cloud_fuse()
+ #c.ensure_cache(fs)
+ for i, c in tqdm(zip(img_tsvs, cap_tsvs)):
+ assert len(TSVFile(i)) == len(TSVFile(c)), (i, c)
+
+
+def generate_key_idximage_idxcaption(data, split, version=None):
+ dataset = TSVDataset(data)
+ if not dataset.has(split, 'caption', version):
+ logging.info('ignore to generate as caption file does not exist')
+ return
+ #from qd.data_layer.loader import iter_data_loader
+ #iter_caption = iter_data_loader(
+ #data, split, 'caption', version=version,
+ #transform=lambda x: (x[0], json.loads(x[1])),
+ #num_workers=8,
+ #)
+ info = defaultdict(int)
+ def row_processor(row, idx_img):
+ key, s = row
+ try:
+ cs = json.loads(s)
+ except:
+ logging.info('{}/{}'.format(s, idx_img))
+ raise
+ for i in range(len(cs)):
+ if ('caption' in cs[i] and isinstance(cs[i]['caption'], str)) or ('caption' not in cs[i]):
+ yield (key, idx_img, i)
+ info['valid'] += 1
+ else:
+ info['non_str_caption'] += 1
+
+ t = 'key_idximage_idxcaption'
+ if not dataset.has(split, t, version=version):
+ tsv = TSVSplitProperty(data=data, split=split, t='caption', version=version)
+ fs = dataset.get_data(split + 'X', 'caption', version=version)
+ if File.isfile(fs):
+ tsvs = load_list_file(fs)
+ File.prepare(tsvs)
+ File.prepare([get_tsv_associates(t)[0] for t in tsvs])
+ parallel_tsv_process(
+ row_processor,
+ tsv,
+ dataset.get_data(split, t, version=version),
+ 64,
+ with_row_idx=True
+ )
+ logging.info(info)
+
+def generate_idximage_idxcaption(
+ data, split, version=None):
+ dataset = TSVDataset(data)
+ if not dataset.has(split, 'caption', version):
+ logging.info('ignore to generate as caption file does not exist')
+ return
+ info = defaultdict(int)
+ def row_processor(row, idx_img):
+ key, s = row
+ cs = json.loads(s)
+ for i in range(len(cs)):
+ if ('caption' in cs[i] and isinstance(cs[i]['caption'], str)) or ('caption' not in cs[i]):
+ yield idx_img, i
+ info['valid'] += 1
+ else:
+ info['non_str_caption'] += 1
+
+ t = 'idximage_idxcaption'
+ if not dataset.has(split, t, version=version):
+ tsv = TSVSplitProperty(data=data, split=split, t='caption', version=version)
+ c = create_cloud_fuse()
+ fs = dataset.get_data(split + 'X', 'caption', version=version)
+ if File.isfile(fs):
+ tsvs = load_list_file(fs)
+ c.ensure_cache(tsvs)
+ c.ensure_cache([get_tsv_associates(t)[0] for t in tsvs])
+ parallel_tsv_process(
+ row_processor,
+ tsv,
+ dataset.get_data(split, t, version=version),
+ 64,
+ with_row_idx=True
+ )
+ logging.info(info)
+
+@deprecated('use generate_idximage_idxcaption')
+def generate_idximage_idxcaption_parallel(*args, **kwargs):
+ generate_idximage_idxcaption(*args, **kwargs)
+
+#def generate_key_idximage_idxcaption(data, split, version=None):
+ #dataset = TSVDataset(data)
+ #if not dataset.has(split, 'caption', version):
+ #logging.info('ignore to generate as caption file does not exist')
+ #return
+ ##from qd.data_layer.loader import iter_data_loader
+ ##iter_caption = iter_data_loader(
+ ##data, split, 'caption', version=version,
+ ##transform=lambda x: (x[0], json.loads(x[1])),
+ ##num_workers=8,
+ ##)
+ #info = defaultdict(int)
+ #def gen_rows():
+ ##iter_caption = dataset.iter_data(split, 'caption', version=version)
+ ##total = dataset.num_rows(split, 'caption')
+ #iter_caption = TSVSplitProperty(data=data, split=split, t='caption', version=version)
+ ##for idx_img, (key, s) in tqdm(enumerate(iter_caption), total=total):
+ #for idx_img, (key, s) in tqdm(enumerate(iter_caption)):
+ #cs = json.loads(s)
+ #for i in range(len(cs)):
+ #if ('caption' in cs[i] and isinstance(cs[i]['caption'], str)) or ('caption' not in cs[i]):
+ #yield key, idx_img, i
+ #info['valid'] += 1
+ #else:
+ #info['non_str_caption'] += 1
+
+ #t = 'key_idximage_idxcaption'
+ #if not dataset.has(split, t, version=version):
+ #dataset.write_data(gen_rows(), split, t, version=version)
+ #logging.info(info)
+
+def generate_idximage_idxcaption_from_with_key(data, split, version=None):
+ dataset = TSVDataset(data)
+ def gen_rows():
+ #iter_caption = dataset.iter_data(split, 'caption', version=version)
+ #total = dataset.num_rows(split, 'caption')
+ iter_old = TSVSplitProperty(data=data, split=split, t='key_idximage_idxcaption', version=version)
+ #for idx_img, (key, s) in tqdm(enumerate(iter_caption), total=total):
+ for key, idximage, idxcaption in tqdm(iter_old):
+ yield idximage, idxcaption
+
+ t = 'idximage_idxcaption'
+ if not dataset.has(split, t, version=version):
+ dataset.write_data(gen_rows(), split, t, version=version)
+
+
+#def generate_idximage_idxcaption(data, split, version=None):
+ #dataset = TSVDataset(data)
+ #if not dataset.has(split, 'caption', version):
+ #logging.info('ignore to generate as caption file does not exist')
+ #return
+ ##from qd.data_layer.loader import iter_data_loader
+ ##iter_caption = iter_data_loader(
+ ##data, split, 'caption', version=version,
+ ##transform=lambda x: (x[0], json.loads(x[1])),
+ ##num_workers=8,
+ ##)
+ #info = defaultdict(int)
+ #def gen_rows():
+ ##iter_caption = dataset.iter_data(split, 'caption', version=version)
+ ##total = dataset.num_rows(split, 'caption')
+ #iter_caption = TSVSplitProperty(data=data, split=split, t='caption', version=version)
+ ##for idx_img, (key, s) in tqdm(enumerate(iter_caption), total=total):
+ #for idx_img, (key, s) in tqdm(enumerate(iter_caption)):
+ #cs = json.loads(s)
+ #for i in range(len(cs)):
+ #if ('caption' in cs[i] and isinstance(cs[i]['caption'], str)) or ('caption' not in cs[i]):
+ #yield idx_img, i
+ #info['valid'] += 1
+ #else:
+ #info['non_str_caption'] += 1
+
+ #t = 'idximage_idxcaption'
+ #if not dataset.has(split, t, version=version):
+ #dataset.write_data(gen_rows(), split, t, version=version)
+ #logging.info(info)
+
+def generate_num_caption(data, split, version=None):
+ dataset = TSVDataset(data)
+ if not dataset.has(split, 'caption', version):
+ logging.info('ignore to generate as caption file does not exist')
+ return
+ iter_caption = dataset.iter_data(split, 'caption', version=version)
+
+ def gen_rows():
+ for (key, s) in tqdm(iter_caption):
+ cs = json.loads(s)
+ yield key, len(cs)
+
+ if not dataset.has(split, 'num_caption', version=version):
+ dataset.write_data(gen_rows(), split, 'num_caption', version=version)
+
+def create_n_class_label(data_sources, out_data, out_split):
+ frame_info = get_frame_info()
+ out_dataset = TSVDataset(out_data)
+ if out_dataset.has(out_split, 'label'):
+ logging.info('skip for {}'.format(pformat(frame_info)))
+ return
+ all_ds = []
+ for ds in data_sources:
+ expand = ds.get('expand')
+ if expand:
+ curr_dataset = TSVDataset(ds['data'])
+ data_splits = curr_dataset.load_composite_source_data_split(
+ ds['split'])
+ for d, s in data_splits:
+ all_ds.append({'data': d, 'split': s, 'version': ds['version']})
+ else:
+ # in expand, we only support data/split/version. If we add other property, we should also update this code
+ assert len(ds) == 3
+ assert all(k in ds for k in ['data', 'split', 'version'])
+ all_ds.append(ds)
+ data_sources = all_ds
+ # with expand, data_sources will be different. We save this information
+ frame_info['data_sources'] = data_sources
+
+ def gen_rows():
+ for idx_source, data_source in enumerate(data_sources):
+ curr_dataset = TSVDataset(data_source['data'])
+ iter_label = curr_dataset.iter_data(
+ data_source['split'],
+ 'label',
+ version=data_source['version'],
+ )
+ total = curr_dataset.num_rows(data_source['split'])
+ for i, (key, str_rects) in tqdm(enumerate(iter_label), total=total):
+ rects = json.loads(str_rects)
+ if isinstance(rects, int):
+ rects = [{'class': str(rects)}]
+ if len(rects) == 0:
+ continue
+ for r in rects:
+ if '$' not in r['class']:
+ if not r['class'].startswith('-'):
+ r['class'] = '$'.join([data_source['data'], r['class']])
+ else:
+ r['class'] = '$'.join([data_source['data'], r['class'][1:]])
+ r['class'] = '-{}'.format(r['class'])
+ yield (key, json_dump(rects)), (idx_source, i)
+ def gen_info():
+ yield 'create_n_classs_label',
+ ps = dict_get_all_path(frame_info)
+ for p in ps:
+ v = dict_get_path_value(frame_info, p)
+ yield p, v
+
+ label_file = out_dataset.get_data(out_split, 'label')
+ shuffle_file = out_dataset.get_shuffle_file(out_split)
+ if not op.isfile(label_file):
+ tsv_writers(gen_rows(), (label_file, shuffle_file))
+ gen_tsv = out_dataset.get_gen_info_data(out_split, 'label')
+ tsv_writer(gen_info(), gen_tsv)
+ labelmap = []
+ #domain_info = []
+ for ds_data in set(d['data'] for d in data_sources):
+ curr_labelmap = TSVDataset(ds_data).load_labelmap()
+ labelmap.extend(['{}${}'.format(
+ ds_data, l) for l in curr_labelmap])
+ #domain_info.append({'data': ds_data, 'labelmap': curr_labelmap})
+ write_to_file('\n'.join(set(labelmap)), out_dataset.get_labelmap_file())
+ #write_to_yaml_file(domain_info, out_dataset.get_file('domainmap.yaml'))
+ image_tsvs = [TSVDataset(source['data']).get_data(source['split']) for source in
+ data_sources]
+ write_to_file('\n'.join(image_tsvs), out_dataset.get_data(out_split + 'X'))
+ expand_nested_splitX(out_data, out_split)
+
+def merge_prediction_to_data(
+ data, split, in_version, predict_file, conf_th, out_version,
+ merge_colocated_iou=0.8,
+):
+ frame_info = get_frame_info()
+ dataset = TSVDataset(data)
+ assert dataset.has(split, 'label', version=in_version), (
+ dataset, split, in_version
+ )
+ if dataset.has(split, 'label', version=out_version):
+ logging.info('out version esists {}'.format(out_version))
+ return
+ iter_gt = dataset.iter_data(split, 'label', version=in_version)
+ info = defaultdict(int)
+ def gen_rows():
+ debug = False
+ iter_pred = tsv_reader(predict_file)
+ for i, (row_gt, row_pred) in tqdm(enumerate(
+ zip(iter_gt, iter_pred))):
+ key = row_gt[0]
+ assert row_pred[0] == key
+ gt = json.loads(row_gt[1])
+ pred = json.loads(row_pred[1])
+ pred = [p for p in pred if p['conf'] >= conf_th]
+ if debug:
+ origin_gt = copy.deepcopy(gt)
+ extra = []
+ info['num_label_pre'] += len(gt)
+ for g in gt:
+ if 'location_id' not in g:
+ g['location_id'] = hash_sha1(g['rect'])
+ for p in pred:
+ if 'location_id' not in p:
+ p['location_id'] = hash_sha1(p['rect'])
+ for p in pred:
+ idx, iou = find_best_matched_rect_idx(p, gt, check_class=False)
+ if iou >= merge_colocated_iou:
+ p['rect'] = gt[idx]['rect']
+ p['location_id'] = gt[idx]['location_id']
+ info['merge_colocated'] += 1
+ p['predict_file'] = predict_file
+ info['added'] += 1
+ if debug:
+ extra.append(p)
+ gt.append(p)
+ if debug and len(extra) > 0:
+ logging.info('debugging')
+ im = img_from_base64(dataset.seek_by_idx(i, split='train')[-1])
+ im_gt = im.copy()
+ draw_rects(origin_gt, im_gt)
+ im_extra = im.copy()
+ draw_rects(extra, im_extra)
+ save_image(np.concatenate((im_gt, im_extra)),
+ '/mnt/gpu02_raid/jianfw/work/tmp9/{}.jpg'.format(key))
+ info['num_label_after'] += len(gt)
+ yield key, json_dump(gt)
+ def gen_info():
+ for k, v in frame_info.items():
+ yield k, v
+ for k, v in info.items():
+ yield k, v
+ dataset.write_data(gen_rows(), split, 'label', version=out_version,
+ generate_info=gen_info())
+ logging.info(pformat(info))
+
+def create_1_class_label(data_sources, out_data, out_split,
+ cls_name):
+ frame_info = get_frame_info()
+ out_dataset = TSVDataset(out_data)
+ if out_dataset.has(out_split, 'label'):
+ logging.info('skip for {}'.format(pformat(frame_info)))
+ return
+ def gen_rows():
+ for idx_source, data_source in enumerate(data_sources):
+ curr_dataset = TSVDataset(data_source['data'])
+ iter_label = curr_dataset.iter_data(
+ data_source['split'],
+ 'label',
+ version=data_source['version'],
+ )
+ for i, (key, str_rects) in tqdm(enumerate(iter_label)):
+ rects = json.loads(str_rects)
+ if len(rects) == 0:
+ continue
+ for r in rects:
+ assert 'from_class' not in r
+ r['from_class'] = r['class']
+ r['class'] = 'object'
+ yield (key, json_dump(rects)), (idx_source, i)
+ def gen_info():
+ yield 'create_1_classs_label',
+ for k, v in frame_info.items():
+ yield k, v
+
+ label_file = out_dataset.get_data(out_split, 'label')
+ shuffle_file = out_dataset.get_shuffle_file(out_split)
+ assert not op.isfile(label_file)
+ tsv_writers(gen_rows(), (label_file, shuffle_file))
+ gen_tsv = out_dataset.get_gen_info_data(out_split, 'label')
+ tsv_writer(gen_info(), gen_tsv)
+ write_to_file(cls_name, out_dataset.get_labelmap_file())
+
+ image_tsvs = [TSVDataset(source['data']).get_data(source['split']) for source in
+ data_sources]
+ write_to_file('\n'.join(image_tsvs), out_dataset.get_data(out_split + 'X'))
+ expand_nested_splitX(out_data, out_split)
+
+def open_each_tsv(data, split, hold=False):
+ dataset = TSVDataset(data)
+ files = load_list_file(dataset.get_data(split + 'X'))
+ all_tsv = []
+ for f in files:
+ logging.info('open and read {}'.format(f))
+ tsv = TSVFile(f)
+ tsv[0]
+ if hold:
+ all_tsv.append(tsv)
+ else:
+ tsv.close()
+ from .common import print_opened_files
+ print_opened_files()
+
+def iter_caption_to_json(iter_caption, json_file):
+ # save gt caption to json format so thet we can call the api
+ key_captions = [(key, json.loads(p)) for key, p in iter_caption]
+
+ info = {
+ 'info': 'dummy',
+ 'licenses': 'dummy',
+ 'type': 'captions',
+ }
+ info['images'] = [{'file_name': k, 'id': k} for k, _ in key_captions]
+ n = 0
+ annotations = []
+ for k, cs in key_captions:
+ for c in cs:
+ annotations.append({
+ 'image_id': k,
+ 'caption': c['caption'],
+ 'id': n
+ })
+ n += 1
+ info['annotations'] = annotations
+ from .common import write_to_file
+ write_to_file(json.dumps(info), json_file)
+
+def compare_2_way_save(iter_pred1, iter_pred2, iter_image, out_data,
+ diff_iou=0.95, inter_iou=0.95, force=False, hint1='1', hint2='2'):
+ labels = []
+ def gen_rows():
+ for _, ((key1, rects1), (key2, rects2), (im_key, _, str_im)) in tqdm(enumerate(zip(
+ iter_pred1, iter_pred2, iter_image))):
+ assert key1 == key2 == im_key
+ unique_rects1 = rects_diff(rects1, rects2, iou=diff_iou)
+ unique_rects2 = rects_diff(rects2, rects1, iou=diff_iou)
+ k, l = key1 + '_{}'.format(hint1), json_dump(rects1)
+ labels.append((k, l))
+ yield k, l, str_im
+ k, l = key2 + '_{}'.format(hint2), json_dump(rects2)
+ labels.append((k, l))
+ yield k, l, str_im
+ k, l = key1 + '_{}_unique'.format(hint1), json_dump(unique_rects1)
+ labels.append((k, l))
+ yield k, l, str_im
+ k, l = key2 + '_{}_unique'.format(hint2), json_dump(unique_rects2)
+ labels.append((k, l))
+ yield k, l, str_im
+ if force:
+ from .common import ensure_remove_dir
+ ensure_remove_dir(op.join('data', out_data))
+ out_dataset = TSVDataset(out_data)
+ assert not op.isdir(out_dataset._data_root) and \
+ not op.islink(out_dataset._data_root)
+ out_dataset.write_data(gen_rows(), 'test')
+ out_dataset.write_data(labels, 'test', 'label')
+ populate_dataset_details(out_data)
+
+def create_caption_map(data, split, version):
+ dataset = TSVDataset(data)
+ all_cap = []
+ for k, ss in tqdm(dataset.iter_data(
+ split,
+ 'caption',
+ version=version,
+ )):
+ rects = json.loads(ss)
+ for r in rects:
+ all_cap.append(r['caption'])
+ all_cap = list(set(all_cap))
+ dataset.write_data(((c,)for c in all_cap), split, 'captionmap',
+ version=version)
+
+def create_filter_dataset(src_data, excludes, dst_data):
+ filters = []
+ data, split = src_data, 'train'
+ for e in excludes:
+ filter_file = 'data/remove_duplicate/target_{}_{}_exclude_{}_{}_0.995_filter_by_pixel.tsv'.format(
+ data, split, e['data'], e['split']
+ )
+ filters.append(filter_file)
+
+ ensure_directory(op.join('data', dst_data))
+ for f in glob.glob(op.join('data', src_data, 'trainX*')):
+ dest_f = op.join('data', dst_data, op.basename(f))
+ ensure_copy_file(f, dest_f)
+
+ shuffle = [(int(i), int(j)) for i, j in tsv_reader(op.join('data', src_data, 'train.shuffle.txt'))]
+
+ idx = []
+ for f in filters:
+ idx.extend([int(idx_train) for idx_test, idx_train in tsv_reader(f)])
+ all_idx = set(range(len(shuffle)))
+ logging.info('before {}'.format(len(all_idx)))
+ all_idx = all_idx.difference(idx)
+ logging.info('after {}'.format(len(all_idx)))
+ if len(idx) > 0:
+ assert max(idx) < len(shuffle)
+ dest_shuffle = [shuffle[i] for i in all_idx]
+
+ tsv_writer(dest_shuffle, op.join('data', dst_data, 'train.shuffle.txt'))
+
+ #generate_key_idximage_idxcaption(dst_data, 'train', None)
+
+def remove_duplicate_loader(exclude, train_data, train_split):
+ #dataset = TSVDataset('TaxFlickr30K')
+ #dataset = TSVDataset('TaxVQA')
+ num_workers = 64
+ batch_size = 32
+ use_hist = False
+ threshold = 0.995
+ out_file = 'data/remove_duplicate/target_{}_{}_exclude_{}_{}_{}_filter_by_hist.tsv'.format(
+ train_data,
+ train_split,
+ exclude['data'],
+ exclude['split'],
+ threshold)
+ out_file2 = 'data/remove_duplicate/target_{}_{}_exclude_{}_{}_{}_filter_by_pixel.tsv'.format(
+ train_data,
+ train_split,
+ exclude['data'],
+ exclude['split'],
+ threshold)
+ if File.isfile(out_file2):
+ return
+ def get_hist(data):
+ image = data['image']
+ all_hist = []
+ h, w = image.shape[:2]
+ if use_hist:
+ for i in range(3):
+ hist = cv2.calcHist([image], [i], None, [256], [0, 256])
+ hist = torch.tensor(hist)
+ all_hist.append(hist)
+
+ hist = cv2.calcHist([image[:h//2]], [i], None, [256], [0, 256])
+ hist = torch.tensor(hist)
+ all_hist.append(hist)
+
+ hist = cv2.calcHist([image[h//2:]], [i], None, [256], [0, 256])
+ hist = torch.tensor(hist)
+ all_hist.append(hist)
+
+ hist = cv2.calcHist([image[:, :w//2, :]], [i], None, [256], [0, 256])
+ hist = torch.tensor(hist)
+ all_hist.append(hist)
+
+ hist = cv2.calcHist([image[:, w//2:, :]], [i], None, [256], [0, 256])
+ hist = torch.tensor(hist)
+ all_hist.append(hist)
+
+ hist = torch.cat(all_hist, dim=0)
+ hist = torch.nn.functional.normalize(hist, dim=0)
+ #ipdb> pp hist.shape
+ #torch.Size([256, 1])
+ data['hist'] = hist.squeeze()
+ else:
+ image = torch.tensor(cv2.resize(image, (64, 64)))
+ image = image.view(1, -1)
+ image = torch.nn.functional.normalize(image.float(), dim=1)
+ image = image.squeeze()
+ data['hist'] = image
+ del data['image']
+ return data
+
+ hists = []
+ info = exclude
+ loader = create_tsv_dataset_loader(
+ info['data'], info['split'],
+ batch_size=batch_size,
+ num_workers=num_workers,
+ extra_transform=get_hist,
+ )
+ for info in tqdm(loader, total=len(loader)):
+ hist = info['hist']
+ hists.append(hist)
+ hists = torch.cat(hists, dim=0)
+
+ data_loader = create_tsv_dataset_loader(
+ train_data, train_split,
+ extra_transform=get_hist,
+ num_workers=num_workers,
+ batch_size=batch_size,
+ )
+
+ #device = 'cuda'
+ device = 'cpu'
+ hists = hists.to(device)
+ def gen_rows():
+ for i, info in tqdm(enumerate(data_loader), total=len(data_loader)):
+ hist = info['hist']
+ hist = hist.squeeze(-1)
+
+ hist = hist.to(device)
+
+ sim = torch.matmul(hists, hist.t())
+ idx = sim > threshold
+ del sim
+
+ idx_test, idx_train = idx.nonzero(as_tuple=True)
+ idx_train = idx_train + i * batch_size
+ for nz_test, nz_train in zip(idx_test.to('cpu'), idx_train.to('cpu')):
+ yield int(nz_test), int(nz_train)
+ tsv_writer(gen_rows(), out_file)
+
+ remove_duplicate_double_check_im(
+ exclude['data'], exclude['split'], train_data, out_file, out_file2,
+ 1-threshold,
+ )
+
+def remove_duplicate_double_check_im(
+ exclude_data, exclude_split, train_data, tsv_fn, out_tsv, threshold):
+ row_processor = CheckDuplicate(exclude_data, exclude_split, train_data,
+ threshold)
+ parallel_tsv_process(row_processor, tsv_fn, out_tsv, 64)
+
+class CheckDuplicate(object):
+ def __init__(self, exclude_data, exclude_split, train_data, threshold):
+ from .tsv_io import TSVSplitProperty
+ self.tsv_exclude = TSVSplitProperty(exclude_data, exclude_split)
+ self.tsv_train = TSVSplitProperty(train_data, 'train')
+ self.threshold = threshold
+
+ def __call__(self, row):
+ idx_exclude, idx_train = map(int, row)
+ im_exclude = self.tsv_exclude[idx_exclude][-1]
+ im_train = self.tsv_train[idx_train][-1]
+ im_exclude = img_from_base64(im_exclude)
+ im_train = img_from_base64(im_train)
+ im2 = im_exclude
+ im1 = im_train
+ if im2.shape != im1.shape:
+ im2 = cv2.resize(im2, (im1.shape[1], im1.shape[0]))
+ if np.absolute(im1 - im2).mean() < self.threshold * im1.mean():
+ return row
+ return None
+
+
+def create_tsv_dataset_loader(
+ data, split, extra_transform=None, batch_size=1, num_workers=1):
+ from qd.data_layer.loader import create_data_loader
+ from qd.data_layer.dataset import (
+ CaptionIdxTSVDataset,
+ ImageIdxTSVDataset,
+ DatasetPlusTransform,
+ )
+ from qd.data_layer.transform import (
+ LoadLabel,
+ LoadHW,
+ LoadFeature,
+ LoadImage,
+ LoadCaption,
+ IdentifyTextAB,
+ RandomPairNegative,
+ CaptionTensorizer,
+ TokenizeTransform,
+ NoChange,
+ PrepareLabel,
+ RemoveUselessKeys,
+ RenameKey,
+ AppendDummyFeature,
+ )
+ from torchvision.transforms import transforms
+ tsv = ImageIdxTSVDataset(data, split)
+ loader = LoadImage(data, split)
+ hw = LoadHW(data, split)
+ useless = RemoveUselessKeys(['dataset'])
+ ts = [
+ loader,
+ hw,
+ useless,
+ ]
+ if extra_transform is not None:
+ ts.append(extra_transform)
+ transform = transforms.Compose(ts)
+ return create_data_loader(tsv, transform, batch_size, num_workers=num_workers)
+
+def parse_hw_column(s_hw):
+ try:
+ h, w = map(int, s_hw.split(' '))
+ return h, w
+ except:
+ info = json.loads(s_hw)
+ if isinstance(info, list):
+ assert len(info) == 1
+ info = info[0]
+ return info['height'], info['width']
+
+def limit_image_size_with_filter(in_rows, min_size, max_size, resave=True, quality=None):
+ assert len(in_rows) == 2
+ result = limit_image_size(in_rows[:1], min_size, max_size, resave=True, quality=None)
+ if result is None:
+ return None
+ else:
+ assert result[0][0] == in_rows[1][0]
+ return result[0], in_rows[1]
+
+def limit_image_size(in_rows, min_size, max_size, resave=True, quality=None):
+ #debug = True
+ debug = False
+ if len(in_rows) == 2:
+ in_img_row, in_hw_row = in_rows
+ h, w = parse_hw_column(in_hw_row[1])
+ else:
+ in_img_row = in_rows[0]
+ h, w = None, None
+ img = img_from_base64(in_img_row[-1])
+ if img is None:
+ img = pilimg_from_base64(in_img_row[-1])
+ if img is None:
+ return None
+ img = np.array(img)
+ if img.size == 0:
+ return None
+ # Convert RGB to BGR
+ img = img[:, :, ::-1].copy()
+ if h is None:
+ h, w = img.shape[:2]
+ if w != img.shape[1] or h != img.shape[0]:
+ logging.info('{}: w = {}; h = {}; img.shape = {}'.format(
+ in_img_row[0], w, h, img.shape))
+ w = img.shape[1]
+ h = img.shape[0]
+ image_min = min(h, w)
+ image_max = max(h, w)
+ if image_min < min_size and image_max < max_size:
+ if resave or quality:
+ im = img_from_base64(in_img_row[-1])
+ in_img_row[-1] = encoded_from_img(im, quality=quality)
+ return in_img_row,
+ scale = min(min_size * 1. / image_min, max_size * 1. / image_max)
+ w2 = int(round(scale * w))
+ h2 = int(round(scale * h))
+ w2 = max(1, w2)
+ h2 = max(1, h2)
+ #img = pilimg_from_base64(in_img_row[-1])
+ #img = ImageOps.exif_transpose(img)
+ if debug:
+ img.show()
+ img = cv2.resize(img, (w2, h2),
+ interpolation=cv2.INTER_AREA,
+ )
+ #save_image(img, '/tmp/b.jpg')
+ #img = img.resize((w2, h2))
+ in_img_row[-1] = encoded_from_img(img, quality=quality)
+ if debug:
+ img.show()
+ return in_img_row,
+ # we need to do resizing
+
+def parallel_limit_image_size(im_tsv, hw_tsv, min_size, max_size,
+ quality,
+ out_tsv):
+ process_func = lambda x: limit_image_size(x, min_size, max_size,
+ quality=quality)
+ num_process = 64
+ if hw_tsv is not None:
+ parallel_tsv_process_NtoN(process_func, (im_tsv, hw_tsv), (out_tsv, ),
+ num_process)
+ else:
+ parallel_tsv_process_NtoN(process_func, (im_tsv,), (out_tsv, ),
+ num_process)
+
+def parallel_limit_image_size_with_filter(im_tsv, other_tsv, min_size, max_size,
+ quality,
+ out_tsv, out_other_tsv):
+ process_func = lambda x: limit_image_size_with_filter(
+ x, min_size, max_size, quality=quality)
+ num_process = 64
+ parallel_tsv_process_NtoN(process_func, (im_tsv, other_tsv), (out_tsv, out_other_tsv), num_process)
+
+def filter_dataset_by_size(data, out_data):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+ iter_hw = dataset.iter_data('train', 'hw')
+
+ if op.isfile(dataset.get_shuffle_file('train')):
+ iter_shuffle = tsv_reader(dataset.get_shuffle_file('train'))
+ info = defaultdict(int)
+ def gen_rows():
+ for (key, str_hw), s in tqdm(zip(iter_hw, iter_shuffle)):
+ try:
+ h, w = map(int, str_hw.split(' '))
+ except:
+ x = json.loads(str_hw)
+ if isinstance(x, list):
+ x = x[0]
+ h, w = x['height'], x['width']
+ r = 1. * h / w
+ if r > 4 or r < 1. / 4:
+ info['ratio_too_large'] += 1
+ continue
+ if min(h, w) < 64:
+ info['size_too_small'] += 1
+ continue
+ yield s
+ tsv_writer(gen_rows(), out_dataset.get_shuffle_file('train'))
+ for t in [None, 'hw', 'caption']:
+ ensure_copy_file(
+ dataset.get_data('trainX', t),
+ out_dataset.get_data('trainX', t),
+ )
+ else:
+ info = defaultdict(int)
+ def gen_rows():
+ for i, (key, str_hw) in tqdm(enumerate(iter_hw)):
+ try:
+ h, w = map(int, str_hw.split(' '))
+ except:
+ x = json.loads(str_hw)
+ if isinstance(x, list):
+ x = x[0]
+ h, w = x['height'], x['width']
+ r = 1. * h / w
+ if r > 4 or r < 1. / 4:
+ info['ratio_too_large'] += 1
+ continue
+ if min(h, w) < 64:
+ info['size_too_small'] += 1
+ continue
+ yield (0, i)
+ tsv_writer(gen_rows(), out_dataset.get_shuffle_file('train'))
+ for t in [None, 'hw', 'caption']:
+ write_to_file(
+ dataset.get_data('train', t),
+ out_dataset.get_data('trainX', t),
+ )
+
+def limit_dataset_image_size_to_single(
+ data, split, image_t, min_size, max_size,
+ quality, out_data):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+
+ process_func = lambda x: limit_image_size(
+ x, min_size, max_size, quality=quality)
+
+ i = TSVSplitProperty(data, split)
+ h = TSVSplitProperty(data, split, 'hw')
+ o = out_dataset.get_data(split, image_t)
+ if not op.isfile(o):
+ parallel_tsv_process_NtoN(process_func, (i, h), (o, ), 64)
+
+ for t in ['label', 'caption']:
+ if dataset.has(split, t):
+ tsv_writer(
+ TSVSplitProperty(data, split, t),
+ out_dataset.get_data(split, t)
+ )
+ populate_dataset_hw(out_data, splits=[split], img_t=image_t)
+ if File.isfile(dataset.get_labelmap_file()):
+ ensure_copy_file(
+ dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file()
+ )
+
+def limit_dataset_image_size(
+ data, split, image_t, min_size, max_size,
+ quality, out_data):
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+
+ if op.isfile(dataset.get_data(split, image_t)):
+ in_img_tsv = [dataset.get_data(split, image_t)]
+ caption_tsvs = [dataset.get_data(split, 'caption')]
+ in_hw_tsv = [dataset.get_data(split, 'hw')]
+ out_tsv = [out_dataset.get_data(split, image_t)]
+ single_tsv = True
+ else:
+ in_img_tsv = load_list_file(dataset.get_data(split + 'X', image_t))
+ hw_file = dataset.get_data(split + 'X', 'hw')
+ if op.isfile(hw_file):
+ in_hw_tsv = load_list_file(dataset.get_data(split + 'X', 'hw'))
+ else:
+ hw_file = dataset.get_data(split, 'hw')
+ assert op.isfile(hw_file)
+ in_hw_tsv = [hw_file]
+ iter_shuffle = tsv_reader(dataset.get_shuffle_file(split))
+ for i, (idx_source, idx_row) in enumerate(iter_shuffle):
+ assert i == int(idx_row)
+ assert int(idx_source) == 0
+ assert len(in_img_tsv) == 1
+ assert len(TSVFile(hw_file)) == len(TSVFile(in_img_tsv[0]))
+ num_split = len(in_img_tsv)
+ out_tsv = [out_dataset.get_data(split + '_{}_{}'.format(i, num_split))
+ for i in range(num_split)]
+ caption_tsvs = load_list_file(
+ dataset.get_data(split + 'X', 'caption')
+ )
+ label_tsvs = load_list_file(
+ dataset.get_data(split + 'X', 'label')
+ )
+ single_tsv = False
+
+ process_func = lambda x: limit_image_size(
+ x, min_size, max_size, quality=quality)
+
+ for i, h, o in zip(in_img_tsv, in_hw_tsv, out_tsv):
+ from qd.process_tsv import parallel_tsv_process_NtoN
+ if not op.isfile(o):
+ parallel_tsv_process_NtoN(process_func, (i, h), (o, ), 64)
+
+ if not single_tsv:
+ write_to_file(
+ '\n'.join(out_tsv),
+ out_dataset.get_data(split + 'X', image_t),
+ )
+ write_to_file(
+ '\n'.join(caption_tsvs),
+ out_dataset.get_data(split + 'X', 'caption')
+ )
+ write_to_file(
+ '\n'.join(label_tsvs),
+ out_dataset.get_data(split + 'X', 'label')
+ )
+ tsv_copy(
+ dataset.get_shuffle_file(split),
+ out_dataset.get_shuffle_file(split),
+ )
+ splits = ['train_{}_{}'.format(i, num_split) for i in range(num_split)]
+ populate_dataset_hw(out_data, splits=splits)
+ write_to_file(
+ '\n'.join((out_dataset.get_data(
+ split + '_{}_{}'.format(i, num_split), 'hw',
+ ) for i in range(num_split))),
+ out_dataset.get_data(split + 'X', 'hw'),
+ )
+ else:
+ for t in ['label', 'caption']:
+ from_f = dataset.get_data(split, t)
+ if File.isfile(from_f):
+ tsv_copy(
+ dataset.get_data(split, t),
+ out_dataset.get_data(split, t)
+ )
+ populate_dataset_hw(out_data, splits=[split], img_t=image_t)
+ if File.isfile(dataset.get_labelmap_file()):
+ ensure_copy_file(
+ dataset.get_labelmap_file(),
+ out_dataset.get_labelmap_file()
+ )
+
+def video_convert_tsv_one(old_tsv, new_tsv):
+ def gen_rows():
+ for row in tsv_reader(old_tsv):
+ #assert len(row) == 34
+ idx = (len(row) - 2) // 2 + 2
+ yield row[0], row[idx]
+ if not op.isfile(new_tsv):
+ tsv_writer(gen_rows(), new_tsv)
+
+def get_max_iter_for_vl_plus_l_data(
+ data, vl_data_rate, num_epoch_vl, effective_batch_size,
+ effective_batch_size_text_only,
+):
+
+ iter_cache = TSVDataset(data).iter_data(
+ 'train',
+ 'key_idximage_idxcaption_num_valid_image',
+ )
+ info = {k: int(v) for k, v in iter_cache}
+ num_vl_pair = info['num_valid_vl_pair']
+ num_l_pair = info['num_l_only_pair']
+ max_iter = int(num_vl_pair * num_epoch_vl / effective_batch_size / vl_data_rate + 0.5)
+ num_epoch_l = max_iter * (1 - vl_data_rate) * effective_batch_size_text_only / num_l_pair
+ logging.info(f'num_epoch_l = {num_epoch_l}; max_iter={max_iter}')
+ return max_iter
+
+def generate_num_vl_data(data, split, out_type='key_idximage_idxcaption_num_valid_image'):
+ # this is mainly used by VisionLanguagePlusLanguageBatchSampler
+ dataset = TSVDataset(data)
+ source_list = load_list_file(dataset.get_data(split + 'X'))
+ is_valid = tuple([s != 'd' for s in source_list])
+ source = TSVSplitProperty(data, split,
+ 'key_idximage_idxcaption_idxsource')
+ ranges = split_to_chunk_to_range(len(source), num_chunk=64)
+ def process(x):
+ start, end = x
+ info = defaultdict(int)
+ with_image = True
+ for i in tqdm(range(start, end)):
+ s = int(source[i][0])
+ if is_valid[s]:
+ assert with_image
+ info['with_valid_image'] += 1
+ elif with_image:
+ with_image = False
+ info['total'] += 1
+ info['with_image'] = with_image
+ return info
+ infos = parallel_map(process, ranges)
+ ret = defaultdict(int)
+ for i in infos:
+ for k, v in i.items():
+ ret[k] += v
+ assert ret['total'] == len(source)
+ for i, info in enumerate(infos):
+ if not info['with_image']:
+ for j in range(i + 1, len(infos)):
+ assert not info['with_image']
+
+ out_file = dataset.get_data(split, out_type)
+ tsv_writer((
+ ('num_valid_vl_pair', ret['with_valid_image']),
+ ('num_l_only_pair', ret['total'] - ret['with_valid_image']),
+ ('num_total', ret['total']),
+ ), out_file)
+
+def generate_num_vl_data_old(data, split, out_type='key_idximage_idxcaption_num_valid_image'):
+ # this is mainly used by VisionLanguagePlusLanguageBatchSampler
+ dataset = TSVDataset(data)
+ source_list = load_list_file(dataset.get_data(split + 'X'))
+ num_valid_image = 0
+ num_total = 0
+ with_image = True
+ for s, in tqdm(TSVSplitProperty(data, split,
+ 'key_idximage_idxcaption_idxsource')):
+ if source_list[int(s)] != 'd':
+ assert with_image
+ num_valid_image += 1
+ elif with_image:
+ with_image = False
+ num_total += 1
+ out_file = dataset.get_data(split, out_type)
+ tsv_writer((
+ ('num_valid_vl_pair', num_valid_image),
+ ('num_l_only_pair', num_total - num_valid_image),
+ ('num_total', num_total),
+ ), out_file)
+
+def generate_num_each_tsv(data, split,
+ idxsource_type='key_idximage_idxcaption_idxsource',
+ out_type='key_idximage_idxcaption_num_each_tsv',
+ ):
+ result = []
+ dataset = TSVDataset(data)
+ #for s, in tqdm(TSVSplitProperty(data, split, 'key_idximage_idxcaption_idxsource')):
+ # TSVSplitProperty here is twice slower
+ total = dataset.num_rows(split, t=idxsource_type)
+ ranges = split_to_chunk_to_range(total, num_chunk=64)
+
+ def chunk_processor(x):
+ start, end = x
+ tsv = TSVSplitProperty(data, split, idxsource_type)
+ info = defaultdict(int)
+ prev_s = -1
+ for i in tqdm(range(start, end)):
+ s = int(tsv[i][0])
+ info[s] += 1
+ if prev_s == -1:
+ prev_s = s
+ elif prev_s < s:
+ prev_s = s
+ else:
+ assert prev_s == s, (i, prev_s, s)
+ return info
+
+ infos = parallel_map(chunk_processor, ranges, num_worker=64)
+ for i in range(len(infos) - 1):
+ assert max(infos[i].keys()) <= min(infos[i + 1].keys())
+ result = defaultdict(int)
+ for i in infos:
+ for k, v in i.items():
+ result[k] += v
+
+ # we assumed the last tsv is not empty. If it is, it will crash and we need
+ # to append more zeros here.
+ num_tsv = len(load_list_file(dataset.get_data(split + 'X')))
+ assert min(result.keys()) >= 0
+ assert max(result.keys()) < num_tsv
+
+ dataset.write_data(((result.get(i, 0),) for i in range(num_tsv)), split, out_type,)
+
+def generate_num_each_tsv_old(data, split, idxsource_type='key_idximage_idxcaption_idxsource'):
+ result = []
+ curr_num = 0
+ curr_idx = -1
+ dataset = TSVDataset(data)
+ #for s, in tqdm(TSVSplitProperty(data, split, 'key_idximage_idxcaption_idxsource')):
+ # TSVSplitProperty here is twice slower
+ total = dataset.num_rows(split, t=idxsource_type)
+ with File.open(dataset.get_data(split, idxsource_type), 'r') as fp:
+ for line in tqdm(fp, total=total):
+ s = int(line)
+ if s != curr_idx:
+ if curr_idx != -1:
+ # the order should not be random
+ assert len(result) == curr_idx
+ result.append(curr_num)
+ while curr_idx + 1 < s:
+ result.append(0)
+ curr_idx += 1
+ assert s == curr_idx + 1, (curr_idx, s)
+ curr_idx = s
+ curr_num = 0
+ curr_num += 1
+
+ assert len(result) == curr_idx, (len(result), curr_idx)
+ result.append(curr_num)
+
+ # we assumed the last tsv is not empty. If it is, it will crash and we need
+ # to append more zeros here.
+ num_tsv = len(load_list_file(dataset.get_data(split + 'X')))
+ assert num_tsv == len(result), (num_tsv, len(result))
+ dataset.write_data(((r,) for r in result),
+ split,
+ 'key_idximage_idxcaption_num_each_tsv',
+ )
+
+#@deprecated('use generate_idximage_idxcaption_idxsource_parallel')
+#def generate_key_idximage_idxcaption_idxsource(data, split):
+ #logging.info(f'{data}/{split}')
+ #generate_key_idximage_idxcaption(data, split)
+ #k_img_cap = TSVSplitProperty(data, split, 'key_idximage_idxcaption')
+ #dataset = TSVDataset(data)
+ #if dataset.has(split, 'key_idximage_idxcaption_idxsource'):
+ #return
+ #x_tsv = dataset.get_data(split + 'X', 'caption')
+ #if File.isfile(x_tsv):
+ #all_idx_source = [int(idx_source) for idx_source, _ in
+ #tqdm(TSVFile(dataset.get_shuffle_file(split)))]
+ #logging.info('loading composite source idx')
+ #result = ((all_idx_source[int(idx_img)],) for _, idx_img, _ in
+ #tqdm(k_img_cap))
+ #dataset.write_data(result, split, 'key_idximage_idxcaption_idxsource')
+ #else:
+ #dataset.write_data([(0,)] * len(k_img_cap), split, 'key_idximage_idxcaption_idxsource')
+
+def generate_idximage_idxcaption_idxsource(data, split):
+ logging.info(f'{data}/{split}')
+ generate_idximage_idxcaption_parallel(data, split)
+ k_img_cap = TSVSplitProperty(data, split, 'idximage_idxcaption')
+ dataset = TSVDataset(data)
+ if dataset.has(split, 'idximage_idxcaption_idxsource'):
+ return
+ x_tsv = dataset.get_data(split + 'X', 'caption')
+ if File.isfile(x_tsv):
+ shuffle_tsv = TSVFile(dataset.get_shuffle_file(split))
+ def row_processor(row):
+ key, idximage, _ = row
+ ret = int(shuffle_tsv[int(idximage)][0])
+ return (ret, )
+ parallel_tsv_process(
+ row_processor,
+ k_img_cap,
+ dataset.get_data(split, 'idximage_idxcaption_idxsource'),
+ 64,
+ )
+ else:
+ dataset.write_data([(0,)] * len(k_img_cap), split, 'idximage_idxcaption_idxsource')
+
+@deprecated('use generate_idxsource_of_idximage_idxcaption')
+def generate_idxsource_of_idximage_idxcaption_parallel(*args, **kwargs):
+ generate_idxsource_of_idximage_idxcaption(*args, **kwargs)
+
+def generate_idxsource_of_idximage_idxcaption(
+ data, split, in_type='key_idximage_idxcaption', out_type='key_idximage_idxcaption_idxsource'):
+ logging.info(f'{data}/{split}')
+ if in_type == 'key_idximage_idxcaption':
+ generate_key_idximage_idxcaption(data, split)
+ elif in_type == 'idximage_idxcaption':
+ generate_idximage_idxcaption(data, split)
+ k_img_cap = TSVSplitProperty(data, split, in_type)
+ dataset = TSVDataset(data)
+ if dataset.has(split, out_type):
+ return
+ x_tsv = dataset.get_data(split + 'X', 'caption')
+ if File.isfile(x_tsv):
+ shuffle_tsv = TSVFile(dataset.get_shuffle_file(split))
+ def row_processor(row):
+ idximage = row[-2]
+ ret = int(shuffle_tsv[int(idximage)][0])
+ return (ret, )
+ parallel_tsv_process(
+ row_processor,
+ k_img_cap,
+ dataset.get_data(split, out_type),
+ 64,
+ )
+ else:
+ dataset.write_data([(0,)] * len(k_img_cap), split, out_type)
+
+
+@deprecated('use generate_idxsource_of_idximage_idxcaption_parallel')
+def generate_key_idximage_idxcaption_idxsource_parallel(*args, **kwargs):
+ generate_idxsource_of_idximage_idxcaption_parallel(*args, **kwargs)
+
+@deprecated('use generate_idxsource_of_idximage_idxcaption_parallel')
+def generate_key_idximage_idxcaption_idxsource(*args, **kwargs):
+ generate_idxsource_of_idximage_idxcaption_parallel(*args, **kwargs)
+
+
+def generate_cache_tsv(data):
+ dataset = TSVDataset(data)
+ all_file = []
+ for t in [None, 'caption']:
+ files = load_list_file(dataset.get_data('trainX', t=t))
+ all_file.extend(files)
+ all_file = [f for f in all_file if f != 'd']
+ all_file.extend([get_tsv_associates(f)[0] for f in all_file])
+ ret = ','.join(all_file)
+ return ret
+
+def get_precache_tsv_files(data):
+ dataset = TSVDataset(data)
+ all_fs = []
+ for t in [None, 'caption']:
+ if File.isfile(dataset.get_data('trainX', t=t)):
+ fs = load_list_file(dataset.get_data('trainX', t=t))
+ fs = [f for f in fs if f != 'd']
+ fs.append(dataset.get_shuffle_file('train'))
+ else:
+ fs = [dataset.get_data('train', t=t)]
+ fs.extend([x for f in fs for x in get_tsv_associates(f)])
+ all_fs.extend(fs)
+ return ','.join(set(all_fs))
+
+def shuffle_dataset_by_file(in_data, out_data):
+ in_dataset = TSVDataset(in_data)
+ out_dataset = TSVDataset(out_data)
+ ts = [None, 'caption']
+ old2new = None
+ random.seed(666)
+ for t in ts:
+ from_file = in_dataset.get_data('trainX', t=t)
+ out_file = out_dataset.get_data('trainX', t=t)
+ fnames = load_list_file(from_file)
+ if old2new is None:
+ old2new = list(range(len(fnames)))
+ random.shuffle(old2new)
+ new_out = [None] * len(fnames)
+ for i, j in enumerate(old2new):
+ new_out[j] = fnames[i]
+ write_to_file('\n'.join(new_out), out_file)
+
+ def mapper(ret, row, idx):
+ i = int(row[0])
+ if 'x' not in ret:
+ ret['x'] = []
+ ret = ret['x']
+ if len(ret) == 0 or ret[-1]['img_tsv_idx'] != i:
+ ret.append({
+ 'start': idx,
+ 'end': idx,
+ 'img_tsv_idx': i,
+ })
+ else:
+ assert ret[-1]['img_tsv_idx'] == i
+ ret[-1]['end'] = idx
+
+ def reducer(rets):
+ result = []
+ for ret in rets:
+ r = ret['x']
+ for _i, curr_r in enumerate(r):
+ if len(result) == 0:
+ result.append(curr_r)
+ elif result[-1]['img_tsv_idx'] == curr_r['img_tsv_idx']:
+ assert result[-1]['end'] == curr_r['start'] - 1
+ result[-1]['end'] = curr_r['end']
+ else:
+ result.append(curr_r)
+ return result
+
+ results = parallel_tsv_aggregator(
+ mapper,
+ reducer,
+ in_tsv_file=in_dataset.get_shuffle_file('train'),
+ with_row_idx=True,
+ num_process=64,
+ )
+
+ for i in range(len(results) - 1):
+ assert results[i]['img_tsv_idx'] < results[i + 1]['img_tsv_idx']
+ random.shuffle(results)
+ def process(r):
+ folder = get_tmp_folder()
+ new_idx_img = old2new[r['img_tsv_idx']]
+ tmp_file = '{}/{}.tsv'.format(folder, new_idx_img)
+ def gen_rows():
+ in_dataset = TSVDataset(in_data)
+ tsv = TSVFile(in_dataset.get_shuffle_file('train'))
+ for i in range(r['start'], r['end'] + 1):
+ old_idx_img, idx_caption = tsv[i]
+ assert old_idx_img == str(r['img_tsv_idx'])
+ yield new_idx_img, idx_caption
+ tsv_writer(gen_rows(), tmp_file)
+
+ parallel_map(process, results, num_worker=64)
+ folder = get_tmp_folder()
+ tmp_files = ['{}/{}.tsv'.format(folder, i) for i in range(len(results))]
+ logging.info(len(tmp_files))
+ tmp_files = [t for t in tmp_files if op.isfile(t)]
+ logging.info(len(tmp_files))
+ concat_tsv_files(tmp_files, out_dataset.get_shuffle_file('train'))
+ delete_tsv_files(tmp_files)
+
+def populate_vl_dataset(data, split='train'):
+ generate_idximage_idxcaption(data, split)
+ from qd.process_tsv import generate_idxsource_of_idximage_idxcaption
+ generate_idxsource_of_idximage_idxcaption(
+ data, split,
+ in_type='idximage_idxcaption',
+ )
+ from qd.process_tsv import generate_num_each_tsv
+ generate_num_each_tsv(data, split)
+ from qd.process_tsv import generate_num_vl_data
+ generate_num_vl_data(data, split)
+
+def create_simple_tax(data):
+ out_data = 'Tax' + data
+ dataset = TSVDataset(data)
+ out_dataset = TSVDataset(out_data)
+ for split in ['train', 'val', 'test', 'trainval']:
+ if not dataset.has(split):
+ continue
+ for t in [None, 'caption']:
+ src_file = dataset.get_data(split, t)
+ write_to_file(
+ src_file,
+ out_dataset.get_data(split + 'X', t)
+ )
+ num = dataset.num_rows(split)
+ tsv_writer(((0, i) for i in range(num)),
+ out_dataset.get_shuffle_file(split))
+
+def convert_cap_to_tag(predict_file, tag_predict):
+ def gen_rows():
+ if isinstance(predict_file, str):
+ iter_pred = tsv_reader(predict_file)
+ else:
+ iter_pred = predict_file
+ for key, s in iter_pred:
+ s = json.loads(s)
+ assert len(s) == 1
+ tags = map(lambda x: x.strip(), s[0]['caption'].split(','))
+ ret = [{'class': t, 'conf': 1.} for t in tags]
+ yield key, json_dump(ret)
+ tsv_writer(gen_rows(), tag_predict)
+
+def create_question_annotation_json(data, split):
+ gt = TSVSplitProperty(data, split, 'caption')
+ questions = []
+ annotations = []
+ for image_id, s in gt:
+ s = json.loads(s)
+ for i in s:
+ q = {
+ 'image_id': image_id,
+ 'question_id': i.get('question_id'),
+ 'question': i['question'],
+ }
+ questions.append(q)
+ a = copy.deepcopy(q)
+ answers = [{
+ 'answer': ans,
+ } for ans in i['answers']]
+ a['answers'] = answers
+ a['question_type'] = 'null'
+ a['answer_type'] = 'null'
+ annotations.append(a)
+
+ # list of dict (image_id, question, question_id), image_id and question_id
+ # are integer
+ question_info = {
+ 'info': None,
+ 'task_type': 'Open-Ended',
+ 'data_type': 'mscoco',
+ 'license': None,
+ 'data_subtype': None,
+ 'questions': questions,
+ }
+ annotation_info = {
+ 'info': None,
+ 'task_type': 'Open-Ended',
+ 'data_type': 'mscoco',
+ 'license': None,
+ 'data_subtype': None,
+ 'annotations': annotations,
+ }
+ out_f = f'data/{data}/{split}.caption.question.json'
+ write_to_file(json_dump(question_info), out_f)
+ out_f = f'data/{data}/{split}.caption.annotation.json'
+ write_to_file(json_dump(annotation_info), out_f)
+
+if __name__ == '__main__':
+ from .common import parse_general_args
+ init_logging()
+ kwargs = parse_general_args()
+ logging.info('param:\n{}'.format(pformat(kwargs)))
+ function_name = kwargs['type']
+ del kwargs['type']
+ locals()[function_name](**kwargs)
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/taxonomy.py b/One-to-All-Animation/benchmark/DisCo/utils/taxonomy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2153d46417587266574927360d79407803fe34b0
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/taxonomy.py
@@ -0,0 +1,833 @@
+from collections import defaultdict
+from tqdm import tqdm
+from pprint import pformat
+import random
+import json
+import xml.etree.ElementTree as ET
+try:
+ import cPickle as pkl
+except:
+ # python3
+ import pickle as pkl
+from collections import OrderedDict
+import cv2
+import yaml
+import numpy as np
+import logging
+from ete3 import Tree
+import nltk
+from nltk.corpus import wordnet as wn
+from .common import write_to_file, read_to_buffer
+from .common import init_logging, ensure_directory
+from .tsv_io import load_list_file
+from .common import load_from_yaml_file
+from .common import encoded_from_img
+try:
+ import Queue
+except:
+ # this is python 3
+ import queue as Queue
+import os
+import os.path as op
+import glob
+import tarfile
+from .tsv_io import TSVDataset, tsv_reader, tsv_writer
+from .tsv_io import tsv_shuffle_reader
+import base64
+import re
+try:
+ from itertools import izip as zip
+except:
+ # if it comes here, it is python3
+ pass
+import numpy as np
+
+def is_noffset(label):
+ return re.match('^n[0-9]{8}$', label)
+
+def labels2noffsets(labels):
+ mapper = LabelToSynset()
+ result = []
+ for label in labels:
+ result.append(synset_to_noffset(mapper.convert(label)))
+ return result
+
+def get_nick_name(s):
+ n = s.name()
+ result = n[: -5]
+ return result.replace('_', ' ')
+
+def create_markdown_url(noffsets):
+ urls = ['[{0}](http://www.image-net.org/synset?wnid={0})'.format(noffset) for
+ noffset in noffsets]
+ return urls
+
+def update_with_path(root, path, psudo=False):
+ curr_root = root
+ for i in xrange(len(path)):
+ s = path[i]
+ existings = curr_root.search_nodes(noffset=synset_to_noffset(s))
+ assert len(existings) <= 1
+ if len(existings) == 1:
+ curr_root = existings[0]
+ continue
+ else:
+ if psudo:
+ return len(path) - i
+ else:
+ curr_root = curr_root.add_child(name=s.name())
+ curr_root.add_features(nick_name=get_nick_name(s),
+ noffset=synset_to_noffset(s))
+ if psudo:
+ return 0
+
+def update_with_synsets(root, ss):
+ '''
+ build the tree based on the method described in yolo9k paper
+ '''
+ ambiguities = []
+ c = 0
+ for i, s in enumerate(ss):
+ ps = [p for p in s.hypernym_paths() if any(pn for pn in p if
+ synset_to_noffset(pn)==root.noffset)]
+ if len(ps) == 0:
+ logging.info('ignore {}'.format(s))
+ continue
+ c = c + 1
+ if len(ps) == 1:
+ update_with_path(root, ps[0])
+ else:
+ ambiguities.append(ps)
+ if (i % 500) == 0:
+ logging.info('non-ambiguities: {}/{}'.format(i, len(ss)))
+
+ for j, ps in enumerate(ambiguities):
+ ns = [update_with_path(root, p, psudo=True) for p in ps]
+ i = np.argmin(np.asarray(ns))
+ update_with_path(root, ps[i])
+ if (j % 500) == 0:
+ logging.info('ambiguities: {}/{}'.format(j, len(ambiguities)))
+
+def prune_root(root):
+ curr = root
+ while True:
+ if len(curr.children) == 1:
+ curr = curr.children[0]
+ else:
+ break
+ root = curr
+ return root
+
+def prune(root):
+ '''
+ remove any node who has only one child
+ '''
+ root = prune_root(root)
+ cs = []
+ for c in root.children:
+ cs.append(prune(c))
+ root.children = cs
+ return root
+
+def check_prune(root):
+ if len(root.children) == 1:
+ logging.info('{}->{}'.format(root.synset.name(),
+ root.children[0].synset.name()))
+ for c in root.children:
+ check_prune(c)
+
+def tree_size(root):
+ if root == None:
+ return 0
+ else:
+ s = 0
+ for c in root.children:
+ s = s + tree_size(c)
+ return 1 + s
+
+def populate_dataset_count(root, images_root):
+ for n in root.iter_search_nodes():
+ noffset = '{}{}'.format(n.synset.pos(), n.synset.offset())
+ image_dir = op.join(images_root, noffset)
+ if not op.exists(image_dir):
+ num_image = 0
+ else:
+ num_image = len(glob.glob(op.join(image_dir, '*.*')))
+ n.add_feature('num_image', num_image)
+
+class LabelTree(object):
+ def __init__(self, tree_file):
+ r = load_label_parent(tree_file)
+ self.noffset_idx, self.noffset_parentidx, self.noffsets = r
+ self.root, self.noffset_node = load_label_tree(self.noffset_parentidx, self.noffsets)
+ self.basefilename = op.basename(tree_file)
+
+def synset_to_noffset(synset):
+ return '{}{:0>8}'.format(synset.pos(), synset.offset())
+
+def child_parent_print_tree2(root, field):
+ def get_field(n):
+ key = n.__getattribute__(field)
+ key = key.replace(' ', '_')
+ return key
+ name_to_lineidx = {}
+ q = Queue.Queue()
+ q.put(root)
+ idx = -1
+ while not q.empty():
+ n = q.get()
+ key = get_field(n)
+ name_to_lineidx[key] = idx
+ idx = idx + 1
+ for c in n.children:
+ q.put(c)
+ q.put(root)
+ lines = []
+ labels = []
+ while not q.empty():
+ n = q.get()
+ ps = n.get_ancestors()
+ if len(ps) >= 1:
+ key = get_field(n)
+ lines.append((key, name_to_lineidx[get_field(ps[0])], n.__getattribute__('sub_group')))
+ labels.append(n.__getattribute__(field))
+ for c in n.children:
+ q.put(c)
+ return labels, lines
+
+def child_parent_print_tree(root):
+ synset_to_lineidx = {}
+ q = Queue.Queue()
+ q.put(root)
+ idx = -1
+ while not q.empty():
+ n = q.get()
+ synset_to_lineidx[n.synset] = idx
+ idx = idx + 1
+ for c in n.children:
+ q.put(c)
+ q.put(root)
+ lines = []
+ while not q.empty():
+ n = q.get()
+ ps = n.get_ancestors()
+ if len(ps) >= 1:
+ lines.append('{}{:0>8} {}'.format(n.synset.pos(),
+ n.synset.offset(),
+ synset_to_lineidx[ps[0].synset]))
+ for c in n.children:
+ q.put(c)
+ return lines
+
+def breadth_first_print_tree(root):
+ if root == None or len(root.children) == 0:
+ return []
+ parts = []
+ n = get_nick_name(root.synset)
+ parts.append('{}({}):{}'.format(n, synset_to_noffset(root.synset),
+ len(root.children)))
+ if len(root.children) > 0:
+ parts.append(':')
+ parts.append(','.join(map(lambda c:
+ '{}({})'.format(get_nick_name(c.synset),
+ synset_to_noffset(c.synset)),
+ root.children)))
+ result = []
+ result.append(''.join(parts))
+ for c in root.children:
+ result += breadth_first_print_tree(c)
+ return result
+
+def populate_cum_images(root):
+ cum_images_with_bb = root.images_with_bb
+ cum_images_no_bb = root.images_no_bb
+ for c in root.children:
+ populate_cum_images(c)
+ cum_images_with_bb = cum_images_with_bb + c.cum_images_with_bb
+ cum_images_no_bb = cum_images_no_bb + c.cum_images_no_bb
+
+ root.add_feature('cum_images_with_bb', cum_images_with_bb)
+ root.add_feature('cum_images_no_bb', cum_images_no_bb)
+
+def load_label_parentidx_as_tree(label_parentidx, labels):
+ root = Tree()
+ root.name = 'root'
+ label_node = {}
+ for label in labels:
+ parientid = label_parentidx[label]
+ if parientid == -1:
+ c = root.add_child(name=label)
+ else:
+ parentnode = label_node[labels[parientid]]
+ c = parentnode.add_child(name=label)
+ label_node[label] = c
+ return root
+
+def load_label_tree(noffset_parentidx, noffsets):
+ root = Tree()
+ root_synset = wn.synset('physical_entity.n.01')
+ root.name = root_synset.name()
+ root.add_feature('synset', root_synset)
+ noffset_node = {}
+ for noffset in noffsets:
+ parientid = noffset_parentidx[noffset]
+ if parientid == -1:
+ c = root.add_child(name=noffset)
+ else:
+ parentnode = noffset_node[noffsets[parientid]]
+ c = parentnode.add_child(name=noffset)
+ noffset_node[noffset] = c
+ return prune_root(root), noffset_node
+
+def load_label_parent(label_tree_file):
+ buf = read_to_buffer(label_tree_file).split('\n')
+ label_map = [b.split(' ') for b in buf]
+ # hack: the labelmap should be in the same folder with the tree file
+ # sometimes, the label in the tree file is different than the name in
+ # labelmap because there should be no whitespace in the label part. Thus,
+ # we have to use the labelmap to replace the labels in the tree file
+ true_labels = load_list_file(op.join(op.dirname(label_tree_file), 'labelmap.txt'))
+ for i, true_label in enumerate(true_labels):
+ label_map[i][0] = true_label
+ if len(label_map[-1]) == 1:
+ label_map = label_map[:-1]
+ label_idx, label_parentidx = {}, {}
+ labels = []
+ idx = 0
+ for l_pi in label_map:
+ label, pi = l_pi[:2]
+ pi = int(pi)
+ label_parentidx[label] = pi
+ label_idx[label] = idx
+ idx = idx + 1
+ labels.append(label)
+ return label_idx, label_parentidx, labels
+
+def dump_tree(root, feature_name=None, for_train=False):
+ # we use ordereddict to keep teh way how to add. We add the name at the
+ # very end so that the result is first with property and then with the
+ # name, which might have children
+ result = OrderedDict()
+ if feature_name is None:
+ for f in sorted(root.features):
+ if f in ['support', 'name', 'dist', 'synset']:
+ continue
+ result[f] = root.__getattribute__(f)
+ elif type(feature_name) == list:
+ for f in feature_name:
+ if hasattr(root, f):
+ result[f] = root.__getattribute__(f)
+ elif type(feature_name) == str:
+ if feature_name != 'name':
+ result[feature_name] = root.__getattribute__(feature_name)
+ if for_train:
+ if 'sub_group' in result:
+ # we remove the sub group here since it is auto-generated. we will add
+ # the __ node if the sub group changes
+ del result['sub_group']
+ if len(result) == 0 and len(root.children) == 0:
+ # in this case, we just use a string to represent the node
+ return str(root.name)
+ else:
+ result[root.name] = []
+ if for_train:
+ pre_sub_group = None
+ for c in root.children:
+ if for_train:
+ if pre_sub_group is None:
+ pre_sub_group = c.sub_group
+ if c.sub_group != pre_sub_group:
+ # we add the seperator to denote a new sub group
+ result[root.name].append('__')
+ pre_sub_group = c.sub_group
+ result[str(root.name)].append(dump_tree(c, feature_name, for_train))
+ return result
+
+def synonym_list():
+ p = []
+ p.append(('airplane', 'aeroplane'))
+ #p.append(('tv', 'tvmonitor'))
+ p.append(('motorcycle', 'motorbike'))
+ p.append(('couch', 'sofa'))
+ return p
+
+def synonym():
+ p = synonym_list()
+ result = {}
+ for a, b in p:
+ result[a] = b
+ result[b] = a
+ return result
+
+def noffset_to_synset(noffset):
+ noffset = noffset.strip()
+ return wn.synset_from_pos_and_offset(noffset[0], int(noffset[1:]))
+
+def create_labelmap_map(from_labelmap, to_labelmap):
+ with open(from_labelmap, 'r') as fp:
+ from_labels = [line.strip() for line in fp.readlines()]
+ with open(to_labelmap, 'r') as fp:
+ to_labels = [line.strip() for line in fp.readlines()]
+ to_labels2 = [label.replace(' ', '') for label in to_labels]
+ result = {}
+ syn = synonym()
+ for label in from_labels:
+ label2 = label.replace(' ', '')
+ if label2 in to_labels2:
+ idx = to_labels2.index(label2)
+ result[label] = to_labels[idx]
+ elif label2 in syn and syn[label2] in to_labels2:
+ idx = to_labels2.index(syn[label2])
+ result[label] = to_labels2[idx]
+ else:
+ result[label] = None
+ return result
+
+class LabelToSynset(object):
+ def __init__(self, disambiguity_by_22k=False):
+ self._white_list = {'apple': [wn.synset_from_pos_and_offset('n', 7739125)],
+ 'banana': [wn.synset_from_pos_and_offset('n', 7753592)],
+ 'bear': [wn.synset_from_pos_and_offset('n', 2131653)],
+ 'bed': [wn.synset_from_pos_and_offset('n', 2818832)],
+ 'bench': [wn.synset_from_pos_and_offset('n', 2828884)],
+ 'device': [wn.synset_from_pos_and_offset('n', 3183080)],
+ 'chair': [wn.synset_from_pos_and_offset('n', 3001627)],
+ 'pen': [wn.synset_from_pos_and_offset('n', 3906997)],
+ 'marker': [wn.synset_from_pos_and_offset('n', 3722007)],
+ 'book': [wn.synset_from_pos_and_offset('n', 6410904)],
+ 'coke': [wn.synset_from_pos_and_offset('n', 7928696)],
+ 'ring': [wn.synset_from_pos_and_offset('n', 4092609)],
+ 'tv': [wn.synset_from_pos_and_offset('n', 6277280)],
+ 'television': [wn.synset_from_pos_and_offset('n', 6277280)],
+ 'projector': [wn.synset_from_pos_and_offset('n', 4009552)],
+ 'telephone': [wn.synset_from_pos_and_offset('n', 4401088)],
+ 'dish': [wn.synset_from_pos_and_offset('n', 3206908)],
+ 'monitor': [wn.synset_from_pos_and_offset('n', 3782190)],
+ 'eyeglasses': [wn.synset_from_pos_and_offset('n', 4272054)],
+ 'sun glasses': [wn.synset_from_pos_and_offset('n', 4356056)],
+ 'pencil': [wn.synset_from_pos_and_offset('n', 3908204)],
+ }
+ self._update_by_name_map('./aux_data/label_to_noffset')
+ s = synonym()
+ for k1 in s:
+ k2 = s[k1]
+ if k1 in self._white_list:
+ if k2 in self._white_list:
+ assert self._white_list[k1] == self._white_list[k2]
+ else:
+ self._white_list[k2] = self._white_list[k1]
+ elif k2 in self._white_list:
+ self._white_list[k1] = self._white_list[k2]
+
+ labels = list(self._white_list.keys())
+ for label in labels:
+ anchor = self._white_list[label]
+ equal_ls = self._equal_labels(label)
+ for l in equal_ls:
+ if l in self._white_list:
+ assert self._white_list[l] == anchor
+ else:
+ self._white_list[l] = anchor
+ self.disambiguity_by_22k = disambiguity_by_22k
+ if disambiguity_by_22k:
+ self.imagenet22k_noffsets = \
+ set(load_list_file('./data/imagenet22k_448/labelmap.txt'))
+
+ def populate_noffset(self, root):
+ if not hasattr(root, 'noffset') or root.noffset is None:
+ if root.up and hasattr(root.up, 'noffset') and root.up.noffset:
+ cresult, s = self.convert(root.name,
+ [noffset_to_synset(no) for no in
+ root.up.noffset.split(',')])
+ else:
+ cresult, s = self.convert(root.name)
+ assert type(s) is list
+ if cresult:
+ root.add_feature('noffset', ','.join([synset_to_noffset(x) for
+ x in s]))
+ else:
+ root.add_feature('noffset', None)
+ if len(s) >= 1:
+ root.add_feature('noffsets', ','.join([synset_to_noffset(o) for o in
+ s]))
+ else:
+ logging.info('cannot find {}'.format(root.name.encode('UTF-8')))
+
+ for c in root.children:
+ self.populate_noffset(c)
+
+ def _update_by_name_map(self, folder):
+ for yaml_file in glob.glob(op.join(folder, '*.yaml')):
+ logging.info('loadding {}'.format(yaml_file))
+ wl = load_from_yaml_file(yaml_file)
+ for d in wl:
+ if d['noffset'] is None:
+ continue
+ d['name'] = d['name'].lower()
+ if d['name'] not in self._white_list:
+ self._white_list[d['name']] = []
+ self._white_list[d['name']].extend([noffset_to_synset(x) for x in
+ d['noffset'].split(',')])
+ self._white_list[d['name']] = list(set(self._white_list[d['name']]))
+
+ def convert(self, label, parent_synsets=None):
+ '''
+ return: correct, list of synset
+ '''
+ if re.match('^n[0-9]{8}$', label):
+ return True, [noffset_to_synset(label)]
+ label = label.lower()
+
+ labels = self._equal_labels(label)
+ for label in labels:
+ if label in self._white_list:
+ return True, self._white_list[label]
+
+ result = []
+ for label in labels:
+ sss = wn.synsets(label, pos='n')
+ result.extend(sss)
+ result = list(set(result))
+
+ if len(result) > 1 and parent_synsets:
+ matched_parent = [True] * len(result)
+ for i, r in enumerate(result):
+ matched = False
+ for p in r.hypernym_paths():
+ for n in p:
+ if n in parent_synsets:
+ matched = True
+ break
+ if not matched:
+ matched_parent[i] = False
+ result = [r for r, m in zip(result, matched_parent) if m]
+ if len(result) == 1:
+ logging.info('successfully disambiguate {} based on the parent {}'.format(
+ label, [ps.name() for ps in parent_synsets]))
+
+ if len(result) > 1 and self.disambiguity_by_22k:
+ result = [r for r in result if synset_to_noffset(r) in
+ self.imagenet22k_noffsets]
+
+ if len(result) == 1:
+ return True, result
+
+ return False, result
+
+ def _equal_labels(self, label):
+ r = [label]
+ if ' ' in label:
+ r += [label.replace(' ', '_'), label.replace(' ', '')]
+ return r
+
+
+def populate_url_for_offset(root):
+ if not hasattr(root, 'noffset'):
+ populate_noffset(root)
+ if root.noffset:
+ noffsets = root.noffset.split(',')
+ urls = ['[{0}](http://www.image-net.org/synset?wnid={0})'.format(noffset) for
+ noffset in noffsets]
+ root.add_feature('url', ','.join(urls))
+ if hasattr(root, 'noffsets'):
+ noffsets = root.noffsets.split(',')
+ urls = ['[{0}](http://www.image-net.org/synset?wnid={0})'.format(noffset) for
+ noffset in noffsets]
+ root.add_feature('markdown_url', ','.join(urls))
+ for c in root.children:
+ populate_url_for_offset(c)
+
+def populate_noffset(root):
+ logging.info('deprecated here')
+ mapper = LabelToSynset()
+ mapper.populate_noffset(root)
+
+def disambibuity_noffsets(root, keys):
+ if hasattr(root, 'noffsets') and root.noffsets:
+ noffsets = root.noffsets.split(',')
+ exists = [noffset in keys for noffset in noffsets]
+ left = [noffset for noffset, exist in zip(noffsets, exists) if exist]
+ if len(left) == 1:
+ root.del_feature('noffsets')
+ root.add_feature('noffset', left[0])
+ elif len(left) != noffsets and len(left) > 0:
+ root.noffsets = ','.join(left)
+ elif len(left) == 0:
+ root.del_feature('noffsets')
+ for c in root.children:
+ disambibuity_noffsets(c, keys)
+
+class Taxonomy(object):
+ def __init__(self, tax, name='root'):
+ self.root = None
+ self.tax = tax
+ self.name = name
+ self.build_from_local()
+
+ # cache information
+ self.name_to_ancestors = None
+ self.update()
+
+ def get_name_to_nodes(self):
+ name_to_nodes = defaultdict(list)
+ for node in tqdm(self.root.iter_search_nodes()):
+ if node == self.root:
+ continue
+ name_to_nodes[node.name].append(node)
+ return name_to_nodes
+
+ def get_name_to_ancestor_names(self):
+ # we can have duplicate names in the structure. one example is
+ # openimage v5 dataset
+ name_to_nodes = self.get_name_to_nodes()
+ name_to_ancestor_names = {}
+ for name, nodes in name_to_nodes.items():
+ ancestor_names = []
+ for n in nodes:
+ ancestor_names.extend([a.name for a in n.get_ancestors()[:-1]])
+ name_to_ancestor_names[name] = list(set(ancestor_names))
+ return name_to_ancestor_names
+
+ def update(self):
+ self.name_to_ancestors = {}
+ self.name_to_ancestors_list = {}
+ for node in self.root.iter_search_nodes():
+ if node == self.root:
+ continue
+ name = node.name
+ ancestors = node.get_ancestors()[:-1]
+ self.name_to_ancestors[name] = set(a.name for a in ancestors)
+ self.name_to_ancestors_list[name] = [a.name for a in ancestors]
+
+ def _add_current_as_child(self, one, root):
+ '''
+ one has not been in root
+ '''
+ if type(one) is dict:
+ list_value_keys = [k for k in one if type(one[k]) is list]
+ if len(list_value_keys) == 1:
+ name = list_value_keys[0]
+ else:
+ assert 'name' in one, one
+ name = one['name']
+ assert isinstance(name, str), "{} in {} not string".format(name, root)
+ child_subgroups = getattr(root, 'child_subgroups', -1)
+ if name.startswith('__'):
+ # just increase the subgroups count of the root
+ setattr(root, 'child_subgroups', child_subgroups + 1)
+ return
+ sub_root = root.add_child(name=name)
+ feats = {'sub_group': child_subgroups}
+ for k in one:
+ v = one[k]
+ if type(v) is not list and k != 'name':
+ feats[k] = v
+ sub_root.add_features(**feats)
+ if len(list_value_keys) == 1:
+ for sub_one in one[list_value_keys[0]]:
+ self._add_current_as_child(sub_one, sub_root)
+ else:
+ if one is None:
+ one = 'None'
+ name = one
+ assert type(name) is str or type(name) is unicode
+ child_subgroups = getattr(root, 'child_subgroups', -1)
+ if name.startswith('__'):
+ # just increase the subgroups count of the root
+ setattr(root, 'child_subgroups', child_subgroups + 1)
+ return
+ sub_root = root.add_child(name=name)
+ sub_root.add_features(sub_group=child_subgroups)
+
+ def build_from_local(self):
+ tax = self.tax
+ assert type(tax) is list
+ self.root = Tree()
+ self.root.name = self.name
+ for one in tax:
+ self._add_current_as_child(one, self.root)
+
+ def dump(self, feature_name=None, for_train=False):
+ result = []
+ for c in self.root.children:
+ result.append(dump_tree(c, feature_name, for_train))
+ return result
+
+ def _add_children(self, one, root):
+ '''
+ deprecated
+ one: a dictionary, whose information has already been in root
+ '''
+ if type(one) is str:
+ return
+ assert type(one) is dict, type(one)
+ values = [one[k] for k in one if type(one[k]) is list]
+ if len(values) == 1:
+ for one_value in values[0]:
+ if type(one_value) is str:
+ sub_root = root.add_child(name = one_value)
+ else:
+ feats = {}
+ for k in one_value:
+ v = one_value[k]
+ if type(v) is not list:
+ feats[k] = v
+ else:
+ n = k
+ sub_root = root.add_child(name=n)
+ sub_root.add_features(**feats)
+ self._add_children(one_value, sub_root)
+ else:
+ assert len(values) == 0
+
+def noffset_to_url(noffset):
+ return 'http://www.image-net.org/synset?wnid={}'.format(noffset)
+
+def load_voc_xml(filename):
+ tree = ET.parse(filename)
+ objs = tree.findall('object')
+ if not False:
+ # Exclude the samples labeled as difficult
+ non_diff_objs = [
+ obj for obj in objs if int(obj.find('difficult').text) == 0]
+ # if len(non_diff_objs) != len(objs):
+ # print 'Removed {} difficult objects'.format(
+ # len(objs) - len(non_diff_objs))
+ objs = non_diff_objs
+ num_objs = len(objs)
+
+ gt = []
+
+ size = tree.find('size')
+ width = float(size.find('width').text)
+ height = float(size.find('height').text)
+
+ # Load object bounding boxes into a data frame.
+ for ix, obj in enumerate(objs):
+ name = obj.find('name').text.lower().strip()
+ diff = int(obj.find('difficult').text)
+ bbox = obj.find('bndbox')
+ # Make pixel indexes 0-based
+ x1 = float(bbox.find('xmin').text) - 1
+ y1 = float(bbox.find('ymin').text) - 1
+ x2 = float(bbox.find('xmax').text) - 1
+ y2 = float(bbox.find('ymax').text) - 1
+ bbox = [x1, y1, x2, y2]
+ gt.append({'diff': diff, 'class': name, 'rect': bbox})
+ return gt, height, width
+
+def gen_image_gt_by_noffset(noffset, annotation_root, image_root):
+ if not ensure_untar(noffset):
+ return
+ curr_folder = op.join(annotation_root, noffset)
+ files = glob.glob(op.join(curr_folder, '*.xml'))
+ for curr_file in files:
+ xml_basename = op.splitext(op.basename(curr_file))[0]
+ image_file_name = op.join(image_root, noffset,
+ xml_basename + ".JPEG")
+ if not op.isfile(image_file_name):
+ logging.info('not exist: {}'.format(image_file_name))
+ continue
+ gt, height, width = load_voc_xml(curr_file)
+ if len(gt) == 0:
+ logging.info('no bb: {}'.format(image_file_name))
+ continue
+ yield xml_basename, image_file_name, gt, height, width
+
+def load_all_tax(tax_folder):
+ logging.info(tax_folder)
+ all_yaml = glob.glob(op.join(tax_folder, '*.yaml'))
+ all_tax = []
+ for y in all_yaml:
+ logging.info(y)
+ with open(y, 'r') as fp:
+ config_tax = yaml.safe_load(fp)
+ name = op.splitext(op.basename(y))[0]
+ tax = Taxonomy(config_tax, name=name)
+ all_tax.append(tax)
+ return all_tax
+
+def merge_all_tax(all_tax):
+ if len(all_tax) == 0:
+ logging.info('no taxonomy found')
+ return
+ while True:
+ all_tax2 = []
+ for i in range(len(all_tax)):
+ found = False
+ for j in range(len(all_tax)):
+ if i == j:
+ continue
+ tax1 = all_tax[i]
+ tax2 = all_tax[j]
+ nodes = tax2.root.search_nodes(name=tax1.root.name)
+ if len(nodes) == 0:
+ continue
+ else:
+ assert len(nodes) == 1, 'more than 1 {} in {}.yaml'.format(
+ tax1.root.name, tax2.root.name)
+ node = nodes[0]
+ node.children.extend(tax1.root.children)
+ found = True
+ break
+ if not found:
+ all_tax2.append(all_tax[i])
+ else:
+ all_tax2.extend(all_tax[i + 1:])
+ break
+ if len(all_tax2) == 1:
+ root_tax = all_tax2[0]
+ break
+ else:
+ assert len(all_tax) == len(all_tax2) + 1, \
+ '{} can not be merged'.format(','.join([t.root.name for t in all_tax]))
+ all_tax = all_tax2
+ all_node_names = {}
+ duplicate_names = []
+ for n in root_tax.root.iter_search_nodes():
+ if n == root_tax.root:
+ continue
+ if n.name.lower() in all_node_names:
+ duplicate_names.append(n.name)
+ else:
+ all_node_names[n.name.lower()] = True
+ if len(duplicate_names) > 0:
+ raise Exception('duplicate names detected: {}'.format(', '.join(duplicate_names)))
+ else:
+ logging.info('Good: no duplicate names detected. ')
+ return root_tax
+
+
+def gen_noffset(tax_input_folder, tax_output_folder):
+ all_tax = load_all_tax(tax_input_folder)
+ ensure_directory(tax_output_folder)
+ for tax in all_tax:
+ populate_noffset(tax.root)
+ out_file = op.join(tax_output_folder, tax.root.name + '.yaml')
+ with open(out_file, 'w') as fp:
+ yaml.dump(tax.dump(), fp)
+
+def gen_term_list(tax_folder, term_list):
+ all_tax = load_all_tax(tax_folder)
+ root_tax = merge_all_tax(all_tax)
+
+ all_term = ['\n'.join(['\t'.join([node.name, node.name + query_aug_str, node.name]) for query_aug_str in ['', ' instagram', ' pinterest']]) for node in root_tax.root.iter_search_nodes() if
+ node.name != root_tax.root.name]
+
+ write_to_file('\n'.join(map(lambda x: x.encode('utf-8'), all_term)),
+ term_list)
+
+def gen_cls_specific_th(tree_file, th, th_file):
+ label_idx, label_parentidx, labels = load_label_parent(tree_file)
+ root = load_label_parentidx_as_tree(label_parentidx, labels)
+ label_threshold = {}
+ for node in root.iter_search_nodes():
+ if node.name == root.name:
+ continue
+ num = len(node.get_sisters()) + 1
+ label_threshold[node.name] = 1. / num * th
+
+ write_to_file('\n'.join(['{}\t{}'.format(l, label_threshold[l])
+ for l in labels]), th_file)
+
+
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/tsv_file.py b/One-to-All-Animation/benchmark/DisCo/utils/tsv_file.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac37fc5439cb923b582d67d585b7ba0575046eb8
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/tsv_file.py
@@ -0,0 +1,166 @@
+import logging
+import os
+import os.path as op
+from .dist import is_main_process
+from .common import exclusive_open_to_read
+try:
+ from azfuse import File
+except ImportError:
+ print("azfuse is not installed")
+
+
+logger = logging.getLogger(__name__)
+if not is_main_process():
+ logger.disabled = True
+
+
+def create_lineidx(filein, idxout):
+ idxout_tmp = idxout + '.tmp'
+ with exclusive_open_to_read(filein, 'r') as tsvin, open(idxout_tmp,'w') as tsvout:
+ fsize = os.fstat(tsvin.fileno()).st_size
+ fpos = 0
+ while fpos != fsize:
+ tsvout.write(str(fpos)+"\n")
+ tsvin.readline()
+ fpos = tsvin.tell()
+ os.rename(idxout_tmp, idxout)
+
+
+def read_to_character(fp, c):
+ result = []
+ while True:
+ s = fp.read(32)
+ assert s != ''
+ if c in s:
+ result.append(s[: s.index(c)])
+ break
+ else:
+ result.append(s)
+ return ''.join(result)
+
+
+class TSVFile(object):
+ def __init__(self, tsv_file, generate_lineidx=False):
+ self.tsv_file = tsv_file
+ self.lineidx = op.splitext(tsv_file)[0] + '.lineidx'
+ self._fp = None
+ self._lineidx = None
+ # the process always keeps the process which opens the file.
+ # If the pid is not equal to the currrent pid, we will re-open the file.
+ self.pid = None
+ # generate lineidx if not exist
+ if not op.isfile(self.lineidx) and generate_lineidx:
+ create_lineidx(self.tsv_file, self.lineidx)
+
+ def __del__(self):
+ if self._fp:
+ self._fp.close()
+
+ def __str__(self):
+ return "TSVFile(tsv_file='{}')".format(self.tsv_file)
+
+ def __repr__(self):
+ return str(self)
+
+ def num_rows(self):
+ self._ensure_lineidx_loaded()
+ return len(self._lineidx)
+
+ def seek(self, idx):
+ self._ensure_tsv_opened()
+ self._ensure_lineidx_loaded()
+ try:
+ pos = self._lineidx[idx]
+ except:
+ logger.info('{}-{}'.format(self.tsv_file, idx))
+ raise
+ self._fp.seek(pos)
+ return [s.strip() for s in self._fp.readline().split('\t')]
+
+ def seek_first_column(self, idx):
+ self._ensure_tsv_opened()
+ self._ensure_lineidx_loaded()
+ pos = self._lineidx[idx]
+ self._fp.seek(pos)
+ return read_to_character(self._fp, '\t')
+
+ def get_key(self, idx):
+ return self.seek_first_column(idx)
+
+ def __getitem__(self, index):
+ return self.seek(index)
+
+ def __len__(self):
+ return self.num_rows()
+
+ def _ensure_lineidx_loaded(self):
+ if self._lineidx is None:
+ logger.info('loading lineidx: {}'.format(self.lineidx))
+ with exclusive_open_to_read(self.lineidx, 'r') as fp:
+ self._lineidx = [int(i.strip()) for i in fp.readlines()]
+
+ def _ensure_tsv_opened(self):
+ if self._fp is None:
+ self._fp = exclusive_open_to_read(self.tsv_file, 'r')
+ self.pid = os.getpid()
+
+ if self.pid != os.getpid():
+ logger.info('re-open {} because the process id changed'.format(self.tsv_file))
+ self._fp = exclusive_open_to_read(self.tsv_file, 'r')
+ self.pid = os.getpid()
+
+
+class CompositeTSVFile():
+ def __init__(self, file_list, seq_file, root='.'):
+ if isinstance(file_list, str):
+ self.file_list = load_list_file(file_list)
+ else:
+ assert isinstance(file_list, list)
+ self.file_list = file_list
+
+ self.seq_file = seq_file
+ self.root = root
+ self.initialized = False
+ self.initialize()
+
+ def get_key(self, index):
+ idx_source, idx_row = self.seq[index]
+ k = self.tsvs[idx_source].get_key(idx_row)
+ return '_'.join([self.file_list[idx_source], k])
+
+ def num_rows(self):
+ return len(self.seq)
+
+ def __getitem__(self, index):
+ idx_source, idx_row = self.seq[index]
+ return self.tsvs[idx_source].seek(idx_row)
+
+ def __len__(self):
+ return len(self.seq)
+
+ def initialize(self):
+ '''
+ this function has to be called in init function if cache_policy is
+ enabled. Thus, let's always call it in init funciton to make it simple.
+ '''
+ if self.initialized:
+ return
+ self.seq = []
+ with exclusive_open_to_read(self.seq_file, 'r') as fp:
+ for line in fp:
+ parts = line.strip().split('\t')
+ self.seq.append([int(parts[0]), int(parts[1])])
+ self.tsvs = [TSVFile(op.join(self.root, f)) for f in self.file_list]
+ self.initialized = True
+
+ def get_composite_source_idx(self):
+ return [int(i) for i, _ in self.seq]
+
+
+def load_list_file(fname):
+ with exclusive_open_to_read(fname, 'r') as fp:
+ lines = fp.readlines()
+ result = [line.strip() for line in lines]
+ if len(result) > 0 and result[-1] == '':
+ result = result[:-1]
+ return result
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/tsv_file_ops.py b/One-to-All-Animation/benchmark/DisCo/utils/tsv_file_ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..78156faec1bb873a37e02a84af5b5ffea9094c88
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/tsv_file_ops.py
@@ -0,0 +1,523 @@
+import os
+import os.path as op
+import json
+import numpy as np
+import base64
+import cv2
+import math
+from tqdm import tqdm
+
+from .misc import load_from_yaml_file, write_to_yaml_file
+from .tsv_file import TSVFile
+from .misc import ensure_directory, exclusive_open_to_read
+
+
+def img_from_base64(imagestring):
+ try:
+ jpgbytestring = base64.b64decode(imagestring)
+ nparr = np.frombuffer(jpgbytestring, np.uint8)
+ r = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
+ return r
+ except ValueError:
+ return None
+
+
+def load_linelist_file(linelist_file):
+ if linelist_file is not None:
+ line_list = []
+ with exclusive_open_to_read(linelist_file, 'r') as fp:
+ for i in fp:
+ line_list.append(int(i.strip()))
+ return line_list
+
+
+def tsv_writer(values, tsv_file_name, sep='\t'):
+ ensure_directory(os.path.dirname(tsv_file_name))
+ tsv_lineidx_file = os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ tsv_8b_file = tsv_lineidx_file + '.8b'
+ idx = 0
+ tsv_file_name_tmp = tsv_file_name + '.tmp'
+ tsv_lineidx_file_tmp = tsv_lineidx_file + '.tmp'
+ tsv_8b_file_tmp = tsv_8b_file + '.tmp'
+ import sys
+ is_py2 = sys.version_info.major == 2
+ if not is_py2:
+ sep = sep.encode()
+ with open(tsv_file_name_tmp, 'wb') as fp, open(
+ tsv_lineidx_file_tmp, 'w') as fpidx, open(
+ tsv_8b_file_tmp, 'wb') as fp8b:
+ assert values is not None
+ for value in values:
+ assert value is not None
+ if is_py2:
+ v = sep.join(map(
+ lambda v: v.encode('utf-8')
+ if isinstance(v, unicode)
+ else str(v), value)) + '\n'
+ else:
+ value = map(
+ lambda v: v
+ if type(v) == bytes
+ else str(v).encode(),
+ value)
+ v = sep.join(value) + b'\n'
+ fp.write(v)
+ fpidx.write(str(idx) + '\n')
+ # although we can use sys.byteorder to retrieve the system-default
+ # byte order, let's use little always to make it consistent and
+ # simple
+ fp8b.write(idx.to_bytes(8, 'little'))
+ idx = idx + len(v)
+ # the following might crash if there are two processes which are writing at
+ # the same time. One process finishes the renaming first and the second one
+ # will crash. In this case, we know there must be some errors when you run
+ # the code, and it should be a bug to fix rather than to use try-catch to
+ # protect it here.
+ os.rename(tsv_lineidx_file_tmp, tsv_lineidx_file)
+ os.rename(tsv_8b_file_tmp, tsv_8b_file)
+ os.rename(tsv_file_name_tmp, tsv_file_name)
+ assert os.path.exists(tsv_file_name)
+
+
+def generate_lineidx_file(tsv_file_name, sep='\t'):
+ ensure_directory(os.path.dirname(tsv_file_name))
+ tsv_lineidx_file = os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ tsv_8b_file = tsv_lineidx_file + '.8b'
+ idx = 0
+ tsv_lineidx_file_tmp = tsv_lineidx_file + '.tmp'
+ tsv_8b_file_tmp = tsv_8b_file + '.tmp'
+ import sys
+ is_py2 = sys.version_info.major == 2
+ if not is_py2:
+ sep = sep.encode()
+ values = tsv_reader(tsv_file_name)
+ with open(
+ tsv_lineidx_file_tmp, 'w') as fpidx, open(
+ tsv_8b_file_tmp, 'wb') as fp8b:
+ for value in values:
+ assert value is not None
+ if is_py2:
+ v = sep.join(map(
+ lambda v: v.encode('utf-8')
+ if isinstance(v, unicode)
+ else str(v), value)) + '\n'
+ else:
+ value = map(
+ lambda v: v
+ if type(v) == bytes
+ else str(v).encode(),
+ value)
+ v = sep.join(value) + b'\n'
+ fpidx.write(str(idx) + '\n')
+ # although we can use sys.byteorder to retrieve the system-default
+ # byte order, let's use little always to make it consistent and
+ # simple
+ fp8b.write(idx.to_bytes(8, 'little'))
+ idx = idx + len(v)
+ # the following might crash if there are two processes which are writing at
+ # the same time. One process finishes the renaming first and the second one
+ # will crash. In this case, we know there must be some errors when you run
+ # the code, and it should be a bug to fix rather than to use try-catch to
+ # protect it here.
+ os.rename(tsv_lineidx_file_tmp, tsv_lineidx_file)
+ os.rename(tsv_8b_file_tmp, tsv_8b_file)
+ assert os.path.exists(tsv_lineidx_file)
+
+
+def tsv_reader(tsv_file, sep='\t'):
+ with exclusive_open_to_read(tsv_file, 'r') as fp:
+ for i, line in enumerate(fp):
+ yield [x.strip() for x in line.split(sep)]
+
+
+def config_save_file(tsv_file, save_file=None, append_str='.new.tsv'):
+ if save_file is not None:
+ return save_file
+ return op.splitext(tsv_file)[0] + append_str
+
+
+def get_line_list(linelist_file=None, num_rows=None):
+ if linelist_file is not None:
+ return load_linelist_file(linelist_file)
+
+ if num_rows is not None:
+ return [i for i in range(num_rows)]
+
+
+def generate_hw_file(img_file, save_file=None):
+ rows = tsv_reader(img_file)
+
+ def gen_rows():
+ for i, row in tqdm(enumerate(rows)):
+ row1 = [row[0]]
+ img = img_from_base64(row[-1])
+ height = img.shape[0]
+ width = img.shape[1]
+ row1.append(json.dumps([{"height": height, "width": width}]))
+ yield row1
+
+ save_file = config_save_file(img_file, save_file, '.hw.tsv')
+ tsv_writer(gen_rows(), save_file)
+
+
+def generate_labelmap_file(label_file, save_file=None):
+ rows = tsv_reader(label_file)
+ labelmap = []
+ for i, row in enumerate(rows):
+ labelmap.extend(set([rect['class'] for rect in json.loads(row[1])]))
+ labelmap = sorted(list(set(labelmap)))
+
+ save_file = config_save_file(label_file, save_file, '.labelmap.tsv')
+ with open(save_file, 'w') as f:
+ f.write('\n'.join(labelmap))
+
+
+def extract_column(tsv_file, col=1, save_file=None):
+ rows = tsv_reader(tsv_file)
+
+ def gen_rows():
+ for i, row in enumerate(rows):
+ row1 = [row[0], row[col]]
+ yield row1
+
+ save_file = config_save_file(
+ tsv_file, save_file, '.col.{}.tsv'.format(col))
+ tsv_writer(gen_rows(), save_file)
+
+
+def remove_column(tsv_file, col=1, save_file=None):
+ rows = tsv_reader(tsv_file)
+
+ def gen_rows():
+ for i, row in enumerate(rows):
+ del row[col]
+ yield row
+
+ save_file = config_save_file(
+ tsv_file, save_file, '.remove.{}.tsv'.format(col))
+ tsv_writer(gen_rows(), save_file)
+
+
+def generate_linelist_file(label_file, save_file=None, ignore_attrs=()):
+ # generate a list of image that has labels
+ # images with only ignore labels are not selected.
+ line_list = []
+ rows = tsv_reader(label_file)
+ for i, row in tqdm(enumerate(rows)):
+ labels = json.loads(row[1])
+ if labels:
+ if ignore_attrs and all([
+ any([lab[attr] for attr in ignore_attrs if attr in lab])
+ for lab in labels]):
+ continue
+ line_list.append([i])
+
+ save_file = config_save_file(label_file, save_file, '.linelist.tsv')
+ tsv_writer(line_list, save_file)
+
+
+def random_drop_labels(
+ label_file, drop_ratio, linelist_file=None,
+ save_file=None, drop_image=False):
+ # randomly drop labels by the ratio
+ # if drop_image is true, can drop an image by removing all labels
+ # otherwise will keep at least one label for each image to make sure
+ # the number of images is equal
+ rows = tsv_reader(label_file)
+ line_list = get_line_list(linelist_file)
+ rows_new = []
+ cnt_original = 0
+ cnt_new = 0
+ for i, row in enumerate(rows):
+ if line_list and (i not in line_list):
+ row_new = [row[0], json.dumps([])]
+ else:
+ labels = json.loads(row[1])
+ if len(labels) == 0:
+ labels_new = []
+ else:
+ rand = np.random.random(len(labels))
+ labels_new = [
+ obj for j, obj in enumerate(labels)
+ if rand[j] >= drop_ratio]
+ if not drop_image and not labels_new:
+ # make sure there is at least one label
+ # if drop image is not allowed
+ labels_new = [labels[0]]
+ cnt_original += len(labels)
+ cnt_new += len(labels_new)
+ row_new = [row[0], json.dumps(labels_new)]
+ rows_new.append(row_new)
+
+ save_file = config_save_file(
+ label_file, save_file, '.drop.{}.tsv'.format(drop_ratio))
+ tsv_writer(rows_new, save_file)
+ print("original labels = {}".format(cnt_original))
+ print("new labels = {}".format(cnt_new))
+ print("given drop_ratio = {}".format(drop_ratio))
+ print("real drop_ratio = {}".format(
+ float(cnt_original - cnt_new) / cnt_original))
+
+
+def merge_two_label_files(label_file1, label_file2, save_file=None):
+ rows1 = tsv_reader(label_file1)
+ rows2 = tsv_reader(label_file2)
+
+ rows_new = []
+ for row1, row2 in zip(rows1, rows2):
+ assert row1[0] == row2[0]
+ labels = json.loads(row1[1]) + json.loads(row2[1])
+ rows_new.append([row1[0], json.dumps(labels)])
+
+ save_file = config_save_file(label_file1, save_file, '.merge.tsv')
+ tsv_writer(rows_new, save_file)
+
+
+def is_same_keys_for_files(
+ tsv_file1, tsv_file2, linelist_file1=None,
+ linelist_file2=None):
+ # check if two files have the same keys for all rows
+ tsv1 = TSVFile(tsv_file1)
+ tsv2 = TSVFile(tsv_file2)
+ line_list1 = get_line_list(linelist_file1, tsv1.num_rows())
+ line_list2 = get_line_list(linelist_file2, tsv2.num_rows())
+ assert len(line_list1) == len(line_list2)
+ for idx1, idx2 in zip(line_list1, line_list2):
+ row1 = tsv1.seek(idx1)
+ row2 = tsv2.seek(idx2)
+ if row1[0] == row2[0]:
+ continue
+ else:
+ print("key mismatch {}-{}".format(row1[0], row2[0]))
+ return False
+ return True
+
+
+def sort_file_based_on_keys(ref_file, tsv_file, save_file=None):
+ # sort tsv_file to have the same key in each row as ref_file
+ if is_same_keys_for_files(ref_file, tsv_file):
+ print("file keys are the same, skip sorting")
+ return tsv_file
+
+ ref_keys = [row[0] for row in tsv_reader(ref_file)]
+ all_keys = [row[0] for row in tsv_reader(tsv_file)]
+ indexes = [all_keys.index(key) for key in ref_keys]
+ tsv = TSVFile(tsv_file)
+
+ def gen_rows():
+ for idx in indexes:
+ yield tsv.seek(idx)
+
+ save_file = config_save_file(tsv_file, save_file, '.sorted.tsv')
+ tsv_writer(gen_rows(), save_file)
+
+
+def reorder_tsv_keys(in_tsv_file, ordered_keys, out_tsv_file):
+ tsv = TSVFile(in_tsv_file)
+ keys = [tsv.seek(i)[0] for i in tqdm(range(len(tsv)))]
+ key_to_idx = {key: i for i, key in enumerate(keys)}
+
+ def gen_rows():
+ for key in tqdm(ordered_keys):
+ idx = key_to_idx[key]
+ yield tsv.seek(idx)
+ tsv_writer(gen_rows(), out_tsv_file)
+
+
+def reorder_tsv_keys_with_file(in_tsv_file, ref_tsv_file, out_tsv_file):
+ ordered_keys = [row[0] for row in tsv_reader(ref_tsv_file)]
+ reorder_tsv_keys(in_tsv_file, ordered_keys, out_tsv_file)
+
+
+def convert_caption_json_to_tsv(caption_json_file, key_tsv_file, out_tsv_file):
+ keys = [row[0] for row in tsv_reader(key_tsv_file)]
+ rows_dict = {key: [] for key in keys}
+
+ with open(caption_json_file, 'r') as f:
+ captions = json.load(f)
+
+ for cap in captions:
+ image_id = cap['image_id']
+ del cap['image_id']
+ if image_id in rows_dict:
+ rows_dict[image_id].append(cap)
+
+ rows = [[key, json.dumps(rows_dict[key])] for key in keys]
+ tsv_writer(rows, out_tsv_file)
+
+
+def generate_caption_linelist_file(caption_tsv_file, save_file=None):
+ num_captions = []
+ for row in tsv_reader(caption_tsv_file):
+ num_captions.append(len(json.loads(row[1])))
+
+ cap_linelist = [
+ '\t'.join([str(img_idx), str(cap_idx)])
+ for img_idx in range(len(num_captions))
+ for cap_idx in range(num_captions[img_idx])
+ ]
+ save_file = config_save_file(caption_tsv_file, save_file, '.linelist.tsv')
+ with open(save_file, 'w') as f:
+ f.write('\n'.join(cap_linelist))
+
+
+def convert_feature_format(in_tsv, out_tsv, fea_dim=None):
+ # convert the old feature file format to new one
+ # set fea_dim to remove spatial features if necessary.
+ def gen_rows():
+ for row in tqdm(tsv_reader(in_tsv)):
+ key = row[0]
+ feat_info = json.loads(row[1])
+ num_boxes = feat_info['num_boxes']
+ features = np.frombuffer(
+ base64.b64decode(feat_info['features']), np.float32
+ ).reshape(num_boxes, -1)
+ if fea_dim:
+ feat_info_new = [
+ {'feature': base64.b64encode(
+ features[i][:fea_dim]).decode('utf-8')}
+ for i in range(num_boxes)]
+ else:
+ feat_info_new = [
+ {'feature': base64.b64encode(
+ features[i]).decode('utf-8')}
+ for i in range(num_boxes)]
+ yield [key, json.dumps(feat_info_new)]
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def convert_feature_format2(in_tsv, out_tsv, fea_dim=None):
+ # new format from Pengchuan
+ def gen_rows():
+ for row in tqdm(tsv_reader(in_tsv)):
+ key = row[0]
+ num_boxes = int(row[1])
+ features = np.frombuffer(
+ base64.b64decode(row[2]), np.float32).reshape(num_boxes, -1)
+ if fea_dim:
+ feat_info = [
+ {'feature': base64.b64encode(
+ features[i][:fea_dim]).decode('utf-8')}
+ for i in range(num_boxes)]
+ else:
+ feat_info = [
+ {'feature': base64.b64encode(
+ features[i]).decode('utf-8')}
+ for i in range(num_boxes)]
+ yield [key, json.dumps(feat_info)]
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def merge_label_fields(in_tsv1, in_tsv2, out_tsv):
+ # merge the label fields for each box
+ def gen_rows():
+ for row1, row2 in tqdm(zip(tsv_reader(in_tsv1), tsv_reader(in_tsv2))):
+ assert row1[0] == row2[0]
+ label_info1 = json.loads(row1[1])
+ label_info2 = json.loads(row2[1])
+ assert len(label_info1) == len(label_info2)
+ for lab1, lab2 in zip(label_info1, label_info2):
+ lab1.update(lab2)
+ yield [row1[0], json.dumps(label_info1)]
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def remove_label_fields(in_tsv, out_tsv, remove_fields):
+ if type(remove_fields) == str:
+ remove_fields = [remove_fields]
+ assert type(remove_fields) == list
+
+ def gen_rows():
+ for row in tqdm(tsv_reader(in_tsv)):
+ label_info = json.loads(row[1])
+ for lab in label_info:
+ for field in remove_fields:
+ if field in lab:
+ del lab[field]
+ yield [row[0], json.dumps(label_info)]
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def random_permute_label_file(in_tsv, out_tsv):
+ # take a label file as input and randomly match image
+ # with the label from a different image
+ tsv = TSVFile(in_tsv)
+ random_index = np.random.permutation(tsv.num_rows())
+
+ def gen_rows():
+ for idx, rand_idx in enumerate(random_index):
+ key = tsv.seek(idx)[0]
+ labels = tsv.seek(rand_idx)[1]
+ yield [key, labels]
+ tsv_writer(gen_rows(), out_tsv)
+ # save the random index for reference
+ save_file = op.splitext(out_tsv)[0] + '.random_index.tsv'
+ with open(save_file, 'w') as f:
+ f.write('\n'.join([str(idx) for idx in random_index]))
+
+
+def create_mini_yaml_with_linelist(in_yaml, num_files):
+ # create linelist files to split a yaml into multiple ones
+ # useful for inference on large-scale dataset
+ data_cfg = load_from_yaml_file(in_yaml)
+ data_dir = op.dirname(in_yaml)
+ split_name = op.basename(in_yaml).split('.')[0]
+ hw_file = op.join(data_dir, data_cfg['hw'])
+ num_rows = TSVFile(hw_file).num_rows()
+ rows_per_file = math.ceil(num_rows / num_files)
+ for idx in range(num_files):
+ start_idx = idx * rows_per_file
+ end_idx = min(start_idx + rows_per_file, num_rows)
+ linelist = [str(i) for i in range(start_idx, end_idx)]
+ linelist_file = op.join(
+ data_dir, split_name + '.linelist_{}.tsv'.format(idx))
+ print("create linelist file: " + linelist_file)
+ with open(linelist_file, 'w') as f:
+ f.write('\n'.join(linelist))
+ data_cfg['linelist'] = op.basename(linelist_file)
+ out_yaml = op.splitext(in_yaml)[0] + '_{}.yaml'.format(idx)
+ write_to_yaml_file(data_cfg, out_yaml)
+ print("create yaml file: " + out_yaml)
+
+
+def mapping_labels(in_tsv, out_tsv, label_mapping_dict):
+ def gen_rows():
+ for row in tsv_reader(in_tsv):
+ label_info = json.loads(row[1])
+ for lab in label_info:
+ if lab['class'] in label_mapping_dict:
+ lab['class'] = label_mapping_dict[lab['class']]
+ yield [row[0], json.dumps(label_info)]
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def select_rows_in_linelist(in_tsv, out_tsv, linelist_file):
+ tsv = TSVFile(in_tsv)
+ line_list = load_linelist_file(linelist_file)
+
+ def gen_rows():
+ for idx in line_list:
+ yield tsv.seek(idx)
+ tsv_writer(gen_rows(), out_tsv)
+
+
+def generate_full_region_label_file(
+ hw_tsv, out_tsv, class_name=None):
+ # given a height/width file, generate a label file
+ def gen_rows():
+ for row in tsv_reader(hw_tsv):
+ try:
+ data = json.loads(row[1])
+ assert type(data) in (list, dict)
+ if type(data) == list:
+ height, width = data[0]['height'], data[0]['width']
+ else:
+ height, width = data['height'], data['width']
+ except ValueError:
+ hw_str = row[1].split(' ')
+ height, width = int(hw_str[0]), int(hw_str[1])
+ label = {'rect': [0, 0, width, height]}
+ if class_name:
+ label.update({'class': class_name})
+ yield [row[0], json.dumps([label])]
+ tsv_writer(gen_rows(), out_tsv)
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/tsv_io.py b/One-to-All-Animation/benchmark/DisCo/utils/tsv_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..4588464bddaeb06d1e8d304541f3bd1c739cc8ac
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/tsv_io.py
@@ -0,0 +1,1801 @@
+import contextlib
+import mmap
+from .common import get_file_size
+from .common import exclusive_open_to_read
+import time
+import multiprocessing as mp
+from .common import limited_retry_agent
+import logging
+from pprint import pformat
+import glob
+import json
+import random
+from .common import ensure_directory
+from .common import robust_open_to_write
+from .common import copy_file
+from .common import worth_create
+from .common import hash_sha1
+from .common import get_user_name
+from .common import load_from_yaml_str
+from .common import get_all_path, dict_get_path_value, dict_update_path_value
+import six
+import os
+import os.path as op
+from azfuse import File
+import shutil
+import re
+try:
+ from itertools import izip as zip
+except ImportError:
+ # python 3
+ pass
+#import progressbar
+from .common import qd_tqdm as tqdm
+
+
+def generate_lineidx(filein, idxout):
+ with File.open(filein, 'r') as tsvin, File.open(idxout,'w') as tsvout:
+ fsize = os.fstat(tsvin.fileno()).st_size
+ fpos = 0
+ fbar_last_pos = 0
+ fbar = tqdm(total=fsize, unit_scale=True)
+ while fpos!=fsize:
+ tsvout.write(str(fpos)+"\n");
+ tsvin.readline()
+ fpos = tsvin.tell();
+ fbar.update(fpos - fbar_last_pos)
+ fbar_last_pos = fpos
+
+def tsv_exists(o):
+ return File.isfile(o) and all(File.isfile(f) for f in get_tsv_associates(o))
+
+def get_default_splits():
+ return ['train', 'trainval', 'test', 'val']
+
+def get_tsv_lineidx(tsv_file):
+ #assert tsv_file.endswith('.tsv') or tsv_file.endswith('.txt')
+ return tsv_file[:-3] + 'lineidx'
+
+def get_tsv_lineidx_8b(tsv_file):
+ assert tsv_file.endswith('tsv') or tsv_file.endswith('txt')
+ return tsv_file[:-3] + 'lineidx.8b'
+
+def get_tsv_associates(tsv_file):
+ return [
+ #get_tsv_lineidx(tsv_file),
+ get_tsv_lineidx_8b(tsv_file)
+ ]
+
+def rm_tsv(tsv_file):
+ if op.isfile(tsv_file):
+ os.remove(tsv_file)
+ for line_idx in [get_tsv_lineidx(tsv_file),
+ get_tsv_lineidx_8b(tsv_file)]:
+ if op.isfile(line_idx):
+ os.remove(line_idx)
+
+def tsv_rm(tsv_file):
+ rm_tsv(tsv_file)
+
+def tsv_copy(src_tsv, dst_tsv):
+ copy_file(src_tsv, dst_tsv)
+ for s, t in zip(get_tsv_associates(src_tsv), get_tsv_associates(dst_tsv)):
+ if op.isfile(s):
+ copy_file(s, t)
+
+def tsv_mv(src_file, dst_file):
+ shutil.move(src_file, dst_file)
+ for s, t in zip(get_tsv_associates(src_file), get_tsv_associates(dst_file)):
+ if op.isfile(s):
+ shutil.move(s, t)
+
+def reorder_tsv_keys(in_tsv_file, ordered_keys, out_tsv_file):
+ tsv = TSVFile(in_tsv_file)
+ logging.info('loading keys in input')
+ keys = [tsv.seek_first_column(i) for i in tqdm(range(len(tsv)), mininterval=2)]
+ key_to_idx = {key: i for i, key in enumerate(keys)}
+ def gen_rows():
+ logging.info('writing')
+ for key in tqdm(ordered_keys, mininterval=2):
+ idx = key_to_idx[key]
+ yield tsv.seek(idx)
+ tsv_writer(gen_rows(), out_tsv_file)
+
+def read_to_character(fp, c):
+ result = []
+ while True:
+ s = fp.read(32)
+ assert s != b'' and s != ''
+ if c in s:
+ result.append(s[: s.index(c)])
+ break
+ else:
+ result.append(s)
+ return b''.join(result)
+
+class EqualSplitTSVFile(object):
+ def __init__(self, list_file):
+ self.list_tsv = TSVFile(list_file)
+ self.split_size = None
+ self.split2tsv = None
+
+ def ensure_initialized(self):
+ if self.split_size is None:
+ num_split = len(self.list_tsv)
+ self.split2tsv = [None for _ in range(num_split)]
+ self.split2tsv[0] = TSVFile(self.list_tsv[0][0])
+ self.split_size = len(self.split2tsv[0])
+ if num_split == 1:
+ self.len = self.split_size
+ else:
+ self.split2tsv[-1] = TSVFile(self.list_tsv[num_split - 1][0])
+ self.len = (num_split - 1) * self.split_size + len(self.split2tsv[-1])
+
+ def __iter__(self):
+ for i in range(len(self.split2tsv)):
+ if self.split2tsv[i] is None:
+ self.split2tsv[i] = TSVFile(self.list_tsv[i][0])
+ tsv = self.split2tsv[i]
+ for x in tsv:
+ yield x
+
+ def __getitem__(self, index):
+ self.ensure_initialized()
+ idx_split = index // self.split_size
+ offset = index % self.split_size
+ if self.split2tsv[idx_split] is None:
+ self.split2tsv[idx_split] = TSVFile(self.list_tsv[idx_split][0])
+ return self.split2tsv[idx_split][offset]
+
+ def __len__(self):
+ self.ensure_initialized()
+ return self.len
+
+class CompositeTSVFile(object):
+ def __init__(self, list_file, seq_file, cache_policy=False,
+ hold_buffer=0, data_dir=None,
+ ):
+ # list_file can be a loaded or constructed pair of index, rather than a
+ # filename to load. In this case, seq_file will be a list of dataset,
+ # which should implement len() and __getitem__() so that we can
+ # reference it.
+ self.seq_file = seq_file
+ self.list_file = list_file
+ self.cache_policy = cache_policy
+ self.seq = None
+ self.tsvs = []
+ # please do ont call ensure_initialized here. we wil always do it
+ # lazily. we may load a huge amount of seq, which could be super slow
+ # when spawning multiple processes.
+
+ # this means, how many tsv fp pointer we will hold. If it is 0 or less
+ # than 0, we will hold all fp pointers we need. If it is larger than 0,
+ # we only hold some, which are kept in self.hold_sources
+ self.hold_buffer = hold_buffer
+ self.hold_sources = []
+ self.data_dir = data_dir
+
+ def __repr__(self):
+ return 'CompositeTSVFile(list_file={}, seq_file={})'.format(
+ self.seq_file,
+ self.list_file
+ )
+
+ def get_row_len(self, i):
+ self.ensure_initialized()
+ idx_source, idx_row = map(int, self.seq[i])
+ result = self.tsvs[idx_source].get_row_len(idx_row)
+ return result
+
+ def get_key(self, index):
+ # added by Linjie
+ self.ensure_initialized()
+ idx_source, idx_row = map(int, self.seq[index])
+ k = self.tsvs[idx_source].get_key(idx_row)
+ return '_'.join([self.list_file[idx_source], k])
+
+ def __getitem__(self, index):
+ self.ensure_initialized()
+ idx_source, idx_row = map(int, self.seq[index])
+ start = time.time()
+ result = self.tsvs[idx_source].seek(idx_row)
+ end = time.time()
+ if end - start > 10:
+ logging.warning('too long to load fname = {}, source={}, row={}, time={}'.format(
+ self.tsvs[idx_source],
+ idx_source,
+ idx_row,
+ end - start
+ ))
+ if self.hold_buffer > 0 and idx_source not in self.hold_sources:
+ if len(self.hold_sources) >= self.hold_buffer:
+ close_idx_source = self.hold_sources.pop(0)
+ self.tsvs[close_idx_source].close_fp()
+ self.hold_sources.append(idx_source)
+ return result
+
+ def __len__(self):
+ self.ensure_initialized()
+ return len(self.seq)
+
+ def num_rows(self):
+ # added by Linjie
+ self.ensure_initialized()
+ return len(self.seq)
+
+ def __iter__(self):
+ self.ensure_initialized()
+ self.next_row = 0
+ for idx_source, idx_row in self.seq:
+ idx_source, idx_row = int(idx_source), int(idx_row)
+ yield self.tsvs[idx_source][idx_row]
+
+ def release(self):
+ # this is to ensure we released all the resources
+ self.seq = None
+ for t in self.tsvs:
+ t.close()
+
+ def close(self):
+ self.release()
+
+ def seek_first_column(self, index):
+ self.ensure_initialized()
+ idx_source, idx_row = map(int, self.seq[index])
+ return self.tsvs[idx_source].seek_first_column(idx_row)
+
+ def get_composite_source_idx(self):
+ return [int(i) for i, _ in self.seq]
+
+ def is_from_valid_file(self, idx=None):
+ self.ensure_initialized()
+ if idx is None:
+ return [self.tsvs[int(idx_source)] is not None for idx_source, _ in tqdm(self.seq)]
+ else:
+ return self.tsvs[int(self.seq[idx][0])] is not None
+
+ def ensure_initialized(self):
+ if self.seq is None:
+ if isinstance(self.list_file, str) and \
+ isinstance(self.seq_file, str):
+ self.seq = TSVFile(self.seq_file)
+ if self.data_dir is not None:
+ self.tsvs = [TSVFile(f.replace('data', self.data_dir), self.cache_policy) if f != 'd' else None for f in load_list_file(self.list_file)]
+ else:
+ self.tsvs = [TSVFile(f, self.cache_policy) if f != 'd' else None for f in load_list_file(self.list_file)]
+ else:
+ self.seq = self.list_file
+ self.tsvs = self.seq_file
+
+# wrapper of lineidx.8b
+class LongFile(object):
+ def __init__(self, fname):
+ self.fname = fname
+ self._len = None
+ self.fp = None
+ self.pid = None
+
+ def __len__(self):
+ if self._len is None:
+ self._len = File.get_file_size(self.fname) // 8
+ return self._len
+
+ def __getitem__(self, index):
+ self.ensure_opened()
+ self.fp.seek(index * 8)
+ return int.from_bytes(self.fp.read(8), 'little')
+
+ def ensure_opened(self):
+ if self.fp is None:
+ self.fp = File.open(self.fname, 'rb')
+ self.pid = os.getpid()
+ if self.pid != os.getpid():
+ self.fp.close()
+ logging.info('re-open {} because the process id changed'.format(
+ self.fname))
+ self.fp= File.open(self.fname, 'rb')
+ self.pid = os.getpid()
+
+class TSVFile(object):
+ def __init__(self, tsv_file, cache_policy=None):
+ self.tsv_file = tsv_file
+ #print(tsv_file)
+ self.lineidx = op.splitext(tsv_file)[0] + '.lineidx'
+ self.lineidx_8b = self.lineidx + '.8b'
+ self._fp = None
+ self._mfp = None
+ self._lineidx = None
+ self.fp8b = None
+ self.cache_policy= cache_policy
+ self.close_fp_after_read = False
+ if os.environ.get('QD_TSV_CLOSE_FP_AFTER_READ'):
+ self.close_fp_after_read = bool(os.environ['QD_TSV_CLOSE_FP_AFTER_READ'])
+ self.use_mmap = False
+ if os.environ.get('QD_TSV_MMAP'):
+ self.use_mmap = int(os.environ['QD_TSV_MMAP'])
+ self.use_fuse = False
+ #if os.environ.get('QD_TSV_USE_FUSE'):
+ #self.use_fuse = int(os.environ['QD_TSV_USE_FUSE'])
+ #from qd.cloud_storage import create_cloud_fuse
+ #self.fuser = create_cloud_fuse()
+ self.has_lineidx_8b = int(os.environ.get('QD_USE_LINEIDX_8B', '0'))
+ # the process always keeps the process which opens the
+ # file. If the pid is not equal to the currrent pid, we will re-open
+ # teh file.
+ self.pid = None
+ self.lineidx_8b_pid = None
+ self.open_once = False
+
+ self._len = None
+ self._tsv_file_size = None
+ print(f'{self.__repr__()}')
+
+ @property
+ def tsv_file_size(self):
+ if self._tsv_file_size is None:
+ self._tsv_file_size = File.get_file_size(self.tsv_file)
+ return self._tsv_file_size
+
+ def get_row_len(self, i):
+ start = self.get_offset(i)
+ if i < len(self) - 1:
+ end = self.get_offset(i + 1)
+ else:
+ end = self.tsv_file_size
+ return end - start
+
+ def get_row_offsets(self, i):
+ start = self.get_offset(i)
+ if i < len(self) - 1:
+ end = self.get_offset(i + 1)
+ else:
+ end = self.tsv_file_size
+ return start, end
+
+ def close_fp(self):
+ if self._fp:
+ self._fp.close()
+ self._fp = None
+ if self._mfp:
+ self._mfp.close()
+ self._mfp = None
+ if self.has_lineidx_8b and self.fp8b:
+ self.fp8b.close()
+ self.fp8b = None
+
+ def release(self):
+ self.close_fp()
+ self._lineidx = None
+
+ def close(self):
+ #@deprecated('use release to make it more clear not to release lineidx')
+ self.close_fp()
+
+ def __del__(self):
+ self.release()
+
+ def __str__(self):
+ return "TSVFile(tsv_file='{}')".format(self.tsv_file)
+
+ def __repr__(self):
+ return str(self)
+
+ def __iter__(self):
+ self._ensure_tsv_opened()
+ self.fp_seek(0)
+ if not self.use_mmap:
+ for line in self._fp:
+ result = [s.strip() for s in line.decode().split('\t')]
+ yield result
+ else:
+ while True:
+ line = self._mfp.readline()
+ if line == b'':
+ break
+ result = [s.strip() for s in line.decode().split('\t')]
+ yield result
+
+ def num_rows(self):
+ if self._len is None:
+ if self.has_lineidx_8b:
+ self._len = File.get_file_size(self.lineidx_8b) // 8
+ else:
+ self._ensure_lineidx_loaded()
+ self._len = len(self._lineidx)
+ return self._len
+
+ def get_key(self, idx):
+ return self.seek_first_column(idx)
+
+ def get_current_column(self):
+ if self.use_mmap:
+ result = [s.strip() for s in self._mfp.readline().decode().split('\t')]
+ else:
+ result = [s.strip() for s in self._fp.readline().split('\t')]
+ return result
+
+ def get_current_column2(self, size):
+ if self.use_mmap:
+ result = [s.strip() for s in self._mfp.read(size).decode().split('\t')]
+ else:
+ result = [s.strip() for s in self._fp.read(size).decode().split('\t')]
+ return result
+
+ def fp_seek(self, pos):
+ if self.use_mmap:
+ self._mfp.seek(pos)
+ else:
+ self._fp.seek(pos)
+
+ def seek(self, idx):
+ self._ensure_tsv_opened()
+ pos, end = self.get_row_offsets(idx)
+ self.fp_seek(pos)
+ result = self.get_current_column2(end - pos)
+ if self.close_fp_after_read:
+ self.close_fp()
+ return result
+
+ def seek3(self, idx):
+ self._ensure_tsv_opened()
+ pos = self.get_offset(idx)
+ self.fp_seek(pos)
+ result = self.get_current_column()
+ if self.close_fp_after_read:
+ self.close_fp()
+ return result
+
+ def seek_first_column(self, idx):
+ self._ensure_tsv_opened()
+ pos = self.get_offset(idx)
+ self._fp.seek(pos)
+ return read_to_character(self._fp, b'\t').decode()
+
+ def seek_first_columns(self):
+ # assert self.has_lineidx_8b
+ self._ensure_tsv_opened()
+ result = []
+ if self.has_lineidx_8b:
+ self.ensure_lineidx_8b_opened()
+ for idx in range(len(self)):
+ self.fp8b.seek(idx * 8)
+ pos = int.from_bytes(self.fp8b.read(8), 'little')
+ self._fp.seek(pos)
+ result.append(read_to_character(self._fp, b'\t').decode())
+ else:
+ self._ensure_lineidx_loaded()
+ for idx in range(len(self)):
+ pos = self._lineidx[idx]
+ self._fp.seek(pos)
+ result.append(read_to_character(self._fp, b'\t').decode())
+ return result
+
+ def open(self, fname, mode):
+ return File.open(fname, mode)
+ #if self.use_fuse:
+ #return self.fuser.open(fname, mode)
+ #else:
+ #return exclusive_open_to_read(fname, mode)
+
+ def ensure_lineidx_8b_opened(self):
+ if not self.has_lineidx_8b:
+ self.fp8b = None
+ self.lineidx_8b_pid = None
+ return
+ if self.fp8b is None:
+ self.fp8b = self.open(self.lineidx_8b, 'rb')
+ self.lineidx_8b_pid = os.getpid()
+ if self.lineidx_8b_pid != os.getpid():
+ self.fp8b.close()
+ logging.info('re-open {} because the process id changed'.format(
+ self.lineidx_8b))
+ self.fp8b= self.open(self.lineidx_8b, 'rb')
+ self.lineidx_8b_pid = os.getpid()
+
+ def get_offset(self, idx):
+ # do not use op.isfile() to check whether lineidx_8b exists as it may
+ # incur API call for blobfuse, which will be super slow if we enumerate
+ # a bunch of data
+ if self.has_lineidx_8b:
+ self.ensure_lineidx_8b_opened()
+ self.fp8b.seek(idx * 8)
+ ret = int.from_bytes(self.fp8b.read(8), 'little')
+ return ret
+ else:
+ self._ensure_lineidx_loaded()
+ pos = self._lineidx[idx]
+ return pos
+
+ def __getitem__(self, index):
+ return self.seek(index)
+
+ def __len__(self):
+ return self.num_rows()
+
+ def _ensure_lineidx_loaded(self):
+ if self._lineidx is None:
+ with File.open(self.lineidx, 'r') as fp:
+ self._lineidx = tuple([int(i.strip()) for i in fp.readlines()])
+ logging.info('loaded {} from {}'.format(
+ len(self._lineidx),
+ self.lineidx
+ ))
+
+ def get_tsv_fp(self):
+ start = time.time()
+ fp = File.open(self.tsv_file, 'rb')
+ #if self.use_fuse:
+ #fp = self.fuser.open(self.tsv_file, 'rb')
+ #else:
+ #if not self.open_once:
+ #fp = exclusive_open_to_read(self.tsv_file, 'rb')
+ #self.open_once = True
+ #else:
+ #fp = open(self.tsv_file, 'rb')
+ if self.use_mmap:
+ mfp = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
+ else:
+ mfp = fp
+ end = time.time()
+ if (end - start) > 10:
+ logging.info('too long ({}) to open {}'.format(
+ end - start,
+ self.tsv_file))
+ return mfp, fp
+
+ def _ensure_tsv_opened(self):
+ if self.cache_policy == 'memory':
+ assert self._fp is not None
+ return
+
+ if self._fp is None:
+ self._mfp, self._fp = self.get_tsv_fp()
+ self.pid = os.getpid()
+
+ if self.pid != os.getpid():
+ self._mfp.close()
+ self._fp.close()
+ logging.info('re-open {} because the process id changed'.format(self.tsv_file))
+ from .common import print_opened_files
+ print_opened_files()
+ self._mfp, self._fp = self.get_tsv_fp()
+ self.pid = os.getpid()
+
+def get_all_associate_files(all_info):
+ result = []
+ for info in all_info:
+ result.extend(get_associate_files(info))
+ return result
+
+def get_associate_files(info):
+ data, split, t, version = info
+ dataset = TSVDataset(data)
+ fname = dataset.get_data(split, t, version)
+ result = []
+ if op.isfile(fname):
+ result.append(fname)
+ else:
+ result.extend(load_list_file(dataset.get_data(split + 'X', t, version)))
+ result.append(dataset.get_shuffle_file(split))
+ extra = [get_tsv_lineidx_8b(r) for r in result]
+ result.extend(extra)
+ return result
+
+
+class TSVDataset(object):
+ def __init__(self, name, data_root=None):
+ self.name = name
+ if data_root is None:
+ if os.environ.get('QD_DATA_ROOT') is not None:
+ data_root = os.environ['QD_DATA_ROOT']
+ else:
+ proj_root = op.dirname(op.dirname(op.dirname(op.realpath(__file__))))
+ data_root = op.join(proj_root, 'data')
+ data_root = op.join(data_root, name)
+ #print(f'data_root {data_root}')
+ self._data_root = op.relpath(data_root)
+ self._fname_to_tsv = {}
+
+ self._split_to_key_to_idx = {}
+
+ def __repr__(self):
+ return 'TSVDataset({})'.format(self.name)
+
+ def __str__(self):
+ return 'TSVDataset({})'.format(self.name)
+
+ def seek_by_key(self, key, split, t=None, version=None):
+ idx = self.get_idx_by_key(key, split)
+ return next(self.iter_data(split, t, version, filter_idx=[idx]))
+
+ def seek_by_idx(self, idx, split, t=None, version=None):
+ return next(self.iter_data(split, t, version, filter_idx=[idx]))
+
+ def load_labelmap(self):
+ return load_list_file(self.get_labelmap_file())
+
+ def load_pos_labelmap(self):
+ return load_list_file(self.get_pos_labelmap_file())
+
+ def get_tree_file(self):
+ return op.join(self._data_root, 'tree.txt')
+
+ def get_labelmap_file(self):
+ return op.join(self._data_root, 'labelmap.txt')
+
+ def load_txt(self, t='labelmap'):
+ return load_list_file(self.get_txt(t))
+
+ # labelmap or attribute map
+ def get_txt(self, t='labelmap'):
+ return op.join(self._data_root, '{}.txt'.format(t))
+
+ def get_pos_labelmap_file(self):
+ return op.join(self._data_root, 'labelmap.pos.txt')
+
+ def get_train_shuffle_file(self):
+ return self.get_shuffle_file('train')
+
+ def get_shuffle_file(self, split_name):
+ return op.join(self._data_root, '{}.shuffle.txt'.format(split_name))
+
+ def get_labelmap_of_noffset_file(self):
+ return op.join(self._data_root, 'noffsets.label.txt')
+
+ def get_idx_by_key(self, key, split):
+ if split in self._split_to_key_to_idx:
+ key_to_idx = self._split_to_key_to_idx[split]
+ else:
+ key_to_idx = {k: i for i, k in enumerate(self.load_keys(split))}
+ self._split_to_key_to_idx[split] = key_to_idx
+ idx = key_to_idx[key]
+ return idx
+
+ def load_key_to_idx(self, split):
+ result = {}
+ for i, row in enumerate(self.iter_data(split, 'label')):
+ key = row[0]
+ assert key not in result
+ result[key] = i
+ return result
+
+ def load_keys(self, split, t='label'):
+ assert self.has(split, t)
+ result = []
+ for row in tqdm(self.iter_data(split, t), mininterval=2):
+ result.append(row[0])
+ return result
+
+ def dynamic_update(self, dataset_ops):
+ '''
+ sometimes, we update the dataset, and here, we should update the file
+ path
+ '''
+ if len(dataset_ops) >= 1 and dataset_ops[0]['op'] == 'sample':
+ self._data_root = op.join('./output/data/',
+ '{}_{}_{}'.format(self.name,
+ dataset_ops[0]['sample_label'],
+ dataset_ops[0]['sample_image']))
+ elif len(dataset_ops) >= 1 and dataset_ops[0]['op'] == 'mask_background':
+ target_folder = op.join('./output/data',
+ '{}_{}_{}'.format(self.name,
+ '.'.join(map(str, dataset_ops[0]['old_label_idx'])),
+ dataset_ops[0]['new_label_idx']))
+ self._data_root = target_folder
+
+ def get_test_tsv_file(self, t=None):
+ return self.get_data('test', t)
+
+ def get_test_tsv_lineidx_file(self):
+ return op.join(self._data_root, 'test.lineidx')
+
+ def get_train_tsvs(self, t=None):
+ if op.isfile(self.get_data('train', t)):
+ return [self.get_data('train', t)]
+ trainx_file = op.join(self._data_root, 'trainX.tsv')
+ if not op.isfile(trainx_file):
+ return []
+ train_x = load_list_file(trainx_file)
+ if t is None:
+ return train_x
+ elif t =='label':
+ if op.isfile(self.get_data('trainX', 'label')):
+ return load_list_file(self.get_data('trainX', 'label'))
+ else:
+ files = [op.splitext(f)[0] + '.label.tsv' for f in train_x]
+ return files
+
+ def get_train_tsv(self, t=None):
+ return self.get_data('train', t)
+
+ def get_lineidx(self, split_name):
+ return op.join(self._data_root, '{}.lineidx'.format(split_name))
+
+ def get_latest_version(self, split, t=None):
+ assert t is not None, 'if it is none, it is always 0'
+ v = 0
+ if t is None:
+ pattern = op.join(self._data_root, '{}.v*.tsv'.format(split))
+ re_pattern = '{}\.v([0-9]*)\.tsv'.format(split)
+ else:
+ pattern = op.join(self._data_root, '{}.{}.v*.tsv'.format(
+ split, t))
+ re_pattern = '{}\.{}\.v([0-9]*)\.tsv'.format(split, t)
+ all_file = glob.glob(pattern)
+ import re
+ re_results = [re.match(re_pattern, op.basename(f)) for f in all_file]
+ candidates = ([int(re_result.groups()[0]) for re_result, f in
+ zip(re_results, all_file) if re_result])
+ if len(candidates) > 0:
+ v = max(candidates)
+ assert v >= 0
+ return v
+
+ def get_gen_info_data(self, split, t=None, version=None):
+ return self.get_data(split, '{}.generate.info'.format(t), version=version)
+
+ def get_file(self, fname):
+ return op.join(self._data_root, fname)
+
+ def get_data(self, split_name, t=None, version=None):
+ '''
+ e.g. split_name = train, t = label
+ if version = None or 0, return train.label.tsv
+ we don't have train.label.v0.tsv
+ if version = 3 > 0, return train.label.v3.tsv
+ if version = -1, return the highest version
+ '''
+ if t is None:
+ # in this case, it is an image split, which has no version
+ version = None
+ if version is None or version in [0,'None','0']:
+ if t is None:
+ return op.join(self._data_root, '{}.tsv'.format(split_name))
+ else:
+ return op.join(self._data_root, '{}.{}.tsv'.format(split_name,
+ t))
+ elif version == -1:
+ if not op.isfile(self.get_data(split_name, t)):
+ return self.get_data(split_name, t)
+ v = self.get_latest_version(split_name, t)
+ return self.get_data(split_name, t, v)
+ else:
+ return op.join(self._data_root, '{}.{}.v{}.tsv'.format(split_name,
+ t, version))
+
+ def get_num_train_image(self):
+ if op.isfile(self.get_data('trainX')):
+ if op.isfile(self.get_shuffle_file('train')):
+ return len(load_list_file(self.get_shuffle_file('train')))
+ else:
+ return 0
+ else:
+ return len(load_list_file(op.join(self._data_root, 'train.lineidx')))
+
+ def get_trainval_tsv(self, t=None):
+ return self.get_data('trainval', t)
+
+ def get_noffsets_file(self):
+ return op.join(self._data_root, 'noffsets.txt')
+
+ def load_noffsets(self):
+ logging.info('deprecated: pls generate it on the fly')
+ return load_list_file(self.get_noffsets_file())
+
+ def load_inverted_label(self, split, version=None, label=None):
+ fname = self.get_data(split, 'inverted.label', version)
+ if not op.isfile(fname):
+ return {}
+ elif label is None:
+ tsv = TSVFile(fname)
+ num_rows = len(tsv)
+ result = {}
+ for row in tqdm(tsv, total=num_rows, mininterval=2):
+ assert row[0] not in result
+ assert len(row) == 2
+ ss = row[1].split(' ')
+ if len(ss) == 1 and ss[0] == '':
+ result[row[0]] = []
+ else:
+ result[row[0]] = list(map(int, ss))
+ return result
+ else:
+ all_label = load_list_file(self.get_data(split, 'labelmap', version))
+ if label not in all_label:
+ return {}
+ result = {}
+ idx = all_label.index(label)
+ tsv = self._retrieve_tsv(fname)
+ row = tsv.seek(idx)
+ assert row[0] == label
+ ss = row[1].split(' ')
+ if len(ss) == 1 and ss[0] == '':
+ result[row[0]] = []
+ else:
+ result[row[0]] = list(map(int, ss))
+ return result
+
+ def load_inverted_label_as_list(self, split, version=None, label=None):
+ fname = self.get_data(split, 'inverted.label', version)
+ if not op.isfile(fname):
+ return []
+ elif label is None:
+ rows = tsv_reader(fname)
+ result = []
+ for row in rows:
+ assert len(row) == 2
+ ss = row[1].split(' ')
+ if len(ss) == 1 and ss[0] == '':
+ result.append((row[0], []))
+ else:
+ result.append((row[0], list(map(int, ss))))
+ return result
+ else:
+ all_label = self.load_labelmap()
+ result = []
+ idx = all_label.index(label)
+ tsv = self._retrieve_tsv(fname)
+ row = tsv.seek(idx)
+ assert row[0] == label
+ ss = row[1].split(' ')
+ if len(ss) == 1 and ss[0] == '':
+ result.append((row[0], []))
+ else:
+ result.append((row[0], list(map(int, ss))))
+ return result
+
+ def has(self, split, t=None, version=None):
+ return tsv_exists(self.get_data(split, t, version)) or (
+ File.isfile(self.get_data('{}X'.format(split), t, version)) and
+ tsv_exists(self.get_shuffle_file(split)))
+
+ def last_update_time(self, split, t=None, version=None):
+ tsv_file = self.get_data(split, t, version)
+ if op.isfile(tsv_file):
+ return os.path.getmtime(tsv_file)
+ assert version is None or version == 0, 'composite dataset always v=0'
+ tsv_file = self.get_data('{}X'.format(split), t, version)
+ assert op.isfile(tsv_file)
+ return os.path.getmtime(tsv_file)
+
+ def iter_composite(self, split, t, version, filter_idx=None):
+ splitX = split + 'X'
+ file_list = load_list_file(self.get_data(splitX, t, version))
+ tsvs = [self._retrieve_tsv(f) for f in file_list]
+ shuffle_file = self.get_shuffle_file(split)
+ if filter_idx is None:
+ shuffle_tsv_rows = tsv_reader(shuffle_file)
+ for idx_source, idx_row in shuffle_tsv_rows:
+ idx_source, idx_row = int(idx_source), int(idx_row)
+ row = tsvs[idx_source].seek(idx_row)
+ if len(row) == 3:
+ row[1] == 'dont use'
+ yield row
+ else:
+ shuffle_tsv = self._retrieve_tsv(shuffle_file)
+ for i in filter_idx:
+ idx_source, idx_row = shuffle_tsv.seek(i)
+ idx_source, idx_row = int(idx_source), int(idx_row)
+ row = tsvs[idx_source].seek(idx_row)
+ if len(row) == 3:
+ row[1] == 'dont use'
+ yield row
+
+ def num_rows(self, split, t=None, version=None):
+ f = self.get_data(split, t, version)
+ if op.isfile(f) or op.islink(f):
+ return TSVFile(f).num_rows()
+ else:
+ #f = self.get_data(split + 'X', t, version=version)
+ #assert op.isfile(f), f
+ #return len(load_list_file(self.get_shuffle_file(split)))
+ return len(TSVFile(self.get_shuffle_file(split)))
+
+ def iter_data(self, split, t=None, version=None,
+ unique=False, filter_idx=None, progress=False):
+ if progress:
+ if filter_idx is None:
+ num_rows = self.num_rows(split)
+ else:
+ num_rows = len(filter_idx)
+ pbar = progressbar.ProgressBar(maxval=num_rows).start()
+ splitX = split + 'X'
+ if not op.isfile(self.get_data(split, t, version)) and \
+ op.isfile(self.get_data(splitX, t, version)):
+ if t is not None:
+ if unique:
+ returned = set()
+ for i, row in enumerate(self.iter_composite(split, t, version,
+ filter_idx=filter_idx)):
+ if unique and row[0] in returned:
+ continue
+ else:
+ yield row
+ if unique:
+ returned.add(row[0])
+ if progress:
+ pbar.update(i)
+ else:
+ rows_data = self.iter_composite(split, None, version=version,
+ filter_idx=filter_idx)
+ #logging.info('breaking change: label is ignore for t=None')
+ #rows_label = self.iter_data(split, 'label', version=version,
+ #filter_idx=filter_idx)
+ if unique:
+ returned = set()
+ for i, r in enumerate(rows_data):
+ if unique and r[0] in returned:
+ continue
+ else:
+ yield r
+ if unique:
+ returned.add(r[0])
+ if progress:
+ pbar.update(i)
+ else:
+ fname = self.get_data(split, t, version)
+ if not op.isfile(fname):
+ logging.info('no {}'.format(fname))
+ return
+ if filter_idx is None:
+ for i, row in enumerate(tsv_reader(self.get_data(
+ split, t, version))):
+ yield row
+ if progress:
+ pbar.update(i)
+ else:
+ fname = self.get_data(split, t, version)
+ tsv = self._retrieve_tsv(fname)
+ if progress:
+ for i in tqdm(filter_idx):
+ yield tsv.seek(i)
+ else:
+ for i in filter_idx:
+ yield tsv.seek(i)
+
+
+ def _retrieve_tsv(self, fname):
+ if fname in self._fname_to_tsv:
+ tsv = self._fname_to_tsv[fname]
+ else:
+ tsv = TSVFile(fname)
+ self._fname_to_tsv[fname] = tsv
+ return tsv
+
+ def safe_write_data(self, rows, split, t=None, version=None,
+ generate_info=None, force=False):
+ assert force or not self.has(split, t, version)
+ if generate_info is None:
+ from .common import get_frame_info
+ info = get_frame_info(last=1)
+ def gen_info():
+ for k, v in info.items():
+ if isinstance(v, str):
+ yield k, v
+ generate_info = gen_info()
+ self.write_data(rows, split, t, version,
+ generate_info=generate_info)
+
+ def write_data(self, rows, split, t=None, version=None, generate_info=None):
+ out_tsv = self.get_data(split, t, version)
+ tsv_writer(rows, out_tsv)
+ if generate_info is not None:
+ out_tsv = self.get_data(split, '{}.generate.info'.format(t), version=version)
+ tsv_writer(generate_info, out_tsv)
+
+ def update_data(self, rows, split, t, generate_info=None):
+ '''
+ if the data are the same, we will not do anything.
+ '''
+ assert t is not None
+ v = self.get_latest_version(split, t)
+ if self.has(split, t, v):
+ is_equal = True
+ # we first save it to a tmp tsv file
+ self.write_data(rows, split, t + '.tmp', v + 1)
+ for origin_row, new_row in zip(self.iter_data(split, t, v),
+ self.iter_data(split, t + '.tmp', v + 1)):
+ if len(origin_row) != len(new_row):
+ is_equal = False
+ break
+ for o, n in zip(origin_row, new_row):
+ if o != n:
+ is_equal = False
+ break
+ if not is_equal:
+ break
+ if not is_equal:
+ logging.info('creating {} for {}'.format(v + 1, self.name))
+ if generate_info:
+ self.write_data(generate_info, split, '{}.generate.info'.format(t), v + 1)
+ tsv_mv(self.get_data(split, t + '.tmp', v + 1),
+ self.get_data(split, t, v + 1))
+ return v + 1
+ else:
+ logging.info('ignore to create since the label matches the latest')
+ else:
+ assert v == 0
+ v = -1
+ logging.info('creating {} for {}'.format(v + 1, self.name))
+ if generate_info:
+ self.write_data(generate_info, split, '{}.generate.info'.format(t), v + 1)
+ self.write_data(rows, split, t, version=v + 1)
+ return v + 1
+
+ def load_composite_source_data_split(self, split):
+ splitX = split + 'X'
+ pattern = 'data/(.*)/(.*)\.tsv'
+ tsv_sources = [l for l, in tsv_reader(self.get_data(splitX))]
+ matched_result = [re.match(pattern, l).groups()
+ for l in tsv_sources]
+
+ return [(d, s) for d, s in matched_result]
+
+ def load_composite_source_data_split_versions(self, split):
+ # this function is only valid if we generated the composite dataset
+ # from tsv, not from db. if it is from db, there is no file of
+ # origin.label. use load_composite_source_data_split, instead.
+ splitX = split + 'X'
+ pattern = 'data/(.*)/(train|trainval|test)\.label\.v(.*)\.tsv'
+ tsv_sources = [l for l, in tsv_reader(self.get_data(splitX,
+ 'origin.label'))]
+ matched_result = [re.match(pattern, l).groups()
+ for l in tsv_sources]
+
+ return [(d, s, int(v)) for d, s, v in matched_result]
+
+def csv_writer(values, file_name):
+ tsv_writer(values, file_name, sep=',')
+ return
+
+class TSVSplitProperty(object):
+ '''
+ one instance of this class mean one tsv file or one composite tsv, it could
+ be label tsv, or hw tsv, or image tsv
+ currently, it depends on TSVDataset, and we should remove such dependency
+ in future and deprecate TSVDataset
+ '''
+ def __init__(self, data, split, t=None, version=0, cache_policy=None,
+ hold_buffer=0, data_dir=None):
+ self.data = data
+ self.split = split
+ self.t = t
+ self.version = version
+ dataset = TSVDataset(data, data_root=data_dir)
+
+ split_tsv = dataset.get_data(split + 'S', t, version)
+ single_tsv = dataset.get_data(split, t, version)
+
+ if int(os.environ.get('QD_ENABLE_EQUAL_SPLIT', '0')) and File.isfile(split_tsv):
+ self.tsv = EqualSplitTSVFile(split_tsv)
+ elif File.isfile(single_tsv):
+ self.tsv = TSVFile(dataset.get_data(split, t, version),
+ cache_policy)
+ else:
+ splitX = split + 'X'
+ list_file = dataset.get_data(splitX, t, version=version)
+ seq_file = dataset.get_shuffle_file(split)
+ #print(list_file)
+ #print(seq_file)
+ assert File.isfile(list_file) and File.isfile(seq_file), (
+ '{}, {}/{} not available'.format(single_tsv, list_file, seq_file)
+ )
+ self.tsv = CompositeTSVFile(list_file, seq_file, cache_policy,
+ hold_buffer=hold_buffer, data_dir=data_dir)
+
+ def is_from_valid_file(self, idx=None):
+ return self.tsv.is_from_valid_file(idx)
+
+ def get_row_len(self, i):
+ return self.tsv.get_row_len(i)
+
+ def __repr__(self):
+ return 'TSVSplitProperty(tsv={})'.format(
+ self.tsv
+ )
+
+ def __getitem__(self, index):
+ row = self.tsv[index]
+ return row
+
+ def __len__(self):
+ return len(self.tsv)
+
+ def num_rows(self):
+ return len(self)
+
+ def close(self):
+ self.tsv.close()
+
+ def __iter__(self):
+ return iter(self.tsv)
+
+ def get_key(self, i):
+ return self.tsv.seek_first_column(i)
+
+ def seek_first_column(self, idx):
+ return self.tsv.seek_first_column(idx)
+
+ def get_composite_source_idx(self):
+ return self.tsv.get_composite_source_idx()
+
+def tsv_writers(all_values, tsv_file_names, sep='\t'):
+ # values: a list of [row1, row2]. each row goes to each tsv_file_name
+ for tsv_file_name in tsv_file_names:
+ ensure_directory(os.path.dirname(tsv_file_name))
+ tsv_lineidx_files = [os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ for tsv_file_name in tsv_file_names]
+ tsv_lineidx_8b_files = [x + '.8b' for x in tsv_lineidx_files]
+ sep = sep.encode()
+ assert all_values is not None
+ from contextlib import ExitStack
+ with ExitStack() as stack:
+ fps = [stack.enter_context(File.open(f, 'wb')) for f in
+ tsv_file_names]
+ fpidxs = [stack.enter_context(File.open(f, 'w')) for f in
+ tsv_lineidx_files]
+ fpidx8bs = [stack.enter_context(File.open(f, 'wb')) for f in tsv_lineidx_8b_files]
+ idxs = [0 for _ in fps]
+ for values in all_values:
+ assert values is not None
+ for i, (value, fp, fpidx, fpidx8b) in enumerate(zip(values, fps, fpidxs, fpidx8bs)):
+ value = map(lambda v: v if type(v) == bytes else str(v).encode(),
+ value)
+ v = sep.join(value) + b'\n'
+ fp.write(v)
+ fpidx.write(str(idxs[i]) + '\n')
+ fpidx8b.write(idxs[i].to_bytes(8, 'little'))
+ idxs[i] = idxs[i]+ len(v)
+
+
+def tsv_writers_backup(all_values, tsv_file_names, sep='\t'):
+ # values: a list of [row1, row2]. each row goes to each tsv_file_name
+ for tsv_file_name in tsv_file_names:
+ ensure_directory(os.path.dirname(tsv_file_name))
+ tsv_lineidx_files = [os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ for tsv_file_name in tsv_file_names]
+ tsv_lineidx_8b_files = [x + '.8b' for x in tsv_lineidx_files]
+ tsv_lineidx_8b_file_tmps = [x + '.tmp' for x in tsv_lineidx_8b_files]
+ tsv_file_name_tmps = [tsv_file_name + '.tmp' for tsv_file_name in
+ tsv_file_names]
+ tsv_lineidx_file_tmps = [tsv_lineidx_file + '.tmp' for tsv_lineidx_file in
+ tsv_lineidx_files]
+ sep = sep.encode()
+ assert all_values is not None
+ fps = [open(tsv_file_name_tmp, 'wb') for tsv_file_name_tmp in
+ tsv_file_name_tmps]
+ fpidxs = [open(tsv_lineidx_file_tmp, 'w') for tsv_lineidx_file_tmp in
+ tsv_lineidx_file_tmps]
+ fpidx8bs = [open(x, 'wb') for x in tsv_lineidx_8b_file_tmps]
+ idxs = [0 for _ in fps]
+ for values in all_values:
+ assert values is not None
+ for i, (value, fp, fpidx, fpidx8b) in enumerate(zip(values, fps, fpidxs, fpidx8bs)):
+ value = map(lambda v: v if type(v) == bytes else str(v).encode(),
+ value)
+ v = sep.join(value) + b'\n'
+ fp.write(v)
+ fpidx.write(str(idxs[i]) + '\n')
+ fpidx8b.write(idxs[i].to_bytes(8, 'little'))
+ idxs[i] = idxs[i]+ len(v)
+ for f in fps:
+ f.close()
+ for f in fpidxs:
+ f.close()
+ for f in fpidx8bs:
+ f.close()
+ # the following might crash if there are two processes which are writing at
+ # the same time. One process finishes the renaming first and the second one
+ # will crash. In this case, we know there must be some errors when you run
+ # the code, and it should be a bug to fix rather than to use try-catch to
+ # protect it here.
+ for tsv_file_name_tmp, tsv_file_name in zip(tsv_file_name_tmps,
+ tsv_file_names):
+ os.rename(tsv_file_name_tmp, tsv_file_name)
+ for tsv_lineidx_file_tmp, tsv_lineidx_file in zip(tsv_lineidx_file_tmps,
+ tsv_lineidx_files):
+ os.rename(tsv_lineidx_file_tmp, tsv_lineidx_file)
+ for x, y in zip(tsv_lineidx_8b_file_tmps, tsv_lineidx_8b_files,):
+ os.rename(x, y)
+
+#def tsv_writer(values, tsv_file_name, sep='\t'):
+ #ensure_directory(os.path.dirname(tsv_file_name))
+ #tsv_lineidx_file = os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ #tsv_8b_file = tsv_lineidx_file + '.8b'
+ #idx = 0
+ #tsv_file_name_tmp = tsv_file_name + '.tmp'
+ #tsv_lineidx_file_tmp = tsv_lineidx_file + '.tmp'
+ #tsv_8b_file_tmp = tsv_8b_file + '.tmp'
+ #import sys
+ #is_py2 = sys.version_info.major == 2
+ #if not is_py2:
+ #sep = sep.encode()
+ #with open(tsv_file_name_tmp, 'wb') as fp, open(tsv_lineidx_file_tmp, 'w') as fpidx, open(tsv_8b_file_tmp, 'wb') as fp8b:
+ #assert values is not None
+ #for value in values:
+ #assert value is not None
+ #if is_py2:
+ #v = sep.join(map(lambda v: str(v) if not isinstance(v, six.string_types) else v, value)) + '\n'
+ #if type(v) is unicode:
+ #v = v.encode('utf-8')
+ #else:
+ #value = map(lambda v: v if type(v) == bytes else str(v).encode(),
+ #value)
+ #v = sep.join(value) + b'\n'
+ #fp.write(v)
+ #fpidx.write(str(idx) + '\n')
+ ## although we can use sys.byteorder to retrieve the system-default
+ ## byte order, let's use little always to make it consistent and
+ ## simple
+ #fp8b.write(idx.to_bytes(8, 'little'))
+ #idx = idx + len(v)
+ ## the following might crash if there are two processes which are writing at
+ ## the same time. One process finishes the renaming first and the second one
+ ## will crash. In this case, we know there must be some errors when you run
+ ## the code, and it should be a bug to fix rather than to use try-catch to
+ ## protect it here.
+ #os.rename(tsv_file_name_tmp, tsv_file_name)
+ #os.rename(tsv_lineidx_file_tmp, tsv_lineidx_file)
+
+ #os.rename(tsv_8b_file_tmp, tsv_8b_file)
+
+def load_from_yaml_file(file_name):
+ # do not use File.open as File.open depends on this function
+ with File.open(file_name, 'r') as fp:
+ #with open(file_name, 'r') as fp:
+ data = load_from_yaml_str(fp)
+ while isinstance(data, dict) and '_base_' in data:
+ b = op.join(op.dirname(file_name), data['_base_'])
+ result = load_from_yaml_file(b)
+ assert isinstance(result, dict)
+ del data['_base_']
+ all_key = get_all_path(data, with_list=False)
+ for k in all_key:
+ v = dict_get_path_value(data, k)
+ dict_update_path_value(result, k, v)
+ data = result
+ return data
+
+def write_to_file(contxt, file_name, append=False):
+ if type(contxt) is str:
+ contxt = contxt.encode()
+ flag = 'wb'
+ if append:
+ flag = 'ab'
+ with File.open(file_name, flag) as fp:
+ fp.write(contxt)
+
+def load_list_file(fname):
+ with File.open(fname, 'r') as fp:
+ lines = fp.readlines()
+ result = [line.strip() for line in lines]
+ if len(result) > 0 and result[-1] == '':
+ result = result[:-1]
+ return result
+
+def tsv_writer(values, tsv_file_name, sep='\t'):
+ ensure_directory(os.path.dirname(tsv_file_name))
+ tsv_lineidx_file = os.path.splitext(tsv_file_name)[0] + '.lineidx'
+ tsv_8b_file = tsv_lineidx_file + '.8b'
+ idx = 0
+ sep = sep.encode()
+ with File.open(tsv_file_name, 'wb') as fp, File.open(tsv_lineidx_file, 'w') as fpidx, File.open(tsv_8b_file, 'wb') as fp8b:
+ assert values is not None
+ for value in tqdm(values):
+ assert value is not None
+ value = map(lambda v: v if type(v) == bytes else str(v).encode(),
+ value)
+ v = sep.join(value) + b'\n'
+ fp.write(v)
+ fpidx.write(str(idx) + '\n')
+ # although we can use sys.byteorder to retrieve the system-default
+ # byte order, let's use little always to make it consistent and
+ # simple
+ fp8b.write(idx.to_bytes(8, 'little'))
+ idx = idx + len(v)
+
+def tsv_reader(tsv_file_name, sep='\t'):
+ #with open(tsv_file_name, 'r') as fp:
+ with File.open(tsv_file_name, 'r') as fp:
+ for i, line in enumerate(fp):
+ yield [x.strip() for x in line.split(sep)]
+
+def csv_reader(tsv_file_name):
+ return tsv_reader(tsv_file_name, ',')
+
+def get_meta_file(tsv_file):
+ return op.splitext(tsv_file)[0] + '.meta.yaml'
+
+def extract_label(full_tsv, label_tsv):
+ if op.isfile(label_tsv):
+ logging.info('label file exists and will skip to generate: {}'.format(
+ label_tsv))
+ return
+ if not op.isfile(full_tsv):
+ logging.info('the file of {} does not exist'.format(full_tsv))
+ return
+ rows = tsv_reader(full_tsv)
+ def gen_rows():
+ for i, row in enumerate(rows):
+ if (i % 1000) == 0:
+ logging.info('extract_label: {}-{}'.format(full_tsv, i))
+ del row[2]
+ assert len(row) == 2
+ assert type(row[0]) == str
+ assert type(row[1]) == str
+ yield row
+ tsv_writer(gen_rows(), label_tsv)
+
+def create_inverted_tsv(rows, inverted_label_file, label_map):
+ '''
+ deprecated, use create_inverted_list
+ save the results based on the label_map in label_map_file. The benefit is
+ to seek the row given a label
+ '''
+ inverted = {}
+ for i, row in enumerate(rows):
+ labels = json.loads(row[1])
+ if type(labels) is list:
+ # detection dataset
+ curr_unique_labels = set([l['class'] for l in labels])
+ else:
+ assert type(labels) is int
+ curr_unique_labels = [label_map[labels]]
+ for l in curr_unique_labels:
+ assert type(l) == str or type(l) == unicode
+ if l not in inverted:
+ inverted[l] = [i]
+ else:
+ inverted[l].append(i)
+ def gen_rows():
+ for label in inverted:
+ assert label in label_map
+ for label in label_map:
+ i = inverted[label] if label in inverted else []
+ yield label, ' '.join(map(str, i))
+ tsv_writer(gen_rows(), inverted_label_file)
+
+def create_inverted_list2(rows, th=None):
+ inverted = {}
+ keys = []
+ for i, row in enumerate(rows):
+ keys.append(row[0])
+ labels = json.loads(row[1])
+ if th is not None:
+ labels = [r for r in labels if 'conf' in r and r['conf'] > th or
+ 'conf' not in r]
+ if type(labels) is list:
+ # detection dataset
+ curr_unique_labels = set([l['class'] for l in labels])
+ else:
+ assert type(labels) is int
+ curr_unique_labels = [str(labels)]
+ for l in curr_unique_labels:
+ assert type(l) == str or type(l) == unicode
+ if l not in inverted:
+ inverted[l] = [i]
+ else:
+ inverted[l].append(i)
+ return inverted, keys
+
+def is_verified_rect(rect):
+ #allowed_keys = set(['class', 'rect', 'uhrs_confirm', 'uhrs_uncertain',
+ #'conf', 'merge_from', 'class_from', 'change_from', 'from', 'diff',
+ #'IsInside', 'IsGroupOf', 'IsDepiction', 'IsOccluded',
+ #'IsTruncated', 'workerId', 'class_propagate_from', 'obj', 'uhrs'])
+ #unknown_keys = [k for k in rect if k not in allowed_keys]
+ #if len(unknown_keys) > 0:
+ #logging.info('unknown keys = {}\n'.format(pformat(unknown_keys)))
+ #pass
+
+ if 'uhrs' in rect:
+ judge_result = rect['uhrs']
+ assert judge_result.get('1', 0) >= judge_result.get('2', 0)
+ return True
+
+ if 'class' not in rect or 'rect' not in rect:
+ return False
+
+ if 'uhrs_confirm' in rect:
+ assert rect['uhrs_confirm'] > 0
+ return True
+
+ if 'conf' in rect and rect['conf'] < 1:
+ return False
+
+ if 'merge_from' in rect:
+ return all(is_verified_rect(r) for r in rect['merge_from'])
+
+ return True
+
+def create_inverted_list(rows):
+ inverted = {}
+ inverted_with_bb = {}
+ inverted_no_bb = {}
+ inverted_with_bb_verified = {}
+ inverted_with_bb_noverified = {}
+ logging.info('creating inverted')
+ for i, row in tqdm(enumerate(rows), mininterval=2):
+ labels = json.loads(row[1])
+ if type(labels) is list:
+ # detection dataset
+ curr_unique_labels = set([l['class'] for l in labels])
+ curr_unique_with_bb_labels = set([l['class'] for l in labels
+ if 'rect' in l and any(x != 0 for x in l['rect'])])
+ curr_unique_no_bb_labels = set([l['class'] for l in labels
+ if 'rect' not in l or all(x == 0 for x in l['rect'])])
+ curr_unique_with_bb_verified_labels = set([l['class'] for l in labels
+ if 'rect' in l and any(x != 0 for x in l['rect']) and is_verified_rect(l)])
+ curr_unique_with_bb_noverified_labels = set([l['class'] for l in labels
+ if 'rect' in l and any(x != 0 for x in l['rect']) and not is_verified_rect(l)])
+ else:
+ assert type(labels) is int
+ curr_unique_labels = [str(labels)]
+ curr_unique_with_bb_labels = []
+ curr_unique_no_bb_labels = curr_unique_labels
+ curr_unique_with_bb_verified_labels = set()
+ curr_unique_with_bb_noverified_labels = set()
+ def update(unique_labels, inv):
+ for l in unique_labels:
+ assert type(l) == str
+ if l not in inv:
+ inv[l] = [i]
+ else:
+ inv[l].append(i)
+ update(curr_unique_labels, inverted)
+ update(curr_unique_with_bb_labels, inverted_with_bb)
+ update(curr_unique_no_bb_labels, inverted_no_bb)
+ update(curr_unique_with_bb_verified_labels, inverted_with_bb_verified)
+ update(curr_unique_with_bb_noverified_labels, inverted_with_bb_noverified)
+ return {'inverted.label': inverted,
+ 'inverted.label.with_bb': inverted_with_bb,
+ 'inverted.label.no_bb': inverted_no_bb,
+ 'inverted.label.with_bb.verified': inverted_with_bb_verified,
+ 'inverted.label.with_bb.noverified': inverted_with_bb_noverified}
+
+def tsv_shuffle_reader(tsv_file):
+ logging.warn('deprecated: using TSVFile to randomly seek')
+ lineidx_file = op.splitext(tsv_file)[0] + '.lineidx'
+ lineidx = load_list_file(lineidx_file)
+ random.shuffle(lineidx)
+ with open(tsv_file, 'r') as fp:
+ for l in lineidx:
+ fp.seek(int(float(l)))
+ yield [x.strip() for x in fp.readline().split('\t')]
+
+def load_labelmap(data):
+ dataset = TSVDataset(data)
+ return dataset.load_labelmap()
+
+def get_caption_data_info(name):
+ dataset = TSVDataset(name)
+ splits = get_default_splits()
+ from collections import defaultdict
+ split_to_versions = defaultdict(list)
+ for split in splits:
+ v = 0
+ while True:
+ if not dataset.has(split, 'caption', v):
+ break
+ split_to_versions[split].append(v)
+ v = v + 1
+ return split_to_versions
+
+def get_all_data_info2(name=None):
+ if name is None:
+ return sorted(os.listdir('./data'))
+ else:
+ dataset = TSVDataset(name)
+ valid_split_versions = []
+ splits = get_default_splits()
+
+ for split in splits:
+ v = 0
+ while True:
+ if not dataset.has(split, 'label', v):
+ break
+ if dataset.has(split, 'inverted.label.count', v):
+ label_count_rows = dataset.iter_data(split, 'inverted.label.count', v)
+ label_count = [(r[0], int(r[1])) for r in label_count_rows]
+ label_count = sorted(label_count, key=lambda x: x[1])
+ else:
+ label_count = []
+ valid_split_versions.append((split, v, "", [(i, l, c) for i, (l, c) in
+ enumerate(label_count)]))
+ v = v + 1
+ name_splits_labels = [(name, valid_split_versions)]
+ return name_splits_labels
+
+def get_all_data_info():
+ names = os.listdir('./data')
+ name_splits_labels = []
+ names.sort(key=lambda n: n.lower())
+ for name in names:
+ dataset = TSVDataset(name)
+ if not op.isfile(dataset.get_labelmap_file()):
+ continue
+ labels = dataset.load_labelmap()
+ valid_splits = []
+ if len(dataset.get_train_tsvs()) > 0:
+ valid_splits.append('train')
+ for split in ['trainval', 'test']:
+ if not op.isfile(dataset.get_data(split)):
+ continue
+ valid_splits.append(split)
+ name_splits_labels.append((name, valid_splits, labels))
+ return name_splits_labels
+
+def load_labels(file_name):
+ rows = tsv_reader(file_name)
+ key_to_rects = {}
+ key_to_idx = {}
+ for i, row in enumerate(rows):
+ key = row[0]
+ rects = json.loads(row[1])
+ #assert key not in labels, '{}-{}'.format(file_name, key)
+ key_to_rects[key] = rects
+ key_to_idx[key] = i
+ return key_to_rects, key_to_idx
+
+def azcopy_read(fname):
+ # we ignore fname since it could be a mounted blobfuse folder in AML
+ local_file_name = op.join('/tmp', '{}_{}'.format(get_user_name(),
+ hash_sha1(op.realpath(op.abspath(fname))) +
+ op.splitext(fname)[1]))
+ if op.isfile(local_file_name):
+ return open(local_file_name, 'r')
+ config_file = os.environ['FILE_OPEN_AZCOPY_BLOB_ACCOUNT_PATH']
+ from qd.cloud_storage import create_cloud_storage
+ remote_path = op.join(os.environ['FILE_OPEN_AZCOPY_REMOTE_PATH'],
+ op.relpath(fname, os.environ['FILE_OPEN_AZCOPY_LOCAL_PATH']))
+ c = create_cloud_storage(config_file=config_file)
+ logging.info('downloading from {} to {} for {}'.format(remote_path,
+ local_file_name, fname))
+ c.az_download(remote_path, local_file_name)
+ return open(local_file_name, 'r')
+
+def parallel_generate_lineidx8b_from_lineidx(x):
+ lineidx, lineidx_8b = x
+ generate_lineidx8b_from_lineidx(lineidx, lineidx_8b)
+
+def generate_lineidx8b_from_lineidx(lineidx, lineidx_8b):
+ logging.info(lineidx)
+ with File.open(lineidx_8b, 'wb') as fp8b:
+ for i, in tqdm(tsv_reader(lineidx)):
+ fp8b.write(int(i).to_bytes(8, 'little'))
+
+def convert_data_to_yaml(
+ data, split, yaml,
+ is_train=True,
+ label=None,
+ feature=None,
+ qd_format=False,
+ label_version=None,
+ feature_version=None):
+ # used for captioning-related scripts
+ if qd_format:
+ info = {
+ 'feature': feature if feature is not None else {
+ 'data': data,
+ 'split': split,
+ 't': 'feature',
+ 'version': feature_version,
+ },
+ 'hw': {'data': data, 'split': split, 't': 'hw'},
+ 'img': {'data': data, 'split': split},
+ 'label': label if label is not None else {
+ 'data': data,
+ 'split': split,
+ 't': 'label',
+ 'version': label_version,
+ },
+ 'caption': {'data': data, 'split': split, 't': 'hw'},
+ 'composite': False,
+ 'qd_format': True,
+ }
+ else:
+ assert label is None and feature is None
+ # will be deprecated
+ from qd.tsv_io import TSVDataset
+ yaml_folder = op.dirname(yaml)
+ dataset = TSVDataset(data)
+ if not op.isfile(dataset.get_data(split + 'X')):
+ # we prefer to use the composite
+ info = {
+ 'feature': op.relpath(dataset.get_data('train', 'feature', version=feature_version), yaml_folder),
+ 'label': op.relpath(dataset.get_data(split, 'label', version=label_version), yaml_folder),
+ 'hw': op.relpath(dataset.get_data(split, 'hw'), yaml_folder),
+ 'img': op.relpath(dataset.get_data(split), yaml_folder),
+ 'caption': op.relpath(dataset.get_data(split, 'caption'), yaml_folder),
+ 'composite': False,
+ }
+ else:
+ def get_rel_path(p):
+ return op.relpath(op.realpath(p), op.realpath(yaml_folder))
+ splitX = split + 'X'
+ from .common import load_list_file
+ info = {
+ 'feature': list(map(get_rel_path, load_list_file(dataset.get_data(splitX, 'feature', version=feature_version)))),
+ 'label': list(map(get_rel_path, load_list_file(dataset.get_data( splitX, 'label', version=label_version)))),
+ 'hw': list(map(get_rel_path, load_list_file(dataset.get_data(splitX, 'hw')))),
+ 'img': list(map(get_rel_path, load_list_file(dataset.get_data(splitX)))),
+ 'caption': list(map(get_rel_path, load_list_file(dataset.get_data(splitX, 'caption')))),
+ 'composite': True,
+ }
+ if is_train:
+ caption_linelist = dataset.get_data(split, 'caption_linelist')
+ assert op.isfile(caption_linelist)
+ info['caption_linelist'] = caption_linelist
+ else:
+ caption_linelist = dataset.get_data(split, 'caption_linelist_test')
+ if not op.isfile(caption_linelist):
+ from qd.tsv_io import tsv_reader
+ tsv_writer(((a, b, 0) for a, b in
+ tsv_reader(dataset.get_shuffle_file(split))),
+ caption_linelist)
+ info['caption_linelist'] = caption_linelist
+ from .common import write_to_yaml_file
+ write_to_yaml_file(info, yaml)
+
+def save_to_yaml_file(context, file_name):
+ with File.open(file_name, 'w') as fp:
+ import yaml
+ yaml.dump(context, fp, default_flow_style=False,
+ encoding='utf-8', allow_unicode=True)
+
+def concat_files(ins, out):
+ File.prepare(ins)
+ with File.open(out, 'wb') as fp_out:
+ for i, f in enumerate(ins):
+ logging.info('concating {}/{} - {}'.format(i, len(ins), f))
+ with File.open(f, 'rb') as fp_in:
+ shutil.copyfileobj(fp_in, fp_out, 1024*1024*10)
+
+def is_folder_content_same(folder1, folder2):
+ files1 = [op.join(r, f) for r, _, fs in os.walk(folder1) for f in fs]
+ files2 = [op.join(r, f) for r, _, fs in os.walk(folder2) for f in fs]
+ if len(files1) != len(files2):
+ return False
+ sub_names1 = [f[len(folder1):] for f in files1]
+ sub_names2 = [f[len(folder2):] for f in files2]
+ sub_names1 = sorted(sub_names1)
+ sub_names2 = sorted(sub_names2)
+ from .common import float_tolorance_equal
+ if not float_tolorance_equal(sub_names1, sub_names2):
+ return False
+ for f1 in files1:
+ f2 = folder2 + f1[len(folder1):]
+ if not is_file_content_same(f1, f2):
+ return False
+ return True
+
+
+def is_file_content_same(f1, f2):
+ s1 = File.get_file_size(f1)
+ s2 = File.get_file_size(f2)
+ if s1 != s2:
+ return False
+ with File.open(f1, 'rb') as fp1, File.open(f2, 'rb') as fp2:
+ while True:
+ s1 = fp1.read(1024*1024 * 10)
+ s2 = fp2.read(1024*1024 * 10)
+ if s1 == b'' and s2 == b'':
+ break
+ if s1 != s2:
+ return False
+ return True
+
+def read_to_buffer(file_name):
+ with File.open(file_name, 'rb') as fp:
+ return fp.read()
+
+'''class File(object):
+ initialized = False
+ use_fuser = False
+ fuser = None
+
+ @classmethod
+ def ensure_initialized(cls):
+ if not cls.initialized:
+ cls.initialized = True
+ cls.use_fuser = int(os.environ.get('QD_TSV_USE_FUSE', '0'))
+ if cls.use_fuser:
+ from qd.cloud_storage import create_cloud_fuse
+ cls.fuser = create_cloud_fuse()
+ gc = int(os.environ.get('QD_USE_FUSE_ENABLE_GARBAGE_COLLECTION', '0'))
+ from .common import get_mpi_local_rank
+ if gc and get_mpi_local_rank() == 0:
+ cls.fuser.ensure_invoke_garbage_collect()
+ fs = os.environ.get('QD_USE_FUSE_DOWNLOAD_FILE_LIST_AT_INIT')
+ if fs:
+ cache = []
+ for f in fs.split(','):
+ with cls.fuser.open(f) as fp:
+ cache.extend([l.strip() for l in fp])
+ cls.fuser.ensure_cache(cache)
+
+ @classmethod
+ def isfile(cls, path):
+ cls.ensure_initialized()
+ if cls.use_fuser:
+ return cls.fuser.isfile(path)
+ else:
+ return op.isfile(path)
+
+ @classmethod
+ def open(cls, fname, mode='r'):
+ cls.ensure_initialized()
+ if mode in ['r', 'rb']:
+ if cls.use_fuser:
+ return cls.fuser.open(fname, mode)
+ else:
+ return exclusive_open_to_read(fname, mode)
+ elif mode in ['w', 'wb']:
+ if cls.use_fuser:
+ return cls.fuser.open(fname, mode)
+ else:
+ return robust_open_to_write(fname, mode)
+
+ @classmethod
+ def clear_cache(cls, folder):
+ cls.ensure_initialized()
+ if not cls.use_fuser:
+ return
+ return cls.fuser.clear_cache(folder)
+
+ @classmethod
+ def rm(cls, fname):
+ cls.ensure_initialized()
+ if cls.use_fuser:
+ cls.fuser.rm(fname)
+ else:
+ os.remove(fname)
+
+ @classmethod
+ def async_upload(cls, enabled=False, shm_as_tmp=False):
+ cls.ensure_initialized()
+ if not cls.use_fuser:
+ return contextlib.nullcontext()
+ return cls.fuser.async_upload(enabled, shm_as_tmp)
+
+ @classmethod
+ @property
+ def async_upload_queue(cls):
+ cls.ensure_initialized()
+ if not cls.use_fuser:
+ return
+ return cls.fuser.async_upload_queue
+
+ @classmethod
+ def get_file_size(cls, fname):
+ cls.ensure_initialized()
+ if cls.use_fuser:
+ return cls.fuser.get_file_size(fname)
+ else:
+ return get_file_size(fname)
+
+ @classmethod
+ def list(cls, folder, recursive=False):
+ cls.ensure_initialized()
+ if cls.use_fuser:
+ return cls.fuser.list(folder, recursive=recursive)
+ else:
+ return glob.glob(op.join(folder, '*'), recursive=recursive)
+
+ @classmethod
+ def prepare(cls, file_or_fnames, allow_aux_storage=False):
+ cls.ensure_initialized()
+ if cls.use_fuser:
+ cls.fuser.ensure_cache(file_or_fnames,
+ allow_aux_storage=allow_aux_storage)
+
+QDFile = File'''
+
+'''a=TSVSplitProperty('TaxCCSBUCocoVGCap384Q90SF', 'train', 'caption')
+print(a.__getitem__(0))
+print(a.__getitem__(0)[1])
+['00000000', '[{"caption": "a very typical bus station", "tokens": ["a", "very", "typical", "bus", "station"], "deptree": [[4, 0], [2, 1], [4, 2], [4, 3], [-1, 4]]}]']
+
+a=TSVSplitProperty('TaxCCSBUCocoVGCap384Q90SF', 'train')
+print(a.__getitem__(0))
+print(a.__getitem__(0)[1]) #'''
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/wutils.py b/One-to-All-Animation/benchmark/DisCo/utils/wutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..cd458ed514816afc7e7009e985aaaa3c43675952
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/wutils.py
@@ -0,0 +1,1467 @@
+# -*- coding:utf-8 -*-
+import os
+import sys
+import shutil
+import subprocess
+import logging
+import colorlog
+import argparse
+import copy
+import pathlib
+import shlex
+import deepdish
+from tqdm import tqdm
+import time
+import platform
+import pickle
+import yaml
+import glob
+import random
+import msgpack
+import importlib
+import traceback
+from PIL import Image
+import functools
+from functools import partial
+import urllib.request
+from warnings import simplefilter
+from datetime import timedelta
+from timeit import default_timer
+from configobj import ConfigObj
+import requests
+import psutil
+import hashlib
+import imageio
+import math
+import h5py
+import csv
+import collections
+import json
+import json_lines
+import numpy as np
+import pandas as pd
+import torch
+import torch.nn as nn
+from torch.optim import Adam
+import torch.nn.functional as F
+from torch.utils.data import DataLoader
+from torch.utils.data import DataLoader, Dataset
+from einops import rearrange, repeat
+import torch.distributed as dist
+from torchvision import datasets, transforms, utils
+import torchvision
+
+# Disable transformers outputs weights.
+logging.getLogger().setLevel(logging.WARNING)
+simplefilter(action='ignore', category=FutureWarning)
+
+
+def get_logger(filename=None):
+ """
+ examples:
+ logger = get_logger('try_logging.txt')
+
+ logger.debug("Do something.")
+ logger.info("Start print log.")
+ logger.warning("Something maybe fail.")
+ try:
+ raise ValueError()
+ except ValueError:
+ logger.error("Error", exc_info=True)
+
+ tips:
+ DO NOT logger.inf(some big tensors since color may not helpful.)
+ """
+ logger = logging.getLogger('utils')
+ level = logging.DEBUG
+ logger.setLevel(level=level)
+ # Use propagate to avoid multiple loggings.
+ logger.propagate = False
+ # Remove %(levelname)s since we have colorlog to represent levelname.
+ format_str = '[%(asctime)s <%(filename)s:%(lineno)d> %(funcName)s] %(message)s'
+
+ streamHandler = logging.StreamHandler()
+ streamHandler.setLevel(level)
+ coloredFormatter = colorlog.ColoredFormatter(
+ '%(log_color)s' + format_str,
+ datefmt='%Y-%m-%d %H:%M:%S',
+ reset=True,
+ log_colors={
+ 'DEBUG': 'cyan',
+ # 'INFO': 'white',
+ 'WARNING': 'yellow',
+ 'ERROR': 'red',
+ 'CRITICAL': 'reg,bg_white',
+ }
+ )
+
+ streamHandler.setFormatter(coloredFormatter)
+ logger.addHandler(streamHandler)
+
+ if filename:
+ fileHandler = logging.FileHandler(filename)
+ fileHandler.setLevel(level)
+ formatter = logging.Formatter(format_str)
+ fileHandler.setFormatter(formatter)
+ logger.addHandler(fileHandler)
+
+ # Fix multiple logging for torch.distributed
+ try:
+ class UniqueLogger:
+ def __init__(self, logger):
+ self.logger = logger
+ self.local_rank = torch.distributed.get_rank()
+
+ def info(self, msg, *args, **kwargs):
+ if self.local_rank == 0:
+ return self.logger.info(msg, *args, **kwargs)
+
+ def warning(self, msg, *args, **kwargs):
+ if self.local_rank == 0:
+ return self.logger.warning(msg, *args, **kwargs)
+
+ logger = UniqueLogger(logger)
+ # AssertionError for gpu with no distributed
+ # AttributeError for no gpu.
+ except Exception:
+ pass
+ return logger
+
+
+logger = get_logger()
+logger.info(": Deep Learning Utils @ Chenfei Wu")
+
+
+def path_join(path, *paths):
+ output = os.path.join(path, *paths).replace('\\', '/')
+ return output
+
+
+class Timer:
+ def __init__(self):
+ '''
+ t = Timer()
+ time.sleep(1)
+ print(t.elapse())
+ '''
+ self.start = default_timer()
+
+ def elapse(self, readable=False):
+ seconds = default_timer() - self.start
+ if readable:
+ seconds = str(timedelta(seconds=seconds))
+ return seconds
+
+
+def timing(f):
+ def wrap(*args):
+ time1 = time.time()
+ ret = f(*args)
+ time2 = time.time()
+ logger.info('%s function took %0.3f ms' % (f.__name__, (time2 - time1) * 1000.0))
+ return ret
+
+ return wrap
+
+
+def identity(x):
+ return x
+
+
+def groupby(l, key=lambda x: x):
+ d = collections.defaultdict(list)
+ for item in l:
+ d[key(item)].append(item)
+ return dict(d.items())
+
+
+def list_filenames(dirname, filter_fn=None, sort_fn=None, printable=True):
+ dirname = os.path.abspath(dirname)
+ filenames = os.listdir(dirname)
+ filenames = [os.path.join(dirname, filename) for filename in filenames]
+ if filter_fn:
+ tmp = len(filenames)
+ if printable:
+ logger.info('Start filtering files in %s by %s.' % (dirname, filter_fn))
+ filenames = [e for e in filenames if filter_fn(e)]
+ if printable: logger.info(
+ 'Detected %s files/dirs in %s, filtering to %s files.' % (tmp, dirname, len(filenames)))
+ else:
+ if printable: logger.info('Detected %s files/dirs in %s, No filtering.' % (len(filenames), dirname))
+ if sort_fn:
+ filenames = sorted(filenames, key=sort_fn)
+
+ return filenames
+
+
+def listdict2dict2list(listdict, printable=True):
+ tmp_dict = collections.defaultdict(list)
+ for example_dict in listdict:
+ for k, v in example_dict.items():
+ tmp_dict[k].append(v)
+ if printable: logger.info('%s' % tmp_dict.keys())
+ return dict(tmp_dict)
+
+
+def split_filename(filename):
+ absname = os.path.abspath(filename)
+ dirname, basename = os.path.split(absname)
+ split_tmp = basename.rsplit('.', maxsplit=1)
+ if len(split_tmp) == 2:
+ rootname, extname = split_tmp
+ elif len(split_tmp) == 1:
+ rootname = split_tmp[0]
+ extname = None
+ else:
+ raise ValueError("programming error!")
+ return dirname, rootname, extname
+
+def get_suffix(file_path):
+ try:
+ return os.path.splitext(file_path)[-1]
+ except:
+ raise ValueError(f"file_path:{file_path} error!")
+
+def data2file(data, filename, type=None, override=False, printable=False, **kwargs):
+ dirname, rootname, extname = split_filename(filename)
+ print_did_not_save_flag = True
+ if type:
+ extname = type
+ if not os.path.exists(dirname):
+ try:
+ os.makedirs(dirname, exist_ok=True)
+ except:
+ pass
+
+ if not os.path.exists(filename) or override:
+ if extname == 'pkl':
+ with open(filename, 'wb') as f:
+ pickle.dump(data, f)
+ elif extname == 'msg':
+ with open(filename, 'wb') as f:
+ msgpack.dump(data, f)
+ elif extname == 'h5':
+ if kwargs is None:
+ params = {}
+ split_num = kwargs.get('split_num')
+
+ if split_num:
+ if not isinstance(data, list):
+ raise ValueError(
+ '[error] utils.data2file: data must have type of list when use split_num, but got %s' % (
+ type(data)))
+
+ if not split_num <= len(data):
+ raise ValueError(
+ '[error] utils.data2file: split_num(%s) must <= data(%s)' % (len(split_num), len(data)))
+
+ print_save_flag = False
+ print_did_not_save_flag = False
+ pre_define_filenames = ["%s_%d" % (filename, i) for i in range(split_num)]
+ pre_search_filenames = glob.glob("%s*" % filename)
+
+ strict_existed = (set(pre_define_filenames) == set(pre_search_filenames) and len(
+ set([os.path.exists(e) for e in pre_define_filenames])) == 1)
+ common_existed = len(set([os.path.exists(e) for e in pre_search_filenames])) == 1
+
+ def rewrite():
+ logger.info('Spliting data to %s parts before saving...' % split_num)
+ data_splits = np.array_split(data, indices_or_sections=split_num)
+ for i, e in enumerate(data_splits):
+ deepdish.io.save("%s_%d" % (filename, i), list(e))
+ logger.info('Saved data to %s_(0~%d)' % (
+ os.path.abspath(filename), len(data_splits) - 1))
+
+ if strict_existed and not override:
+ logger.info(
+ 'Did not save data to %s_(0~%d) because the files strictly exist and override is False' % (
+ os.path.abspath(filename), len(pre_search_filenames) - 1))
+ elif common_existed:
+ logger.warning('Old wrong files (maybe a differnt split) exist, auto delete them.')
+ for e in pre_search_filenames:
+ os.remove(e)
+ rewrite()
+ else:
+ rewrite()
+ else:
+ deepdish.io.save(filename, data)
+ elif extname == 'hy':
+ # hy support 2 params: key and max_step
+ # if key, then create group using key, else create group using index
+ # if max_step, then the loop may early stopping, used for debug
+ # Remove filename since h5py may corrupt.
+ if override:
+ remove_filename(filename)
+ key_str = kwargs.pop('key_str', None)
+ topk = kwargs.pop('topk', None)
+
+ with h5py.File(filename, 'w') as f:
+ for i, datum in enumerate(tqdm(data)):
+ if key_str:
+ grp = f.create_group(name=datum[key_str])
+ else:
+ grp = f.create_group(name=str(i))
+ for k in datum.keys():
+ grp[k] = datum[k]
+ if topk is not None and i + 1 == topk:
+ break
+ elif extname == 'csv':
+ with open(filename, 'w') as f:
+ writer = csv.writer(f)
+ writer.writerows(data)
+ elif extname == 'json':
+ with open(filename, 'w') as f:
+ json.dump(data, f)
+ elif extname == 'npy':
+ np.save(filename, data)
+ elif extname in ['jpg', 'png', 'jpeg']:
+ utils.save_image(data, filename, **kwargs)
+ elif extname == 'gif':
+ imageio.mimsave(filename, data, format='GIF', duration=kwargs.get('duration'))
+ elif extname == ['pth', 'pt', 'ckpt']:
+ torch.save(data, filename)
+ elif extname == 'txt':
+ if kwargs is None:
+ kwargs = {}
+ max_step = kwargs.get('max_step')
+ if max_step is None:
+ max_step = np.Infinity
+
+ with open(filename, 'w', encoding='utf-8') as f:
+ for i, e in enumerate(data):
+ if i < max_step:
+ f.write(str(e) + '\n')
+ else:
+ break
+ else:
+ raise ValueError('type can only support h5, csv, json, sess')
+ if printable: logger.info('Saved data to %s' % os.path.abspath(filename))
+ else:
+ if print_did_not_save_flag: logger.info(
+ 'Did not save data to %s because file exists and override is False' % os.path.abspath(
+ filename))
+
+
+def file2data(filename, type=None, printable=True, **kwargs):
+ dirname, rootname, extname = split_filename(filename)
+ print_load_flag = True
+ if type:
+ extname = type
+ if extname == 'pkl':
+ with open(filename, 'rb') as f:
+ data = pickle.load(f)
+ elif extname == 'msg':
+ with open(filename, 'rb') as f:
+ data = msgpack.load(f, encoding="utf-8")
+ elif extname == 'h5':
+ split_num = kwargs.get('split_num')
+ if split_num:
+ print_load_flag = False
+ if isinstance(split_num, int):
+ filenames = ["%s_%i" % (filename, i) for i in range(split_num)]
+ if split_num != len(glob.glob("%s*" % filename)):
+ logger.warning('Maybe you are giving a wrong split_num(%d) != seached num (%d)' % (
+ split_num, len(glob.glob("%s*" % filename))))
+
+ elif split_num == 'auto':
+ filenames = glob.glob("%s*" % filename)
+ logger.info('Auto located %d splits linked to %s' % (len(filenames), filename))
+ else:
+ raise ValueError("params['split_num'] got unexpected value: %s, which is not supported." % split_num)
+ data = []
+ for e in filenames:
+ data.extend(deepdish.io.load(e))
+ logger.info('Loaded data from %s_(%s)' % (
+ os.path.abspath(filename), ','.join(sorted([e.split('_')[-1] for e in filenames]))))
+ else:
+ data = deepdish.io.load(filename)
+ elif extname == 'csv':
+ data = pd.read_csv(filename)
+ elif extname == 'tsv': # Returns generator since tsv file is large.
+ if not kwargs.get('delimiter'): # Set default delimiter
+ kwargs['delimiter'] = '\t'
+ if not kwargs.get('fieldnames'): # Check field names
+ raise ValueError('You must specify fieldnames when load tsv data.')
+ # Required args.
+ key_str = kwargs.pop('key_str')
+ decode_fn = kwargs.pop('decode_fn')
+ # Optimal args.
+ topk = kwargs.pop('topk', None)
+ redis = kwargs.pop('redis', None)
+ if not redis:
+ data = dict()
+ else:
+ data = redis
+ if not redis or not redis.check():
+ with open(filename) as f:
+ reader = csv.DictReader(f, **kwargs)
+ for i, item in enumerate(tqdm(reader)):
+ if not redis: # if memory way
+ decode_fn(item)
+ data[item[key_str]] = item
+ if topk is not None and i + 1 == topk:
+ break
+ else:
+ logger.warning('check_str %s in redis, skip loading.' % data.check_str)
+ elif extname == 'hy':
+ data = h5py.File(filename, 'r')
+ elif extname in ['npy', 'npz']:
+ try:
+ data = np.load(filename, allow_pickle=True)
+ except UnicodeError:
+ logger.warning('%s is python2 format, auto use latin1 encoding.' % os.path.abspath(filename))
+ data = np.load(filename, encoding='latin1', allow_pickle=True)
+ elif extname == 'json':
+ with open(filename) as f:
+ try:
+ data = json.load(f)
+ except json.decoder.JSONDecodeError as e:
+ raise ValueError('[error] utils.file2data: failed to load json file %s' % filename)
+ elif extname == 'jsonl':
+ with open(filename, 'rb') as f:
+ data = [e for e in json_lines.reader(f)]
+ elif extname == 'ini':
+ data = ConfigObj(filename, encoding='utf-8')
+ elif extname in ['pth', 'ckpt']:
+ data = torch.load(filename, map_location=kwargs.get('map_location'))
+ elif extname == 'txt':
+ top = kwargs.get('top', None)
+ with open(filename, encoding='utf-8') as f:
+ if top:
+ data = [f.readline() for _ in range(top)]
+ else:
+ data = [e for e in f.read().split('\n') if e]
+ elif extname == 'yaml':
+ with open(filename, 'r') as f:
+ data = yaml.load(f)
+ else:
+ raise ValueError('type can only support h5, npy, json, txt')
+ if printable:
+ if print_load_flag:
+ logger.info('Loaded data from %s' % os.path.abspath(filename))
+ return data
+
+
+def download_file(fileurl, filedir=None, progress_bar=True, override=False, fast=False, printable=True):
+ if filedir:
+ ensure_dirname(filedir)
+ assert os.path.isdir(filedir)
+ else:
+ filedir = ''
+ filename = os.path.abspath(os.path.join(filedir, fileurl.split('/')[-1]))
+ # print(filename)
+ dirname = os.path.dirname(filename)
+ if not os.path.exists(dirname):
+ os.makedirs(dirname)
+ logger.info("%s not exist, automatic makedir." % dirname)
+ if not os.path.exists(filename) or override:
+ if fast:
+ p = subprocess.Popen('axel -n 10 -o {0} {1}'.format(filename, fileurl), shell=True,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ for line in iter(p.stdout.readline, ''):
+ if line:
+ logger.info(line.decode('utf-8').replace('\n', ''))
+ else:
+ p.kill()
+ break
+ else:
+ if progress_bar:
+ def my_hook(t):
+ last_b = [0]
+
+ def inner(b=1, bsize=1, tsize=None):
+ if tsize is not None:
+ t.total = tsize
+ t.update((b - last_b[0]) * bsize)
+ last_b[0] = b
+
+ return inner
+
+ with tqdm(unit='B', unit_scale=True, miniters=1,
+ desc=fileurl.split('/')[-1]) as t:
+ urllib.request.urlretrieve(fileurl, filename=filename,
+ reporthook=my_hook(t), data=None)
+ else:
+ urllib.request.urlretrieve(fileurl, filename=filename)
+ if printable: logger.info("%s downloaded sucessfully." % filename)
+ else:
+ if printable: logger.info("%s already existed" % filename)
+ return filename
+
+
+def copy_file(filename, targetname, override=False, printable=True):
+ filename = os.path.abspath(filename)
+ targetname = os.path.abspath(targetname)
+ if not os.path.exists(targetname) or override:
+ shutil.copy2(filename, targetname)
+ if printable:
+ logger.info('Copied %s to %s.' % (filename, targetname))
+ else:
+ if printable:
+ logger.info('Did not copy because %s exists.' % targetname)
+
+
+def videofile2videometa(input_video):
+ out = execute_cmd('ffprobe -i %s -print_format json -show_streams' % input_video)
+ meta = json.loads(out.decode('utf-8'))
+
+ if 'duration' in meta['streams'][0]:
+ duration = float(meta['streams'][0]['duration'])
+ elif 'DURATION' in meta['streams'][0]['tags']: # Fix Duration for webm format.
+ duration_str = meta['streams'][0]['tags']['DURATION']
+ h, m, s = duration_str.split(':')
+ duration = float(h) * 3600 + float(m) * 60 + float(s)
+ else:
+ duration = execute_cmd("ffprobe -i %s -show_entries format=duration -v quiet -of csv=\"p=0\"" %(input_video))
+ duration = float(duration)
+
+ res = {'width': meta['streams'][0]['width'],
+ 'height': meta['streams'][0]['height'],
+ 'duration': duration,
+ 'fps': eval(meta['streams'][0]['r_frame_rate'])}
+ return res
+
+
+def videofile2videoarr(input_file, seek_start=None, seek_duration=None, seek_fps=None):
+ ffprob_out = execute_cmd(f'ffprobe -i {input_file} -print_format json -show_streams')
+ meta = json.loads(ffprob_out.decode('utf-8'))
+ width = meta['streams'][0]['width']
+ height = meta['streams'][0]['height']
+ cmd = f'ffmpeg -y -i {input_file} '
+ if seek_start:
+ cmd += f'-ss {seek_start} '
+ if seek_duration:
+ cmd += f'-t {seek_duration} '
+ if seek_fps:
+ cmd += f'-filter_complex [0]fps=fps={seek_fps}[s0] -map [s0] '
+ cmd += '-f rawvideo -pix_fmt rgb24 pipe:'
+ # assert cmd == 'ffmpeg -y -i pipe: -ss 2 -t 4 -filter_complex [0]fps=fps=0.5[s0] -map [s0] -f rawvideo -pix_fmt rgb24 pipe:'
+ ffmpeg_out = execute_cmd(cmd)
+ video = np.frombuffer(ffmpeg_out, np.uint8)
+ video = video.reshape([-1, height, width, 3])
+ return video
+
+
+def ensure_dirname(dirname, override=False):
+ if os.path.exists(dirname) and override:
+ logger.info('Removing dirname: %s' % os.path.abspath(dirname))
+ try:
+ shutil.rmtree(dirname)
+ except OSError as e:
+ raise ValueError('Failed to delete %s because %s' % (dirname, e))
+
+ if not os.path.exists(dirname):
+ logger.info('Making dirname: %s' % os.path.abspath(dirname))
+ try:
+ os.makedirs(dirname, exist_ok=True)
+ except:
+ pass
+
+def ensure_filename(filename, override=False):
+ dirname, rootname, extname = split_filename(filename)
+ ensure_dirname(dirname, override=False)
+ if os.path.exists(filename) and override:
+ os.remove(filename)
+ logger.info('Deleted filename %s' % filename)
+
+
+def remove_filename(filename, printable=False):
+ if os.path.isfile(filename) or os.path.islink(filename):
+ os.remove(filename)
+ if printable:
+ logger.info('Deleted file %s.' % filename)
+ elif os.path.isdir(filename):
+ shutil.rmtree(filename)
+ if printable:
+ logger.info('Deleted dir %s.' % filename)
+ else:
+ raise ValueError("%s is not a file or dir." % filename)
+
+
+def execute(cmd, wait=True, printable=True):
+ if wait:
+ if printable: logger.warning('Executing: '"%s"', waiting...' % cmd)
+ try:
+ output = subprocess.check_output(cmd, shell=True)
+ except subprocess.CalledProcessError as e:
+ logger.warning(e.output)
+ output = None
+ # sys.exit(-1)
+
+ return output
+ else:
+ if platform.system() == 'Windows':
+ black_hole = 'NUL'
+ elif platform.system() == 'Linux':
+ black_hole = '/dev/null'
+ else:
+ raise ValueError('Unsupported system %s' % platform.system())
+ cmd = cmd + ' 1>%s 2>&1' % black_hole
+ if printable: logger.info('Executing: '"%s"', not wait.' % cmd)
+ subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+
+# def execute_cmd(cmd, input_data=None, printable=False):
+# if printable:
+# print(f'Running CMD:\n{cmd}')
+# process = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+# out, err = process.communicate(input=input_data)
+# retcode = process.poll()
+# if retcode:
+# raise SystemError(f"\nCMD is:\n{cmd}\nERROR is:\n{err.decode('utf-8')}")
+# return out
+
+# def execute_cmd(cmd, input_data=None, printable=False):
+# if printable:
+# print(f'Running CMD:\n{cmd}')
+# if input_data:
+# process = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+# out, err = process.communicate(input=input_data)
+# retcode = process.poll()
+# if retcode:
+# raise subprocess.CalledProcessError(f"\nCMD is:\n{cmd}\nERROR is:\n{err.decode('utf-8')}")
+# return out
+#
+# else:
+# with subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
+# out = []
+# for line in p.stdout:
+# print(line, end='')
+# out.append(line)
+# if p.returncode != 0:
+# raise subprocess.CalledProcessError(p.returncode, p.args)
+# return out
+
+# def execute_cmd(cmd, input_data=None, printable=False):
+# # add shlex.quote
+# # remove shlex.split
+# process = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+# out, err = process.communicate(input=input_data)
+# retcode = process.poll()
+# if retcode:
+# raise ValueError(err.decode('utf-8'))
+# return out
+
+def execute_cmd(cmd, input_data=None, printable=False):
+ if printable:
+ print(f'Running CMD:\n{cmd}')
+ process = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ out, err = process.communicate(input=input_data)
+ retcode = process.poll()
+ if retcode:
+ raise subprocess.CalledProcessError(f"\nCMD is:\n{cmd}\nERROR is:\n{err.decode('utf-8')}")
+ return out
+
+def import_filename(filename):
+ spec = importlib.util.spec_from_file_location("mymodule", filename)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def pname2pid(str_proc_name):
+ map_proc_info = {}
+ for proc in psutil.process_iter():
+ if proc.name() == str_proc_name:
+ map_proc_info[proc.pid] = str_proc_name
+
+ return map_proc_info
+
+
+def get_parameters(net: torch.nn.Module):
+ trainable_params = sum(p.numel() for p in net.parameters() if p.requires_grad)
+ frozen_params = sum(p.numel() for p in net.parameters() if not p.requires_grad)
+ fp32_trainable_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float32 and p.requires_grad)
+ fp16_trainable_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float16 and p.requires_grad)
+ fp32_frozen_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float32 and not p.requires_grad)
+ fp16_frozen_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float16 and not p.requires_grad)
+ return {'trainable': trainable_params, 'frozen': frozen_params,
+ 'trainable_fp32': fp32_trainable_params,
+ 'trainalbe_fp16': fp16_trainable_params,
+ 'frozen_fp32': fp32_frozen_params, 'frozen_fp16': fp16_frozen_params}
+
+
+def adaptively_load_state_dict(target, state_dict):
+ target_dict = target.state_dict()
+
+ try:
+ common_dict = {k: v for k, v in state_dict.items() if k in target_dict and v.size() == target_dict[k].size()}
+ except Exception as e:
+ logger.warning('load error %s', e)
+ common_dict = {k: v for k, v in state_dict.items() if k in target_dict}
+
+ if 'param_groups' in common_dict and common_dict['param_groups'][0]['params'] != \
+ target.state_dict()['param_groups'][0]['params']:
+ logger.warning('Detected mismatch params, auto adapte state_dict to current')
+ common_dict['param_groups'][0]['params'] = target.state_dict()['param_groups'][0]['params']
+ target_dict.update(common_dict)
+ target.load_state_dict(target_dict)
+
+ missing_keys = [k for k in target_dict.keys() if k not in common_dict]
+ unexpected_keys = [k for k in state_dict.keys() if k not in common_dict]
+
+ if len(unexpected_keys) != 0:
+ logger.warning(
+ f"Some weights of state_dict were not used in target: {unexpected_keys}"
+ )
+ if len(missing_keys) != 0:
+ logger.warning(
+ f"Some weights of target are missing in state_dict: {missing_keys}"
+ )
+ if len(unexpected_keys) == 0 and len(missing_keys) == 0:
+ logger.warning("Strictly Loaded state_dict.")
+
+
+class Meter(object):
+ def __init__(self):
+ self.val = None
+ self.avg = None
+ self.sum = None
+ self.count = None
+
+ def update(self, val, n=1):
+ if isinstance(val, torch.Tensor):
+ val = val.item()
+ if isinstance(val, (int, float)):
+ self.val = val
+ if self.sum:
+ self.sum += val * n
+ else:
+ self.sum = val * n
+ if self.count:
+ self.count += n
+ else:
+ self.count = n
+ self.avg = self.sum / self.count
+ elif isinstance(val, dict):
+ for k, v in val.items():
+ if isinstance(v, torch.Tensor):
+ val[k] = v.item()
+ if self.val:
+ for k in val.keys():
+ self.val[k] = val[k]
+ else:
+ self.val = val
+ if self.sum:
+ for k in val.keys():
+ if k in self.sum:
+ self.sum[k] = self.sum[k] + val[k] * n
+ else:
+ self.sum[k] = val[k] * n
+ else:
+ self.sum = {k: val[k] * n for k in val.keys()}
+ if self.count:
+ for k in val.keys():
+ if k in self.count:
+ self.count[k] = self.count[k] + n
+ else:
+ self.count[k] = n
+ else:
+ self.count = {k: n for k in val.keys()}
+ self.avg = {k: self.sum[k] / self.count[k] for k in self.count.keys()}
+ else:
+ raise ValueError('Not supported type %s' % type(val))
+
+ def __str__(self):
+ if isinstance(self.avg, dict):
+ return str({k: "%.4f" % v for k, v in self.avg.items()})
+
+
+def set_seed(seed=42):
+ random.seed(seed)
+ os.environ['PYHTONHASHSEED'] = str(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+
+class Trainer:
+ """
+ Trainer
+ """
+
+ def __init__(self, args, model, optimizers=None, scheduler=None, pretrained_model=None, use_amp=True,
+ find_unused_parameters=True):
+ # Basic Params
+ self.args = args
+ self.log_dir = args.log_dir
+ self.model = model
+ self.optimizers = optimizers
+ self.scheduler = scheduler
+ self.pretrained_model = pretrained_model
+ self.use_amp = use_amp
+ self.find_unused_parameters = find_unused_parameters
+ # Load Pretrained Models.
+ if pretrained_model:
+ self.from_pretrained(pretrained_model)
+ # Get Variables from ENV
+ self.rank = int(os.getenv('RANK', '-1'))
+ self.local_rank = int(os.getenv('LOCAL_RANK', '-1'))
+ # Define Running mode.
+ if self.local_rank == -1:
+ self.mode = 'common'
+ self.enable_write_model = True
+ self.enable_collect = True
+ self.enable_write_metric = True
+ else:
+ self.mode = 'dist'
+ self.enable_write_model = (self.rank == 0)
+ self.enable_collect = True
+ self.enable_write_metric = (self.rank == 0)
+
+ if self.enable_write_metric:
+ ensure_dirname(self.log_dir, override=False)
+ self.metric_filename = os.path.join(self.log_dir, 'metric.json')
+ self.last_checkpoint_filename = os.path.join(self.log_dir, 'last.pth')
+ self.best_checkpoint_filename = os.path.join(self.log_dir, 'best.pth')
+ self.each_checkpoint_filename = os.path.join(self.log_dir, 'epoch%s.pth')
+ self.epoch = -1
+
+ # Get device and number of GPUs
+ self.n_gpu = torch.cuda.device_count()
+ if self.n_gpu >= 1:
+ self.device = torch.device("cuda")
+ else:
+ self.device = torch.device("cpu")
+
+ if self.use_amp and self.n_gpu < 1:
+ raise ValueError('AMP Does not support CPU!')
+ if self.use_amp and self.mode == 'common':
+ logger.warning('In common mode, remember to @autocast before forward function.')
+ self.scalar = torch.cuda.amp.GradScaler(enabled=self.use_amp)
+
+ # TODO
+ if hasattr(args, 'iterative_model_class'):
+ self.iterative_model = args.iterative_model_class(args=args)
+ else:
+ self.iterative_model = None
+
+ def reduce_mean(self, tensor):
+ rt = tensor.clone()
+ size = int(os.environ['WORLD_SIZE'])
+ dist.all_reduce(rt, op=dist.ReduceOp.SUM)
+ rt = rt / size
+ return rt
+
+ def wrap_model(self):
+ if hasattr(self.model, 'module'):
+ raise ValueError('You do not need to wrap a models with modules.')
+
+ if self.mode == 'common':
+ logger.info('Wrapped models to common %s.' % self.device)
+
+ self.model.to(self.device)
+ if self.n_gpu > 1:
+ logger.warning('Detected %s gpus, auto using DataParallel.' % self.n_gpu)
+ self.model = torch.nn.DataParallel(self.model)
+ elif self.mode == 'dist':
+ logger.info('Wrapped models to distributed %s.' % self.device)
+
+ self.device = torch.device("cuda", self.local_rank)
+ self.model.to(self.device)
+ self.model = torch.nn.parallel.DistributedDataParallel(
+ self.model, device_ids=[self.local_rank],
+ output_device=self.local_rank,
+ find_unused_parameters=self.find_unused_parameters)
+ else:
+ raise ValueError
+ # wrap_optimizers
+ if self.optimizers:
+ for i in range(len(self.optimizers)):
+ self.optimizers[i].load_state_dict(
+ complex_to_device(self.optimizers[i].state_dict(), device=self.device))
+
+ def check_outputs(self, outputs):
+ error_message = 'Model output must be a dict. The key must be "class_subclass" format.' \
+ ' "class" can only be loss, metric, or logits. "subclass" should be a string.' \
+ ' But got an unexpected key %s'
+ loss_total_list = [e for e in outputs.keys() if e.startswith('loss_total')]
+ if not loss_total_list:
+ raise ValueError('Model output must contain a key startswith "loss_total"!')
+
+ for k, v in outputs.items():
+ split_res = k.split('_')
+ if len(split_res) < 2:
+ raise ValueError(error_message % k)
+ if k.split('_')[0] not in ['loss', 'metric', 'logits']:
+ raise ValueError(error_message % k)
+
+ def train(self, train_loader, eval_loader=None, epochs=5, resume=True, eval_step=10,
+ save_step=None, use_tqdm=None, max_norm=None, gradient_accumulate_steps=1,
+ inner_collect_fn=None, best_metric_fn=lambda x: x['train']['loss_total']):
+ if not save_step:
+ save_step = eval_step
+ best_eval_metric = np.Infinity
+ if resume:
+ if os.path.exists(self.last_checkpoint_filename):
+ self.load_checkpoint(self.last_checkpoint_filename)
+ else:
+ if self.enable_write_metric:
+ logger.warning('Dangerous! You set resume=False. Auto cleaning all the logs under %s' % self.log_dir)
+ ensure_dirname(self.log_dir, override=True)
+
+ self.wrap_model()
+
+ epoch_iter = range(self.epoch + 1, epochs, 1)
+ if len(epoch_iter):
+ logger.warning('Start train & val phase...')
+ else:
+ logger.warning('Skip train & val phase...')
+ logger.warning(f'Train examples: {len(train_loader.dataset)}, epochs: {epochs}, '
+ f'global_batch_size: {self.args.train_batch_size}, local_batch_size: {train_loader.batch_size}.')
+
+ # Train & Eval phase
+ for epoch in epoch_iter:
+ self.epoch = epoch
+ # Train phase
+ train_meter, train_time = self.train_fn(train_loader,
+ max_norm=max_norm,
+ gradient_accumulate_steps=gradient_accumulate_steps,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ metric = {'Epoch%s' % (epoch + 1): {'train': {**train_meter.avg, **{'time': train_time}}}}
+
+ if self.enable_write_metric:
+ self.update_metric_file(metric)
+ if (epoch + 1) % save_step == 0:
+ if self.enable_write_model:
+ self.save_checkpoint(self.last_checkpoint_filename)
+ copy_file(self.last_checkpoint_filename, self.each_checkpoint_filename % str(epoch + 1),
+ override=True)
+
+ if (epoch + 1) % eval_step == 0:
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, epochs, eval_time, eval_meter.avg))
+
+ # Update metric with eval metrics
+ metric['Epoch%s' % (epoch + 1)].update({'eval': {**eval_meter.avg, **{'time': eval_time}}})
+
+ # Save metric file
+ if self.enable_write_metric:
+ self.update_metric_file(metric)
+
+ # If the best models, save another checkpoint.
+ # if best_metric_fn(metric['Epoch%s' % (epoch + 1)]) < best_eval_metric and self.enable_write_model:
+ # best_eval_metric = best_metric_fn(metric['Epoch%s' % (epoch + 1)])
+ # if os.path.exists(self.last_checkpoint_filename):
+ # copy_file(self.last_checkpoint_filename, self.best_checkpoint_filename, override=True)
+ # else:
+ # logger.warning('No checkpoint_file %s' % self.last_checkpoint_filename)
+
+ def eval(self, eval_loader, inner_collect_fn=None, use_tqdm=True):
+ # This function is used to do evaluating after training.
+ if not self.pretrained_model:
+ logger.warning('You should create a new config file and specify pretrained_model in Args when using eval.')
+ # Wrap models before evaluating. This will support ddp evaluating.
+ self.wrap_model()
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn, use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Time: %s\n %s' % (self.rank, eval_time, eval_meter.avg))
+
+ def update_metric_file(self, metric):
+ if os.path.exists(self.metric_filename):
+ r = file2data(self.metric_filename, printable=False)
+ data2file(dict(r, **metric), self.metric_filename, override=True)
+ else:
+ data2file(metric, self.metric_filename)
+
+ def train_fn(self, train_loader, max_norm, gradient_accumulate_steps=1, use_tqdm=True):
+ self.model.train()
+ train_meter = Meter()
+ train_timer = Timer()
+ train_iter = tqdm(train_loader, total=len(train_loader), disable=not use_tqdm)
+ for step, inputs in enumerate(train_iter):
+ for optimizer_idx in range(len(self.optimizers)):
+ if not getattr(self.optimizers[optimizer_idx], 'is_enabled', lambda x: True)(self.epoch):
+ continue
+ inputs = complex_to_device(inputs, self.device)
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.epoch * len(train_loader) + step
+ inputs['optimizer_idx'] = optimizer_idx
+
+ # for outputs in self.models(inputs):
+ for outputs in self.iterative_model.forward(self.model, inputs) \
+ if self.iterative_model else [self.model(inputs)]:
+ self.check_outputs(outputs)
+ # If we use nn.Parallel, we will get a list of metric or losses from different GPUs, we need to mean them.
+ if self.mode == 'common' and self.n_gpu > 1:
+ for k, v in outputs.items():
+ if k.split('_')[0] in ['metric', 'loss']:
+ outputs[k] = v.mean()
+
+ if optimizer_idx == 0:
+ outputs['loss_total'].backward()
+ else:
+ outputs['loss_total_%s' % optimizer_idx].backward()
+
+ if (step + 1) % gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ if max_norm:
+ nn.utils.clip_grad_norm_(self.model.parameters(), max_norm)
+ self.optimizers[optimizer_idx].step()
+ self.optimizers[optimizer_idx].zero_grad()
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ if self.mode != 'common':
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ if self.scheduler:
+ self.scheduler.step()
+
+ train_iter.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+ return train_meter, train_time
+
+ def eval_fn(self, eval_loader, inner_collect_fn=None, use_tqdm=True):
+ # TODO Note that eval_fn supports ddp. So we do not need to unwrap things here.
+ model_to_eval = self.model
+ model_to_eval.eval()
+ eval_meter = Meter()
+ eval_timer = Timer()
+ with torch.no_grad():
+ eval_loader = tqdm(eval_loader, total=len(eval_loader)) if use_tqdm else eval_loader
+ for inputs in eval_loader:
+ inputs = complex_to_device(inputs, self.device)
+ outputs = model_to_eval(inputs)
+ if self.mode == 'common' and self.n_gpu > 1:
+ for k, v in outputs.items():
+ if k.split('_')[0] in ['metric', 'loss']:
+ outputs[k] = v.mean()
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ if self.mode != 'common':
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ eval_meter.update(metric_and_loss)
+
+ if inner_collect_fn and self.enable_collect:
+ inner_collect_fn(self.args, inputs, outputs, self.log_dir, self.epoch, self.args.eval_save_filename)
+
+ eval_time = eval_timer.elapse(True)
+ return eval_meter, eval_time
+
+ def load_checkpoint(self, checkpoint_filename):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load checkpoint into wrapped models, ensure self.models is CPU.")
+ checkpoint = file2data(checkpoint_filename, map_location='cpu')
+ adaptively_load_state_dict(self.model, checkpoint['models'])
+ if self.optimizers:
+ if len(self.optimizers) > 1:
+ for i, optimizer in enumerate(self.optimizers):
+ adaptively_load_state_dict(self.optimizers[i], checkpoint['optimizer'][i])
+
+ elif len(self.optimizers) == 1:
+ adaptively_load_state_dict(self.optimizers[0], checkpoint['optimizer'])
+
+ else:
+ raise ValueError
+ if self.scheduler:
+ adaptively_load_state_dict(self.scheduler, checkpoint['scheduler'])
+
+ self.epoch = checkpoint['epoch'] - 1
+
+ # IMPORTANT! The models will be wrapped automatically.
+ logger.warning('Loaded checkpoint %s of epoch %s' % (checkpoint_filename, checkpoint['epoch']))
+
+ def save_checkpoint(self, checkpoint_filename):
+ model_to_save = self.model.module if hasattr(self.model, 'module') else self.model
+ if len(self.optimizers) > 1:
+ optimizer_to_save = [optimizer.state_dict() for optimizer in self.optimizers]
+ elif len(self.optimizers) == 1:
+ optimizer_to_save = self.optimizers[0].state_dict()
+ else:
+ raise ValueError
+ checkpoint = {
+ 'models': model_to_save.state_dict(),
+ 'optimizer': optimizer_to_save,
+ 'epoch': self.epoch + 1,
+ }
+ if self.scheduler:
+ checkpoint['scheduler'] = self.scheduler.state_dict()
+ data2file(checkpoint, checkpoint_filename, override=True)
+ logger.warning('Saved epoch %s to %s.' % (checkpoint['epoch'], checkpoint_filename))
+
+ def from_pretrained(self, pretrained_model):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load pretrained models into wrapped models, ensure self.models is CPU.")
+ if isinstance(pretrained_model, str):
+ logger.warning('Loading Pretrained Model Path: %s...' % pretrained_model)
+ pretrained_dict = file2data(pretrained_model, map_location='cpu')
+ if 'models' in pretrained_dict:
+ pretrained_dict = pretrained_dict['models']
+ if 'model' in pretrained_dict:
+ pretrained_dict = pretrained_dict['model']
+ else:
+ logger.warning('Loading Given Pretrained Dict...')
+ pretrained_dict = pretrained_model
+ adaptively_load_state_dict(self.model, pretrained_dict)
+
+
+def dl2ld(dl):
+ return [dict(zip(dl, e)) for e in zip(*dl.values())]
+
+
+def ld2dl(ld):
+ return {k: [dic[k] for dic in ld] for k in ld[0]}
+
+
+def complex_to_device(complex, device, non_blocking=False):
+ # added by Linjie
+ if complex is None:
+ return complex
+ if isinstance(complex, torch.Tensor):
+ return complex.to(device, non_blocking=non_blocking)
+ elif isinstance(complex, dict):
+ return {k: complex_to_device(v, device, non_blocking=non_blocking) for k, v in complex.items()}
+ elif isinstance(complex, list) or isinstance(complex, tuple):
+ return [complex_to_device(e, device, non_blocking=non_blocking) for e in complex]
+ elif isinstance(complex, str) or isinstance(complex, bytes) or \
+ isinstance(complex, int) or isinstance(complex, float):
+ return complex
+ else:
+ raise ValueError('Unsupported complex', complex)
+
+
+'''
+=====================================================================================================================
+ Sync With Blob
+=====================================================================================================================
+'''
+
+
+# def azsync(path, local_rootdir, remote_rootdir='https://chenfei.blob.core.windows.net/data/'):
+# if not local_rootdir:
+# raise ValueError('local_root_dir must be specified, i.e., /workspace/f_ndata')
+# # r'D:\f_ndata' or /workspace/f_ndata
+# else:
+# local_rootdir = os.path.abspath(local_rootdir)
+# print('Local Root Dir is %s' % local_rootdir)
+#
+# if path.startswith('https:'):
+# local_path = None
+# remote_path = path
+# else:
+# local_path = path
+# remote_path = None
+# if not os.path.exists(local_path):
+# raise ValueError(f'The local_path {local_path} you specified does not exist or you have no permission!')
+#
+# if not os.environ.get('SAS'):
+# raise ValueError('You must specify SAS as environment variable manually before using azsync.\n'
+# 'Ask Chenfei Wu for this SAS')
+# else:
+# SAS = os.environ.get('SAS')
+# # print("SAS is: ", SAS)
+#
+# if remote_path:
+# if remote_path.startswith('https:'):
+# target_remote_path = remote_path
+# else:
+# target_remote_path = os.path.join(remote_rootdir, remote_path)
+# relative_path = target_remote_path.replace(remote_rootdir, "")
+# target_local_path = os.path.join(local_rootdir, relative_path)
+# if pathlib.Path(target_local_path).suffix:
+# print('Detected file transfer R->L')
+# method = "cp"
+# if not os.path.exists(target_local_path):
+# print('target_local_path: %s' % target_local_path)
+# os.makedirs(os.path.basename(target_local_path), exist_ok=True)
+#
+# else:
+# print('Detected dir transfer R->L.')
+# method = "sync"
+# if not os.path.exists(target_local_path):
+# os.makedirs(target_local_path, exist_ok=True)
+# cmd = f'azcopy {method} {target_remote_path}"{SAS}" "{target_local_path}"'
+# execute_cmd(cmd, printable=True)
+#
+# if local_path:
+# target_local_path = os.path.abspath(local_path)
+# relative_path = os.path.relpath(target_local_path, local_rootdir)
+# target_remote_path = os.path.join(remote_rootdir, relative_path).replace('\\', '/')
+# if pathlib.Path(target_local_path).suffix:
+# print('Detected file transfer L->R.')
+# method = "copy"
+# else:
+# print('Detected dir transfer L->R.')
+# method = "sync"
+# cmd = f'azcopy {method} "{target_local_path}" {target_remote_path}"{SAS}"'
+# execute_cmd(cmd, printable=True)
+
+
+
+# def azsync(path, local_rootdir, remote_rootdir='https://chenfei.blob.core.windows.net/data/'):
+# if not local_rootdir:
+# raise ValueError('local_root_dir must be specified, i.e., /workspace/f_ndata')
+# # r'D:\f_ndata' or /workspace/f_ndata
+# else:
+# local_rootdir = os.path.abspath(local_rootdir)
+# print('Local Root Dir is %s' % local_rootdir)
+#
+# if path.startswith('https:'):
+# local_path = None
+# remote_path = path
+# else:
+# local_path = path
+# remote_path = None
+# if not os.path.exists(local_path):
+# raise ValueError(f'The local_path {local_path} you specified does not exist or you have no permission!')
+#
+# if not os.environ.get('SAS'):
+# raise ValueError('You must specify SAS as environment variable manually before using azsync.\n'
+# 'Ask Chenfei Wu for this SAS')
+# else:
+# SAS = os.environ.get('SAS')
+# # print("SAS is: ", SAS)
+#
+# if remote_path:
+# if remote_path.startswith('https:'):
+# target_remote_path = remote_path
+# else:
+# target_remote_path = os.path.join(remote_rootdir, remote_path)
+# relative_path = target_remote_path.replace(remote_rootdir, "")
+# target_local_path = os.path.join(local_rootdir, relative_path)
+# if pathlib.Path(target_local_path).suffix:
+# print('Detected file transfer R->L')
+# method = "cp"
+# if not os.path.exists(target_local_path):
+# print('target_local_path: %s' % target_local_path)
+# os.makedirs(os.path.dirname(target_local_path), exist_ok=True)
+#
+# else:
+# print('Detected dir transfer R->L.')
+# method = "sync"
+# if not os.path.exists(target_local_path):
+# os.makedirs(target_local_path, exist_ok=True)
+# cmd = f'azcopy {method} {target_remote_path}"{SAS}" "{target_local_path}"'
+# execute_cmd(cmd, printable=True)
+#
+# if local_path:
+# target_local_path = os.path.abspath(local_path)
+# relative_path = os.path.relpath(target_local_path, local_rootdir)
+# target_remote_path = os.path.join(remote_rootdir, relative_path).replace('\\', '/')
+# if pathlib.Path(target_local_path).suffix:
+# print('Detected file transfer L->R.')
+# method = "copy"
+# else:
+# print('Detected dir transfer L->R.')
+# method = "sync"
+# cmd = f'azcopy {method} "{target_local_path}" {target_remote_path}"{SAS}"'
+# execute_cmd(cmd, printable=True)
+
+
+def azsync(path, local_rootdir, remote_rootdir='https://chenfei.blob.core.windows.net/data/'):
+ if not local_rootdir:
+ raise ValueError('local_root_dir must be specified, i.e., /workspace/f_ndata')
+ # r'D:\f_ndata' or /workspace/f_ndata
+ else:
+ local_rootdir = os.path.abspath(local_rootdir)
+ print('Local Root Dir is %s' % local_rootdir)
+
+ if path.startswith('https:'):
+ local_path = None
+ remote_path = path
+ else:
+ local_path = path
+ remote_path = None
+ if not os.path.exists(local_path):
+ raise ValueError(f'The local_path {local_path} you specified does not exist or you have no permission!')
+
+ if not os.environ.get('SAS'):
+ raise ValueError('You must specify SAS as environment variable manually before using azsync.\n'
+ 'Ask Chenfei Wu for this SAS')
+ else:
+ SAS = os.environ.get('SAS')
+ # print("SAS is: ", SAS)
+
+ if remote_path:
+ if remote_path.startswith('https:'):
+ target_remote_path = remote_path
+ else:
+ target_remote_path = os.path.join(remote_rootdir, remote_path)
+ relative_path = target_remote_path.replace(remote_rootdir, "")
+ target_local_path = os.path.join(local_rootdir, relative_path)
+ if pathlib.Path(target_local_path).suffix:
+ print('Detected file transfer R->L')
+ method = "cp"
+ if not os.path.exists(target_local_path):
+ print('target_local_path: %s' % target_local_path)
+ os.makedirs(os.path.dirname(target_local_path), exist_ok=True)
+
+ else:
+ print('Detected dir transfer R->L.')
+ method = "sync"
+ if not os.path.exists(target_local_path):
+ os.makedirs(target_local_path, exist_ok=True)
+ cmd = f'azcopy {method} {target_remote_path}"{SAS}" "{target_local_path}"'
+ print(f'cmd is {cmd}')
+ with subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
+ for line in p.stdout:
+ print(line, end='')
+
+ if local_path:
+ target_local_path = os.path.abspath(local_path)
+ relative_path = os.path.relpath(target_local_path, local_rootdir)
+ target_remote_path = os.path.join(remote_rootdir, relative_path).replace('\\', '/')
+ if pathlib.Path(target_local_path).suffix:
+ print('Detected file transfer L->R.')
+ method = "copy"
+ else:
+ print('Detected dir transfer L->R.')
+ method = "sync"
+ cmd = f'azcopy {method} "{target_local_path}" {target_remote_path}"{SAS}"'
+ print(f'cmd is {cmd}')
+ with subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, bufsize=1, universal_newlines=True) as p:
+ for line in p.stdout:
+ print(line, end='')
+
+'''
+=====================================================================================================================
+ Common Transformations
+=====================================================================================================================
+'''
+
+
+def npy2object(filename):
+ try:
+ data = np.load(filename, allow_pickle=True)
+ except UnicodeError:
+ logger.warning('%s is python2 format, auto use latin1 encoding.' % os.path.abspath(filename))
+ data = np.load(filename, encoding='latin1', allow_pickle=True)
+ return data
+
+
+def video2bytes(input_video):
+ out = execute_cmd('ffmpeg -y -i "%s" -c copy -movflags +faststart -f nut pipe:' % input_video, input_data=None)
+ return out
+
+
+def video2meta(input_video):
+ out = execute_cmd('ffprobe -i "%s" -print_format json -show_format -show_streams' % input_video)
+ meta = json.loads(out.decode('utf-8'))
+
+ # if 'duration' in meta['streams'][0]:
+ # duration = float(meta['streams'][0]['duration'])
+ # else: # Fix Duration for webm format.
+ # duration_str = meta['streams'][0]['tags']['DURATION']
+ # h, m, s = duration_str.split(':')
+ # duration = float(h) * 3600 + float(m) * 60 + float(s)
+
+ res = {'width': meta['streams'][0]['width'],
+ 'height': meta['streams'][0]['height'],
+ 'duration': eval(meta['format']['duration']),
+ 'fps': eval(meta['streams'][0]['r_frame_rate'])}
+ return res
+
+
+def video2arr(input_filename, seek_start=None, seek_duration=None, seek_fps=None, fast=True):
+ # 支持所有视频类型
+ ffprob_out = execute_cmd(f'ffprobe -i "{input_filename}" -print_format json -show_streams')
+ meta = json.loads(ffprob_out.decode('utf-8'))
+ width = meta['streams'][0]['width']
+ height = meta['streams'][0]['height']
+ if fast:
+ cmd = 'ffmpeg -y '
+ else:
+ cmd = f'ffmpeg -y -i "{input_filename}" '
+ if seek_start:
+ cmd += f'-ss {seek_start} '
+ if seek_duration:
+ cmd += f'-t {seek_duration} '
+ if seek_fps:
+ cmd += f'-filter_complex [0]fps=fps={seek_fps}[s0] -map [s0] '
+ # 专为处理gif服务
+ if not seek_start and not seek_duration and not seek_fps:
+ cmd += '-vsync 0 '
+ if fast:
+ cmd += f'-i "{input_filename}" '
+ cmd += '-f rawvideo -pix_fmt rgb24 pipe:'
+ # assert cmd == 'ffmpeg -y -i pipe: -ss 2 -t 4 -filter_complex [0]fps=fps=0.5[s0] -map [s0] -f rawvideo -pix_fmt rgb24 pipe:'
+ ffmpeg_out = execute_cmd(cmd)
+ video = np.frombuffer(ffmpeg_out, np.uint8)
+ video = video.reshape([-1, height, width, 3])
+ return video # hxwxc format
+
+
+
+
+def arr2video(arr, filename, fps):
+ imageio.mimsave(filename, arr, format=pathlib.Path(filename).suffix, fps=fps)
+
+
+def pil2image(pil, filename):
+ pil.save(filename)
+
+
+def arr2image(arr, filename):
+ pil = arr2pil(arr)
+ pil2image(pil, filename)
+
+
+def arr2gridimage(arr, filename, nrow=4):
+ if arr.ndim != 4:
+ raise ValueError("arr must has ndim of 4")
+ torchvision.utils.save_image([transforms.ToTensor()(frame) for frame in arr], filename, nrow=nrow)
+
+
+def image2pil(filename):
+ return Image.open(filename)
+
+
+def image2arr(filename):
+ pil = image2pil(filename)
+ return pil2arr(pil)
+
+
+# 格式转换
+def pil2arr(pil):
+ if isinstance(pil, list):
+ arr = np.array(
+ [np.array(e.convert('RGB').getdata(), dtype=np.uint8).reshape(e.size[1], e.size[0], 3) for e in pil])
+ else:
+ arr = np.array(pil)
+ return arr
+
+
+def arr2pil(arr):
+ if arr.ndim == 3:
+ return Image.fromarray(arr.astype('uint8'), 'RGB')
+ elif arr.ndim == 4:
+ return [Image.fromarray(e.astype('uint8'), 'RGB') for e in list(arr)]
+ else:
+ raise ValueError('arr must has ndim of 3 or 4, but got %s' % arr.ndim)
+
+
+def arr2tensor(arr):
+ if arr.ndim == 3:
+ return transforms.ToTensor()(arr)
+ elif arr.ndim == 4:
+ return [transforms.ToTensor()(frame) for frame in arr]
+ else:
+ raise ValueError('arr must has ndim of 3 or 4, but got %s' % arr.ndim)
+
+
+'''
+=====================================================================================================================
+ Jupyter Notebooks
+=====================================================================================================================
+'''
+
+
+def notebook_show(*images):
+ from IPython.display import Image
+ from IPython.display import display
+ display(*[Image(e) for e in images])
+
+
+if __name__ == '__main__':
+ function = getattr(sys.modules[__name__], sys.argv[1])
+ function(*sys.argv[2:])
\ No newline at end of file
diff --git a/One-to-All-Animation/benchmark/DisCo/utils/wutils_ldm.py b/One-to-All-Animation/benchmark/DisCo/utils/wutils_ldm.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e5e9f662240155c49c6cb62e2d422cc3027e4df
--- /dev/null
+++ b/One-to-All-Animation/benchmark/DisCo/utils/wutils_ldm.py
@@ -0,0 +1,1192 @@
+# -*- coding:utf-8 -*-
+import os
+import sys
+import shutil
+import subprocess
+import logging
+import colorlog
+import argparse
+import copy
+import pathlib
+import shlex
+import deepdish
+from tqdm import tqdm
+import time
+import platform
+import pickle
+import yaml
+import glob
+import random
+import msgpack
+import importlib
+import traceback
+from PIL import Image
+import functools
+from functools import partial
+import urllib.request
+from warnings import simplefilter
+from datetime import timedelta
+from timeit import default_timer
+from configobj import ConfigObj
+import requests
+import psutil
+import hashlib
+import imageio
+import math
+import h5py
+import csv
+import collections
+import json
+import json_lines
+import numpy as np
+import pandas as pd
+import torch
+import torch.nn as nn
+from torch.optim import Adam
+import torch.nn.functional as F
+from torch.utils.data import DataLoader
+from torch.utils.data import DataLoader, Dataset
+from einops import rearrange, repeat
+import torch.distributed as dist
+from torchvision import datasets, transforms, utils
+from torch import autocast
+
+# Disable transformers outputs weights.
+logging.getLogger().setLevel(logging.WARNING)
+simplefilter(action='ignore', category=FutureWarning)
+
+def ldm_tensor2img_wt(input):
+ assert len(input.shape) == 3
+ return Image.fromarray(input.mul(255).add_(0.5).clamp_(0.5, 255).permute(1,2,0).to("cpu", torch.uint8).numpy())
+
+def ldm_tensor2img(input, preprocess=False):
+ if preprocess:
+ input = (input / 2 + 0.5).clamp(0, 1)
+ assert len(input.shape) == 3
+ image = input.cpu().permute(1, 2, 0).float().numpy()
+ image = (image * 255).round().astype("uint8")
+ if image.shape[-1] == 1:
+ # special case for grayscale (single channel) images
+ pil_images = Image.fromarray(image.squeeze(), mode="L")
+ else:
+ pil_images = Image.fromarray(image)
+
+ return pil_images
+
+
+def get_logger(filename=None):
+ """
+ examples:
+ logger = get_logger('try_logging.txt')
+
+ logger.debug("Do something.")
+ logger.info("Start print log.")
+ logger.warning("Something maybe fail.")
+ try:
+ raise ValueError()
+ except ValueError:
+ logger.error("Error", exc_info=True)
+
+ tips:
+ DO NOT logger.inf(some big tensors since color may not helpful.)
+ """
+ logger = logging.getLogger('utils')
+ level = logging.DEBUG
+ logger.setLevel(level=level)
+ # Use propagate to avoid multiple loggings.
+ logger.propagate = False
+ # Remove %(levelname)s since we have colorlog to represent levelname.
+ format_str = '[%(asctime)s <%(filename)s:%(lineno)d> %(funcName)s] %(message)s'
+
+ streamHandler = logging.StreamHandler()
+ streamHandler.setLevel(level)
+ coloredFormatter = colorlog.ColoredFormatter(
+ '%(log_color)s' + format_str,
+ datefmt='%Y-%m-%d %H:%M:%S',
+ reset=True,
+ log_colors={
+ 'DEBUG': 'cyan',
+ # 'INFO': 'white',
+ 'WARNING': 'yellow',
+ 'ERROR': 'red',
+ 'CRITICAL': 'reg,bg_white',
+ }
+ )
+
+ streamHandler.setFormatter(coloredFormatter)
+ logger.addHandler(streamHandler)
+
+ if filename:
+ fileHandler = logging.FileHandler(filename)
+ fileHandler.setLevel(level)
+ formatter = logging.Formatter(format_str)
+ fileHandler.setFormatter(formatter)
+ logger.addHandler(fileHandler)
+
+ # Fix multiple logging for torch.distributed
+ try:
+ class UniqueLogger:
+ def __init__(self, logger):
+ self.logger = logger
+ self.local_rank = torch.distributed.get_rank()
+
+ def info(self, msg, *args, **kwargs):
+ if self.local_rank == 0:
+ return self.logger.info(msg, *args, **kwargs)
+
+ def warning(self, msg, *args, **kwargs):
+ if self.local_rank == 0:
+ return self.logger.warning(msg, *args, **kwargs)
+
+ logger = UniqueLogger(logger)
+ # AssertionError for gpu with no distributed
+ # AttributeError for no gpu.
+ except Exception:
+ pass
+ return logger
+
+
+logger = get_logger()
+logger.info(": Deep Learning Utils @ Chenfei Wu")
+
+
+def path_join(path, *paths):
+ output = os.path.join(path, *paths).replace('\\', '/')
+ return output
+
+
+class Timer:
+ def __init__(self):
+ '''
+ t = Timer()
+ time.sleep(1)
+ print(t.elapse())
+ '''
+ self.start = default_timer()
+
+ def elapse(self, readable=False):
+ seconds = default_timer() - self.start
+ if readable:
+ seconds = str(timedelta(seconds=seconds))
+ return seconds
+
+
+def timing(f):
+ def wrap(*args):
+ time1 = time.time()
+ ret = f(*args)
+ time2 = time.time()
+ logger.info('%s function took %0.3f ms' % (f.__name__, (time2 - time1) * 1000.0))
+ return ret
+
+ return wrap
+
+
+def identity(x):
+ return x
+
+
+def groupby(l, key=lambda x: x):
+ d = collections.defaultdict(list)
+ for item in l:
+ d[key(item)].append(item)
+ return dict(d.items())
+
+
+def list_filenames(dirname, filter_fn=None, sort_fn=None, printable=True):
+ dirname = os.path.abspath(dirname)
+ filenames = os.listdir(dirname)
+ filenames = [os.path.join(dirname, filename) for filename in filenames]
+ if filter_fn:
+ tmp = len(filenames)
+ if printable:
+ logger.info('Start filtering files in %s by %s.' % (dirname, filter_fn))
+ filenames = [e for e in filenames if filter_fn(e)]
+ if printable: logger.info(
+ 'Detected %s files/dirs in %s, filtering to %s files.' % (tmp, dirname, len(filenames)))
+ else:
+ if printable: logger.info('Detected %s files/dirs in %s, No filtering.' % (len(filenames), dirname))
+ if sort_fn:
+ filenames = sorted(filenames, key=sort_fn)
+
+ return filenames
+
+
+def listdict2dict2list(listdict, printable=True):
+ tmp_dict = collections.defaultdict(list)
+ for example_dict in listdict:
+ for k, v in example_dict.items():
+ tmp_dict[k].append(v)
+ if printable: logger.info('%s' % tmp_dict.keys())
+ return dict(tmp_dict)
+
+
+def split_filename(filename):
+ absname = os.path.abspath(filename)
+ dirname, basename = os.path.split(absname)
+ split_tmp = basename.rsplit('.', maxsplit=1)
+ if len(split_tmp) == 2:
+ rootname, extname = split_tmp
+ elif len(split_tmp) == 1:
+ rootname = split_tmp[0]
+ extname = None
+ else:
+ raise ValueError("programming error!")
+ return dirname, rootname, extname
+
+def get_suffix(file_path):
+ try:
+ return os.path.splitext(file_path)[-1]
+ except:
+ raise ValueError(f"file_path:{file_path} error!")
+
+def data2file(data, filename, type=None, override=False, printable=False, **kwargs):
+ dirname, rootname, extname = split_filename(filename)
+ print_did_not_save_flag = True
+ if type:
+ extname = type
+ if not os.path.exists(dirname):
+ os.makedirs(dirname, exist_ok=True)
+
+ if not os.path.exists(filename) or override:
+ if extname == 'pkl':
+ with open(filename, 'wb') as f:
+ pickle.dump(data, f)
+ elif extname == 'msg':
+ with open(filename, 'wb') as f:
+ msgpack.dump(data, f)
+ elif extname == 'h5':
+ if kwargs is None:
+ params = {}
+ split_num = kwargs.get('split_num')
+
+ if split_num:
+ if not isinstance(data, list):
+ raise ValueError(
+ '[error] utils.data2file: data must have type of list when use split_num, but got %s' % (
+ type(data)))
+
+ if not split_num <= len(data):
+ raise ValueError(
+ '[error] utils.data2file: split_num(%s) must <= data(%s)' % (len(split_num), len(data)))
+
+ print_save_flag = False
+ print_did_not_save_flag = False
+ pre_define_filenames = ["%s_%d" % (filename, i) for i in range(split_num)]
+ pre_search_filenames = glob.glob("%s*" % filename)
+
+ strict_existed = (set(pre_define_filenames) == set(pre_search_filenames) and len(
+ set([os.path.exists(e) for e in pre_define_filenames])) == 1)
+ common_existed = len(set([os.path.exists(e) for e in pre_search_filenames])) == 1
+
+ def rewrite():
+ logger.info('Spliting data to %s parts before saving...' % split_num)
+ data_splits = np.array_split(data, indices_or_sections=split_num)
+ for i, e in enumerate(data_splits):
+ deepdish.io.save("%s_%d" % (filename, i), list(e))
+ logger.info('Saved data to %s_(0~%d)' % (
+ os.path.abspath(filename), len(data_splits) - 1))
+
+ if strict_existed and not override:
+ logger.info(
+ 'Did not save data to %s_(0~%d) because the files strictly exist and override is False' % (
+ os.path.abspath(filename), len(pre_search_filenames) - 1))
+ elif common_existed:
+ logger.warning('Old wrong files (maybe a differnt split) exist, auto delete them.')
+ for e in pre_search_filenames:
+ os.remove(e)
+ rewrite()
+ else:
+ rewrite()
+ else:
+ deepdish.io.save(filename, data)
+ elif extname == 'hy':
+ # hy support 2 params: key and max_step
+ # if key, then create group using key, else create group using index
+ # if max_step, then the loop may early stopping, used for debug
+ # Remove filename since h5py may corrupt.
+ if override:
+ remove_filename(filename)
+ key_str = kwargs.pop('key_str', None)
+ topk = kwargs.pop('topk', None)
+
+ with h5py.File(filename, 'w') as f:
+ for i, datum in enumerate(tqdm(data)):
+ if key_str:
+ grp = f.create_group(name=datum[key_str])
+ else:
+ grp = f.create_group(name=str(i))
+ for k in datum.keys():
+ grp[k] = datum[k]
+ if topk is not None and i + 1 == topk:
+ break
+ elif extname == 'csv':
+ with open(filename, 'w') as f:
+ writer = csv.writer(f)
+ writer.writerows(data)
+ elif extname == 'json':
+ with open(filename, 'w') as f:
+ json.dump(data, f)
+ elif extname == 'npy':
+ np.save(filename, data)
+ elif extname in ['jpg', 'png', 'jpeg']:
+ utils.save_image(data, filename, **kwargs)
+ elif extname == 'gif':
+ imageio.mimsave(filename, data, format='GIF', duration=kwargs.get('duration'))
+ elif extname == 'pth':
+ torch.save(data, filename)
+ elif extname == 'txt':
+ if kwargs is None:
+ kwargs = {}
+ max_step = kwargs.get('max_step')
+ if max_step is None:
+ max_step = np.Infinity
+
+ with open(filename, 'w', encoding='utf-8') as f:
+ for i, e in enumerate(data):
+ if i < max_step:
+ f.write(str(e) + '\n')
+ else:
+ break
+ else:
+ raise ValueError('type can only support h5, csv, json, sess')
+ if printable: logger.info('Saved data to %s' % os.path.abspath(filename))
+ else:
+ if print_did_not_save_flag: logger.info(
+ 'Did not save data to %s because file exists and override is False' % os.path.abspath(
+ filename))
+
+
+def file2data(filename, type=None, printable=True, **kwargs):
+ dirname, rootname, extname = split_filename(filename)
+ print_load_flag = True
+ if type:
+ extname = type
+ if extname == 'pkl':
+ with open(filename, 'rb') as f:
+ data = pickle.load(f)
+ elif extname == 'msg':
+ with open(filename, 'rb') as f:
+ data = msgpack.load(f, encoding="utf-8")
+ elif extname == 'h5':
+ split_num = kwargs.get('split_num')
+ if split_num:
+ print_load_flag = False
+ if isinstance(split_num, int):
+ filenames = ["%s_%i" % (filename, i) for i in range(split_num)]
+ if split_num != len(glob.glob("%s*" % filename)):
+ logger.warning('Maybe you are giving a wrong split_num(%d) != seached num (%d)' % (
+ split_num, len(glob.glob("%s*" % filename))))
+
+ elif split_num == 'auto':
+ filenames = glob.glob("%s*" % filename)
+ logger.info('Auto located %d splits linked to %s' % (len(filenames), filename))
+ else:
+ raise ValueError("params['split_num'] got unexpected value: %s, which is not supported." % split_num)
+ data = []
+ for e in filenames:
+ data.extend(deepdish.io.load(e))
+ logger.info('Loaded data from %s_(%s)' % (
+ os.path.abspath(filename), ','.join(sorted([e.split('_')[-1] for e in filenames]))))
+ else:
+ data = deepdish.io.load(filename)
+ elif extname == 'csv':
+ data = pd.read_csv(filename)
+ elif extname == 'tsv': # Returns generator since tsv file is large.
+ if not kwargs.get('delimiter'): # Set default delimiter
+ kwargs['delimiter'] = '\t'
+ if not kwargs.get('fieldnames'): # Check field names
+ raise ValueError('You must specify fieldnames when load tsv data.')
+ # Required args.
+ key_str = kwargs.pop('key_str')
+ decode_fn = kwargs.pop('decode_fn')
+ # Optimal args.
+ topk = kwargs.pop('topk', None)
+ redis = kwargs.pop('redis', None)
+ if not redis:
+ data = dict()
+ else:
+ data = redis
+ if not redis or not redis.check():
+ with open(filename) as f:
+ reader = csv.DictReader(f, **kwargs)
+ for i, item in enumerate(tqdm(reader)):
+ if not redis: # if memory way
+ decode_fn(item)
+ data[item[key_str]] = item
+ if topk is not None and i + 1 == topk:
+ break
+ else:
+ logger.warning('check_str %s in redis, skip loading.' % data.check_str)
+ elif extname == 'hy':
+ data = h5py.File(filename, 'r')
+ elif extname in ['npy', 'npz']:
+ try:
+ data = np.load(filename, allow_pickle=True)
+ except UnicodeError:
+ logger.warning('%s is python2 format, auto use latin1 encoding.' % os.path.abspath(filename))
+ data = np.load(filename, encoding='latin1', allow_pickle=True)
+ elif extname == 'json':
+ with open(filename) as f:
+ try:
+ data = json.load(f)
+ except json.decoder.JSONDecodeError as e:
+ raise ValueError('[error] utils.file2data: failed to load json file %s' % filename)
+ elif extname == 'jsonl':
+ with open(filename, 'rb') as f:
+ data = [e for e in json_lines.reader(f)]
+ elif extname == 'ini':
+ data = ConfigObj(filename, encoding='utf-8')
+ elif extname in ['pth', 'ckpt', 'pt']:
+ data = torch.load(filename, map_location=kwargs.get('map_location'))
+ elif extname == 'txt':
+ top = kwargs.get('top', None)
+ with open(filename, encoding='utf-8') as f:
+ if top:
+ data = [f.readline() for _ in range(top)]
+ else:
+ data = [e for e in f.read().split('\n') if e]
+ elif extname == 'yaml':
+ with open(filename, 'r') as f:
+ data = yaml.load(f)
+ else:
+ raise ValueError('type can only support h5, npy, json, txt')
+ if printable:
+ if print_load_flag:
+ logger.info('Loaded data from %s' % os.path.abspath(filename))
+ return data
+
+
+def download_file(fileurl, filedir=None, progress_bar=True, override=False, fast=False, printable=True):
+ if filedir:
+ ensure_dirname(filedir)
+ assert os.path.isdir(filedir)
+ else:
+ filedir = ''
+ filename = os.path.abspath(os.path.join(filedir, fileurl.split('/')[-1]))
+ # print(filename)
+ dirname = os.path.dirname(filename)
+ if not os.path.exists(dirname):
+ os.makedirs(dirname)
+ logger.info("%s not exist, automatic makedir." % dirname)
+ if not os.path.exists(filename) or override:
+ if fast:
+ p = subprocess.Popen('axel -n 10 -o {0} {1}'.format(filename, fileurl), shell=True,
+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
+ for line in iter(p.stdout.readline, ''):
+ if line:
+ logger.info(line.decode('utf-8').replace('\n', ''))
+ else:
+ p.kill()
+ break
+ else:
+ if progress_bar:
+ def my_hook(t):
+ last_b = [0]
+
+ def inner(b=1, bsize=1, tsize=None):
+ if tsize is not None:
+ t.total = tsize
+ t.update((b - last_b[0]) * bsize)
+ last_b[0] = b
+
+ return inner
+
+ with tqdm(unit='B', unit_scale=True, miniters=1,
+ desc=fileurl.split('/')[-1]) as t:
+ urllib.request.urlretrieve(fileurl, filename=filename,
+ reporthook=my_hook(t), data=None)
+ else:
+ urllib.request.urlretrieve(fileurl, filename=filename)
+ if printable: logger.info("%s downloaded sucessfully." % filename)
+ else:
+ if printable: logger.info("%s already existed" % filename)
+ return filename
+
+
+def copy_file(filename, targetname, override=False, printable=True):
+ filename = os.path.abspath(filename)
+ targetname = os.path.abspath(targetname)
+ if not os.path.exists(targetname) or override:
+ shutil.copy2(filename, targetname)
+ if printable:
+ logger.info('Copied %s to %s.' % (filename, targetname))
+ else:
+ if printable:
+ logger.info('Did not copy because %s exists.' % targetname)
+
+
+def videofile2videometa(input_video):
+ out = execute_cmd('ffprobe -i %s -print_format json -show_streams' % input_video)
+ meta = json.loads(out.decode('utf-8'))
+
+ if 'duration' in meta['streams'][0]:
+ duration = float(meta['streams'][0]['duration'])
+ else: # Fix Duration for webm format.
+ duration_str = meta['streams'][0]['tags']['DURATION']
+ h, m, s = duration_str.split(':')
+ duration = float(h) * 3600 + float(m) * 60 + float(s)
+
+ res = {'width': meta['streams'][0]['width'],
+ 'height': meta['streams'][0]['height'],
+ 'duration': duration,
+ 'fps': eval(meta['streams'][0]['r_frame_rate'])}
+ return res
+
+
+def videofile2videoarr(input_file, seek_start=None, seek_duration=None, seek_fps=None):
+ ffprob_out = execute_cmd(f'ffprobe -i {input_file} -print_format json -show_streams')
+ meta = json.loads(ffprob_out.decode('utf-8'))
+ width = meta['streams'][0]['width']
+ height = meta['streams'][0]['height']
+ cmd = f'ffmpeg -y -i {input_file} '
+ if seek_start:
+ cmd += f'-ss {seek_start} '
+ if seek_duration:
+ cmd += f'-t {seek_duration} '
+ if seek_fps:
+ cmd += f'-filter_complex [0]fps=fps={seek_fps}[s0] -map [s0] '
+ cmd += '-f rawvideo -pix_fmt rgb24 pipe:'
+ # assert cmd == 'ffmpeg -y -i pipe: -ss 2 -t 4 -filter_complex [0]fps=fps=0.5[s0] -map [s0] -f rawvideo -pix_fmt rgb24 pipe:'
+ ffmpeg_out = execute_cmd(cmd)
+ video = np.frombuffer(ffmpeg_out, np.uint8)
+ video = video.reshape([-1, height, width, 3])
+ return video
+
+
+def ensure_dirname(dirname, override=False):
+ if os.path.exists(dirname) and override:
+ logger.info('Removing dirname: %s' % os.path.abspath(dirname))
+ try:
+ shutil.rmtree(dirname)
+ except OSError as e:
+ raise ValueError('Failed to delete %s because %s' % (dirname, e))
+
+ if not os.path.exists(dirname):
+ logger.info('Making dirname: %s' % os.path.abspath(dirname))
+ os.makedirs(dirname, exist_ok=True)
+
+
+def ensure_filename(filename, override=False):
+ dirname, rootname, extname = split_filename(filename)
+ ensure_dirname(dirname, override=False)
+ if os.path.exists(filename) and override:
+ os.remove(filename)
+ logger.info('Deleted filename %s' % filename)
+
+
+def remove_filename(filename, printable=False):
+ if os.path.isfile(filename) or os.path.islink(filename):
+ os.remove(filename)
+ if printable:
+ logger.info('Deleted file %s.' % filename)
+ elif os.path.isdir(filename):
+ shutil.rmtree(filename)
+ if printable:
+ logger.info('Deleted dir %s.' % filename)
+ else:
+ raise ValueError("%s is not a file or dir." % filename)
+
+
+def execute(cmd, wait=True, printable=True):
+ if wait:
+ if printable: logger.warning('Executing: '"%s"', waiting...' % cmd)
+ try:
+ output = subprocess.check_output(cmd, shell=True)
+ except subprocess.CalledProcessError as e:
+ logger.warning(e.output)
+ output = None
+ # sys.exit(-1)
+
+ return output
+ else:
+ if platform.system() == 'Windows':
+ black_hole = 'NUL'
+ elif platform.system() == 'Linux':
+ black_hole = '/dev/null'
+ else:
+ raise ValueError('Unsupported system %s' % platform.system())
+ cmd = cmd + ' 1>%s 2>&1' % black_hole
+ if printable: logger.info('Executing: '"%s"', not wait.' % cmd)
+ subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+
+
+def execute_cmd(cmd, input_data=None):
+ process = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ out, err = process.communicate(input=input_data)
+ retcode = process.poll()
+ if retcode:
+ raise ValueError(err.decode('utf-8'))
+ return out
+
+
+def import_filename(filename):
+ spec = importlib.util.spec_from_file_location("mymodule", filename)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ spec.loader.exec_module(module)
+ return module
+
+
+def pname2pid(str_proc_name):
+ map_proc_info = {}
+ for proc in psutil.process_iter():
+ if proc.name() == str_proc_name:
+ map_proc_info[proc.pid] = str_proc_name
+
+ return map_proc_info
+
+
+def get_parameters(net: torch.nn.Module):
+ trainable_params = sum(p.numel() for p in net.parameters() if p.requires_grad)
+ frozen_params = sum(p.numel() for p in net.parameters() if not p.requires_grad)
+ fp32_trainable_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float32 and p.requires_grad)
+ fp16_trainable_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float16 and p.requires_grad)
+ fp32_frozen_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float32 and not p.requires_grad)
+ fp16_frozen_params = sum(p.numel() for p in net.parameters() if p.dtype == torch.float16 and not p.requires_grad)
+ return {'trainable': trainable_params, 'frozen': frozen_params,
+ 'trainable_fp32': fp32_trainable_params,
+ 'trainalbe_fp16': fp16_trainable_params,
+ 'frozen_fp32': fp32_frozen_params, 'frozen_fp16': fp16_frozen_params}
+
+
+def adaptively_load_state_dict(target, state_dict):
+ target_dict = target.state_dict()
+
+ common_dict = {}
+ mismatched_keys, unexpected_keys = [], []
+ for k, v in state_dict.items():
+ if k in target_dict:
+ try:
+ if v.size() != target_dict[k].size():
+ mismatched_keys.append(k)
+ else:
+ common_dict[k] = v
+ except Exception as e:
+ logger.warning(f'load error for {k} {e}')
+ common_dict[k] = v
+ else:
+ unexpected_keys.append(k)
+
+
+ # try:
+ # common_dict = {k: v for k, v in state_dict.items() if k in target_dict and v.size() == target_dict[k].size()}
+ # except Exception as e:
+ # logger.warning('load error %s', e)
+ # common_dict = {k: v for k, v in state_dict.items() if k in target_dict}
+
+ if 'param_groups' in common_dict and common_dict['param_groups'][0]['params'] != \
+ target.state_dict()['param_groups'][0]['params']:
+ logger.warning('Detected mismatch params, auto adapte state_dict to current')
+ common_dict['param_groups'][0]['params'] = target.state_dict()['param_groups'][0]['params']
+ target_dict.update(common_dict)
+ target.load_state_dict(target_dict)
+
+ missing_keys = [k for k in target_dict.keys() if k not in common_dict and k not in mismatched_keys]
+ # unexpected_keys = [k for k in state_dict.keys() if k not in common_dict]
+
+ if len(unexpected_keys) != 0:
+ logger.warning(
+ f"Some weights of state_dict were not used in target: {unexpected_keys}"
+ )
+ if len(mismatched_keys) != 0:
+ logger.warning(
+ f"Mismatched shape of weights loaded from state_dict: {mismatched_keys}"
+ )
+ if len(missing_keys) != 0:
+ logger.warning(
+ f"Some weights of target are missing in state_dict: {missing_keys}"
+ )
+ if len(unexpected_keys) == 0 and len(missing_keys) == 0 and len(mismatched_keys) == 0:
+ logger.warning("Strictly Loaded state_dict.")
+
+
+class Meter(object):
+ def __init__(self):
+ self.val = None
+ self.avg = None
+ self.sum = None
+ self.count = None
+
+ def update(self, val, n=1):
+ if isinstance(val, torch.Tensor):
+ val = val.item()
+ if isinstance(val, (int, float)):
+ self.val = val
+ if self.sum:
+ self.sum += val * n
+ else:
+ self.sum = val * n
+ if self.count:
+ self.count += n
+ else:
+ self.count = n
+ self.avg = self.sum / self.count
+ elif isinstance(val, dict):
+ for k, v in val.items():
+ if isinstance(v, torch.Tensor):
+ val[k] = v.item()
+ # if 'loss_total' in val.keys():
+ # if not math.isnan(val['loss_total']):
+ # # print('it is not nan!!!')
+ if self.val:
+ for k in val.keys():
+ self.val[k] = val[k]
+ else:
+ self.val = val
+ if self.sum:
+ for k in val.keys():
+ if k in self.sum:
+ self.sum[k] = self.sum[k] + val[k] * n
+ else:
+ self.sum[k] = val[k] * n
+ else:
+ self.sum = {k: val[k] * n for k in val.keys()}
+ if self.count:
+ for k in val.keys():
+ if k in self.count:
+ self.count[k] = self.count[k] + n
+ else:
+ self.count[k] = n
+ else:
+ self.count = {k: n for k in val.keys()}
+ self.avg = {k: self.sum[k] / self.count[k] for k in self.count.keys()}
+ else:
+ raise ValueError('Not supported type %s' % type(val))
+
+ def __str__(self):
+ if isinstance(self.avg, dict):
+ return str({k: "%.4f" % v for k, v in self.avg.items()})
+ else:
+ return 'Nan'
+
+
+def set_seed(seed=42):
+ random.seed(seed)
+ os.environ['PYHTONHASHSEED'] = str(seed)
+ np.random.seed(seed)
+ torch.manual_seed(seed)
+ torch.cuda.manual_seed(seed)
+ torch.backends.cudnn.deterministic = True
+
+
+class Trainer:
+ """
+ Trainer
+ """
+
+ def __init__(self, args, model, optimizers=None, scheduler=None, pretrained_model=None, use_amp=True,
+ find_unused_parameters=True):
+ # Basic Params
+ self.args = args
+ self.log_dir = args.log_dir
+ self.model = model
+ self.optimizers = optimizers
+ self.scheduler = scheduler
+ self.pretrained_model = pretrained_model
+ self.use_amp = use_amp
+ self.find_unused_parameters = find_unused_parameters
+ # Load Pretrained Models.
+ if pretrained_model:
+ self.from_pretrained(pretrained_model)
+ # Get Variables from ENV
+ self.rank = int(os.getenv('RANK', '-1'))
+ self.local_rank = int(os.getenv('LOCAL_RANK', '-1'))
+ # Define Running mode.
+ if self.local_rank == -1:
+ self.mode = 'common'
+ self.enable_write_model = True
+ self.enable_collect = True
+ self.enable_write_metric = True
+ else:
+ self.mode = 'dist'
+ self.enable_write_model = (self.rank == 0)
+ self.enable_collect = True
+ self.enable_write_metric = (self.rank == 0)
+
+ if self.enable_write_metric:
+ ensure_dirname(self.log_dir, override=False)
+ self.metric_filename = os.path.join(self.log_dir, 'metric.json')
+ self.last_checkpoint_filename = os.path.join(self.log_dir, 'last.pth')
+ self.best_checkpoint_filename = os.path.join(self.log_dir, 'best.pth')
+ self.each_checkpoint_filename = os.path.join(self.log_dir, 'epoch%s.pth')
+ self.epoch = -1
+
+ # Get device and number of GPUs
+ self.n_gpu = torch.cuda.device_count()
+ if self.n_gpu >= 1:
+ self.device = torch.device("cuda")
+ else:
+ self.device = torch.device("cpu")
+
+ if (self.use_amp or self.args.deepspeed) and self.n_gpu < 1:
+ raise ValueError('AMP/Deepspeed Does not support CPU!')
+ if self.use_amp and self.mode == 'common':
+ logger.warning('In common mode, remember to @autocast before forward function.')
+ if self.use_amp:
+ logger.warning('Attntion!!! you are using amp')
+ if self.args.deepspeed:
+ logger.warning('Attntion!!! you are using deepspeed')
+
+ self.scalar = torch.cuda.amp.GradScaler(enabled=self.use_amp)
+
+ # TODO
+ if hasattr(args, 'iterative_model_class'):
+ self.iterative_model = args.iterative_model_class(args=args)
+ else:
+ self.iterative_model = None
+
+ def reduce_mean(self, tensor):
+ rt = tensor.clone()
+ size = int(os.environ['WORLD_SIZE'])
+ dist.all_reduce(rt, op=dist.ReduceOp.SUM)
+ rt = rt / size
+ return rt
+
+ def wrap_model(self):
+ if hasattr(self.model, 'module'):
+ raise ValueError('You do not need to wrap a models with modules.')
+
+ if self.mode == 'common':
+ logger.info('Wrapped models to common %s.' % self.device)
+
+ self.model.to(self.device)
+ if self.n_gpu > 1:
+ logger.warning('Detected %s gpus, auto using DataParallel.' % self.n_gpu)
+ self.model = torch.nn.DataParallel(self.model)
+ elif self.mode == 'dist':
+ logger.info('Wrapped models to distributed %s.' % self.device)
+
+ self.device = torch.device("cuda", self.local_rank)
+ self.model.to(self.device)
+ self.model = torch.nn.parallel.DistributedDataParallel(
+ self.model, device_ids=[self.local_rank],
+ output_device=self.local_rank,
+ find_unused_parameters=self.find_unused_parameters)
+ else:
+ raise ValueError
+ # wrap_optimizers
+ if self.optimizers:
+ for i in range(len(self.optimizers)):
+ self.optimizers[i].load_state_dict(
+ complex_to_device(self.optimizers[i].state_dict(), device=self.device))
+
+ def check_outputs(self, outputs):
+ error_message = 'Model output must be a dict. The key must be "class_subclass" format.' \
+ ' "class" can only be loss, metric, or logits. "subclass" should be a string.' \
+ ' But got an unexpected key %s'
+ loss_total_list = [e for e in outputs.keys() if e.startswith('loss_total')]
+ if not loss_total_list:
+ raise ValueError('Model output must contain a key startswith "loss_total"!')
+
+ for k, v in outputs.items():
+ split_res = k.split('_')
+ if len(split_res) < 2:
+ raise ValueError(error_message % k)
+ if k.split('_')[0] not in ['loss', 'metric', 'logits']:
+ raise ValueError(error_message % k)
+
+ def train(self, train_loader, eval_loader=None, epochs=5, resume=True, eval_step=10,
+ save_step=None, use_tqdm=None, max_norm=None, gradient_accumulate_steps=1,
+ inner_collect_fn=None, best_metric_fn=lambda x: x['train']['loss_total']):
+ if not save_step:
+ save_step = eval_step
+ best_eval_metric = np.Infinity
+ if resume:
+ if os.path.exists(self.last_checkpoint_filename):
+ self.load_checkpoint(self.last_checkpoint_filename)
+ #self.load_checkpoint('/workspace/f_ndata_tmp/last.pth')
+ else:
+ if self.enable_write_metric:
+ logger.warning('Dangerous! You set resume=False. Auto cleaning all the logs under %s' % self.log_dir)
+ ensure_dirname(self.log_dir, override=True)
+
+ self.wrap_model()
+
+ epoch_iter = range(self.epoch + 1, epochs, 1)
+ if len(epoch_iter):
+ logger.warning('Start train & val phase...')
+ else:
+ logger.warning('Skip train & val phase...')
+ logger.warning(f'Train examples: {len(train_loader.dataset)}, epochs: {epochs}, '
+ f'global_batch_size: {self.args.train_batch_size}, local_batch_size: {train_loader.batch_size}.')
+
+ # Train & Eval phase
+ for epoch in epoch_iter:
+ self.epoch = epoch
+ # Train phase
+ train_meter, train_time = self.train_fn(train_loader,
+ max_norm=max_norm,
+ gradient_accumulate_steps=gradient_accumulate_steps,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Train Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, epochs, train_time, train_meter.avg))
+ if not isinstance(train_meter.avg, dict):
+ raise ValueError(type(train_meter.avg))
+ metric = {'Epoch%s' % (epoch + 1): {'train': {**train_meter.avg, **{'time': train_time}}}}
+
+ if self.enable_write_metric:
+ self.update_metric_file(metric)
+ if (epoch + 1) % save_step == 0:
+ if self.enable_write_model:
+ self.save_checkpoint(self.last_checkpoint_filename)
+ # copy_file(self.last_checkpoint_filename, self.each_checkpoint_filename % str(epoch + 1),
+ # override=True) # TODO sometimes we need to copy file
+
+ if (epoch + 1) % eval_step == 0:
+ if eval_loader:
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn,
+ use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Epoch: %d/%d, Time: %s\n %s' %
+ (self.rank, epoch + 1, epochs, eval_time, eval_meter.avg))
+
+ # Update metric with eval metrics
+ # metric['Epoch%s' % (epoch + 1)].update({'eval': {**eval_meter.avg, **{'time': eval_time}}})
+
+ # Save metric file
+ # if self.enable_write_metric:
+ # self.update_metric_file(metric)
+
+ # If the best models, save another checkpoint.
+ # if best_metric_fn(metric['Epoch%s' % (epoch + 1)]) < best_eval_metric and self.enable_write_model:
+ # best_eval_metric = best_metric_fn(metric['Epoch%s' % (epoch + 1)])
+ # if os.path.exists(self.last_checkpoint_filename):
+ # copy_file(self.last_checkpoint_filename, self.best_checkpoint_filename, override=True)
+ # else:
+ # logger.warning('No checkpoint_file %s' % self.last_checkpoint_filename)
+
+ def eval(self, eval_loader, inner_collect_fn=None, use_tqdm=True):
+ # This function is used to do evaluating after training.
+ if not self.pretrained_model:
+ logger.warning('You should create a new config file and specify pretrained_model in Args when using eval.')
+ # Wrap models before evaluating. This will support ddp evaluating.
+ self.wrap_model()
+ eval_meter, eval_time = self.eval_fn(eval_loader, inner_collect_fn=inner_collect_fn, use_tqdm=use_tqdm)
+ logger.info('[Rank %s] Valid Time: %s\n %s' % (self.rank, eval_time, eval_meter.avg))
+
+ def update_metric_file(self, metric):
+ if os.path.exists(self.metric_filename):
+ r = file2data(self.metric_filename, printable=False)
+ data2file(dict(r, **metric), self.metric_filename, override=True)
+ else:
+ data2file(metric, self.metric_filename)
+
+ def train_fn(self, train_loader, max_norm, gradient_accumulate_steps=1, use_tqdm=True):
+ self.model.train()
+ train_meter = Meter()
+ train_timer = Timer()
+ train_iter = tqdm(train_loader, total=len(train_loader), disable=not use_tqdm)
+ for step, inputs in enumerate(train_iter):
+ # torch.cuda.empty_cache()
+ for optimizer_idx in range(len(self.optimizers)):
+ # if not getattr(self.optimizers[optimizer_idx], 'is_enabled', lambda x: True)(self.epoch):
+ # continue
+ if not getattr(self.optimizers[optimizer_idx], 'is_enabled', lambda x: True)(self.epoch * len(train_loader) + step):
+ continue # adjust to sdm KL-VAE
+ inputs = complex_to_device(inputs, self.device)
+
+ inputs['epoch'] = self.epoch
+ inputs['global_step'] = self.epoch * len(train_loader) + step
+ inputs['optimizer_idx'] = optimizer_idx
+
+ # for outputs in self.models(inputs):
+ # for outputs in self.iterative_model.forward(self.model, inputs) \
+ # if self.iterative_model else [self.model(inputs)]:
+ # self.check_outputs(outputs)
+ # # If we use nn.Parallel, we will get a list of metric or losses from different GPUs, we need to mean them.
+ # if self.mode == 'common' and self.n_gpu > 1:
+ # for k, v in outputs.items():
+ # if k.split('_')[0] in ['metric', 'loss']:
+ # outputs[k] = v.mean()
+ #
+ # if optimizer_idx == 0:
+ # outputs['loss_total'].backward()
+ # else:
+ # outputs['loss_total_%s' % optimizer_idx].backward()
+ #
+ # if (step + 1) % gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ # if max_norm:
+ # nn.utils.clip_grad_norm_(self.model.parameters(), max_norm)
+ # self.optimizers[optimizer_idx].step()
+ # self.optimizers[optimizer_idx].zero_grad()
+ #
+ # metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ # if self.mode != 'common':
+ # for k, v in metric_and_loss.items():
+ # metric_and_loss[k] = self.reduce_mean(v)
+ # train_meter.update(metric_and_loss)
+ if self.use_amp:
+ with autocast(device_type='cuda'):
+ outputs = self.model(inputs)
+
+ self.check_outputs(outputs)
+ # If we use nn.Parallel, we will get a list of metric or losses from different GPUs, we need to mean them.
+ if self.mode == 'common' and self.n_gpu > 1:
+ for k, v in outputs.items():
+ if k.split('_')[0] in ['metric', 'loss']:
+ outputs[k] = v.mean()
+
+ if optimizer_idx == 0:
+ # outputs['loss_total'].backward()
+ self.scalar.scale(outputs['loss_total']).backward()
+ else:
+ # outputs['loss_total_%s' % optimizer_idx].backward()
+ self.scalar.scale(outputs['loss_total_%s' % optimizer_idx]).backward()
+
+ if (step + 1) % gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ if max_norm:
+ nn.utils.clip_grad_norm_(self.model.parameters(), max_norm)
+ # self.optimizers[optimizer_idx].step()
+ self.scalar.step(self.optimizers[optimizer_idx])
+ self.scalar.update()
+ self.optimizers[optimizer_idx].zero_grad()
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ if self.mode != 'common':
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ if self.scheduler:
+ self.scheduler.step()
+ else:
+ outputs = self.model(inputs)
+ self.check_outputs(outputs)
+ # If we use nn.Parallel, we will get a list of metric or losses from different GPUs, we need to mean them.
+ if self.mode == 'common' and self.n_gpu > 1:
+ for k, v in outputs.items():
+ if k.split('_')[0] in ['metric', 'loss']:
+ outputs[k] = v.mean()
+
+ if optimizer_idx == 0:
+ outputs['loss_total'].backward()
+ else:
+ outputs['loss_total_%s' % optimizer_idx].backward()
+
+ if (step + 1) % gradient_accumulate_steps == 0 and outputs.get('logits_last', True):
+ if max_norm:
+ nn.utils.clip_grad_norm_(self.model.parameters(), max_norm)
+ self.optimizers[optimizer_idx].step()
+ self.optimizers[optimizer_idx].zero_grad()
+
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ if self.mode != 'common':
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ train_meter.update(metric_and_loss)
+
+ if self.scheduler:
+ self.scheduler.step()
+
+ if (inputs['global_step'] + 1) % (int(getattr(self.args, 'save_setp', 8000)) + 1) == 0:
+ if self.enable_write_model:
+ self.save_checkpoint(os.path.join(self.log_dir, str(inputs['global_step']) + '.pth'))
+ train_iter.set_description("Metering:" + str(train_meter))
+ train_time = train_timer.elapse(True)
+ return train_meter, train_time
+
+ def eval_fn(self, eval_loader, inner_collect_fn=None, use_tqdm=True):
+ # TODO Note that eval_fn supports ddp. So we do not need to unwrap things here.
+ model_to_eval = self.model
+ model_to_eval.eval()
+ eval_meter = Meter()
+ eval_timer = Timer()
+ with torch.no_grad():
+ eval_loader = tqdm(eval_loader, total=len(eval_loader)) if use_tqdm else eval_loader
+ for inputs in eval_loader:
+ inputs = complex_to_device(inputs, self.device)
+ outputs = model_to_eval(inputs)
+ if self.mode == 'common' and self.n_gpu > 1:
+ for k, v in outputs.items():
+ if k.split('_')[0] in ['metric', 'loss']:
+ outputs[k] = v.mean()
+ metric_and_loss = {k: v for k, v in outputs.items() if k.split('_')[0] in ['metric', 'loss']}
+ if self.mode != 'common':
+ for k, v in metric_and_loss.items():
+ metric_and_loss[k] = self.reduce_mean(v)
+ eval_meter.update(metric_and_loss)
+
+ if inner_collect_fn and self.enable_collect:
+ inner_collect_fn(self.args, inputs, outputs, self.log_dir, self.epoch, self.args.eval_save_filename)
+
+ eval_time = eval_timer.elapse(True)
+ return eval_meter, eval_time
+
+ def load_checkpoint(self, checkpoint_filename):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load checkpoint into wrapped models, ensure self.models is CPU.")
+ checkpoint = file2data(checkpoint_filename, map_location='cpu')
+ adaptively_load_state_dict(self.model, checkpoint['models'])
+ if self.optimizers:
+ if len(self.optimizers) > 1:
+ for i, optimizer in enumerate(self.optimizers):
+ adaptively_load_state_dict(self.optimizers[i], checkpoint['optimizer'][i])
+
+ elif len(self.optimizers) == 1:
+ adaptively_load_state_dict(self.optimizers[0], checkpoint['optimizer'])
+
+ else:
+ raise ValueError
+ if self.scheduler:
+ adaptively_load_state_dict(self.scheduler, checkpoint['scheduler'])
+
+ self.epoch = checkpoint['epoch'] - 1
+
+ # IMPORTANT! The models will be wrapped automatically.
+ logger.warning('Loaded checkpoint %s of epoch %s' % (checkpoint_filename, checkpoint['epoch']))
+
+ def save_checkpoint(self, checkpoint_filename):
+ model_to_save = self.model.module if hasattr(self.model, 'module') else self.model
+ if len(self.optimizers) > 1:
+ optimizer_to_save = [optimizer.state_dict() for optimizer in self.optimizers]
+ elif len(self.optimizers) == 1:
+ optimizer_to_save = self.optimizers[0].state_dict()
+ else:
+ raise ValueError
+ checkpoint = {
+ 'models': model_to_save.state_dict(),
+ 'optimizer': optimizer_to_save,
+ 'epoch': self.epoch + 1,
+ }
+ if self.scheduler:
+ checkpoint['scheduler'] = self.scheduler.state_dict()
+ data2file(checkpoint, checkpoint_filename, override=True)
+ logger.warning('Saved epoch %s to %s.' % (checkpoint['epoch'], checkpoint_filename))
+
+ def from_pretrained(self, pretrained_model):
+ if hasattr(self.model, "module"):
+ raise ValueError("Please do not load pretrained models into wrapped models, ensure self.models is CPU.")
+ if isinstance(pretrained_model, str):
+ logger.warning('Loading Pretrained Model Path: %s...' % pretrained_model)
+ pretrained_dict = file2data(pretrained_model, map_location='cpu')
+ if 'models' in pretrained_dict:
+ pretrained_dict = pretrained_dict['models']
+ else:
+ logger.warning('Loading Given Pretrained Dict...')
+ pretrained_dict = pretrained_model
+ adaptively_load_state_dict(self.model, pretrained_dict)
+
+
+def dl2ld(dl):
+ return [dict(zip(dl, e)) for e in zip(*dl.values())]
+
+
+def ld2dl(ld):
+ return {k: [dic[k] for dic in ld] for k in ld[0]}
+
+
+def complex_to_device(complex, device, non_blocking=False):
+ # added by Linjie
+ if complex is None:
+ return complex
+ if isinstance(complex, torch.Tensor):
+ return complex.to(device, non_blocking=non_blocking)
+ elif isinstance(complex, dict):
+ return {k: complex_to_device(v, device, non_blocking=non_blocking) for k, v in complex.items()}
+ elif isinstance(complex, list) or isinstance(complex, tuple):
+ return [complex_to_device(e, device, non_blocking=non_blocking) for e in complex]
+ elif isinstance(complex, str) or isinstance(complex, bytes) or \
+ isinstance(complex, int) or isinstance(complex, float):
+ return complex
+ else:
+ raise ValueError('Unsupported complex', complex)
diff --git a/One-to-All-Animation/benchmark/download_benchmark.py b/One-to-All-Animation/benchmark/download_benchmark.py
new file mode 100644
index 0000000000000000000000000000000000000000..31dc2f4fd855a6724cb7846e48ac2303324c4b91
--- /dev/null
+++ b/One-to-All-Animation/benchmark/download_benchmark.py
@@ -0,0 +1,55 @@
+import os
+import zipfile
+from pathlib import Path
+
+# Set HuggingFace mirror
+os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
+
+from huggingface_hub import snapshot_download
+
+print("Using HF Mirror: https://hf-mirror.com")
+print("="*50)
+
+def extract_zip(zip_path, extract_to="."):
+ """Extract zip file and remove it after extraction"""
+ print(f"\n📦 Extracting {zip_path}...")
+ try:
+ with zipfile.ZipFile(zip_path, 'r') as zip_ref:
+ zip_ref.extractall(extract_to)
+ print(f"✓ Extracted to {extract_to}")
+
+ # Remove zip file after extraction
+ # os.remove(zip_path)
+ # print(f"✓ Removed {zip_path}")
+ except Exception as e:
+ print(f"❌ Error extracting {zip_path}: {e}")
+
+# Download datasets
+datasets = [
+ "tiktok_test_set.zip",
+ "cartoon_test_set.zip"
+]
+
+for dataset in datasets:
+ print(f"\n{'='*50}")
+ print(f"📥 Downloading {dataset}...")
+ print(f"{'='*50}")
+
+ snapshot_download(
+ repo_id="MochunniaN1/One-to-All-sub",
+ local_dir=".",
+ allow_patterns=dataset,
+ local_dir_use_symlinks=False,
+ repo_type="dataset",
+ resume_download=True,
+ )
+
+ zip_path = Path(dataset)
+ if zip_path.exists():
+ extract_zip(zip_path)
+ else:
+ print(f"⚠️ {dataset} not found, skipping extraction")
+
+print("\n" + "="*50)
+print("✓ All datasets downloaded and extracted!")
+print("="*50)
diff --git a/One-to-All-Animation/benchmark/prepare_eval_frames_cartoon.py b/One-to-All-Animation/benchmark/prepare_eval_frames_cartoon.py
new file mode 100644
index 0000000000000000000000000000000000000000..07874d7047191f35018e4d7914f8be635e3ef890
--- /dev/null
+++ b/One-to-All-Animation/benchmark/prepare_eval_frames_cartoon.py
@@ -0,0 +1,98 @@
+import os
+import cv2
+import torch
+import shutil
+import numpy as np
+from PIL import Image
+from concurrent.futures import ThreadPoolExecutor
+from tqdm import tqdm
+import glob
+
+device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
+base_temp_dir = "./temp_eval_cartoon_frames"
+
+gt_base_dir = "./cartoon_test_set"
+
+model_paths = {
+ "14b": "../output_benchmark/cartoon/One-to-All-14b/2025-11-27_cartoon_ref_2.5_pose_1.5",
+ # "1.3b": "xxx"
+}
+
+def read_video_frames(video_path):
+ if not os.path.exists(video_path):
+ return []
+ cap = cv2.VideoCapture(video_path)
+ frames = []
+ while True:
+ ret, frame = cap.read()
+ if not ret:
+ break
+ frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
+ frames.append(Image.fromarray(frame_rgb))
+ cap.release()
+ return frames
+
+def read_model_frames(model_name, video_id):
+ matches = glob.glob(os.path.join(model_paths[model_name], f"{video_id}*"))
+ matches = [m for m in matches if os.path.isdir(m)]
+ if not matches:
+ raise ValueError(f"⚠ 没找到前缀 {video_id} 对应的目录")
+ else:
+ folder = matches[0]
+ print(f"✅ 匹配到目录: {folder}")
+
+ if not os.path.exists(folder):
+ return []
+ files = sorted(os.listdir(folder))
+ return [Image.open(os.path.join(folder, f)).convert('RGB') for f in files]
+
+video_ids = [f.replace(".mp4", "") for f in os.listdir(gt_base_dir) if f.endswith(".mp4")]
+
+for model_name in model_paths.keys():
+ print(f"\n=== 处理模型: {model_name} ===")
+
+ for vid_id in video_ids:
+ gt_video_path = os.path.join(gt_base_dir, f"{vid_id}.mp4")
+
+ if not os.path.exists(gt_video_path):
+ print(f"[{model_name}][{vid_id}] 缺少GT视频,跳过")
+ continue
+
+ gt_frames = read_video_frames(gt_video_path)
+
+ pred_frames = read_model_frames(model_name, vid_id)
+
+ if len(gt_frames) == 0 or len(pred_frames) == 0:
+ print(f"[{model_name}][{vid_id}] 缺少帧数据,跳过")
+ continue
+
+ min_len = min(len(gt_frames), len(pred_frames))
+ gt_frames = gt_frames[:min_len]
+ pred_frames = pred_frames[:min_len]
+ size = gt_frames[0].size
+
+ temp_pred_video_dir = os.path.join(base_temp_dir, model_name, "pred", vid_id)
+ temp_gt_video_dir = os.path.join(base_temp_dir, model_name, "gt", vid_id)
+ shutil.rmtree(temp_pred_video_dir, ignore_errors=True)
+ shutil.rmtree(temp_gt_video_dir, ignore_errors=True)
+ os.makedirs(temp_pred_video_dir, exist_ok=True)
+ os.makedirs(temp_gt_video_dir, exist_ok=True)
+
+ def save_frame(i, pred_frame, gt_frame):
+ try:
+ pred_resized = pred_frame.resize(size, Image.BICUBIC)
+ gt_resized = gt_frame.resize(size, Image.BICUBIC)
+ pred_resized.save(os.path.join(temp_pred_video_dir, f"{i:04d}.png"))
+ gt_resized.save(os.path.join(temp_gt_video_dir, f"{i:04d}.png"))
+ except Exception as e:
+ print(f"[{model_name}][{vid_id}] 保存第 {i} 帧失败: {e}")
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ list(tqdm(
+ executor.map(lambda idx: save_frame(idx, pred_frames[idx], gt_frames[idx]),
+ range(min_len)),
+ total=min_len,
+ desc=f"[{model_name}][{vid_id}] 保存中"
+ ))
+
+ print(f"[{model_name}] 处理完成 ✅")
diff --git a/One-to-All-Animation/benchmark/prepare_eval_frames_tiktok.py b/One-to-All-Animation/benchmark/prepare_eval_frames_tiktok.py
new file mode 100644
index 0000000000000000000000000000000000000000..989e59fe4e524b9d2bb977b67940786bbd932fba
--- /dev/null
+++ b/One-to-All-Animation/benchmark/prepare_eval_frames_tiktok.py
@@ -0,0 +1,83 @@
+import os
+import cv2
+import torch
+import shutil
+import numpy as np
+from PIL import Image
+from concurrent.futures import ThreadPoolExecutor
+from tqdm import tqdm
+import glob
+
+device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
+base_temp_dir = "./temp_eval_tiktok_frames"
+
+# GT
+gt_base_dir = "./tiktok_test_set"
+
+# model output
+model_paths = {
+ "14b": "../output_benchmark/tiktok/One-to-All-14b/2025-11-27",
+ # "1.3b": "xxx"
+}
+
+def read_model_frames(model_name, video_id):
+ matches = glob.glob(os.path.join(model_paths[model_name], f"{video_id}*"))
+ matches = [m for m in matches if os.path.isdir(m)]
+ if not matches:
+ raise ValueError(f"⚠ 没找到前缀 {video_id} 对应的目录")
+ else:
+ folder = matches[0]
+ print(f"✅ 匹配到目录: {folder}")
+ if not os.path.exists(folder):
+ return []
+ files = sorted(os.listdir(folder))
+ return [Image.open(os.path.join(folder, f)).convert('RGB') for f in files]
+
+video_ids = [f"{i:03d}" for i in range(10)]
+
+for model_name in model_paths.keys():
+ print(f"\n=== 处理模型: {model_name} ===")
+
+ for vid_id in video_ids:
+ gt_video_path = os.path.join(gt_base_dir, f"{vid_id}")
+ if not os.path.exists(gt_video_path):
+ print(f"[{model_name}][{vid_id}] 缺少GT视频目录,跳过")
+ continue
+
+ files = sorted(os.listdir(gt_video_path))
+ gt_frames = [Image.open(os.path.join(gt_video_path, f)).convert('RGB') for f in files]
+
+ pred_frames = read_model_frames(model_name, vid_id)
+
+ if len(gt_frames) == 0 or len(pred_frames) == 0:
+ print(f"[{model_name}][{vid_id}] 缺少帧数据,跳过")
+ continue
+
+ # 保持两边帧数一致
+ min_len = min(len(gt_frames), len(pred_frames))
+ gt_frames = gt_frames[:min_len]
+ pred_frames = pred_frames[:min_len]
+ size = gt_frames[0].size
+
+ temp_pred_video_dir = os.path.join(base_temp_dir, model_name, "pred", vid_id)
+ temp_gt_video_dir = os.path.join(base_temp_dir, model_name, "gt", vid_id)
+ shutil.rmtree(temp_pred_video_dir, ignore_errors=True)
+ shutil.rmtree(temp_gt_video_dir, ignore_errors=True)
+ os.makedirs(temp_pred_video_dir, exist_ok=True)
+ os.makedirs(temp_gt_video_dir, exist_ok=True)
+
+ def save_frame(i, pred_frame, gt_frame):
+ pred_resized = pred_frame.resize(size, Image.BICUBIC)
+ gt_resized = gt_frame.resize(size, Image.BICUBIC)
+ pred_resized.save(os.path.join(temp_pred_video_dir, f"{i:04d}.png"))
+ gt_resized.save(os.path.join(temp_gt_video_dir, f"{i:04d}.png"))
+
+ with ThreadPoolExecutor(max_workers=8) as executor:
+ list(tqdm(
+ executor.map(lambda idx: save_frame(idx, pred_frames[idx], gt_frames[idx]),
+ range(min_len)),
+ total=min_len,
+ desc=f"[{model_name}][{vid_id}] 保存中"
+ ))
+
+ print(f"[{model_name}] 处理完成 ✅")
\ No newline at end of file
diff --git a/One-to-All-Animation/datasets/download_datasets.py b/One-to-All-Animation/datasets/download_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee3c2d15a8d7f5d1f6642f8ff0c796ddb85c6db0
--- /dev/null
+++ b/One-to-All-Animation/datasets/download_datasets.py
@@ -0,0 +1,42 @@
+import os
+# Set HuggingFace mirror
+os.environ['HF_ENDPOINT'] = 'https://hf-mirror.com'
+
+from huggingface_hub import snapshot_download
+
+os.makedirs("opensource_dataset", exist_ok=True)
+os.makedirs("opensource_pose_pool", exist_ok=True)
+
+print("Using HF Mirror: https://hf-mirror.com")
+print("="*50)
+
+try:
+ # 1. Download training datasets
+ print("\n[1/2] Downloading training datasets...")
+ snapshot_download(
+ repo_id="MochunniaN1/One-to-All-sub",
+ allow_patterns="opensource_dataset/*",
+ local_dir="./",
+ local_dir_use_symlinks=False,
+ repo_type="dataset"
+ )
+ print("✓ Training datasets downloaded successfully!")
+
+ # 2. Download pose pool
+ print("\n[2/2] Downloading pose pool...")
+ snapshot_download(
+ repo_id="MochunniaN1/One-to-All-sub",
+ allow_patterns="opensource_pose_pool/*",
+ local_dir="./",
+ local_dir_use_symlinks=False,
+ repo_type="dataset"
+ )
+ print("✓ Pose pool downloaded successfully!")
+
+ print("\n" + "="*50)
+ print("All downloads completed successfully!")
+ print("="*50)
+
+except Exception as e:
+ print(f"\n❌ Error occurred: {str(e)}")
+ print("Please check your internet connection.")
diff --git a/One-to-All-Animation/datasets/prepare_pose_pool.py b/One-to-All-Animation/datasets/prepare_pose_pool.py
new file mode 100644
index 0000000000000000000000000000000000000000..efc2a59bc967f51b7ba055be684fe25cbb259ca6
--- /dev/null
+++ b/One-to-All-Animation/datasets/prepare_pose_pool.py
@@ -0,0 +1,41 @@
+import pandas as pd
+import os
+
+WORK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opensource_pose_pool')
+os.makedirs(WORK_DIR, exist_ok=True)
+os.chdir(WORK_DIR)
+print(f"📂 工作目录: {os.getcwd()}")
+
+CSV_A = 'images_pose_pool_18_16pt.csv'
+CSV_B = 'images_pose_pool_24_18pt.csv'
+
+
+print(f"\n📊 读取 CSV 文件...")
+df_a = pd.read_csv(CSV_A)
+df_b = pd.read_csv(CSV_B)
+
+
+print(f"\n🔄 转换为绝对路径...")
+for col in ['pose_path']:
+ df_a[col] = df_a[col].apply(lambda x: os.path.abspath(x) if isinstance(x, str) else x)
+ df_b[col] = df_b[col].apply(lambda x: os.path.abspath(x) if isinstance(x, str) else x)
+
+
+print(f"\n✅ 检查文件是否存在...")
+for col in ['pose_path']:
+ df_a[col + '_exists'] = df_a[col].apply(lambda x: os.path.exists(x) if isinstance(x, str) else False)
+ print(f" {CSV_A} 存在文件数量: {df_a[col + '_exists'].sum()} / {len(df_a)}")
+ df_b[col + '_exists'] = df_b[col].apply(lambda x: os.path.exists(x) if isinstance(x, str) else False)
+ print(f" {CSV_B} 存在文件数量: {df_b[col + '_exists'].sum()} / {len(df_b)}")
+
+df_a.drop(columns=[c for c in df_a.columns if c.endswith('_exists')], inplace=True)
+df_b.drop(columns=[c for c in df_b.columns if c.endswith('_exists')], inplace=True)
+
+output_a = CSV_A.replace(".csv", "_abs.csv")
+output_b = CSV_B.replace(".csv", "_abs.csv")
+
+df_a.to_csv(output_a, index=False)
+df_b.to_csv(output_b, index=False)
+
+print(f" {os.path.abspath(output_a)}")
+print(f" {os.path.abspath(output_b)}")
diff --git a/One-to-All-Animation/datasets/prepare_training_data.py b/One-to-All-Animation/datasets/prepare_training_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ac07ed4d26cc9392dcab36df4e82ecdd0a0759b3
--- /dev/null
+++ b/One-to-All-Animation/datasets/prepare_training_data.py
@@ -0,0 +1,174 @@
+import pandas as pd
+import os
+from pandarallel import pandarallel
+import zipfile
+from concurrent.futures import ThreadPoolExecutor, as_completed
+
+pandarallel.initialize(progress_bar=True)
+
+WORK_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'opensource_dataset')
+os.makedirs(WORK_DIR, exist_ok=True)
+os.chdir(WORK_DIR)
+print(f"📂 工作目录: {os.getcwd()}")
+
+def unzip_one(zip_path, extract_dir):
+ zip_name = os.path.splitext(os.path.basename(zip_path))[0]
+ with zipfile.ZipFile(zip_path, 'r') as zf:
+ names = zf.namelist()
+ common_prefix = os.path.commonprefix(names).split('/')[0] if names else ''
+ if common_prefix.lower() == zip_name.lower():
+ target_dir = extract_dir
+ else:
+ target_dir = os.path.join(extract_dir, zip_name)
+ os.makedirs(target_dir, exist_ok=True)
+
+ zf.extractall(target_dir)
+ return f"✅ {zip_name}.zip 已解压到 {target_dir}"
+
+def unzip_all(base_dir=".", extract_dir=None, max_workers=8):
+ if extract_dir is None:
+ extract_dir = base_dir
+
+ zip_files = [
+ os.path.join(base_dir, f)
+ for f in os.listdir(base_dir)
+ if f.endswith(".zip")
+ ]
+
+ if not zip_files:
+ print("⚠️ 未找到 zip 文件")
+ return
+
+ print(f"🔍 共发现 {len(zip_files)} 个 zip 文件,开始多线程解压…")
+
+ results = []
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
+ futures = {executor.submit(unzip_one, z, extract_dir): z for z in zip_files}
+ for future in as_completed(futures):
+ try:
+ result = future.result()
+ print(result)
+ results.append(result)
+ except Exception as e:
+ print(f"❌ 解压失败: {futures[future]} - {e}")
+
+ print("🎉 所有文件已解压完成!")
+
+# unzip
+unzip_all(base_dir=".", max_workers=8)
+
+VID_CSV = 'opensource_data_vid.csv'
+IMG_CSV = 'opensource_data_fashion_img.csv'
+OUTPUT_CSV = 'combined_imgvid_dataset.csv'
+
+# vid:img = 6:1
+GROUP_RATIO = 6
+
+# -----------------------------
+# 读取数据
+# -----------------------------
+print(f"\n📊 读取数据...")
+df_vid = pd.read_csv(VID_CSV)
+df_img = pd.read_csv(IMG_CSV)
+
+# -----------------------------
+# 转为绝对路径
+# -----------------------------
+print(f"🔄 转换为绝对路径...")
+for col in ['path', 'pose_path']:
+ df_vid[col] = df_vid[col].apply(lambda x: os.path.abspath(x) if isinstance(x, str) else x)
+
+for col in ['path', 'target_path', 'pose_path']:
+ df_img[col] = df_img[col].apply(lambda x: os.path.abspath(x) if isinstance(x, str) else x)
+
+# 检查文件是否存在
+print(f"\n✅ 检查视频文件是否存在...")
+for col in ['path', 'pose_path']:
+ df_vid[col + '_exists'] = df_vid[col].parallel_apply(lambda x: os.path.exists(x) if isinstance(x, str) else False)
+ print(f" {col} 存在文件数量: {df_vid[col + '_exists'].sum()} / {len(df_vid)}")
+
+print(f"\n✅ 检查图片文件是否存在...")
+for col in ['path', 'target_path', 'pose_path']:
+ df_img[col + '_exists'] = df_img[col].parallel_apply(lambda x: os.path.exists(x) if isinstance(x, str) else False)
+ print(f" {col} 存在文件数量: {df_img[col + '_exists'].sum()} / {len(df_img)}")
+
+df_vid.drop(columns=[c for c in df_vid.columns if c.endswith('_exists')], inplace=True)
+df_img.drop(columns=[c for c in df_img.columns if c.endswith('_exists')], inplace=True)
+
+
+n_vid = len(df_vid)
+n_img = len(df_img)
+
+GROUP_NUMBER = int(n_vid / GROUP_RATIO)
+GROUP_SIZE = max(1, n_img // GROUP_NUMBER)
+
+print(f"\n📈 视频数量: {n_vid}, 图片数量: {n_img}")
+print(f"📈 计算得到 GROUP_SIZE: {GROUP_SIZE}")
+
+# -----------------------------
+# 对 img 数据分组
+# -----------------------------
+print(f"\n🔄 对图片数据进行分组...")
+fields = ['height', 'width', 'aspect_ratio', 'resolution']
+df_img_sorted = df_img.sort_values(fields + ['path']).reset_index(drop=True)
+
+group_rows = []
+bad_rows = []
+group_id_counter = 0
+
+for combo, subdf in df_img_sorted.groupby(fields, sort=False):
+ n = len(subdf)
+ n_groups = n // GROUP_SIZE
+ remainder = n % GROUP_SIZE
+ idxs = subdf.index.to_list()
+
+ for g in range(n_groups):
+ slice_idx = idxs[g*GROUP_SIZE:(g+1)*GROUP_SIZE]
+ group = subdf.loc[slice_idx]
+
+ first = group.iloc[0]
+
+ img_pairs = [
+ {
+ 'src_path' : row['path'],
+ 'tgt_path' : row['target_path'],
+ 'tgt_pose_path': row['pose_path'],
+ 'qwen_caption' : row['qwen_caption'] if 'qwen_caption' in row and pd.notnull(row['qwen_caption']) else "",
+ 'text' : row['text'] if 'text' in row and pd.notnull(row['text']) else ""
+ }
+ for _, row in group.iterrows()
+ ]
+
+ group_rows.append(
+ {
+ 'path' : f'image_{group_id_counter+2800:05d}',
+ 'img_pairs' : img_pairs,
+ 'height' : int(first['height']),
+ 'width' : int(first['width']),
+ 'aspect_ratio' : first['aspect_ratio'],
+ 'resolution' : first['resolution'],
+ 'num_frames' : 1
+ }
+ )
+ group_id_counter += 1
+
+ if remainder:
+ bad_rows.extend(subdf.loc[idxs[-remainder:]].to_dict('records'))
+
+df_groups = pd.DataFrame(group_rows)
+df_bad = pd.DataFrame(bad_rows)
+
+print(f"📊 生成 df_groups: {len(df_groups)} 条, df_bad: {len(df_bad)} 条")
+
+# -----------------------------
+# 合并数据
+# -----------------------------
+df_final = pd.concat([df_groups, df_vid], ignore_index=True, sort=False)
+print(f"📊 最终合并后的数据集: {len(df_final)} 条")
+
+# -----------------------------
+# 保存 CSV
+# -----------------------------
+df_final.to_csv(OUTPUT_CSV, index=False)
+print(f"\n✅ 已保存为 {OUTPUT_CSV}")
+print(f"📂 完整路径: {os.path.abspath(OUTPUT_CSV)}")
\ No newline at end of file
diff --git a/One-to-All-Animation/datasets/setup_datasets.sh b/One-to-All-Animation/datasets/setup_datasets.sh
new file mode 100644
index 0000000000000000000000000000000000000000..3e5f631e2e89d7ddaedc2f201b931626bf12f088
--- /dev/null
+++ b/One-to-All-Animation/datasets/setup_datasets.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+
+set -e
+
+echo "=========================================="
+echo " Setting up One-to-All Training Datasets"
+echo "=========================================="
+
+echo ""
+echo "[Step 1/3] Downloading datasets from HuggingFace..."
+python download_datasets.py
+
+echo ""
+echo "[Step 2/3] Preparing training data (unzip & process)..."
+python prepare_training_data.py
+
+echo ""
+echo "[Step 3/3] Preparing pose pool..."
+python prepare_pose_pool.py
+
+echo ""
+echo "=========================================="
+echo " ✅ Setup completed successfully!"
+echo "=========================================="
+echo "Training data: $(pwd)/opensource_dataset/"
+echo "Pose pool: $(pwd)/opensource_pose_pool/"
diff --git a/One-to-All-Animation/requirements.txt b/One-to-All-Animation/requirements.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ae41974e0a7b6b05399f7eb0daaa5ef4ff5a585f
--- /dev/null
+++ b/One-to-All-Animation/requirements.txt
@@ -0,0 +1,22 @@
+diffusers==0.33.0
+transformers==4.40.1
+deepspeed==0.15.4
+accelerate==0.29.3
+onnxruntime-gpu
+numpy==1.26.4
+opencv-python-headless==4.8.0.74
+imageio==2.37.0
+imageio-ffmpeg==0.6.0
+einops
+ninja
+pandas
+decord
+tensorboard
+pytorch-lightning
+IPython
+timm
+pandarallel
+beautifulsoup4
+ftfy
+matplotlib
+# flash_attn_3 3.0.0b1
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B.json b/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B.json
new file mode 100644
index 0000000000000000000000000000000000000000..4e0cd69461d5b24b4a7e7100eb4d4242be07e095
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.32.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 16,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 48,
+ "num_layers": 42,
+ "out_channels": 16,
+ "patch_bias": false,
+ "patch_size": 2,
+ "patch_size_t": 2,
+ "sample_frames": 81,
+ "sample_height": 96,
+ "sample_width": 170,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_learned_positional_embeddings": false,
+ "use_rotary_positional_embeddings": true
+ }
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B_i2v.json b/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B_i2v.json
new file mode 100644
index 0000000000000000000000000000000000000000..79300ab18dce363e01bd11653483e16791f5f5d1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_1_5_5B_i2v.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.32.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 32,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 48,
+ "num_layers": 42,
+ "ofs_embed_dim": 512,
+ "out_channels": 16,
+ "patch_bias": false,
+ "patch_size": 2,
+ "patch_size_t": 2,
+ "sample_frames": 81,
+ "sample_height": 300,
+ "sample_width": 300,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_learned_positional_embeddings": false,
+ "use_rotary_positional_embeddings": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_2B.json b/One-to-All-Animation/video-generation/configs/cogvideo_2B.json
new file mode 100644
index 0000000000000000000000000000000000000000..4b9685851a877b64575328b511a234f2ce7b96c4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_2B.json
@@ -0,0 +1,29 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.30.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 16,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 30,
+ "num_layers": 30,
+ "out_channels": 16,
+ "patch_size": 2,
+ "sample_frames": 49,
+ "sample_height": 60,
+ "sample_width": 90,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_rotary_positional_embeddings": false
+ }
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_5B.json b/One-to-All-Animation/video-generation/configs/cogvideo_5B.json
new file mode 100644
index 0000000000000000000000000000000000000000..fe2686b9c3cab2c81f0e5629ddbb6376fc5e5014
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_5B.json
@@ -0,0 +1,29 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.31.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 16,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 48,
+ "num_layers": 42,
+ "out_channels": 16,
+ "patch_size": 2,
+ "sample_frames": 49,
+ "sample_height": 60,
+ "sample_width": 90,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_rotary_positional_embeddings": true
+ }
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_controlnet.json b/One-to-All-Animation/video-generation/configs/cogvideo_controlnet.json
new file mode 100644
index 0000000000000000000000000000000000000000..c545b770ff47ef6e381725bf09f66a0e82f2b9d5
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_controlnet.json
@@ -0,0 +1,40 @@
+{
+ "_class_name": "CogVideoXControlnet",
+ "_diffusers_version": "0.32.1",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "block_out_channels": [
+ 16,
+ 32,
+ 32,
+ 64
+ ],
+ "downscale_coef": 8,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 3,
+ "layers_per_block": 3,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "norm_num_groups": 8,
+ "num_attention_heads": 48,
+ "num_layers": 7,
+ "out_proj": true,
+ "pad_mode": "first",
+ "patch_size": 2,
+ "sample_frames": 49,
+ "sample_height": 60,
+ "sample_width": 90,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_learned_positional_embeddings": false,
+ "use_rotary_positional_embeddings": false,
+ "vae_channels": 16
+ }
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_i2v_1_5_5B.json b/One-to-All-Animation/video-generation/configs/cogvideo_i2v_1_5_5B.json
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/configs/cogvideo_i2v_5B.json b/One-to-All-Animation/video-generation/configs/cogvideo_i2v_5B.json
new file mode 100644
index 0000000000000000000000000000000000000000..0703c6900bb90c2cc70abcd41fe7101244af8fdf
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/cogvideo_i2v_5B.json
@@ -0,0 +1,29 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.31.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 32,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 48,
+ "num_layers": 42,
+ "out_channels": 16,
+ "patch_size": 2,
+ "sample_frames": 49,
+ "sample_height": 60,
+ "sample_width": 90,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_learned_positional_embeddings": true,
+ "use_rotary_positional_embeddings": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/config.json b/One-to-All-Animation/video-generation/configs/config.json
new file mode 100644
index 0000000000000000000000000000000000000000..7298d569fb645c249614fa3763c56046e0a34e90
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/config.json
@@ -0,0 +1,28 @@
+{
+ "_class_name": "CogVideoXTransformer3DModel",
+ "_diffusers_version": "0.31.0.dev0",
+ "activation_fn": "gelu-approximate",
+ "attention_bias": true,
+ "attention_head_dim": 64,
+ "dropout": 0.0,
+ "flip_sin_to_cos": true,
+ "freq_shift": 0,
+ "in_channels": 16,
+ "max_text_seq_length": 226,
+ "norm_elementwise_affine": true,
+ "norm_eps": 1e-05,
+ "num_attention_heads": 48,
+ "num_layers": 42,
+ "out_channels": 16,
+ "patch_size": 2,
+ "sample_frames": 49,
+ "sample_height": 60,
+ "sample_width": 90,
+ "spatial_interpolation_scale": 1.875,
+ "temporal_compression_ratio": 4,
+ "temporal_interpolation_scale": 1.0,
+ "text_embed_dim": 4096,
+ "time_embed_dim": 512,
+ "timestep_activation_fn": "silu",
+ "use_rotary_positional_embeddings": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/flux_2B.json b/One-to-All-Animation/video-generation/configs/flux_2B.json
new file mode 100644
index 0000000000000000000000000000000000000000..89e62ce5cee6b3b8512a5571c24c6d503c4a9dbc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/flux_2B.json
@@ -0,0 +1,21 @@
+{
+ "_class_name": "PyramidFluxTransformer",
+ "_diffusers_version": "0.30.3",
+ "attention_head_dim": 64,
+ "axes_dims_rope": [
+ 16,
+ 24,
+ 24
+ ],
+ "in_channels": 64,
+ "interp_condition_pos": true,
+ "joint_attention_dim": 4096,
+ "num_attention_heads": 30,
+ "num_layers": 8,
+ "num_single_layers": 16,
+ "patch_size": 1,
+ "pooled_projection_dim": 768,
+ "use_flash_attn": false,
+ "use_gradient_checkpointing": false,
+ "use_temporal_causal": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_i2v.json b/One-to-All-Animation/video-generation/configs/hunyuan_i2v.json
new file mode 100644
index 0000000000000000000000000000000000000000..d64188ee241ca87ccdfdcd7e1ad6c38692232d68
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_i2v.json
@@ -0,0 +1,31 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 32,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_i2v_controlnet.json b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_controlnet.json
new file mode 100644
index 0000000000000000000000000000000000000000..904823f6f865bce5f903714a3ca5b6154d357104
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_controlnet.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 32,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 5,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "conditioning_embedding_channels": 8
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_i2v_end2end.json b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_end2end.json
new file mode 100644
index 0000000000000000000000000000000000000000..64b595d9930a6c30f8feedac9c6275f96fea209a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_end2end.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 32,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "conditioning_embedding_channels": 8
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_i2v_official.json b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_official.json
new file mode 100644
index 0000000000000000000000000000000000000000..6953f6ea97721e9012cf54d2db4d5d429b3b08af
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_i2v_official.json
@@ -0,0 +1,31 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.2",
+ "guidance_embed": false,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 33,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "i2v_condition_type": "concat"
+ }
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_ipadapter.json b/One-to-All-Animation/video-generation/configs/hunyuan_ipadapter.json
new file mode 100644
index 0000000000000000000000000000000000000000..44acdaf92e9cd761505ae4575e35ef1d30e20f5e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_ipadapter.json
@@ -0,0 +1,21 @@
+{
+ "enable_ipadapter": true,
+ "ipadapter_scale" : 1,
+ "ipadapter_hidden_size": 3072,
+ "ipadapter_cross_attention_dim": 4096,
+ "ipadapter_num_tokens": 4,
+
+ "ipadapter_scale_start": 0.0,
+ "ipadapter_scale_end": 1.0,
+ "ipadapter_total_steps" : 1.0,
+
+ "ipadapter_double_blocks_depth":20,
+ "ipadapter_single_blocks_depth":40,
+
+
+ "mlp_in_dim": 1152,
+ "mlp_out_dim": 4096,
+ "mlp_num_tokens": 4,
+ "mlp_act": "gelu"
+
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v.json
new file mode 100644
index 0000000000000000000000000000000000000000..c9d959f36820573c2e8846019e677f73428364eb
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v.json
@@ -0,0 +1,31 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet.json
new file mode 100644
index 0000000000000000000000000000000000000000..8d1e94aae64d5a25cf15d7ec988f4f79c4b75a0d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 5,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "conditioning_embedding_channels": 4
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet_restore2_exclude.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet_restore2_exclude.json
new file mode 100644
index 0000000000000000000000000000000000000000..c2aa7cb0d7f6eeede799541f78cbc9e7b575b2df
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_controlnet_restore2_exclude.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 10,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "exclude_noise" : true
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor.json
new file mode 100644
index 0000000000000000000000000000000000000000..86e7ea5b24514a7f559c47a3b88198c96068ade3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 4,
+ "mm_single_blocks_depth": 9,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2.json
new file mode 100644
index 0000000000000000000000000000000000000000..623d4cb08c2c3383f6cfa9d25c62ff899b6e3e5d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 5,
+ "mm_single_blocks_depth": 9,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2_2d.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2_2d.json
new file mode 100644
index 0000000000000000000000000000000000000000..66fa475c18ae19da58d5a43b53dce034d70f6ce3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor2_2d.json
@@ -0,0 +1,33 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 5,
+ "mm_single_blocks_depth": 9,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false,
+ "ref_repeat": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor3.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor3.json
new file mode 100644
index 0000000000000000000000000000000000000000..9dcabdd1b8f208650526ceeac6cb2ea678f0586d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor3.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 0,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2.json
new file mode 100644
index 0000000000000000000000000000000000000000..237be83edfce3acc5900c6643ed55aa97322e384
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 9,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2_2d.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2_2d.json
new file mode 100644
index 0000000000000000000000000000000000000000..51b8b72fe49722c250d9c40ec50224769e0dc0be
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_double2_2d.json
@@ -0,0 +1,33 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 9,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false,
+ "ref_repeat": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_small2.json b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_small2.json
new file mode 100644
index 0000000000000000000000000000000000000000..6cef2a77a41fcec174a06e9235ef2fa45d282413
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/hunyuan_t2v_refextractor_small2.json
@@ -0,0 +1,32 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 16,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 4,
+ "mm_single_blocks_depth": 0,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true,
+ "embedded_guidance_scale": 6.0,
+ "controlnet_ref": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/minihunyuan_config.json b/One-to-All-Animation/video-generation/configs/minihunyuan_config.json
new file mode 100644
index 0000000000000000000000000000000000000000..a1509108913011f643d47b1b3014123d4db10ed2
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/minihunyuan_config.json
@@ -0,0 +1,30 @@
+{
+ "_class_name": "HYVideoDiffusionTransformer",
+ "_diffusers_version": "0.32.0.dev0",
+ "guidance_embed": true,
+ "heads_num": 24,
+ "hidden_size": 3072,
+ "in_channels": 32,
+ "mlp_act_type": "gelu_tanh",
+ "mlp_width_ratio": 4,
+ "mm_double_blocks_depth": 1,
+ "mm_single_blocks_depth": 2,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": true,
+ "qk_norm_type": "rms",
+ "qkv_bias": true,
+ "rope_dim_list": [
+ 16,
+ 56,
+ 56
+ ],
+ "text_projection": "single_refiner",
+ "text_states_dim": 4096,
+ "text_states_dim_2": 768,
+ "use_attention_mask": true
+}
diff --git a/One-to-All-Animation/video-generation/configs/mochi_10B.json b/One-to-All-Animation/video-generation/configs/mochi_10B.json
new file mode 100644
index 0000000000000000000000000000000000000000..f962b31481b722c6610a33eb5d9dc45850d761c3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/mochi_10B.json
@@ -0,0 +1,16 @@
+{
+ "_class_name": "MochiTransformer3DModel",
+ "_diffusers_version": "0.32.0.dev0",
+ "activation_fn": "swiglu",
+ "attention_head_dim": 128,
+ "in_channels": 12,
+ "max_sequence_length": 256,
+ "num_attention_heads": 24,
+ "num_layers": 48,
+ "out_channels": null,
+ "patch_size": 2,
+ "pooled_projection_dim": 1536,
+ "qk_norm": "rms_norm",
+ "text_embed_dim": 4096,
+ "time_embed_dim": 256
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/mochi_5B.json b/One-to-All-Animation/video-generation/configs/mochi_5B.json
new file mode 100644
index 0000000000000000000000000000000000000000..dd6b354f9f0e5d687bb3ab0c401e911d042920ba
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/mochi_5B.json
@@ -0,0 +1,16 @@
+{
+ "_class_name": "MochiTransformer3DModel",
+ "_diffusers_version": "0.32.0.dev0",
+ "activation_fn": "swiglu",
+ "attention_head_dim": 96,
+ "in_channels": 16,
+ "max_sequence_length": 256,
+ "num_attention_heads": 24,
+ "num_layers": 42,
+ "out_channels": null,
+ "patch_size": 2,
+ "pooled_projection_dim": 1536,
+ "qk_norm": "rms_norm",
+ "text_embed_dim": 4096,
+ "time_embed_dim": 256
+ }
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b.json b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b.json
new file mode 100644
index 0000000000000000000000000000000000000000..998a7ae19a6151f25b78801bfde3ac1c2372d086
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b.json
@@ -0,0 +1,23 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": 5120,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": 1280,
+ "in_channels": 36,
+ "num_attention_heads": 40,
+ "num_layers": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_controlnet_dropmask.json b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_controlnet_dropmask.json
new file mode 100644
index 0000000000000000000000000000000000000000..67e10b7bf55fed197af34b934762712ab0ec1bab
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_controlnet_dropmask.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": 5120,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": 1280,
+ "in_channels": 32,
+ "num_attention_heads": 40,
+ "num_layers": 4,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "conditioning_embedding_channels": 8
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_dropmask.json b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_dropmask.json
new file mode 100644
index 0000000000000000000000000000000000000000..46db0863b8bd036eb3331b04cd539d60f43b567a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_i2v_14b_dropmask.json
@@ -0,0 +1,23 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": 5120,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": 1280,
+ "in_channels": 32,
+ "num_attention_heads": 40,
+ "num_layers": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b.json
new file mode 100644
index 0000000000000000000000000000000000000000..f17ace25ed5a587503dbd3052741b15ad0e0ff88
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b.json
@@ -0,0 +1,23 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 8960,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 12,
+ "num_layers": 30,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_controlnet_2.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_controlnet_2.json
new file mode 100644
index 0000000000000000000000000000000000000000..5976b3d250949358e77d356362c84150f260463a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_controlnet_2.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 8960,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 12,
+ "num_layers": 2,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "conditioning_embedding_channels": 8
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d.json
new file mode 100644
index 0000000000000000000000000000000000000000..86112d9e2a47e305545e844b7a1d48f9a34e9f3e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 8960,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 12,
+ "num_layers": 14,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "ref_repeat": false
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d_withmask2.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d_withmask2.json
new file mode 100644
index 0000000000000000000000000000000000000000..4d5009661012628ea1ea46e1cd2b56d2c7d50845
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_1.3b_refextractor_2d_withmask2.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 8960,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 32,
+ "num_attention_heads": 12,
+ "num_layers": 14,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "ref_repeat": false
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b.json
new file mode 100644
index 0000000000000000000000000000000000000000..bdc0c80f0e7d4edb240a64f3d4c2e3b054eb0ec3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b.json
@@ -0,0 +1,23 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 40,
+ "num_layers": 40,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_controlnet_1.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_controlnet_1.json
new file mode 100644
index 0000000000000000000000000000000000000000..63111fe16d74e93fce38eecb7cb1325a0d9f7bb0
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_controlnet_1.json
@@ -0,0 +1,25 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 40,
+ "num_layers": 1,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "conditioning_embedding_channels": 8
+
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d.json
new file mode 100644
index 0000000000000000000000000000000000000000..23c11231179af8e767b5be887fc912ae9e262664
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 40,
+ "num_layers": 7,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "ref_repeat": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_small.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_small.json
new file mode 100644
index 0000000000000000000000000000000000000000..b5fbdfd3ed491031eb2bc2899d9e09b976f0c146
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_small.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 16,
+ "num_attention_heads": 40,
+ "num_layers": 4,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "ref_repeat": false
+}
diff --git a/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_withmask2.json b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_withmask2.json
new file mode 100644
index 0000000000000000000000000000000000000000..615345087087d7b8b4c3e9ef6ddc4382957076e3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/configs/wan2.1_t2v_14b_refextractor_2d_withmask2.json
@@ -0,0 +1,24 @@
+{
+ "_class_name": "WanTransformer3DModel",
+ "_diffusers_version": "0.33.0.dev0",
+ "added_kv_proj_dim": null,
+ "attention_head_dim": 128,
+ "cross_attn_norm": true,
+ "eps": 1e-06,
+ "ffn_dim": 13824,
+ "freq_dim": 256,
+ "image_dim": null,
+ "in_channels": 32,
+ "num_attention_heads": 40,
+ "num_layers": 7,
+ "out_channels": 16,
+ "patch_size": [
+ 1,
+ 2,
+ 2
+ ],
+ "qk_norm": "rms_norm_across_heads",
+ "rope_max_seq_len": 1024,
+ "text_dim": 4096,
+ "ref_repeat": false
+}
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/__init__.py b/One-to-All-Animation/video-generation/dwpose_utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..817278425648d3d286feb39b15fc286f57cafc40
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/__init__.py
@@ -0,0 +1,120 @@
+# Openpose
+# Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose
+# 2nd Edited by https://github.com/Hzzone/pytorch-openpose
+# 3rd Edited by ControlNet
+# 4th Edited by ControlNet (added face and correct hands)
+
+import os
+os.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
+
+import torch
+import numpy as np
+from . import util
+from .wholebody import Wholebody
+
+def draw_pose(pose, H, W):
+ bodies = pose['bodies']
+ faces = pose['faces']
+ hands = pose['hands']
+ candidate = bodies['candidate']
+ subset = bodies['subset']
+ canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)
+
+ canvas = util.draw_bodypose(canvas, candidate, subset)
+
+ canvas = util.draw_handpose(canvas, hands)
+
+ if faces is not None:
+ canvas = util.draw_facepose(canvas, faces)
+
+ return canvas
+
+
+class DWposeDetector:
+ def __init__(self):
+
+ self.pose_estimation = Wholebody()
+
+ def __call__(self, oriImg, remain_face=True):
+ oriImg = oriImg.copy()
+ H, W, C = oriImg.shape
+ with torch.no_grad():
+ candidate, subset = self.pose_estimation(oriImg)
+ nums, keys, locs = candidate.shape
+ candidate[..., 0] /= float(W)
+ candidate[..., 1] /= float(H)
+ body = candidate[:,:18].copy()
+ body = body.reshape(nums*18, locs)
+ score = subset[:,:18]
+ for i in range(len(score)):
+ for j in range(len(score[i])):
+ if score[i][j] > 0.3:
+ score[i][j] = int(18*i+j)
+ else:
+ score[i][j] = -1
+
+ un_visible = subset<0.3
+ candidate[un_visible] = -1
+
+ foot = candidate[:,18:24]
+
+ faces = candidate[:,24:92]
+
+ hands = candidate[:,92:113]
+ hands = np.vstack([hands, candidate[:,113:]])
+
+ bodies = dict(candidate=body, subset=score)
+ if remain_face:
+ pose = dict(bodies=bodies, hands=hands, faces=faces)
+ else:
+ pose = dict(bodies=bodies, hands=hands, faces=None)
+
+ return draw_pose(pose, H, W)
+
+
+class DWposeDetectorOnlyOnePerson:
+ def __init__(self):
+
+ self.pose_estimation = Wholebody()
+
+ def __call__(self, oriImg, remain_face=True):
+ oriImg = oriImg.copy()
+ H, W, C = oriImg.shape
+ with torch.no_grad():
+ candidate, subset = self.pose_estimation(oriImg)
+
+ if len(subset) > 1:
+ candidate = candidate[0][np.newaxis, :]
+ subset = subset[:1]
+
+ nums, keys, locs = candidate.shape
+ candidate[..., 0] /= float(W)
+ candidate[..., 1] /= float(H)
+ body = candidate[:, :18].copy()
+ body = body.reshape(nums * 18, locs)
+ score = subset[:, :18]
+
+ for i in range(len(score)):
+ for j in range(len(score[i])):
+ if score[i][j] > 0.3:
+ score[i][j] = int(18 * i + j)
+ else:
+ score[i][j] = -1
+
+ # un_visible = subset < 0.3
+ # candidate[un_visible] = -1
+
+ foot = candidate[:, 18:24]
+
+ faces = candidate[:, 24:92]
+
+ hands = candidate[:, 92:113]
+ hands = np.vstack([hands, candidate[:, 113:]])
+
+ bodies = dict(candidate=body, subset=score)
+ if remain_face:
+ pose = dict(bodies=bodies, hands=hands, faces=faces)
+ else:
+ pose = dict(bodies=bodies, hands=hands, faces=None)
+
+ return draw_pose(pose, H, W)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/dwpose_detector.py b/One-to-All-Animation/video-generation/dwpose_utils/dwpose_detector.py
new file mode 100644
index 0000000000000000000000000000000000000000..fe0e0d8fcc1433ec90e631874e4e24607b387f09
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/dwpose_detector.py
@@ -0,0 +1,136 @@
+import os
+
+import numpy as np
+import torch
+
+from .wholebody import Wholebody
+
+os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
+device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+
+class DWposeDetectorAligned:
+ def __init__(self, device='cpu'):
+ self.pose_estimation = Wholebody()
+
+ def release_memory(self):
+ if hasattr(self, 'pose_estimation'):
+ del self.pose_estimation
+ import gc; gc.collect()
+
+ def __call__(self, oriImg):
+ oriImg = oriImg.copy()
+ H, W, C = oriImg.shape
+ with torch.no_grad():
+ candidate, score = self.pose_estimation(oriImg)
+ candidate = candidate[0][np.newaxis, :, :]
+ score = score[0][np.newaxis, :]
+ nums, _, locs = candidate.shape
+ candidate[..., 0] /= float(W)
+ candidate[..., 1] /= float(H)
+ body = candidate[:, :18].copy()
+ body = body.reshape(nums * 18, locs)
+ subset = score[:, :18].copy()
+ for i in range(len(subset)):
+ for j in range(len(subset[i])):
+ if subset[i][j] > 0.3:
+ subset[i][j] = int(18 * i + j)
+ else:
+ subset[i][j] = -1
+
+ un_visible = score < 0.3
+ candidate[un_visible] = -1
+
+ # foot = candidate[:, 18:24]
+
+ faces = candidate[:, 24:92]
+
+ hands = candidate[:, 92:113]
+ hands = np.vstack([hands, candidate[:, 113:]])
+
+ faces_score = score[:, 24:92]
+ hands_score = np.vstack([score[:, 92:113], score[:, 113:]])
+
+ bodies = dict(candidate=body, subset=subset, score=score[:, :18])
+ pose = dict(bodies=bodies, hands=hands, hands_score=hands_score, faces=faces, faces_score=faces_score)
+
+ return pose
+
+
+class DWposeDetectorRaw:
+ def __init__(self, device='cpu'):
+ self.pose_estimation = Wholebody()
+
+ def release_memory(self):
+ if hasattr(self, 'pose_estimation'):
+ del self.pose_estimation
+ import gc; gc.collect()
+
+ def __call__(self, oriImg):
+ oriImg = oriImg.copy()
+ H, W, C = oriImg.shape
+ with torch.no_grad():
+ candidate, score = self.pose_estimation(oriImg)
+ pose = dict(candidate=candidate, score=score)
+ return pose
+
+
+dwpose_detector_aligned = DWposeDetectorAligned(device=device)
+dwpose_detector_raw = DWposeDetectorRaw(device=device)
+
+
+def build_pose_dict(pose_raw,
+ img_h, img_w,
+ target_ratio=None,
+ vis_thr=0.3):
+
+ candidate = pose_raw['candidate'][0][np.newaxis, :, :].copy() # (1,134,2)
+ score = pose_raw['score'][0][np.newaxis, :].copy() # (1,134)
+
+ nums, _, locs = candidate.shape
+
+ cur_ratio = img_h / img_w
+
+ if (target_ratio is None) or abs(cur_ratio - target_ratio) < 1e-6:
+ norm_w, norm_h = img_w, img_h
+ pad_x = pad_y = 0.0
+ else:
+ if target_ratio > cur_ratio:
+ norm_w = img_w
+ norm_h = img_w * target_ratio
+ pad_x = 0.0
+ pad_y = (norm_h - img_h) / 2.0
+ else:
+ norm_h = img_h
+ norm_w = img_h / target_ratio
+ pad_y = 0.0
+ pad_x = (norm_w - img_w) / 2.0
+
+ candidate[:, :, 0] = (candidate[:, :, 0] + pad_x) / float(norm_w)
+ candidate[:, :, 1] = (candidate[:, :, 1] + pad_y) / float(norm_h)
+
+ body = candidate[:, :18].copy()
+ body = body.reshape(nums * 18, locs)
+ subset = score[:, :18].copy()
+ for i in range(len(subset)):
+ for j in range(len(subset[i])):
+ if subset[i][j] > 0.3:
+ subset[i][j] = int(18 * i + j)
+ else:
+ subset[i][j] = -1
+
+ un_visible = score < 0.3
+ candidate[un_visible] = -1
+
+ # foot = candidate[:, 18:24]
+
+ faces = candidate[:, 24:92]
+
+ hands = candidate[:, 92:113]
+ hands = np.vstack([hands, candidate[:, 113:]])
+
+ faces_score = score[:, 24:92]
+ hands_score = np.vstack([score[:, 92:113], score[:, 113:]])
+
+ bodies = dict(candidate=body, subset=subset, score=score[:, :18])
+ pose = dict(bodies=bodies, hands=hands, hands_score=hands_score, faces=faces, faces_score=faces_score)
+ return pose
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/onnxdet.py b/One-to-All-Animation/video-generation/dwpose_utils/onnxdet.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0411c96a5eef41e981bde5481ef7786b242f1fa
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/onnxdet.py
@@ -0,0 +1,125 @@
+import cv2
+import numpy as np
+
+import onnxruntime
+
+def nms(boxes, scores, nms_thr):
+ """Single class NMS implemented in Numpy."""
+ x1 = boxes[:, 0]
+ y1 = boxes[:, 1]
+ x2 = boxes[:, 2]
+ y2 = boxes[:, 3]
+
+ areas = (x2 - x1 + 1) * (y2 - y1 + 1)
+ order = scores.argsort()[::-1]
+
+ keep = []
+ while order.size > 0:
+ i = order[0]
+ keep.append(i)
+ xx1 = np.maximum(x1[i], x1[order[1:]])
+ yy1 = np.maximum(y1[i], y1[order[1:]])
+ xx2 = np.minimum(x2[i], x2[order[1:]])
+ yy2 = np.minimum(y2[i], y2[order[1:]])
+
+ w = np.maximum(0.0, xx2 - xx1 + 1)
+ h = np.maximum(0.0, yy2 - yy1 + 1)
+ inter = w * h
+ ovr = inter / (areas[i] + areas[order[1:]] - inter)
+
+ inds = np.where(ovr <= nms_thr)[0]
+ order = order[inds + 1]
+
+ return keep
+
+def multiclass_nms(boxes, scores, nms_thr, score_thr):
+ """Multiclass NMS implemented in Numpy. Class-aware version."""
+ final_dets = []
+ num_classes = scores.shape[1]
+ for cls_ind in range(num_classes):
+ cls_scores = scores[:, cls_ind]
+ valid_score_mask = cls_scores > score_thr
+ if valid_score_mask.sum() == 0:
+ continue
+ else:
+ valid_scores = cls_scores[valid_score_mask]
+ valid_boxes = boxes[valid_score_mask]
+ keep = nms(valid_boxes, valid_scores, nms_thr)
+ if len(keep) > 0:
+ cls_inds = np.ones((len(keep), 1)) * cls_ind
+ dets = np.concatenate(
+ [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1
+ )
+ final_dets.append(dets)
+ if len(final_dets) == 0:
+ return None
+ return np.concatenate(final_dets, 0)
+
+def demo_postprocess(outputs, img_size, p6=False):
+ grids = []
+ expanded_strides = []
+ strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
+
+ hsizes = [img_size[0] // stride for stride in strides]
+ wsizes = [img_size[1] // stride for stride in strides]
+
+ for hsize, wsize, stride in zip(hsizes, wsizes, strides):
+ xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize))
+ grid = np.stack((xv, yv), 2).reshape(1, -1, 2)
+ grids.append(grid)
+ shape = grid.shape[:2]
+ expanded_strides.append(np.full((*shape, 1), stride))
+
+ grids = np.concatenate(grids, 1)
+ expanded_strides = np.concatenate(expanded_strides, 1)
+ outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides
+ outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
+
+ return outputs
+
+def preprocess(img, input_size, swap=(2, 0, 1)):
+ if len(img.shape) == 3:
+ padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114
+ else:
+ padded_img = np.ones(input_size, dtype=np.uint8) * 114
+
+ r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1])
+ resized_img = cv2.resize(
+ img,
+ (int(img.shape[1] * r), int(img.shape[0] * r)),
+ interpolation=cv2.INTER_LINEAR,
+ ).astype(np.uint8)
+ padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
+
+ padded_img = padded_img.transpose(swap)
+ padded_img = np.ascontiguousarray(padded_img, dtype=np.float32)
+ return padded_img, r
+
+def inference_detector(session, oriImg):
+ input_shape = (640,640)
+ img, ratio = preprocess(oriImg, input_shape)
+
+ ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]}
+ output = session.run(None, ort_inputs)
+ predictions = demo_postprocess(output[0], input_shape)[0]
+
+ boxes = predictions[:, :4]
+ scores = predictions[:, 4:5] * predictions[:, 5:]
+
+ boxes_xyxy = np.ones_like(boxes)
+ boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2]/2.
+ boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3]/2.
+ boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2]/2.
+ boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3]/2.
+ boxes_xyxy /= ratio
+ dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1)
+ if dets is not None:
+ final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5]
+ isscore = final_scores>0.3
+ iscat = final_cls_inds == 0
+ isbbox = [ i and j for (i, j) in zip(isscore, iscat)]
+ final_boxes = final_boxes[isbbox]
+ else:
+ final_boxes = np.array([])
+
+ return final_boxes
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/onnxpose.py b/One-to-All-Animation/video-generation/dwpose_utils/onnxpose.py
new file mode 100644
index 0000000000000000000000000000000000000000..79cd4a06241123af81ea22446a4ca8816716443f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/onnxpose.py
@@ -0,0 +1,360 @@
+from typing import List, Tuple
+
+import cv2
+import numpy as np
+import onnxruntime as ort
+
+def preprocess(
+ img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)
+) -> Tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Do preprocessing for RTMPose model inference.
+
+ Args:
+ img (np.ndarray): Input image in shape.
+ input_size (tuple): Input image size in shape (w, h).
+
+ Returns:
+ tuple:
+ - resized_img (np.ndarray): Preprocessed image.
+ - center (np.ndarray): Center of image.
+ - scale (np.ndarray): Scale of image.
+ """
+ # get shape of image
+ img_shape = img.shape[:2]
+ out_img, out_center, out_scale = [], [], []
+ if len(out_bbox) == 0:
+ out_bbox = [[0, 0, img_shape[1], img_shape[0]]]
+ for i in range(len(out_bbox)):
+ x0 = out_bbox[i][0]
+ y0 = out_bbox[i][1]
+ x1 = out_bbox[i][2]
+ y1 = out_bbox[i][3]
+ bbox = np.array([x0, y0, x1, y1])
+
+ # get center and scale
+ center, scale = bbox_xyxy2cs(bbox, padding=1.25)
+
+ # do affine transformation
+ resized_img, scale = top_down_affine(input_size, scale, center, img)
+
+ # normalize image
+ mean = np.array([123.675, 116.28, 103.53])
+ std = np.array([58.395, 57.12, 57.375])
+ resized_img = (resized_img - mean) / std
+
+ out_img.append(resized_img)
+ out_center.append(center)
+ out_scale.append(scale)
+
+ return out_img, out_center, out_scale
+
+
+def inference(sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray:
+ """Inference RTMPose model.
+
+ Args:
+ sess (ort.InferenceSession): ONNXRuntime session.
+ img (np.ndarray): Input image in shape.
+
+ Returns:
+ outputs (np.ndarray): Output of RTMPose model.
+ """
+ all_out = []
+ # build input
+ for i in range(len(img)):
+ input = [img[i].transpose(2, 0, 1)]
+
+ # build output
+ sess_input = {sess.get_inputs()[0].name: input}
+ sess_output = []
+ for out in sess.get_outputs():
+ sess_output.append(out.name)
+
+ # run model
+ outputs = sess.run(sess_output, sess_input)
+ all_out.append(outputs)
+
+ return all_out
+
+
+def postprocess(outputs: List[np.ndarray],
+ model_input_size: Tuple[int, int],
+ center: Tuple[int, int],
+ scale: Tuple[int, int],
+ simcc_split_ratio: float = 2.0
+ ) -> Tuple[np.ndarray, np.ndarray]:
+ """Postprocess for RTMPose model output.
+
+ Args:
+ outputs (np.ndarray): Output of RTMPose model.
+ model_input_size (tuple): RTMPose model Input image size.
+ center (tuple): Center of bbox in shape (x, y).
+ scale (tuple): Scale of bbox in shape (w, h).
+ simcc_split_ratio (float): Split ratio of simcc.
+
+ Returns:
+ tuple:
+ - keypoints (np.ndarray): Rescaled keypoints.
+ - scores (np.ndarray): Model predict scores.
+ """
+ all_key = []
+ all_score = []
+ for i in range(len(outputs)):
+ # use simcc to decode
+ simcc_x, simcc_y = outputs[i]
+ keypoints, scores = decode(simcc_x, simcc_y, simcc_split_ratio)
+
+ # rescale keypoints
+ keypoints = keypoints / model_input_size * scale[i] + center[i] - scale[i] / 2
+ all_key.append(keypoints[0])
+ all_score.append(scores[0])
+
+ return np.array(all_key), np.array(all_score)
+
+
+def bbox_xyxy2cs(bbox: np.ndarray,
+ padding: float = 1.) -> Tuple[np.ndarray, np.ndarray]:
+ """Transform the bbox format from (x,y,w,h) into (center, scale)
+
+ Args:
+ bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted
+ as (left, top, right, bottom)
+ padding (float): BBox padding factor that will be multilied to scale.
+ Default: 1.0
+
+ Returns:
+ tuple: A tuple containing center and scale.
+ - np.ndarray[float32]: Center (x, y) of the bbox in shape (2,) or
+ (n, 2)
+ - np.ndarray[float32]: Scale (w, h) of the bbox in shape (2,) or
+ (n, 2)
+ """
+ # convert single bbox from (4, ) to (1, 4)
+ dim = bbox.ndim
+ if dim == 1:
+ bbox = bbox[None, :]
+
+ # get bbox center and scale
+ x1, y1, x2, y2 = np.hsplit(bbox, [1, 2, 3])
+ center = np.hstack([x1 + x2, y1 + y2]) * 0.5
+ scale = np.hstack([x2 - x1, y2 - y1]) * padding
+
+ if dim == 1:
+ center = center[0]
+ scale = scale[0]
+
+ return center, scale
+
+
+def _fix_aspect_ratio(bbox_scale: np.ndarray,
+ aspect_ratio: float) -> np.ndarray:
+ """Extend the scale to match the given aspect ratio.
+
+ Args:
+ scale (np.ndarray): The image scale (w, h) in shape (2, )
+ aspect_ratio (float): The ratio of ``w/h``
+
+ Returns:
+ np.ndarray: The reshaped image scale in (2, )
+ """
+ w, h = np.hsplit(bbox_scale, [1])
+ bbox_scale = np.where(w > h * aspect_ratio,
+ np.hstack([w, w / aspect_ratio]),
+ np.hstack([h * aspect_ratio, h]))
+ return bbox_scale
+
+
+def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray:
+ """Rotate a point by an angle.
+
+ Args:
+ pt (np.ndarray): 2D point coordinates (x, y) in shape (2, )
+ angle_rad (float): rotation angle in radian
+
+ Returns:
+ np.ndarray: Rotated point in shape (2, )
+ """
+ sn, cs = np.sin(angle_rad), np.cos(angle_rad)
+ rot_mat = np.array([[cs, -sn], [sn, cs]])
+ return rot_mat @ pt
+
+
+def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray:
+ """To calculate the affine matrix, three pairs of points are required. This
+ function is used to get the 3rd point, given 2D points a & b.
+
+ The 3rd point is defined by rotating vector `a - b` by 90 degrees
+ anticlockwise, using b as the rotation center.
+
+ Args:
+ a (np.ndarray): The 1st point (x,y) in shape (2, )
+ b (np.ndarray): The 2nd point (x,y) in shape (2, )
+
+ Returns:
+ np.ndarray: The 3rd point.
+ """
+ direction = a - b
+ c = b + np.r_[-direction[1], direction[0]]
+ return c
+
+
+def get_warp_matrix(center: np.ndarray,
+ scale: np.ndarray,
+ rot: float,
+ output_size: Tuple[int, int],
+ shift: Tuple[float, float] = (0., 0.),
+ inv: bool = False) -> np.ndarray:
+ """Calculate the affine transformation matrix that can warp the bbox area
+ in the input image to the output size.
+
+ Args:
+ center (np.ndarray[2, ]): Center of the bounding box (x, y).
+ scale (np.ndarray[2, ]): Scale of the bounding box
+ wrt [width, height].
+ rot (float): Rotation angle (degree).
+ output_size (np.ndarray[2, ] | list(2,)): Size of the
+ destination heatmaps.
+ shift (0-100%): Shift translation ratio wrt the width/height.
+ Default (0., 0.).
+ inv (bool): Option to inverse the affine transform direction.
+ (inv=False: src->dst or inv=True: dst->src)
+
+ Returns:
+ np.ndarray: A 2x3 transformation matrix
+ """
+ shift = np.array(shift)
+ src_w = scale[0]
+ dst_w = output_size[0]
+ dst_h = output_size[1]
+
+ # compute transformation matrix
+ rot_rad = np.deg2rad(rot)
+ src_dir = _rotate_point(np.array([0., src_w * -0.5]), rot_rad)
+ dst_dir = np.array([0., dst_w * -0.5])
+
+ # get four corners of the src rectangle in the original image
+ src = np.zeros((3, 2), dtype=np.float32)
+ src[0, :] = center + scale * shift
+ src[1, :] = center + src_dir + scale * shift
+ src[2, :] = _get_3rd_point(src[0, :], src[1, :])
+
+ # get four corners of the dst rectangle in the input image
+ dst = np.zeros((3, 2), dtype=np.float32)
+ dst[0, :] = [dst_w * 0.5, dst_h * 0.5]
+ dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir
+ dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
+
+ if inv:
+ warp_mat = cv2.getAffineTransform(np.float32(dst), np.float32(src))
+ else:
+ warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))
+
+ return warp_mat
+
+
+def top_down_affine(input_size: dict, bbox_scale: dict, bbox_center: dict,
+ img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
+ """Get the bbox image as the model input by affine transform.
+
+ Args:
+ input_size (dict): The input size of the model.
+ bbox_scale (dict): The bbox scale of the img.
+ bbox_center (dict): The bbox center of the img.
+ img (np.ndarray): The original image.
+
+ Returns:
+ tuple: A tuple containing center and scale.
+ - np.ndarray[float32]: img after affine transform.
+ - np.ndarray[float32]: bbox scale after affine transform.
+ """
+ w, h = input_size
+ warp_size = (int(w), int(h))
+
+ # reshape bbox to fixed aspect ratio
+ bbox_scale = _fix_aspect_ratio(bbox_scale, aspect_ratio=w / h)
+
+ # get the affine matrix
+ center = bbox_center
+ scale = bbox_scale
+ rot = 0
+ warp_mat = get_warp_matrix(center, scale, rot, output_size=(w, h))
+
+ # do affine transform
+ img = cv2.warpAffine(img, warp_mat, warp_size, flags=cv2.INTER_LINEAR)
+
+ return img, bbox_scale
+
+
+def get_simcc_maximum(simcc_x: np.ndarray,
+ simcc_y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
+ """Get maximum response location and value from simcc representations.
+
+ Note:
+ instance number: N
+ num_keypoints: K
+ heatmap height: H
+ heatmap width: W
+
+ Args:
+ simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx)
+ simcc_y (np.ndarray): y-axis SimCC in shape (K, Wy) or (N, K, Wy)
+
+ Returns:
+ tuple:
+ - locs (np.ndarray): locations of maximum heatmap responses in shape
+ (K, 2) or (N, K, 2)
+ - vals (np.ndarray): values of maximum heatmap responses in shape
+ (K,) or (N, K)
+ """
+ N, K, Wx = simcc_x.shape
+ simcc_x = simcc_x.reshape(N * K, -1)
+ simcc_y = simcc_y.reshape(N * K, -1)
+
+ # get maximum value locations
+ x_locs = np.argmax(simcc_x, axis=1)
+ y_locs = np.argmax(simcc_y, axis=1)
+ locs = np.stack((x_locs, y_locs), axis=-1).astype(np.float32)
+ max_val_x = np.amax(simcc_x, axis=1)
+ max_val_y = np.amax(simcc_y, axis=1)
+
+ # get maximum value across x and y axis
+ mask = max_val_x > max_val_y
+ max_val_x[mask] = max_val_y[mask]
+ vals = max_val_x
+ locs[vals <= 0.] = -1
+
+ # reshape
+ locs = locs.reshape(N, K, 2)
+ vals = vals.reshape(N, K)
+
+ return locs, vals
+
+
+def decode(simcc_x: np.ndarray, simcc_y: np.ndarray,
+ simcc_split_ratio) -> Tuple[np.ndarray, np.ndarray]:
+ """Modulate simcc distribution with Gaussian.
+
+ Args:
+ simcc_x (np.ndarray[K, Wx]): model predicted simcc in x.
+ simcc_y (np.ndarray[K, Wy]): model predicted simcc in y.
+ simcc_split_ratio (int): The split ratio of simcc.
+
+ Returns:
+ tuple: A tuple containing center and scale.
+ - np.ndarray[float32]: keypoints in shape (K, 2) or (n, K, 2)
+ - np.ndarray[float32]: scores in shape (K,) or (n, K)
+ """
+ keypoints, scores = get_simcc_maximum(simcc_x, simcc_y)
+ keypoints /= simcc_split_ratio
+
+ return keypoints, scores
+
+
+def inference_pose(session, out_bbox, oriImg):
+ h, w = session.get_inputs()[0].shape[2:]
+ model_input_size = (w, h)
+ resized_img, center, scale = preprocess(oriImg, out_bbox, model_input_size)
+ outputs = inference(session, resized_img)
+ keypoints, scores = postprocess(outputs, model_input_size, center, scale)
+
+ return keypoints, scores
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/util.py b/One-to-All-Animation/video-generation/dwpose_utils/util.py
new file mode 100644
index 0000000000000000000000000000000000000000..73d7d0153b38d143eb8090e07a9784a274b619ed
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/util.py
@@ -0,0 +1,297 @@
+import math
+import numpy as np
+import matplotlib
+import cv2
+
+
+eps = 0.01
+
+
+def smart_resize(x, s):
+ Ht, Wt = s
+ if x.ndim == 2:
+ Ho, Wo = x.shape
+ Co = 1
+ else:
+ Ho, Wo, Co = x.shape
+ if Co == 3 or Co == 1:
+ k = float(Ht + Wt) / float(Ho + Wo)
+ return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4)
+ else:
+ return np.stack([smart_resize(x[:, :, i], s) for i in range(Co)], axis=2)
+
+
+def smart_resize_k(x, fx, fy):
+ if x.ndim == 2:
+ Ho, Wo = x.shape
+ Co = 1
+ else:
+ Ho, Wo, Co = x.shape
+ Ht, Wt = Ho * fy, Wo * fx
+ if Co == 3 or Co == 1:
+ k = float(Ht + Wt) / float(Ho + Wo)
+ return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4)
+ else:
+ return np.stack([smart_resize_k(x[:, :, i], fx, fy) for i in range(Co)], axis=2)
+
+
+def padRightDownCorner(img, stride, padValue):
+ h = img.shape[0]
+ w = img.shape[1]
+
+ pad = 4 * [None]
+ pad[0] = 0 # up
+ pad[1] = 0 # left
+ pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down
+ pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
+
+ img_padded = img
+ pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1))
+ img_padded = np.concatenate((pad_up, img_padded), axis=0)
+ pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1))
+ img_padded = np.concatenate((pad_left, img_padded), axis=1)
+ pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1))
+ img_padded = np.concatenate((img_padded, pad_down), axis=0)
+ pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1))
+ img_padded = np.concatenate((img_padded, pad_right), axis=1)
+
+ return img_padded, pad
+
+
+def transfer(model, model_weights):
+ transfered_model_weights = {}
+ for weights_name in model.state_dict().keys():
+ transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])]
+ return transfered_model_weights
+
+
+def draw_bodypose(canvas, candidate, subset):
+ H, W, C = canvas.shape
+ candidate = np.array(candidate)
+ subset = np.array(subset)
+
+ stickwidth = 4
+
+ limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \
+ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \
+ [1, 16], [16, 18], [3, 17], [6, 18]]
+
+ colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \
+ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ for i in range(17):
+ for n in range(len(subset)):
+ index = subset[n][np.array(limbSeq[i]) - 1]
+ if -1 in index:
+ continue
+ Y = candidate[index.astype(int), 0] * float(W)
+ X = candidate[index.astype(int), 1] * float(H)
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5
+ angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(canvas, polygon, colors[i])
+
+ canvas = (canvas * 0.6).astype(np.uint8)
+
+ for i in range(18):
+ for n in range(len(subset)):
+ index = int(subset[n][i])
+ if index == -1:
+ continue
+ x, y = candidate[index][0:2]
+ x = int(x * W)
+ y = int(y * H)
+ cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
+
+ return canvas
+
+
+def draw_handpose(canvas, all_hand_peaks):
+ H, W, C = canvas.shape
+
+ edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
+ [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
+
+ for peaks in all_hand_peaks:
+ peaks = np.array(peaks)
+
+ for ie, e in enumerate(edges):
+ x1, y1 = peaks[e[0]]
+ x2, y2 = peaks[e[1]]
+ x1 = int(x1 * W)
+ y1 = int(y1 * H)
+ x2 = int(x2 * W)
+ y2 = int(y2 * H)
+ if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
+ cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255, thickness=2)
+
+ for i, keyponit in enumerate(peaks):
+ x, y = keyponit
+ x = int(x * W)
+ y = int(y * H)
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1)
+ return canvas
+
+
+def draw_facepose(canvas, all_lmks):
+ H, W, C = canvas.shape
+ for lmks in all_lmks:
+ lmks = np.array(lmks)
+ for lmk in lmks:
+ x, y = lmk
+ x = int(x * W)
+ y = int(y * H)
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), 3, (255, 255, 255), thickness=-1)
+ return canvas
+
+
+# detect hand according to body pose keypoints
+# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cpp
+def handDetect(candidate, subset, oriImg):
+ # right hand: wrist 4, elbow 3, shoulder 2
+ # left hand: wrist 7, elbow 6, shoulder 5
+ ratioWristElbow = 0.33
+ detect_result = []
+ image_height, image_width = oriImg.shape[0:2]
+ for person in subset.astype(int):
+ # if any of three not detected
+ has_left = np.sum(person[[5, 6, 7]] == -1) == 0
+ has_right = np.sum(person[[2, 3, 4]] == -1) == 0
+ if not (has_left or has_right):
+ continue
+ hands = []
+ #left hand
+ if has_left:
+ left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]]
+ x1, y1 = candidate[left_shoulder_index][:2]
+ x2, y2 = candidate[left_elbow_index][:2]
+ x3, y3 = candidate[left_wrist_index][:2]
+ hands.append([x1, y1, x2, y2, x3, y3, True])
+ # right hand
+ if has_right:
+ right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]]
+ x1, y1 = candidate[right_shoulder_index][:2]
+ x2, y2 = candidate[right_elbow_index][:2]
+ x3, y3 = candidate[right_wrist_index][:2]
+ hands.append([x1, y1, x2, y2, x3, y3, False])
+
+ for x1, y1, x2, y2, x3, y3, is_left in hands:
+ # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox
+ # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]);
+ # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]);
+ # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow);
+ # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder);
+ # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder);
+ x = x3 + ratioWristElbow * (x3 - x2)
+ y = y3 + ratioWristElbow * (y3 - y2)
+ distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2)
+ distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
+ width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder)
+ # x-y refers to the center --> offset to topLeft point
+ # handRectangle.x -= handRectangle.width / 2.f;
+ # handRectangle.y -= handRectangle.height / 2.f;
+ x -= width / 2
+ y -= width / 2 # width = height
+ # overflow the image
+ if x < 0: x = 0
+ if y < 0: y = 0
+ width1 = width
+ width2 = width
+ if x + width > image_width: width1 = image_width - x
+ if y + width > image_height: width2 = image_height - y
+ width = min(width1, width2)
+ # the max hand box value is 20 pixels
+ if width >= 20:
+ detect_result.append([int(x), int(y), int(width), is_left])
+
+ '''
+ return value: [[x, y, w, True if left hand else False]].
+ width=height since the network require squared input.
+ x, y is the coordinate of top left
+ '''
+ return detect_result
+
+
+# Written by Lvmin
+def faceDetect(candidate, subset, oriImg):
+ # left right eye ear 14 15 16 17
+ detect_result = []
+ image_height, image_width = oriImg.shape[0:2]
+ for person in subset.astype(int):
+ has_head = person[0] > -1
+ if not has_head:
+ continue
+
+ has_left_eye = person[14] > -1
+ has_right_eye = person[15] > -1
+ has_left_ear = person[16] > -1
+ has_right_ear = person[17] > -1
+
+ if not (has_left_eye or has_right_eye or has_left_ear or has_right_ear):
+ continue
+
+ head, left_eye, right_eye, left_ear, right_ear = person[[0, 14, 15, 16, 17]]
+
+ width = 0.0
+ x0, y0 = candidate[head][:2]
+
+ if has_left_eye:
+ x1, y1 = candidate[left_eye][:2]
+ d = max(abs(x0 - x1), abs(y0 - y1))
+ width = max(width, d * 3.0)
+
+ if has_right_eye:
+ x1, y1 = candidate[right_eye][:2]
+ d = max(abs(x0 - x1), abs(y0 - y1))
+ width = max(width, d * 3.0)
+
+ if has_left_ear:
+ x1, y1 = candidate[left_ear][:2]
+ d = max(abs(x0 - x1), abs(y0 - y1))
+ width = max(width, d * 1.5)
+
+ if has_right_ear:
+ x1, y1 = candidate[right_ear][:2]
+ d = max(abs(x0 - x1), abs(y0 - y1))
+ width = max(width, d * 1.5)
+
+ x, y = x0, y0
+
+ x -= width
+ y -= width
+
+ if x < 0:
+ x = 0
+
+ if y < 0:
+ y = 0
+
+ width1 = width * 2
+ width2 = width * 2
+
+ if x + width > image_width:
+ width1 = image_width - x
+
+ if y + width > image_height:
+ width2 = image_height - y
+
+ width = min(width1, width2)
+
+ if width >= 20:
+ detect_result.append([int(x), int(y), int(width)])
+
+ return detect_result
+
+
+# get max index of 2d array
+def npmax(array):
+ arrayindex = array.argmax(1)
+ arrayvalue = array.max(1)
+ i = arrayvalue.argmax()
+ j = arrayindex[i]
+ return i, j
diff --git a/One-to-All-Animation/video-generation/dwpose_utils/wholebody.py b/One-to-All-Animation/video-generation/dwpose_utils/wholebody.py
new file mode 100644
index 0000000000000000000000000000000000000000..038753bced30f4707fdecd82549c21f50a2fc424
--- /dev/null
+++ b/One-to-All-Animation/video-generation/dwpose_utils/wholebody.py
@@ -0,0 +1,51 @@
+import cv2
+import numpy as np
+
+import onnxruntime as ort
+from .onnxdet import inference_detector
+from .onnxpose import inference_pose
+import torch
+
+class Wholebody:
+ def __init__(self):
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
+ # device = 'cuda'
+ providers = ['CPUExecutionProvider'
+ ] if device == 'cpu' else ['CUDAExecutionProvider']
+ onnx_det = '../pretrained_models/DWPose/yolox_l.onnx'
+ onnx_pose = '../pretrained_models/DWPose/dw-ll_ucoco_384.onnx'
+
+ self.session_det = ort.InferenceSession(path_or_bytes=onnx_det, providers=providers)
+ self.session_pose = ort.InferenceSession(path_or_bytes=onnx_pose, providers=providers)
+
+ def __call__(self, oriImg):
+ det_result = inference_detector(self.session_det, oriImg)
+ keypoints, scores = inference_pose(self.session_pose, det_result, oriImg)
+
+ keypoints_info = np.concatenate(
+ (keypoints, scores[..., None]), axis=-1)
+ # compute neck joint
+ neck = np.mean(keypoints_info[:, [5, 6]], axis=1)
+ # neck score when visualizing pred
+ neck[:, 2:4] = np.logical_and(
+ keypoints_info[:, 5, 2:4] > 0.3,
+ keypoints_info[:, 6, 2:4] > 0.3).astype(int)
+ new_keypoints_info = np.insert(
+ keypoints_info, 17, neck, axis=1)
+ mmpose_idx = [
+ 17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3
+ ]
+ openpose_idx = [
+ 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17
+ ]
+ new_keypoints_info[:, openpose_idx] = \
+ new_keypoints_info[:, mmpose_idx]
+ keypoints_info = new_keypoints_info
+
+ keypoints, scores = keypoints_info[
+ ..., :2], keypoints_info[..., 2]
+
+ return keypoints, scores
+
+
+
diff --git a/One-to-All-Animation/video-generation/infer_function.py b/One-to-All-Animation/video-generation/infer_function.py
new file mode 100644
index 0000000000000000000000000000000000000000..104607fce4c4ff1a4b23203e4351be329db7fd5e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/infer_function.py
@@ -0,0 +1,706 @@
+import numpy as np
+import math
+import copy
+from wanpose_utils.retarget_pose import get_retarget_pose
+
+L_EYE_IDXS = list(range(36, 42))
+R_EYE_IDXS = list(range(42, 48))
+NOSE_TIP = 30
+MOUTH_L = 48
+MOUTH_R = 54
+JAW_LINE = list(range(0, 17))
+
+
+# ===========================Convert wanpose format into our dwpose-like format======================
+def aaposemeta_to_dwpose(meta):
+ candidate_body = meta['keypoints_body'][:-2][:, :2]
+ score_body = meta['keypoints_body'][:-2][:, 2]
+ subset_body = np.arange(len(candidate_body), dtype=float)
+ subset_body[score_body <= 0] = -1
+ bodies = {
+ "candidate": candidate_body,
+ "subset": np.expand_dims(subset_body, axis=0), # shape (1, N)
+ "score": np.expand_dims(score_body, axis=0) # shape (1, N)
+ }
+ hands_coords = np.stack([
+ meta['keypoints_right_hand'][:, :2],
+ meta['keypoints_left_hand'][:, :2]
+ ])
+ hands_score = np.stack([
+ meta['keypoints_right_hand'][:, 2],
+ meta['keypoints_left_hand'][:, 2]
+ ])
+ faces_coords = np.expand_dims(meta['keypoints_face'][1:][:, :2], axis=0)
+ faces_score = np.expand_dims(meta['keypoints_face'][1:][:, 2], axis=0)
+ dwpose_format = {
+ "bodies": bodies,
+ "hands": hands_coords,
+ "hands_score": hands_score,
+ "faces": faces_coords,
+ "faces_score": faces_score
+ }
+ return dwpose_format
+
+def aaposemeta_obj_to_dwpose(pose_meta: "AAPoseMeta"):
+ """
+ 将 AAPoseMeta 对象转换成 dwpose_like 数据结构
+ 坐标恢复为相对坐标 (除以 width, height)
+ 仅处理 None -> 补零
+ """
+ w = pose_meta.width
+ h = pose_meta.height
+
+ # 如果是 None,就补成全 0 数组
+ def safe(arr, like_shape):
+ if arr is None:
+ return np.zeros(like_shape, dtype=np.float32)
+ arr_np = np.array(arr, dtype=np.float32)
+ arr_np = np.nan_to_num(arr_np, nan=0.0)
+ return arr_np
+ # body
+ kps_body = safe(pose_meta.kps_body, (pose_meta.kps_body_p.shape[0], 2))
+ candidate_body = kps_body / np.array([w, h])
+ score_body = safe(pose_meta.kps_body_p, (candidate_body.shape[0],))
+ subset_body = np.arange(len(candidate_body), dtype=float)
+ subset_body[score_body <= 0] = -1
+ bodies = {
+ "candidate": candidate_body,
+ "subset": np.expand_dims(subset_body, axis=0),
+ "score": np.expand_dims(score_body, axis=0)
+ }
+
+ # hands
+ kps_rhand = safe(pose_meta.kps_rhand, (pose_meta.kps_rhand_p.shape[0], 2))
+ kps_lhand = safe(pose_meta.kps_lhand, (pose_meta.kps_lhand_p.shape[0], 2))
+ hands_coords = np.stack([
+ kps_rhand / np.array([w, h]),
+ kps_lhand / np.array([w, h])
+ ])
+ hands_score = np.stack([
+ safe(pose_meta.kps_rhand_p, (kps_rhand.shape[0],)),
+ safe(pose_meta.kps_lhand_p, (kps_lhand.shape[0],))
+ ])
+
+ dwpose_format = {
+ "bodies": bodies,
+ "hands": hands_coords,
+ "hands_score": hands_score,
+ "faces": None,
+ "faces_score": None
+ }
+ return dwpose_format
+
+# ===============================Face Rough alignment======================
+
+def _to_68x2(arr):
+ if arr.shape == (1, 68, 2):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x[np.newaxis, :, :]
+ return arr[0].astype(np.float64), to_orig
+ if arr.shape == (68, 2):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x
+ return arr.astype(np.float64), to_orig
+ if arr.shape == (2, 68):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x.T
+ return arr.T.astype(np.float64), to_orig
+ raise ValueError(f"faces shape {arr.shape} not supported; expected (1,68,2) or (68,2) or (2,68)")
+
+def _eye_center(face68, idxs):
+ return face68[idxs].mean(axis=0)
+
+def _anchors(face68):
+ le = _eye_center(face68, L_EYE_IDXS)
+ re = _eye_center(face68, R_EYE_IDXS)
+ nose = face68[NOSE_TIP]
+ lm = face68[MOUTH_L]
+ rm = face68[MOUTH_R]
+ if re[0] < le[0]:
+ le, re = re, le
+ return np.stack([le, re, nose, lm, rm], axis=0)
+
+def _face_scale_only(src68, ref68, target_nose_pos, alpha=1.0, anchor_pairs=[[36, 45], [27, 8]]):
+ """
+ 粗对齐-根据 ref 的比例调整 src 的脸型,并将鼻尖与 target_nose_pos 对齐。
+ anchor_pairs:
+ - [36, 45] for x
+ - [27, 8] for y
+ """
+ src = np.asarray(src68, dtype=np.float64)
+ ref = np.asarray(ref68, dtype=np.float64)
+
+ center = _anchors(src).mean(axis=0)
+ src_centered = src - center
+
+ src_w = np.linalg.norm(src[anchor_pairs[0][0]] - src[anchor_pairs[0][1]])
+ ref_w = np.linalg.norm(ref[anchor_pairs[0][0]] - ref[anchor_pairs[0][1]])
+
+ src_h = np.linalg.norm(src[anchor_pairs[1][0]] - src[anchor_pairs[1][1]])
+ ref_h = np.linalg.norm(ref[anchor_pairs[1][0]] - ref[anchor_pairs[1][1]])
+
+ scale_x = ref_w / src_w if src_w > 1e-6 else 1.0
+ scale_y = ref_h / src_h if src_h > 1e-6 else 1.0
+
+ scaled_local = src_centered.copy()
+ scaled_local[:, 0] *= (1 - alpha) + scale_x * alpha
+ scaled_local[:, 1] *= (1 - alpha) + scale_y * alpha
+ scaled_global = scaled_local + center
+
+ nose_idx = NOSE_TIP
+ current_nose = scaled_global[nose_idx]
+ offset = target_nose_pos - current_nose
+ scaled_global += offset
+
+ return scaled_global
+
+
+# ===============================Select Anchor Pose For Alignment======================
+
+def count_symmetric_pairs(ratios, th=1e-6, ratio_thr=1.5):
+ pairs = [
+ ('arm3','arm6'),
+ ('arm4','arm7'),
+ ('ll1','rl1'),
+ ('ll2','rl2')
+ ]
+ count = 0
+ for a, b in pairs:
+ v1, v2 = ratios[a], ratios[b]
+ if v1 < th or v2 < th:
+ continue
+ q = v1 / v2
+ if 1.0 / ratio_thr <= q <= ratio_thr:
+ count += 1
+ return count
+
+def pick_good_source_frame(ref_pose, detected_poses, th=1e-6, ratio_thr=1.5,
+ torso_angle_thr_deg=30, horiz_angle_thr_deg=30):
+ if not detected_poses:
+ return None, -1
+ def _angle_with_vertical(v):
+ import math
+ dx, dy = abs(v[0]), abs(v[1]) + 1e-9
+ return math.atan2(dx, dy)
+ def _angle_with_horizontal(v):
+ import math
+ dx, dy = abs(v[0]) + 1e-9, abs(v[1])
+ return math.atan2(dy, dx)
+ def body_is_upright(cand) -> bool:
+ neck = cand[1]; rs = cand[2]; ls = cand[5]
+ lh = cand[8]; rh = cand[11]
+ for p in (neck, rs, ls, lh, rh):
+ if (p <= 0).any():
+ return False
+ shoulder_c = (ls + rs) / 2
+ hip_c = (lh + rh) / 2
+ v_torso = hip_c - shoulder_c
+ if _angle_with_vertical(v_torso) > math.radians(torso_angle_thr_deg):
+ return False
+ if _angle_with_horizontal(ls - rs) > math.radians(horiz_angle_thr_deg):
+ return False
+ if _angle_with_horizontal(lh - rh) > math.radians(horiz_angle_thr_deg):
+ return False
+ return True
+
+ def limb_len(points, i, j):
+ import numpy as np
+ return np.linalg.norm(points[i] - points[j])
+
+ def calc_basic_ratios(ref_cand, src_cand):
+ def _ratio(i, j):
+ l_ref = limb_len(ref_cand, i, j)
+ l_src = limb_len(src_cand, i, j)
+ return 1.0 if l_src < th else (l_ref / l_src)
+ return dict(
+ shoulder2=_ratio(1, 2), shoulder5=_ratio(1, 5),
+ arm3=_ratio(2, 3), arm6=_ratio(5, 6),
+ arm4=_ratio(3, 4), arm7=_ratio(6, 7),
+ ll1=_ratio(8, 9), rl1=_ratio(11, 12),
+ ll2=_ratio(9, 10), rl2=_ratio(12, 13),
+ )
+
+ ref_cand = ref_pose['bodies']['candidate']
+ ref_rs = ref_cand[2]
+ ref_ls = ref_cand[5]
+ ref_neck = ref_cand[1]
+ ref_nose = ref_cand[0]
+ ref_shoulder_angle = _angle_with_horizontal(ref_ls - ref_rs)
+ ref_head_angle = _angle_with_vertical(ref_nose - ref_neck)
+
+ all_candidates = []
+ for idx, pose in enumerate(detected_poses):
+ cand = pose['bodies']['candidate']
+ ratios = calc_basic_ratios(ref_cand, cand)
+
+ shoulder_angle = _angle_with_horizontal(cand[5] - cand[2])
+ head_angle = _angle_with_vertical(cand[0] - cand[1])
+ angle_score = abs(shoulder_angle - ref_shoulder_angle) + abs(head_angle - ref_head_angle)
+
+ sym_count = count_symmetric_pairs(ratios, th, ratio_thr)
+ upright = body_is_upright(cand)
+
+ all_candidates.append({
+ "idx": idx,
+ "score": angle_score,
+ "sym_count": sym_count,
+ "upright": upright
+ })
+
+ sorted_candidates = sorted(
+ all_candidates,
+ key=lambda x: (-x["sym_count"], not x["upright"], x["score"])
+ )
+
+ best = sorted_candidates[0]
+ print(f"[pick_good_source_frame] pick frame {best['idx']} "
+ f"(sym_count={best['sym_count']}/4, upright={best['upright']}, score={best['score']:.4f})")
+
+ print(f"[pick_good_source_frame] 选中第 {best['idx']} 帧"
+ f"(对称匹配={best['sym_count']}/4, 直立={best['upright']}, 角度差={best['score']:.4f})")
+
+ return detected_poses[best["idx"]], best["idx"]
+
+# ===============================Reference Img Pre-Process======================
+
+
+def scale_and_translate_pose(tgt_pose, ref_pose, conf_th=0.9, return_ratio=False):
+ aligned_pose = copy.deepcopy(tgt_pose)
+ th = 1e-6
+ ref_kpt = ref_pose['bodies']['candidate'].astype(np.float32)
+ tgt_kpt = aligned_pose['bodies']['candidate'].astype(np.float32)
+
+ ref_sc = ref_pose['bodies'].get('score', np.ones(ref_kpt.shape[0])).astype(np.float32).reshape(-1)
+ tgt_sc = tgt_pose['bodies'].get('score', np.ones(tgt_kpt.shape[0])).astype(np.float32).reshape(-1)
+
+ ref_shoulder_valid = (ref_sc[2] >= conf_th) and (ref_sc[5] >= conf_th)
+ tgt_shoulder_valid = (tgt_sc[2] >= conf_th) and (tgt_sc[5] >= conf_th)
+ shoulder_ok = ref_shoulder_valid and tgt_shoulder_valid
+
+ ref_hip_valid = (ref_sc[8] >= conf_th) and (ref_sc[11] >= conf_th)
+ tgt_hip_valid = (tgt_sc[8] >= conf_th) and (tgt_sc[11] >= conf_th)
+ hip_ok = ref_hip_valid and tgt_hip_valid
+
+ ref_ear_valid = (ref_sc[16] >= conf_th) and (ref_sc[17] >= conf_th)
+ tgt_ear_valid = (tgt_sc[16] >= conf_th) and (tgt_sc[17] >= conf_th)
+ ear_ok = ref_ear_valid and tgt_ear_valid
+
+ if shoulder_ok and hip_ok:
+ ref_shoulder_w = abs(ref_kpt[5, 0] - ref_kpt[2, 0])
+ tgt_shoulder_w = abs(tgt_kpt[5, 0] - tgt_kpt[2, 0])
+ x_ratio = ref_shoulder_w / tgt_shoulder_w if tgt_shoulder_w > th else 1.0
+
+ ref_torso_h = abs(np.mean(ref_kpt[[8, 11], 1]) - np.mean(ref_kpt[[2, 5], 1]))
+ tgt_torso_h = abs(np.mean(tgt_kpt[[8, 11], 1]) - np.mean(tgt_kpt[[2, 5], 1]))
+ y_ratio = ref_torso_h / tgt_torso_h if tgt_torso_h > th else 1.0
+ scale_ratio = (x_ratio + y_ratio) / 2
+
+ elif shoulder_ok:
+ ref_sh_dist = np.linalg.norm(ref_kpt[2] - ref_kpt[5])
+ tgt_sh_dist = np.linalg.norm(tgt_kpt[2] - tgt_kpt[5])
+ scale_ratio = ref_sh_dist / tgt_sh_dist if tgt_sh_dist > th else 1.0
+
+ else:
+ ref_ear_dist = np.linalg.norm(ref_kpt[16] - ref_kpt[17])
+ tgt_ear_dist = np.linalg.norm(tgt_kpt[16] - tgt_kpt[17])
+ scale_ratio = ref_ear_dist / tgt_ear_dist if tgt_ear_dist > th else 1.0
+
+ if return_ratio:
+ return scale_ratio
+
+ # scale
+ anchor_idx = 1
+ anchor_pt_before_scale = tgt_kpt[anchor_idx].copy()
+ def scale(arr):
+ if arr is not None and arr.size > 0:
+ arr[..., 0] = anchor_pt_before_scale[0] + (arr[..., 0] - anchor_pt_before_scale[0]) * scale_ratio
+ arr[..., 1] = anchor_pt_before_scale[1] + (arr[..., 1] - anchor_pt_before_scale[1]) * scale_ratio
+ scale(tgt_kpt)
+ scale(aligned_pose.get('faces'))
+ scale(aligned_pose.get('hands'))
+
+ # offset
+ offset = ref_kpt[anchor_idx] - tgt_kpt[anchor_idx]
+ def translate(arr):
+ if arr is not None and arr.size > 0:
+ arr += offset
+ translate(tgt_kpt)
+ translate(aligned_pose.get('faces'))
+ translate(aligned_pose.get('hands'))
+ aligned_pose['bodies']['candidate'] = tgt_kpt
+
+ return aligned_pose, shoulder_ok, hip_ok
+
+
+# def warp_ref_to_pose(tgt_img,
+# ref_pose: dict,
+# tgt_pose: dict,
+# bg_val=(0, 0, 0),
+# conf_th=0.8,
+# align_center=False):
+
+# def _euclid(p1, p2):
+# return float(np.linalg.norm(p1 - p2))
+
+# H, W = tgt_img.shape[:2]
+# img_tgt_pose = draw_pose_aligned(tgt_pose, H, W, without_face=True)
+
+# ref_kpt = ref_pose['bodies']['candidate'].astype(np.float32) # (18,2) 0~1
+# tgt_kpt = tgt_pose['bodies']['candidate'].astype(np.float32)
+# ref_sc = ref_pose['bodies']['score'].astype(np.float32).reshape(-1) # (18,)
+# tgt_sc = tgt_pose['bodies']['score'].astype(np.float32).reshape(-1)
+
+# ref_px = ref_kpt.copy()
+# tgt_px = tgt_kpt.copy()
+# th = 1e-6
+
+# # ---------- 计算 scale ----------
+# shoulder_ok = (tgt_sc[2] >= conf_th) & (tgt_sc[5] >= conf_th) & (ref_sc[2] >= conf_th) & (ref_sc[5] >= conf_th)
+# hip_ok = (tgt_sc[8] >= conf_th) & (tgt_sc[11] >= conf_th) & (ref_sc[8] >= conf_th) & (ref_sc[11] >= conf_th)
+
+# ref_sh = _euclid(ref_px[2], ref_px[5]); tgt_sh = _euclid(tgt_px[2], tgt_px[5])
+# ref_torso = _euclid(0.5*(ref_px[2]+ref_px[5]), 0.5*(ref_px[8]+ref_px[11]))
+# tgt_torso = _euclid(0.5*(tgt_px[2]+tgt_px[5]), 0.5*(tgt_px[8]+tgt_px[11]))
+# ref_ear = _euclid(ref_px[16], ref_px[17]); tgt_ear = _euclid(tgt_px[16], tgt_px[17])
+
+# # scale_ratio = 1.0
+# if shoulder_ok and hip_ok and min(ref_sh, tgt_sh, ref_torso, tgt_torso) > th:
+# scale_ratio = 0.5 * (ref_sh / tgt_sh + ref_torso / tgt_torso)
+# print("shoulder_ok and hip_ok",scale_ratio)
+
+# elif shoulder_ok and min(ref_sh, tgt_sh) > th:
+# scale_ratio = ref_sh / tgt_sh
+# print("shoulder_ok",scale_ratio)
+
+# else:
+# scale_ratio = ref_ear / tgt_ear
+# print("ear",scale_ratio)
+
+# anchor = 1
+# x0 = tgt_px[anchor][0] * W
+# y0 = tgt_px[anchor][1] * H
+# ref_x = ref_px[anchor][0] * W if not align_center else W/2
+# ref_y = ref_px[anchor][1] * H
+# dx = ref_x - x0
+# dy = ref_y - y0
+
+# # 仿射变换
+# M = np.array([[scale_ratio, 0, (1-scale_ratio)*x0 + dx],
+# [0, scale_ratio, (1-scale_ratio)*y0 + dy]],
+# dtype=np.float32)
+
+# img_warp = cv2.warpAffine(tgt_img, M, (W, H),
+# flags=cv2.INTER_LINEAR,
+# borderValue=bg_val)
+
+# img_tgt_pose_warp = cv2.warpAffine(img_tgt_pose, M, (W, H),
+# flags=cv2.INTER_LINEAR,
+# borderValue=bg_val)
+
+
+# zeros = np.zeros((H, W), dtype=np.uint8)
+# mask_warp = cv2.warpAffine(zeros, M, (W, H),
+# flags=cv2.INTER_NEAREST,
+# borderValue=1)
+# # pre-processed reference img | reference pose | mask
+# return img_warp, img_tgt_pose_warp, mask_warp
+
+# ===============================Align to Ref Driven Pose Retarget ======================
+
+def align_to_reference(ref_pose_meta, tpl_pose_metas, tpl_dwposes, anchor_idx=None):
+ # pose retarget + face rough align
+
+ ref_pose_dw = aaposemeta_to_dwpose(ref_pose_meta)
+ if anchor_idx is None:
+ _, best_idx = pick_good_source_frame(ref_pose_dw, tpl_dwposes)
+ else:
+ best_idx = anchor_idx
+ tpl_pose_meta_best = tpl_pose_metas[best_idx]
+
+ tpl_retarget_pose_metas = get_retarget_pose(
+ tpl_pose_meta_best,
+ ref_pose_meta,
+ tpl_pose_metas,
+ None, None
+ )
+
+ retarget_dwposes = [aaposemeta_obj_to_dwpose(pm) for pm in tpl_retarget_pose_metas]
+
+ if ref_pose_dw['faces'] is not None:
+ ref68, _ = _to_68x2(ref_pose_dw['faces'])
+ for frame_idx, (tpl_dw, rt_dw) in enumerate(zip(tpl_dwposes, retarget_dwposes)):
+ if tpl_dw['faces'] is None:
+ continue
+ src68, to_orig = _to_68x2(tpl_dw['faces'])
+ target_nose_pos = rt_dw['bodies']['candidate'][0]
+ scaled68 = _face_scale_only(src68, ref68, target_nose_pos, alpha=1.0)
+ rt_dw['faces'] = to_orig(scaled68)
+ rt_dw['faces_score'] = tpl_dw['faces_score']
+
+ return retarget_dwposes
+
+# ===============================Rescale-Ref && Change part of pose(Option)======================
+
+
+def compute_ratios_stepwise(ref_scores, source_scores, ref_pts, src_pts, conf_th=0.9, th=1e-6):
+
+ def keypoint_valid(idx):
+ return ref_scores[0, idx] >= conf_th and source_scores[0, idx] >= conf_th
+
+ def safe_ratio(p1, p2):
+ len_ref = np.linalg.norm(ref_pts[p1] - ref_pts[p2])
+ len_src = np.linalg.norm(src_pts[p1] - src_pts[p2])
+ if len_src > th:
+ return len_ref / len_src
+ else:
+ return 1.0
+
+ ratio_pairs = [
+ (0,1),(1,2),(1,5),(2,3),(3,4),(5,6),(6,7),
+ (0,14),(0,15),(14,16),(15,17),
+ (8,9),(9,10),(11,12),(12,13),
+ (1,8),(1,11)
+ ]
+ ratios = {p: 1.0 for p in ratio_pairs}
+
+ parent_map = {
+ (3, 4): (2, 3),
+ (6, 7): (5, 6),
+ (9, 10): (8, 9),
+ (12, 13): (11, 12)
+ }
+
+ # Group 1 — head only
+ if all(keypoint_valid(i) for i in [0,1,14,15,16,17]):
+ ratios[(0,1)] = safe_ratio(0,1)
+ ratios[(0,14)] = safe_ratio(0,14)
+ ratios[(0,15)] = safe_ratio(0,15)
+ ratios[(14,16)]= safe_ratio(14,16)
+ ratios[(15,17)]= safe_ratio(15,17)
+
+ # Group 2 — +shoulder
+ if all(keypoint_valid(i) for i in [0,1,2,5,14,15,16,17]):
+ ratios[(1,2)] = safe_ratio(1,2)
+ ratios[(1,5)] = safe_ratio(1,5)
+
+ # Group 3 — +upper arm
+ if all(keypoint_valid(i) for i in [0,1,2,5,14,15,16,17,3,6]):
+ ratios[(2,3)] = safe_ratio(2,3)
+ ratios[(5,6)] = safe_ratio(5,6)
+ ratios[(3,4)] = ratios[parent_map[(3,4)]]
+ ratios[(6,7)] = ratios[parent_map[(6,7)]]
+
+ # Group 4 — +hips
+ if all(keypoint_valid(i) for i in [0,1,2,5,14,15,16,17,3,6,8,11]):
+ ratios[(1,8)] = safe_ratio(1,8)
+ ratios[(1,11)] = safe_ratio(1,11)
+
+ # Group 5 — forearm own
+ if all(keypoint_valid(i) for i in [0,1,2,5,14,15,16,17,3,6,8,11,4,7]):
+ ratios[(3,4)] = safe_ratio(3,4)
+ ratios[(6,7)] = safe_ratio(6,7)
+
+ # Group 6 — knees
+ if all(keypoint_valid(i) for i in [0,1,2,5,14,15,16,17,3,6,8,11,4,7,9,12]):
+ ratios[(8,9)] = safe_ratio(8,9)
+ ratios[(11,12)] = safe_ratio(11,12)
+ ratios[(9,10)] = ratios[parent_map[(9,10)]]
+ ratios[(12,13)]= ratios[parent_map[(12,13)]]
+
+ # Full body — all ratios
+ if all(keypoint_valid(i) for i in range(18)):
+ for p in ratio_pairs:
+ ratios[p] = safe_ratio(*p)
+
+ symmetric_pairs = [
+ ((1, 2), (1, 5)), # 两肩
+ ((2, 3), (5, 6)), # 上臂
+ ((3, 4), (6, 7)), # 前臂
+ ((8, 9), (11, 12)), # 大腿
+ ((9, 10), (12, 13)) # 小腿
+ ]
+ for left_key, right_key in symmetric_pairs:
+ left_val = ratios.get(left_key)
+ right_val = ratios.get(right_key)
+ if left_val is not None and right_val is not None:
+ avg_val = (left_val + right_val) / 2.0
+ ratios[left_key] = avg_val
+ ratios[right_key] = avg_val
+
+ eye_pairs = [
+ ((13, 15), (14, 16))
+ ]
+ for left_key, right_key in eye_pairs:
+ left_val = ratios.get(left_key)
+ right_val = ratios.get(right_key)
+ if left_val is not None and right_val is not None:
+ avg_val = (left_val + right_val) / 2.0
+ ratios[left_key] = avg_val
+ ratios[right_key] = avg_val
+
+ return ratios
+
+def align_to_pose(ref_dwpose, tpl_dwposes,anchor_idx=None,conf_th=0.9,):
+ detected_poses = copy.deepcopy(tpl_dwposes)
+
+ th = 1e-6
+ if anchor_idx is None:
+ best_pose, _ = pick_good_source_frame(ref_dwpose, tpl_dwposes)
+ else:
+ best_pose = tpl_dwposes[anchor_idx]
+ ref_pose_scaled, _, _ = scale_and_translate_pose(ref_dwpose, best_pose, conf_th=conf_th)
+
+ ref_candidate = ref_pose_scaled['bodies']['candidate'].astype(np.float32)
+ ref_scores = ref_pose_scaled['bodies']['score'].astype(np.float32)
+
+ source_candidate = best_pose['bodies']['candidate'].astype(np.float32)
+ source_scores = best_pose['bodies']['score'].astype(np.float32)
+
+ has_ref_face = 'faces' in ref_pose_scaled and ref_pose_scaled['faces'] is not None and ref_pose_scaled['faces'].size > 0
+ if has_ref_face:
+ try:
+ ref68, _ = _to_68x2(ref_pose_scaled['faces'])
+ except Exception as e:
+ print("参考脸转换失败:", e)
+ has_ref_face = False
+
+ ratios = compute_ratios_stepwise(ref_scores, source_scores, ref_candidate, source_candidate, conf_th=conf_th, th=1e-6)
+
+ for pose in detected_poses:
+ candidate = pose['bodies']['candidate']
+ faces = pose['faces']
+ hands = pose['hands']
+
+ # ===== Neck =====
+ ratio = ratios[(0, 1)]
+ x_offset = (candidate[1][0] - candidate[0][0]) * (1. - ratio)
+ y_offset = (candidate[1][1] - candidate[0][1]) * (1. - ratio)
+ candidate[[0, 14, 15, 16, 17], 0] += x_offset
+ candidate[[0, 14, 15, 16, 17], 1] += y_offset
+
+ # ===== Shoulder Right =====
+ ratio = ratios[(1, 2)]
+ x_offset = (candidate[1][0] - candidate[2][0]) * (1. - ratio)
+ y_offset = (candidate[1][1] - candidate[2][1]) * (1. - ratio)
+ candidate[[2, 3, 4], 0] += x_offset
+ candidate[[2, 3, 4], 1] += y_offset
+ hands[1, :, 0] += x_offset
+ hands[1, :, 1] += y_offset
+
+ # ===== Shoulder Left =====
+ ratio = ratios[(1, 5)]
+ x_offset = (candidate[1][0] - candidate[5][0]) * (1. - ratio)
+ y_offset = (candidate[1][1] - candidate[5][1]) * (1. - ratio)
+ candidate[[5, 6, 7], 0] += x_offset
+ candidate[[5, 6, 7], 1] += y_offset
+ hands[0, :, 0] += x_offset
+ hands[0, :, 1] += y_offset
+
+ # ===== Upper Arm Right =====
+ ratio = ratios[(2, 3)]
+ x_offset = (candidate[2][0] - candidate[3][0]) * (1. - ratio)
+ y_offset = (candidate[2][1] - candidate[3][1]) * (1. - ratio)
+ candidate[[3, 4], 0] += x_offset
+ candidate[[3, 4], 1] += y_offset
+ hands[1, :, 0] += x_offset
+ hands[1, :, 1] += y_offset
+
+ # ===== Forearm Right =====
+ ratio = ratios[(3, 4)]
+ x_offset = (candidate[3][0] - candidate[4][0]) * (1. - ratio)
+ y_offset = (candidate[3][1] - candidate[4][1]) * (1. - ratio)
+ candidate[4, 0] += x_offset
+ candidate[4, 1] += y_offset
+ hands[1, :, 0] += x_offset
+ hands[1, :, 1] += y_offset
+
+ # ===== Upper Arm Left =====
+ ratio = ratios[(5, 6)]
+ x_offset = (candidate[5][0] - candidate[6][0]) * (1. - ratio)
+ y_offset = (candidate[5][1] - candidate[6][1]) * (1. - ratio)
+ candidate[[6, 7], 0] += x_offset
+ candidate[[6, 7], 1] += y_offset
+ hands[0, :, 0] += x_offset
+ hands[0, :, 1] += y_offset
+
+ # ===== Forearm Left =====
+ ratio = ratios[(6, 7)]
+ x_offset = (candidate[6][0] - candidate[7][0]) * (1. - ratio)
+ y_offset = (candidate[6][1] - candidate[7][1]) * (1. - ratio)
+ candidate[7, 0] += x_offset
+ candidate[7, 1] += y_offset
+ hands[0, :, 0] += x_offset
+ hands[0, :, 1] += y_offset
+
+ # ===== Head parts =====
+ for (p1, p2) in [(0,14),(0,15),(14,16),(15,17)]:
+ ratio = ratios[(p1,p2)]
+ x_offset = (candidate[p1][0] - candidate[p2][0]) * (1. - ratio)
+ y_offset = (candidate[p1][1] - candidate[p2][1]) * (1. - ratio)
+ candidate[p2, 0] += x_offset
+ candidate[p2, 1] += y_offset
+
+ # ===== Hips (added) =====
+ ratio = ratios[(1, 8)]
+ x_offset = (candidate[1][0] - candidate[8][0]) * (1. - ratio)
+ y_offset = (candidate[1][1] - candidate[8][1]) * (1. - ratio)
+ candidate[8, 0] += x_offset
+ candidate[8, 1] += y_offset
+
+ ratio = ratios[(1, 11)]
+ x_offset = (candidate[1][0] - candidate[11][0]) * (1. - ratio)
+ y_offset = (candidate[1][1] - candidate[11][1]) * (1. - ratio)
+ candidate[11, 0] += x_offset
+ candidate[11, 1] += y_offset
+
+ # ===== Legs =====
+ ratio = ratios[(8, 9)]
+ x_offset = (candidate[9][0] - candidate[8][0]) * (ratio - 1.)
+ y_offset = (candidate[9][1] - candidate[8][1]) * (ratio - 1.)
+ candidate[[9, 10], 0] += x_offset
+ candidate[[9, 10], 1] += y_offset
+
+ ratio = ratios[(9, 10)]
+ x_offset = (candidate[10][0] - candidate[9][0]) * (ratio - 1.)
+ y_offset = (candidate[10][1] - candidate[9][1]) * (ratio - 1.)
+ candidate[10, 0] += x_offset
+ candidate[10, 1] += y_offset
+
+ ratio = ratios[(11, 12)]
+ x_offset = (candidate[12][0] - candidate[11][0]) * (ratio - 1.)
+ y_offset = (candidate[12][1] - candidate[11][1]) * (ratio - 1.)
+ candidate[[12, 13], 0] += x_offset
+ candidate[[12, 13], 1] += y_offset
+
+ ratio = ratios[(12, 13)]
+ x_offset = (candidate[13][0] - candidate[12][0]) * (ratio - 1.)
+ y_offset = (candidate[13][1] - candidate[12][1]) * (ratio - 1.)
+ candidate[13, 0] += x_offset
+ candidate[13, 1] += y_offset
+
+ # rough align
+ if has_ref_face and 'faces' in pose and pose['faces'] is not None and pose['faces'].size > 0:
+ try:
+ src68, to_orig = _to_68x2(pose['faces'])
+ scaled68 = _face_scale_only(src68, ref68, candidate[0], alpha=1.0)
+ pose['faces'] = to_orig(scaled68)
+ except Exception as e:
+ print("换脸失败:", e)
+ continue
+
+ return detected_poses
+
+
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/infer_preprocess.py b/One-to-All-Animation/video-generation/infer_preprocess.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1aab4490f23fff66e3e0fce0d336cc5c16d5aaa
--- /dev/null
+++ b/One-to-All-Animation/video-generation/infer_preprocess.py
@@ -0,0 +1,108 @@
+from infer_utils import load_poses_whole_video, resizecrop
+import os
+import cv2
+import json
+import argparse
+import numpy as np
+import glob
+from PIL import Image
+from functools import partial
+
+import decord
+from unit_test.io_utils import save_video
+from concurrent.futures import ThreadPoolExecutor
+from tqdm import tqdm
+
+# Output directory
+cache_base_dir="../input_cache"
+
+# ref_path, video_path, interval, align, mode, h, w, face_change, head_change, without_face
+# interval: Frame interval (sample every N frames)
+# align: Whether to perform retargeting (True/False)
+# mode: Alignment mode
+# - "ref": Align to reference image
+# - "pose": Use original driving video
+# h: Output height
+# w: Output width
+# face_change: Whether to fade facial landmarks (True: fade, False: normal color)
+# head_change: Whether to fade head landmarks (True: fade, False: normal color)
+# without_face: Whether to skip drawing facial landmarks (True: skip, False: draw)
+#
+task_list = [
+ ("../examples/img.png","../examples/vid.mp4",1,True,"ref","","",True,False,False),
+ ("../examples/joker2_resize.png","../examples/douyinvid5_v2.mp4",1,False,"pose","","",True,True,False),
+ ("../examples/musk.jpg","../examples/vid2.mp4",1,True,"ref","","",True,False,False),
+ ("../examples/maodie.png","../examples/vid2.mp4",1,True,"ref","","",True,True,False),
+]
+
+def process_one(reference_path, video_path, frame_interval, do_align, alignmode, h=None, w=None, face_change=True, head_change=True, without_face=False):
+
+ if not h or not w:
+ ref_img_tmp = Image.open(reference_path).convert("RGB")
+ w, h = ref_img_tmp.size
+ else:
+ h = int(h)
+ w = int(w)
+
+
+ max_short = 768
+ if min(h, w) > max_short:
+ if h < w:
+ scale = max_short / h
+ h, w = max_short, int(w * scale)
+ else:
+ scale = max_short / w
+ w, h = max_short, int(h * scale)
+ new_h = (h // 16) * 16
+ new_w = (w // 16) * 16
+ transform = partial(resizecrop, th=new_h, tw=new_w)
+ anchor_idx = 0
+
+ pose_tensor, image_input, pose_input, mask_input = load_poses_whole_video(
+ video_path=video_path,
+ reference=reference_path,
+ frame_interval=frame_interval,
+ do_align=do_align,
+ transform=transform,
+ alignmode=alignmode,
+ anchor_idx=anchor_idx,
+ face_change=face_change,
+ head_change=head_change,
+ without_face=without_face,
+ )
+
+
+ if os.path.isdir(video_path):
+ fps = 30
+ print(f"⚠ {video_path} isdir, use default fps={fps}")
+ else:
+ vr = decord.VideoReader(video_path)
+ fps = vr.get_avg_fps()
+
+ output_fps = fps / frame_interval
+
+
+ video_tensor = pose_tensor / 255 * 2 - 1
+
+
+ vidname = os.path.splitext(os.path.basename(video_path))[0]
+ refname = os.path.splitext(os.path.basename(reference_path))[0]
+ cache_dir = os.path.join(cache_base_dir, f"ref_{refname}_driven_{vidname}_align_{alignmode}_h_{new_h}_w_{new_w}_fps_{output_fps}")
+ os.makedirs(cache_dir, exist_ok=True)
+
+
+ save_video(os.path.join(cache_dir, "pose.mp4"), video_tensor, fps=output_fps)
+ image_input.save(os.path.join(cache_dir, "image_input.png"))
+ pose_input.save(os.path.join(cache_dir, "pose_input.png"))
+ mask_input.save(os.path.join(cache_dir, "mask_input.png"))
+
+if __name__ == "__main__":
+ with ThreadPoolExecutor(max_workers=1) as executor:
+ futures = []
+ for ref_path, video_path , interval, align, mode, h, w, face_change, head_change, without_face in task_list:
+ futures.append(executor.submit(process_one, ref_path, video_path, interval, align, mode, h, w, face_change, head_change, without_face))
+
+ for f in tqdm(futures):
+ f.result()
+
+
diff --git a/One-to-All-Animation/video-generation/infer_utils.py b/One-to-All-Animation/video-generation/infer_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4da6c24fd390ff08b38c65ccbc0da0d929443efd
--- /dev/null
+++ b/One-to-All-Animation/video-generation/infer_utils.py
@@ -0,0 +1,207 @@
+from opensora.dataset.utils import draw_pose_aligned
+import os
+import torch
+from einops import rearrange
+import copy
+import random
+import math
+import cv2
+from PIL import Image
+import numpy as np
+import matplotlib.pyplot as plt
+import decord
+from functools import partial
+import glob
+from dwpose_utils.dwpose_detector import dwpose_detector_aligned
+from wanpose_utils.pose2d import Pose2d
+
+from infer_function import *
+
+pose2d_checkpoint_path = "../pretrained_models/process_checkpoint/pose2d/vitpose_h_wholebody.onnx"
+det_checkpoint_path = "../pretrained_models/process_checkpoint/det/yolov10m.onnx"
+
+wanpose2d = Pose2d(checkpoint=pose2d_checkpoint_path, detector_checkpoint=det_checkpoint_path)
+
+
+def warp_ref_to_pose(tgt_img,
+ ref_pose: dict, #driven pose
+ tgt_pose: dict,
+ bg_val=(0, 0, 0),
+ conf_th=0.9,
+ align_center=False):
+
+ H, W = tgt_img.shape[:2]
+ img_tgt_pose = draw_pose_aligned(tgt_pose, H, W, without_face=True)
+
+ tgt_kpt = tgt_pose['bodies']['candidate'].astype(np.float32)
+ ref_kpt = ref_pose['bodies']['candidate'].astype(np.float32)
+
+ scale_ratio = scale_and_translate_pose(tgt_pose, ref_pose, conf_th=conf_th, return_ratio=True)
+
+ anchor_idx = 1
+ x0 = tgt_kpt[anchor_idx][0] * W
+ y0 = tgt_kpt[anchor_idx][1] * H
+
+ ref_x = ref_kpt[anchor_idx][0] * W if not align_center else W/2
+ ref_y = ref_kpt[anchor_idx][1] * H
+
+ dx = ref_x - x0
+ dy = ref_y - y0
+
+ # 仿射变换矩阵
+ M = np.array([[scale_ratio, 0, (1-scale_ratio)*x0 + dx],
+ [0, scale_ratio, (1-scale_ratio)*y0 + dy]],
+ dtype=np.float32)
+ img_warp = cv2.warpAffine(tgt_img, M, (W, H),
+ flags=cv2.INTER_LINEAR,
+ borderValue=bg_val)
+ img_tgt_pose_warp = cv2.warpAffine(img_tgt_pose, M, (W, H),
+ flags=cv2.INTER_LINEAR,
+ borderValue=bg_val)
+ zeros = np.zeros((H, W), dtype=np.uint8)
+ mask_warp = cv2.warpAffine(zeros, M, (W, H),
+ flags=cv2.INTER_NEAREST,
+ borderValue=255)
+ return img_warp, img_tgt_pose_warp, mask_warp
+
+
+
+
+def load_poses_whole_video(video_path,
+ reference,
+ frame_interval= 2,
+ transform = None,
+ do_align = False,
+ alignmode = "ref", #align to reference or align to pose
+ face_change = False, #lighten color
+ head_change = False, #lighten color
+ anchor_idx = 0,
+ without_face = False ):
+
+ # ---------------- ref dwpose ---------------- #
+ ref_pose = None
+ ref_pose_tensor = None
+
+ ref_img = Image.open(reference).convert('RGB')
+
+ h_ref, w_ref = ref_img.height, ref_img.width
+ ref_rgb = np.array(ref_img)
+
+ ref_pose_meta = wanpose2d([ref_rgb])[0]
+ ref_dwpose = aaposemeta_to_dwpose(ref_pose_meta)
+
+ # ---------------- driven pose ---------------- #
+ if os.path.isdir(video_path):
+ img_paths = sorted(glob.glob(os.path.join(video_path, "*.png")))
+ assert img_paths, f"NO PNG in {video_path}!!"
+ frames_list = []
+ for p in img_paths:
+ img = Image.open(p).convert("RGB")
+ img = resizecrop(img, th=h_ref, tw=w_ref)
+ frames_list.append(np.array(img))
+ frames = np.stack(frames_list)
+ total_frames = len(frames_list)
+ frame_indices = np.arange(0, total_frames, frame_interval).astype(int)
+ frames = frames[frame_indices]
+ h, w = frames[0].shape[:2]
+ else:
+ vr = decord.VideoReader(video_path)
+ total_frames = len(vr)
+ frame_indices = np.arange(0, total_frames, frame_interval).astype(int)
+ frames = vr.get_batch(frame_indices).asnumpy()
+ frames_resized = []
+ for fr in frames:
+ pil_fr = Image.fromarray(fr)
+ pil_fr = resizecrop(pil_fr, th=h_ref, tw=w_ref)
+ frames_resized.append(np.array(pil_fr))
+ frames = np.stack(frames_resized)
+ h, w = frames[0].shape[:2]
+
+ tpl_pose_metas = wanpose2d(frames)
+ tpl_dwposes = [aaposemeta_to_dwpose(meta) for meta in tpl_pose_metas]
+
+ # ---------------- retarget ---------------- #
+
+ if alignmode == "ref":
+ image_input = transform(ref_img)
+ pose_input = draw_pose_aligned(ref_dwpose, h, w, without_face=True)
+ pose_input = transform(Image.fromarray(pose_input))
+ mask_input = Image.new("RGB", image_input.size, (0, 0, 0))
+ if do_align:
+ tpl_dwposes = align_to_reference(ref_pose_meta, tpl_pose_metas, tpl_dwposes, anchor_idx)
+
+
+
+ elif alignmode == "pose":
+ # import pdb;pdb.set_trace()
+ image_input, pose_input, mask_input = warp_ref_to_pose(ref_rgb, tpl_dwposes[anchor_idx], ref_dwpose)
+ image_input = transform(Image.fromarray(image_input))
+ pose_input = transform(Image.fromarray(pose_input))
+ mask_input = transform(Image.fromarray(mask_input).convert("RGB"))
+ # rescale-ref and change part of pose
+ if do_align:
+ tpl_dwposes = align_to_pose(ref_dwpose, tpl_dwposes, anchor_idx)
+
+ # ---------------- draw pose & transform ---------------- #
+ pose_imgs = []
+ for pose_np in tpl_dwposes:
+ pose_img = draw_pose_aligned(pose_np, h, w, without_face=without_face,face_change=face_change,head_change=head_change)
+ pose_img = transform(Image.fromarray(pose_img))
+ pose_img = torch.from_numpy(np.array(pose_img))
+ pose_img = rearrange(pose_img, 'h w c -> c h w')
+ pose_imgs.append(pose_img)
+
+ pose_tensor = torch.stack(pose_imgs) # (T,C,H,W)
+
+ return pose_tensor, image_input, pose_input, mask_input
+
+
+def resizecrop(image, th, tw):
+ w, h = image.size
+ if h / w > th / tw:
+ new_w = int(w)
+ new_h = int(new_w * th / tw)
+ else:
+ new_h = int(h)
+ new_w = int(new_h * tw / th)
+ left = (w - new_w) / 2
+ top = (h - new_h) / 2
+ right = (w + new_w) / 2
+ bottom = (h + new_h) / 2
+ image = image.crop((left, top, right, bottom))
+ image = image.resize((tw, th))
+ return image
+
+
+
+
+if __name__ == "__main__":
+ video_path = "xxx"
+ ref_image_path = "xxx"
+ vr = decord.VideoReader(video_path)
+ fps = vr.get_avg_fps()
+ new_height = 1024
+ new_width = 572
+ transform = partial(resizecrop, th=new_height, tw=new_width)
+ print("video_fps:",fps)
+
+ # 调用函数
+ pose_tensor,image_input, pose_input, mask_input = load_poses_whole_video(
+ video_path=video_path,
+ reference=ref_image_path,
+ frame_interval=1,
+ transform=transform,
+ do_align = True,
+ alignmode="pose",
+ face_change=True,
+ head_change=False,
+ without_face=False,
+ anchor_idx=0,
+ )
+ import pdb;pdb.set_trace()
+ from unit_test.io_utils import save_video
+ video_tensor = pose_tensor / 255 * 2 - 1
+ save_video("pose.mp4", video_tensor,fps=fps)
+
+ # print("Pose tensor shape:", pose_tensor.shape)
+
diff --git a/One-to-All-Animation/video-generation/inference_1.3b.py b/One-to-All-Animation/video-generation/inference_1.3b.py
new file mode 100644
index 0000000000000000000000000000000000000000..15c78092ad7380e9615feef96fc8a52e9ec289ae
--- /dev/null
+++ b/One-to-All-Animation/video-generation/inference_1.3b.py
@@ -0,0 +1,448 @@
+import os
+import glob
+import torch
+import decord
+import imageio
+from PIL import Image
+import torch.multiprocessing as mp
+# os.environ["CUDA_VISIBLE_DEVICES"] = "0,5,6,7"
+from functools import partial
+from tqdm import tqdm
+from datetime import datetime
+
+import numpy as np
+from safetensors.torch import load_file as safe_load
+from opensora.sample.pipeline_wanx_vhuman_tokenreplace import WanPipeline
+from opensora.model_variants.wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D_Controlnet_prefix
+from opensora.encoder_variants import get_text_enc
+from opensora.vae_variants import get_vae
+from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
+
+# ===== Config =====
+model_path = "../pretrained_models/Wan2.1-T2V-1.3B-Diffusers"
+vae_path = "../pretrained_models/Wan2.1-T2V-1.3B-Diffusers/vae"
+config_path = "configs/wan2.1_t2v_1.3b.json"
+model_dtype = torch.bfloat16
+
+ckpt_paths = [
+ # "../checkpoints/One-to-All-1.3b_1",
+ "../checkpoints/One-to-All-1.3b_2",
+]
+default_cfg_combos = [
+ (2.5, 1.5), # 3x inference time
+ # (1.5, 0), # 2x inference time
+]
+cache_base_dir="../input_cache"
+# Modified: Use StableSigner3 generated pose videos
+pose_video_dir = "../../generated_pose_video"
+ref_image_dir = "../../ref_img_dict"
+output_base_dir = "../../generated_sign_video" # 修改:输出到 generated_sign_video
+max_short = 384
+
+MAIN_CHUNK = 81
+OVERLAP_FRAMES = 5
+FINAL_CHUNK_CANDIDATES = [65, 69, 73, 77, 81]
+
+negative_prompt = [
+ "black background, Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion"
+]
+black_pose_cfg = True
+black_image_cfg = True
+controlnet_conditioning_scale = 1.0
+case1 = False
+
+
+def resizecrop(image, th, tw):
+ w, h = image.size
+ if h / w > th / tw:
+ new_w = int(w)
+ new_h = int(new_w * th / tw)
+ else:
+ new_h = int(h)
+ new_w = int(new_h * tw / th)
+ left = (w - new_w) / 2
+ top = (h - new_h) / 2
+ right = (w + new_w) / 2
+ bottom = (h + new_h) / 2
+ image = image.crop((left, top, right, bottom))
+ image = image.resize((tw, th))
+ return image
+
+
+def build_pipe(device, ckpt_path):
+ scheduler = FlowMatchEulerDiscreteScheduler(
+ shift=7.0,
+ num_train_timesteps=1000,
+ use_dynamic_shifting=False
+ )
+
+ vae = get_vae('wanx', vae_path, model_dtype)
+ encoders = get_text_enc('wanx-t2v', model_path, model_dtype)
+ text_encoder = encoders.text_encoder
+ tokenizer = encoders.tokenizer
+
+ model = WanTransformer3DModel_Refextractor_2D_Controlnet_prefix.from_config(config_path).to(model_dtype)
+ model.set_up_controlnet("configs/wan2.1_t2v_1.3b_controlnet_2.json", model_dtype)
+ model.set_up_refextractor("configs/wan2.1_t2v_1.3b_refextractor_2d_withmask2.json", model_dtype)
+ model.eval()
+ model.requires_grad_(False)
+ # load ckpt
+ checkpoint = {}
+ shard_files = [f for f in os.listdir(ckpt_path) if f.endswith(".safetensors")]
+ for shard_file in shard_files:
+ sd = safe_load(os.path.join(ckpt_path, shard_file), device='cpu')
+ checkpoint.update(sd)
+ model.load_state_dict(checkpoint, strict=True)
+
+ pipe = WanPipeline(
+ transformer=model,
+ vae=vae.vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ scheduler=scheduler
+ )
+ pipe.to(device, dtype=model_dtype)
+ return pipe
+
+
+def build_split_plan(total_len: int):
+ ranges = []
+ start = 0
+ while True:
+ current_chunk_end = start + MAIN_CHUNK
+ next_chunk_start = start + (MAIN_CHUNK - OVERLAP_FRAMES)
+ if next_chunk_start + MAIN_CHUNK >= total_len:
+ ranges.append((start, current_chunk_end))
+ final_chunk_start = -1
+ for length in FINAL_CHUNK_CANDIDATES:
+ potential_start = total_len - length
+ if potential_start < current_chunk_end - OVERLAP_FRAMES:
+ final_chunk_start = potential_start
+ break
+ if final_chunk_start == -1:
+ final_chunk_start = next_chunk_start
+ ranges.append((final_chunk_start, total_len))
+ break
+ else:
+ ranges.append((start, current_chunk_end))
+ start = next_chunk_start
+ return ranges
+
+
+def read_pose_video(pose_mp4_path, transform_fn=None):
+ vr = decord.VideoReader(pose_mp4_path)
+ fps = vr.get_avg_fps() if vr.get_avg_fps() > 0 else 30
+ frames_list = []
+ for frame in vr:
+ frame_np = frame.asnumpy()
+ if transform_fn:
+ pil_img = Image.fromarray(frame_np)
+ pil_img = transform_fn(pil_img)
+ frame_np = np.array(pil_img)
+ frames_list.append(frame_np)
+
+ frames_np = np.stack(frames_list)
+ tensor = torch.from_numpy(frames_np).float().permute(3, 0, 1, 2) / 255.0 * 2 - 1
+ tensor = tensor.unsqueeze(0)
+ return tensor, int(fps)
+
+
+def find_cache_dir(cache_dir_root, ref_path, vid_path, alignmode):
+ refname = os.path.splitext(os.path.basename(ref_path))[0]
+ vidname = os.path.splitext(os.path.basename(vid_path))[0]
+ job_name = f"ref_{refname}_vid_{vidname}"
+ pattern = os.path.join(
+ cache_dir_root,
+ f"ref_{refname}_driven_{vidname}_align_{alignmode}_*"
+ )
+ matches = glob.glob(pattern)
+ if not matches:
+ raise FileNotFoundError(f"❌ 未找到缓存目录: {pattern}")
+ if len(matches) > 1:
+ print(f"⚠ 匹配到多个缓存目录,取第一个: {matches}")
+ return matches[0],job_name
+
+
+def unified_worker(rank, world_size, task_list, ckpt_path, use_direct_paths=False):
+ torch.cuda.set_device(rank)
+ device = f"cuda:{rank}"
+ pipe = build_pipe(device, ckpt_path)
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+ for idx, task_info in enumerate(task_list):
+ if idx % world_size != rank:
+ continue
+
+ # Extract task info based on mode
+ if use_direct_paths:
+ job_name = task_info['job_name']
+ ref_path = task_info['ref_path']
+ pose_video_path = task_info['pose_video_path']
+ new_h = task_info['new_h']
+ new_w = task_info['new_w']
+ ref_cfg = task_info['ref_cfg']
+ pose_cfg = task_info['pose_cfg']
+ prompt = task_info['prompt']
+ print(f"[GPU {rank}] 开始任务 (直接路径模式): {pose_video_path}")
+ else:
+ job_name = task_info['job_name']
+ cache_dir = task_info['cache_dir']
+ new_h = task_info['new_h']
+ new_w = task_info['new_w']
+ ref_cfg = task_info['ref_cfg']
+ pose_cfg = task_info['pose_cfg']
+ prompt = task_info['prompt']
+ print(f"[GPU {rank}] 开始任务: {cache_dir}")
+
+ output_root = os.path.join(output_base_dir, f"{current_date}_ref_{ref_cfg}_pose_{pose_cfg}")
+ frames_output_dir = os.path.join(output_root, f"{job_name}_ref_{ref_cfg}_pose_{pose_cfg}")
+ os.makedirs(frames_output_dir, exist_ok=True)
+ final_video_path = os.path.join(output_root, f"{job_name}_ref_{ref_cfg}_pose_{pose_cfg}.mp4")
+ if os.path.exists(final_video_path):
+ print(f"[GPU {rank}] {final_video_path} 已存在,跳过")
+ continue
+
+ # 读取输入 - Different logic for direct paths vs cache
+ if use_direct_paths:
+ # Direct paths mode: read from specified paths
+ image_input = Image.open(ref_path).convert("RGB")
+
+ if new_h and new_w:
+ new_h = float(new_h)
+ new_w = float(new_w)
+ else:
+ new_h, new_w = image_input.height, image_input.width
+
+ if min(new_h, new_w) > max_short:
+ if new_h < new_w:
+ scale = max_short / new_h
+ new_h, new_w = max_short, int(new_w * scale)
+ else:
+ scale = max_short / new_w
+ new_w, new_h = max_short, int(new_h * scale)
+
+ new_h, new_w = int(new_h//16*16), int(new_w//16*16)
+ transform_fn = partial(resizecrop, th=new_h, tw=new_w)
+ image_input = transform_fn(image_input)
+
+ # Read pose video directly
+ pose_tensor, pose_fps = read_pose_video(pose_video_path, transform_fn)
+
+ # Use first frame as pose_input
+ first_frame_np = ((pose_tensor[0, :, 0] / 2 + 0.5).clamp(0, 1) * 255).byte().permute(1, 2, 0).numpy()
+ pose_input_img = Image.fromarray(first_frame_np.astype(np.uint8))
+
+ # Create empty mask (all black = no masking)
+ mask_input = Image.new("L", (new_w, new_h), 0)
+
+ else:
+ # Original cache mode
+ print(f"[GPU {rank}] 处理: {cache_dir}")
+ image_input = Image.open(os.path.join(cache_dir, "image_input.png")).convert("RGB")
+ if new_h and new_w:
+ new_h = float(new_h)
+ new_w = float(new_w)
+ else:
+ new_h, new_w = image_input.height, image_input.width
+
+ if min(new_h, new_w) > max_short:
+ if new_h < new_w:
+ scale = max_short / new_h
+ new_h, new_w = max_short, int(new_w * scale)
+ else:
+ scale = max_short / new_w
+ new_w, new_h = max_short, int(new_h * scale)
+
+ new_h, new_w = int(new_h//16*16), int(new_w//16*16)
+ transform_fn = partial(resizecrop, th=new_h, tw=new_w)
+ image_input = transform_fn(image_input)
+
+ pose_tensor, pose_fps = read_pose_video(os.path.join(cache_dir, "pose.mp4"), transform_fn)
+ pose_input_img = Image.open(os.path.join(cache_dir, "pose_input.png")).convert("RGB")
+ pose_input_img = transform_fn(pose_input_img)
+ mask_input = Image.open(os.path.join(cache_dir, "mask_input.png")).convert("L")
+ mask_input = transform_fn(mask_input)
+
+ # Common processing for both modes
+ mask_np = np.array(mask_input, dtype=np.float32) / 255.0
+ mask_tensor = torch.from_numpy(mask_np).unsqueeze(0).unsqueeze(0).unsqueeze(2)
+
+ src_pose_tensor = torch.from_numpy(np.array(pose_input_img)).unsqueeze(0).float().permute(0, 3, 1, 2) / 255.0 * 2 - 1
+ src_pose_tensor = src_pose_tensor.unsqueeze(2)
+
+ split_plan = build_split_plan(pose_tensor.shape[2])
+ all_generated_frames_np = {}
+
+ for idx, (start, end) in enumerate(split_plan):
+ # Debug mode: uncomment break to only infer the first segment
+ # if idx > 0:
+ # break
+ sub_video = pose_tensor[:, :, start:end] # [B=1, C, T, H, W]
+ prev_frames = None
+ if start > 0:
+ needed_idx = range(start, start + OVERLAP_FRAMES)
+ if all(k in all_generated_frames_np for k in needed_idx):
+ prev_frames = [
+ Image.fromarray(all_generated_frames_np[k]) for k in needed_idx
+ ]
+
+ output_chunk = pipe(
+ image=image_input,
+ image_mask=mask_tensor,
+ control_video=sub_video,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ height=new_h,
+ width=new_w,
+ num_frames=end - start,
+ image_guidance_scale=ref_cfg,
+ pose_guidance_scale=pose_cfg,
+ num_inference_steps=30,
+ generator=torch.Generator(device=device).manual_seed(42),
+ black_image_cfg=black_image_cfg,
+ black_pose_cfg=black_pose_cfg,
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
+ return_tensor=True,
+ case1=case1,
+ token_replace=(prev_frames is not None),
+ prev_frames=prev_frames,
+ image_pose=src_pose_tensor
+ ).frames
+
+
+ output_chunk = (
+ output_chunk[0].detach().cpu() / 2 + 0.5
+ ).float().clamp(0, 1).permute(1, 2, 3, 0).numpy()
+ output_chunk = (output_chunk * 255).astype("uint8")
+
+ for j in range(end - start):
+ gidx = start + j
+ all_generated_frames_np[gidx] = output_chunk[j]
+ imageio.imwrite(os.path.join(frames_output_dir, f"frame_{gidx:06d}.png"), output_chunk[j])
+
+ alpha = 0.6
+ frames_combined = []
+
+ src_uint8 = ((pose_tensor / 2 + 0.5).clamp(0, 1) * 255
+ )[0].byte().permute(1, 2, 3, 0).numpy() # (T,H,W,C)
+ sorted_idx = sorted(all_generated_frames_np.keys())
+
+
+ for t in sorted_idx:
+ src = src_uint8[t].astype(np.float32)
+ pred = all_generated_frames_np[t].astype(np.float32)
+ blended = (alpha * src + (1 - alpha) * pred).round().astype(np.uint8)
+ concat = np.concatenate([blended, pred.astype(np.uint8)], axis=1) # (H,2W,C)
+ frames_combined.append(concat)
+
+ imageio.mimwrite(
+ final_video_path,
+ frames_combined,
+ fps=pose_fps,
+ quality=5
+ )
+
+ print(f"[GPU {rank}] 完成视频: {final_video_path}")
+ del pipe
+ torch.cuda.empty_cache()
+
+
+def run_all_tasks(ckpt_path, img_g, pose_g, cache_dir_root="input_cache2", use_direct_paths=False):
+ """扫描 cache 目录,跑全部任务"""
+ # Modified: Direct paths mode for StableSigner3 generated videos
+ # Format: (ref_image_path, pose_video_path, new_h, new_w, ref_cfg, pose_cfg, prompt)
+ # If use_direct_paths=True, directly use pose video without cache
+ if use_direct_paths:
+ task_list = [
+ # Example: Use your generated pose video
+ (f"{ref_image_dir}/square2.jpg",
+ f"{pose_video_dir}/I_NEED_HELP_PLEASE_28794_37894_69364_43226_20251212_150521.mp4",
+ "", "", "", "", ""),
+ ]
+
+ task_list_resolved = []
+ for ref_path, pose_video_path, new_h, new_w, ref_cfg, pose_cfg, prompt in task_list:
+ if not ref_cfg: ref_cfg = img_g
+ else: ref_cfg = float(ref_cfg)
+ if not pose_cfg: pose_cfg = pose_g
+ else: pose_cfg = float(pose_cfg)
+
+ if not os.path.exists(ref_path):
+ print(f"❌ Reference image not found: {ref_path}")
+ continue
+ if not os.path.exists(pose_video_path):
+ print(f"❌ Pose video not found: {pose_video_path}")
+ continue
+
+ refname = os.path.splitext(os.path.basename(ref_path))[0]
+ vidname = os.path.splitext(os.path.basename(pose_video_path))[0]
+ job_name = f"ref_{refname}_vid_{vidname}"
+
+ # Create a simple dict to hold paths
+ task_info = {
+ 'ref_path': ref_path,
+ 'pose_video_path': pose_video_path,
+ 'job_name': job_name,
+ 'new_h': new_h,
+ 'new_w': new_w,
+ 'ref_cfg': ref_cfg,
+ 'pose_cfg': pose_cfg,
+ 'prompt': prompt
+ }
+ task_list_resolved.append(task_info)
+ else:
+ # Original cache-based mode
+ task_list = [
+ ("../examples/img.png","../examples/vid.mp4","ref","","","","",""),
+ # text prompt for generation (especially important for misaligned/pose mode cases
+ ("../examples/joker2_resize.png","../examples/douyinvid5_v2.mp4","pose","","","","","a clown in a vibrant red suit dancing joyfully on a street, black shoes, with skyscrapers and neon lights in an urban city background, clear hand"),
+ ("../examples/musk.jpg","../examples/vid2.mp4","ref","","","","",""),
+ ("../examples/maodie.png","../examples/vid2.mp4","ref","","","","","a cat is dancing"),
+ ]
+
+ task_list_resolved = []
+ for ref_path, vid_path , alignmode, new_h, new_w, ref_cfg, pose_cfg, prompt in task_list:
+ if not ref_cfg: ref_cfg = img_g
+ else: ref_cfg = float(ref_cfg)
+ if not pose_cfg: pose_cfg = pose_g
+ else: pose_cfg = float(pose_cfg)
+
+ try:
+ cache_dir,job_name = find_cache_dir(cache_dir_root, ref_path, vid_path, alignmode)
+ except FileNotFoundError as e:
+ print(e)
+ continue
+
+ task_info = {
+ 'cache_dir': cache_dir,
+ 'job_name': job_name,
+ 'new_h': new_h,
+ 'new_w': new_w,
+ 'ref_cfg': ref_cfg,
+ 'pose_cfg': pose_cfg,
+ 'prompt': prompt
+ }
+ task_list_resolved.append(task_info)
+
+
+ world_size = torch.cuda.device_count()
+ mp.spawn(
+ unified_worker,
+ args=(world_size, task_list_resolved, ckpt_path, use_direct_paths),
+ nprocs=world_size,
+ join=True
+ )
+
+if __name__ == "__main__":
+ # Modified: Set to True to use direct paths from generated_pose_video
+ USE_DIRECT_PATHS = True
+
+ for ckpt in ckpt_paths:
+ for img_g, pose_g in default_cfg_combos:
+ print(f"\n===== ckpt: {ckpt} | img_g={img_g} | pose_g={pose_g} =====")
+ if USE_DIRECT_PATHS:
+ print("📁 使用直接路径模式: 从 generated_pose_video 读取")
+ run_all_tasks(ckpt, img_g, pose_g, use_direct_paths=True)
+ else:
+ print("📁 使用缓存模式: 从 input_cache 读取")
+ run_all_tasks(ckpt, img_g, pose_g, cache_dir_root=cache_base_dir, use_direct_paths=False)
diff --git a/One-to-All-Animation/video-generation/inference_14b.py b/One-to-All-Animation/video-generation/inference_14b.py
new file mode 100644
index 0000000000000000000000000000000000000000..f000a9bd71f860816f6300e28b02545e3a7509c9
--- /dev/null
+++ b/One-to-All-Animation/video-generation/inference_14b.py
@@ -0,0 +1,338 @@
+import os
+import glob
+import torch
+import decord
+import imageio
+from PIL import Image
+import torch.multiprocessing as mp
+# os.environ["CUDA_VISIBLE_DEVICES"] = "1,2,3,4"
+from functools import partial
+from tqdm import tqdm
+from datetime import datetime
+
+import numpy as np
+from safetensors.torch import load_file as safe_load
+from opensora.sample.pipeline_wanx_vhuman_tokenreplace import WanPipeline
+from opensora.model_variants.wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D_Controlnet_prefix
+from opensora.encoder_variants import get_text_enc
+from opensora.vae_variants import get_vae
+from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
+
+# ===== Config =====
+model_path = "../pretrained_models/Wan2.1-T2V-14B-Diffusers"
+vae_path = "../pretrained_models/Wan2.1-T2V-14B-Diffusers/vae"
+config_path = "configs/wan2.1_t2v_14b.json"
+model_dtype = torch.bfloat16
+
+ckpt_paths = [
+ "../checkpoints/One-to-All-14b",
+]
+default_cfg_combos = [
+ (2.0, 1.5), # 3x inference time
+ # (1.5, 0), # 2x inference time
+]
+cache_base_dir="../input_cache"
+output_base_dir = "../output/One-to-All-14b"
+max_short = 576
+
+MAIN_CHUNK = 81
+OVERLAP_FRAMES = 5
+FINAL_CHUNK_CANDIDATES = [65, 69, 73, 77, 81]
+
+negative_prompt = [
+ "black background, Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion"
+]
+black_pose_cfg = True
+black_image_cfg = True
+controlnet_conditioning_scale = 1.0
+case1 = False
+
+
+def resizecrop(image, th, tw):
+ w, h = image.size
+ if h / w > th / tw:
+ new_w = int(w)
+ new_h = int(new_w * th / tw)
+ else:
+ new_h = int(h)
+ new_w = int(new_h * tw / th)
+ left = (w - new_w) / 2
+ top = (h - new_h) / 2
+ right = (w + new_w) / 2
+ bottom = (h + new_h) / 2
+ image = image.crop((left, top, right, bottom))
+ image = image.resize((tw, th))
+ return image
+
+
+def build_pipe(device, ckpt_path):
+ scheduler = FlowMatchEulerDiscreteScheduler(
+ shift=7.0,
+ num_train_timesteps=1000,
+ use_dynamic_shifting=False
+ )
+
+ vae = get_vae('wanx', vae_path, model_dtype)
+ encoders = get_text_enc('wanx-t2v', model_path, model_dtype)
+ text_encoder = encoders.text_encoder
+ tokenizer = encoders.tokenizer
+
+ model = WanTransformer3DModel_Refextractor_2D_Controlnet_prefix.from_config(config_path).to(model_dtype)
+ model.set_up_controlnet("configs/wan2.1_t2v_14b_controlnet_1.json", model_dtype)
+ model.set_up_refextractor("configs/wan2.1_t2v_14b_refextractor_2d_withmask2.json", model_dtype)
+ model.eval()
+ model.requires_grad_(False)
+ # load ckpt
+ checkpoint = {}
+ shard_files = [f for f in os.listdir(ckpt_path) if f.endswith(".safetensors")]
+ for shard_file in shard_files:
+ sd = safe_load(os.path.join(ckpt_path, shard_file), device='cpu')
+ checkpoint.update(sd)
+ model.load_state_dict(checkpoint, strict=True)
+
+ pipe = WanPipeline(
+ transformer=model,
+ vae=vae.vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ scheduler=scheduler
+ )
+ pipe.to(device, dtype=model_dtype)
+ return pipe
+
+
+def build_split_plan(total_len: int):
+ ranges = []
+ start = 0
+ while True:
+ current_chunk_end = start + MAIN_CHUNK
+ next_chunk_start = start + (MAIN_CHUNK - OVERLAP_FRAMES)
+ if next_chunk_start + MAIN_CHUNK >= total_len:
+ ranges.append((start, current_chunk_end))
+ final_chunk_start = -1
+ for length in FINAL_CHUNK_CANDIDATES:
+ potential_start = total_len - length
+ if potential_start < current_chunk_end - OVERLAP_FRAMES:
+ final_chunk_start = potential_start
+ break
+ if final_chunk_start == -1:
+ final_chunk_start = next_chunk_start
+ ranges.append((final_chunk_start, total_len))
+ break
+ else:
+ ranges.append((start, current_chunk_end))
+ start = next_chunk_start
+ return ranges
+
+
+def read_pose_video(pose_mp4_path, transform_fn=None):
+ vr = decord.VideoReader(pose_mp4_path)
+ fps = vr.get_avg_fps() if vr.get_avg_fps() > 0 else 30
+ frames_list = []
+ for frame in vr:
+ frame_np = frame.asnumpy()
+ if transform_fn:
+ pil_img = Image.fromarray(frame_np)
+ pil_img = transform_fn(pil_img)
+ frame_np = np.array(pil_img)
+ frames_list.append(frame_np)
+
+ frames_np = np.stack(frames_list)
+ tensor = torch.from_numpy(frames_np).float().permute(3, 0, 1, 2) / 255.0 * 2 - 1
+ tensor = tensor.unsqueeze(0)
+ return tensor, int(fps)
+
+
+def find_cache_dir(cache_dir_root, ref_path, vid_path, alignmode):
+ refname = os.path.splitext(os.path.basename(ref_path))[0]
+ vidname = os.path.splitext(os.path.basename(vid_path))[0]
+ job_name = f"ref_{refname}_vid_{vidname}"
+ pattern = os.path.join(
+ cache_dir_root,
+ f"ref_{refname}_driven_{vidname}_align_{alignmode}_*"
+ )
+ matches = glob.glob(pattern)
+ if not matches:
+ raise FileNotFoundError(f"❌ 未找到缓存目录: {pattern}")
+ if len(matches) > 1:
+ print(f"⚠ 匹配到多个缓存目录,取第一个: {matches}")
+ return matches[0],job_name
+
+
+def unified_worker(rank, world_size, task_list, ckpt_path):
+ torch.cuda.set_device(rank)
+ device = f"cuda:{rank}"
+ pipe = build_pipe(device, ckpt_path)
+ current_date = datetime.now().strftime("%Y-%m-%d")
+
+
+
+
+ for idx, (job_name, cache_dir, new_h, new_w, ref_cfg, pose_cfg,prompt) in enumerate(task_list):
+ if idx % world_size != rank:
+ continue
+ print(f"[GPU {rank}] 开始任务: {cache_dir}")
+ output_root = os.path.join(output_base_dir, f"{current_date}_ref_{ref_cfg}_pose_{pose_cfg}")
+ frames_output_dir = os.path.join(output_root, f"{job_name}_ref_{ref_cfg}_pose_{pose_cfg}")
+ os.makedirs(frames_output_dir, exist_ok=True)
+ final_video_path = os.path.join(output_root, f"{job_name}_ref_{ref_cfg}_pose_{pose_cfg}.mp4")
+ if os.path.exists(final_video_path):
+ print(f"[GPU {rank}] {final_video_path} 已存在,跳过")
+ continue
+
+ print(f"[GPU {rank}] 处理: {cache_dir}")
+ # 读取输入
+ image_input = Image.open(os.path.join(cache_dir, "image_input.png")).convert("RGB")
+ if new_h and new_w:
+ new_h = float(new_h)
+ new_w = float(new_w)
+ else:
+ new_h, new_w = image_input.height, image_input.width
+
+ if min(new_h, new_w) > max_short:
+ if new_h < new_w:
+ scale = max_short / new_h
+ new_h, new_w = max_short, int(new_w * scale)
+ else:
+ scale = max_short / new_w
+ new_w, new_h = max_short, int(new_h * scale)
+
+ new_h, new_w = int(new_h//16*16), int(new_w//16*16)
+ # new_h, new_w = 1024, 576
+ transform_fn = partial(resizecrop, th=new_h, tw=new_w)
+ image_input = transform_fn(image_input)
+
+ pose_tensor, pose_fps = read_pose_video(os.path.join(cache_dir, "pose.mp4"),transform_fn)
+ pose_input_img = Image.open(os.path.join(cache_dir, "pose_input.png")).convert("RGB")
+ pose_input_img = transform_fn(pose_input_img)
+ mask_input = Image.open(os.path.join(cache_dir, "mask_input.png")).convert("L")
+ mask_input = transform_fn(mask_input)
+
+ mask_np = np.array(mask_input, dtype=np.float32) / 255.0
+ mask_tensor = torch.from_numpy(mask_np).unsqueeze(0).unsqueeze(0).unsqueeze(2)
+
+ src_pose_tensor = torch.from_numpy(np.array(pose_input_img)).unsqueeze(0).float().permute(0, 3, 1, 2) / 255.0 * 2 - 1
+ src_pose_tensor = src_pose_tensor.unsqueeze(2)
+
+ split_plan = build_split_plan(pose_tensor.shape[2])
+ all_generated_frames_np = {}
+
+ for idx, (start, end) in enumerate(split_plan):
+ # Debug mode: uncomment break to only infer the first segment
+ # if idx > 0:
+ # break
+ sub_video = pose_tensor[:, :, start:end] # [B=1, C, T, H, W]
+ prev_frames = None
+ if start > 0:
+ needed_idx = range(start, start + OVERLAP_FRAMES)
+ if all(k in all_generated_frames_np for k in needed_idx):
+ prev_frames = [
+ Image.fromarray(all_generated_frames_np[k]) for k in needed_idx
+ ]
+
+ output_chunk = pipe(
+ image=image_input,
+ image_mask=mask_tensor,
+ control_video=sub_video,
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ height=new_h,
+ width=new_w,
+ num_frames=end - start,
+ image_guidance_scale=ref_cfg,
+ pose_guidance_scale=pose_cfg,
+ num_inference_steps=30,
+ generator=torch.Generator(device=device).manual_seed(42),
+ black_image_cfg=black_image_cfg,
+ black_pose_cfg=black_pose_cfg,
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
+ return_tensor=True,
+ case1=case1,
+ token_replace=(prev_frames is not None),
+ prev_frames=prev_frames,
+ image_pose=src_pose_tensor
+ ).frames
+
+
+ output_chunk = (
+ output_chunk[0].detach().cpu() / 2 + 0.5
+ ).float().clamp(0, 1).permute(1, 2, 3, 0).numpy()
+ output_chunk = (output_chunk * 255).astype("uint8")
+
+ for j in range(end - start):
+ gidx = start + j
+ all_generated_frames_np[gidx] = output_chunk[j]
+ imageio.imwrite(os.path.join(frames_output_dir, f"frame_{gidx:06d}.png"), output_chunk[j])
+
+ alpha = 0.6
+ frames_combined = []
+
+ src_uint8 = ((pose_tensor / 2 + 0.5).clamp(0, 1) * 255
+ )[0].byte().permute(1, 2, 3, 0).numpy() # (T,H,W,C)
+ sorted_idx = sorted(all_generated_frames_np.keys())
+
+
+ for t in sorted_idx:
+ src = src_uint8[t].astype(np.float32)
+ pred = all_generated_frames_np[t].astype(np.float32)
+ blended = (alpha * src + (1 - alpha) * pred).round().astype(np.uint8)
+ concat = np.concatenate([blended, pred.astype(np.uint8)], axis=1) # (H,2W,C)
+ frames_combined.append(concat)
+
+ imageio.mimwrite(
+ final_video_path,
+ frames_combined,
+ fps=pose_fps,
+ quality=5
+ )
+
+ print(f"[GPU {rank}] 完成视频: {final_video_path}")
+ del pipe
+ torch.cuda.empty_cache()
+
+
+def run_all_tasks(ckpt_path, img_g, pose_g, cache_dir_root="input_cache2"):
+ """扫描 cache 目录,跑全部任务"""
+ # task_list = sorted(glob.glob(os.path.join(cache_dir_root, "*")))
+ # ref, vid , mode, new_h, new_w, ref_cfg, pose_cfg, prompt
+ # new_h, new_w, ref_cfg, pose_cfg: "" means use default
+ # prompt : "" means empty string
+ task_list = [
+ #
+ ("../examples/img.png","../examples/vid.mp4","ref",840,480,"","",""),
+ # text prompt for generation (especially important for misaligned/pose mode cases
+ ("../examples/joker2_resize.png","../examples/douyinvid5_v2.mp4","pose","","","","","a clown in a vibrant red suit dancing joyfully on a street, black shoes, with skyscrapers and neon lights in an urban city background, clear hand"),
+ ("../examples/musk.jpg","../examples/vid2.mp4","ref","","","","",""),
+ ("../examples/maodie.png","../examples/vid2.mp4","ref","","","","",""),
+ ]
+
+
+ task_list_resolved = []
+ for ref_path, vid_path , alignmode, new_h, new_w, ref_cfg, pose_cfg, prompt in task_list:
+ if not ref_cfg: ref_cfg = img_g
+ else: ref_cfg = float(ref_cfg)
+ if not pose_cfg: pose_cfg = pose_g
+ else: pose_cfg = float(pose_cfg)
+
+ try:
+ cache_dir,job_name = find_cache_dir(cache_dir_root, ref_path, vid_path, alignmode)
+ except FileNotFoundError as e:
+ print(e)
+ continue
+
+ task_list_resolved.append((job_name,cache_dir,new_h,new_w,ref_cfg,pose_cfg,prompt))
+
+
+ world_size = torch.cuda.device_count()
+ mp.spawn(
+ unified_worker,
+ args=(world_size, task_list_resolved, ckpt_path),
+ nprocs=world_size,
+ join=True
+ )
+
+if __name__ == "__main__":
+ for ckpt in ckpt_paths:
+ for img_g, pose_g in default_cfg_combos:
+ print(f"\n===== ckpt: {ckpt} | img_g={img_g} | pose_g={pose_g} =====")
+ run_all_tasks(ckpt, img_g, pose_g, cache_dir_root=cache_base_dir)
diff --git a/One-to-All-Animation/video-generation/inference_refextractor.py b/One-to-All-Animation/video-generation/inference_refextractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..022b1566fcc8ed92efe8c8a084d375cbfe1bdd63
--- /dev/null
+++ b/One-to-All-Animation/video-generation/inference_refextractor.py
@@ -0,0 +1,251 @@
+import os
+import glob
+import torch
+import numpy as np
+from opensora.sample.pipeline_wanx_vhuman_tokenreplace import WanPipeline
+from opensora.model_variants.wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D
+from opensora.encoder_variants import get_text_enc
+from opensora.vae_variants import get_vae
+from datetime import datetime
+from einops import rearrange
+import imageio
+from functools import partial
+import traceback
+from PIL import Image
+
+from diffusers.utils import export_to_video, load_image
+from diffusers.schedulers import FlowMatchEulerDiscreteScheduler
+
+# ===== Model Config =====
+model_path = "../pretrained_models/Wan2.1-T2V-1.3B-Diffusers"
+vae_path = "../pretrained_models/Wan2.1-T2V-1.3B-Diffusers/vae"
+config_path = "configs/wan2.1_t2v_1.3b.json"
+
+model_dtype = torch.bfloat16
+
+# Scheduler
+scheduler = FlowMatchEulerDiscreteScheduler(
+ shift=7.0,
+ num_train_timesteps=1000,
+ use_dynamic_shifting=False
+)
+
+# VAE and Text Encoder
+vae = get_vae('wanx', vae_path, model_dtype)
+encoders = get_text_enc('wanx-t2v', model_path, model_dtype)
+text_encoder = encoders.text_encoder
+tokenizer = encoders.tokenizer
+
+# Model
+model = WanTransformer3DModel_Refextractor_2D.from_config(config_path).to(model_dtype)
+model.set_up_refextractor("configs/wan2.1_t2v_1.3b_refextractor_2d_withmask2.json", model_dtype)
+model.eval()
+model.requires_grad_(False)
+
+# Load checkpoint
+def load_state_dict(ckpt_dir):
+ from safetensors.torch import load_file as safe_load
+ shard_files = [f for f in os.listdir(ckpt_dir) if f.endswith('.safetensors')]
+ checkpoint = {}
+ for shard_file in shard_files:
+ state_dict = safe_load(os.path.join(ckpt_dir, shard_file), device='cpu')
+ checkpoint.update(state_dict)
+ return checkpoint
+
+# change your own path
+ckpt_path = "./outputs_wanx1.3b/train1.3b_only_refextractor_2d_2/checkpoint-21366-6788/fp32_model_21366"
+checkpoint = load_state_dict(ckpt_path)
+model.load_state_dict(checkpoint, strict=True)
+
+# Pipeline
+pipe = WanPipeline(
+ transformer=model,
+ vae=vae.vae,
+ text_encoder=text_encoder,
+ tokenizer=tokenizer,
+ scheduler=scheduler
+)
+pipe.to("cuda", dtype=model_dtype)
+
+# ===== Helper Functions =====
+def resizecrop(image, th, tw):
+ w, h = image.size
+ if h / w > th / tw:
+ new_w = int(w)
+ new_h = int(new_w * th / tw)
+ else:
+ new_h = int(h)
+ new_w = int(new_h * tw / th)
+ left = (w - new_w) / 2
+ top = (h - new_h) / 2
+ right = (w + new_w) / 2
+ bottom = (h + new_h) / 2
+ image = image.crop((left, top, right, bottom))
+ image = image.resize((tw, th))
+ return image
+
+def find_cache_dir(cache_dir_root, ref_path, vid_path, alignmode):
+ """Find cache directory based on reference, video and alignment mode"""
+ refname = os.path.splitext(os.path.basename(ref_path))[0]
+ vidname = os.path.splitext(os.path.basename(vid_path))[0]
+ job_name = f"ref_{refname}_vid_{vidname}"
+ pattern = os.path.join(
+ cache_dir_root,
+ f"ref_{refname}_driven_{vidname}_align_{alignmode}_*"
+ )
+ matches = glob.glob(pattern)
+ if not matches:
+ raise FileNotFoundError(f"❌ Cache directory not found: {pattern}")
+ if len(matches) > 1:
+ print(f"⚠ Multiple cache directories found, using first: {matches}")
+ return matches[0], job_name
+
+# ===== Inference Parameters =====
+image_guidance_scale = 2.0
+pose_guidance_scale = 0
+black_pose_cfg = False
+black_image_cfg = True
+zero_neg = False
+negative_prompt = "" if zero_neg else [
+ "Aerial view, aerial view, overexposed, low quality, deformation, a poor composition, bad hands, bad teeth, bad eyes, bad limbs, distortion"
+]
+
+controlnet_conditioning_scale = 0 # No pose
+num_frames = 81 # training 29 but inference 81
+case1 = False
+
+# Cache directory
+cache_base_dir = "../input_cache"
+# Output directory
+output_base_dir = "../output/ref_only_1.3b"
+# stage 1 only trained on 512px
+max_short = 384
+# ===== Task List =====
+# Task list format: (ref_path, vid_path, alignmode, new_h, new_w, ref_cfg, pose_cfg, prompt)
+# new_h, new_w, ref_cfg, pose_cfg: "" means use default
+task_list = [
+ ("../examples/img.png", "../examples/vid.mp4", "ref", "", "", "", "", ""),
+ ("../examples/joker2_resize.png", "../examples/douyinvid5_v2.mp4", "pose", "", "", "", "", "a clown in a vibrant red suit dancing joyfully"),
+ ("../examples/musk.jpg", "../examples/vid2.mp4", "ref", "", "", "", "", ""),
+ ("../examples/maodie.png", "../examples/vid2.mp4", "ref", "", "", "", "", ""),
+]
+
+# ===== Main Inference Loop =====
+for ref_path, vid_path, alignmode, new_h, new_w, ref_cfg, pose_cfg, prompt in task_list:
+ try:
+ if not ref_cfg:
+ ref_cfg = image_guidance_scale
+ else:
+ ref_cfg = float(ref_cfg)
+
+ if not pose_cfg:
+ pose_cfg = pose_guidance_scale
+ else:
+ pose_cfg = float(pose_cfg)
+
+ try:
+ cache_dir, job_name = find_cache_dir(cache_base_dir, ref_path, vid_path, alignmode)
+ except FileNotFoundError as e:
+ print(e)
+ continue
+
+ print(f"Processing: {job_name}")
+ print(f"Using cache: {cache_dir}")
+ print(f"Prompt: {prompt}")
+
+ # Read from cache
+ image_input = Image.open(os.path.join(cache_dir, "image_input.png")).convert("RGB")
+ mask_input = Image.open(os.path.join(cache_dir, "mask_input.png")).convert("L")
+
+ # Get dimensions
+ if new_h and new_w:
+ new_h = int(float(new_h))
+ new_w = int(float(new_w))
+ else:
+ new_h, new_w = image_input.height, image_input.width
+
+ if min(new_h, new_w) > max_short:
+ if new_h < new_w:
+ scale = max_short / new_h
+ new_h, new_w = max_short, int(new_w * scale)
+ else:
+ scale = max_short / new_w
+ new_w, new_h = max_short, int(new_h * scale)
+
+
+
+ # Ensure dimensions are multiples of 16
+ new_h = int(new_h // 16 * 16)
+ new_w = int(new_w // 16 * 16)
+
+ transform = partial(resizecrop, th=new_h, tw=new_w)
+
+ # Apply transform
+ image_input = transform(image_input)
+ mask_input = transform(mask_input)
+
+ # Prepare mask tensor
+ mask_np = np.array(mask_input, dtype=np.float32) / 255.0
+ mask_tensor = torch.from_numpy(mask_np).unsqueeze(0).unsqueeze(0).unsqueeze(2) # [1,1,1,H,W]
+
+
+ # Prepare output path
+ current_date = datetime.now().strftime("%Y-%m-%d")
+ output_dir = os.path.join(output_base_dir, f"{current_date}_ref_{ref_cfg}_pose_{pose_cfg}_frame_{num_frames}")
+ os.makedirs(output_dir, exist_ok=True)
+ output_path = os.path.join(output_dir, f"{job_name}_frames{num_frames}.mp4")
+
+ if os.path.exists(output_path):
+ print(f"✓ {output_path} exists, skipping!")
+ continue
+
+ # Save input image for reference
+ image_input.save(output_path.replace(".mp4", "_input.png"))
+
+ print(f"Generating video...")
+
+ # Inference - only using reference image, no control video
+ output = pipe(
+ image=image_input,
+ image_mask=mask_tensor,
+ control_video=None, # No pose control
+ prompt=prompt,
+ negative_prompt=negative_prompt,
+ height=new_h,
+ width=new_w,
+ num_frames=num_frames,
+ image_guidance_scale=ref_cfg,
+ pose_guidance_scale=pose_cfg,
+ num_inference_steps=30,
+ generator=torch.Generator(device="cuda").manual_seed(42),
+ black_image_cfg=black_image_cfg,
+ black_pose_cfg=black_pose_cfg,
+ controlnet_conditioning_scale=controlnet_conditioning_scale,
+ return_tensor=True,
+ case1=case1,
+ image_pose=None,
+ ).frames[0]
+
+ # Save video
+ pred = output.detach().cpu() # (T,C,H,W)
+
+ # Convert to video format
+ images = (pred / 2 + 0.5).clamp(0, 1)
+ img_tensors = rearrange(images.permute(1, 0, 2, 3) * 255, 't c h w -> t h w c').byte().numpy()
+
+ imageio.mimwrite(
+ output_path,
+ img_tensors,
+ fps=30,
+ quality=8,
+ output_params=["-loglevel", "error"]
+ )
+
+ print(f"✓ Saved to: {output_path}\n")
+
+ except Exception as e:
+ print(f"❌ Error processing {ref_path}: {e}")
+ traceback.print_exc()
+ print()
+
+print("All tasks completed!")
diff --git a/One-to-All-Animation/video-generation/opensora/__init__.py b/One-to-All-Animation/video-generation/opensora/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..4e768b56d84e02be46b30d93be818972220b8462
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/__init__.py
@@ -0,0 +1 @@
+#
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/acceleration/__init__.py b/One-to-All-Animation/video-generation/opensora/acceleration/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/acceleration/communications.py b/One-to-All-Animation/video-generation/opensora/acceleration/communications.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f69a73a05eb31997f79833432c2df1ed92841dc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/acceleration/communications.py
@@ -0,0 +1,133 @@
+import torch
+import torch.distributed as dist
+from einops import rearrange
+from opensora.acceleration.parallel_states import hccl_info, lccl_info, enable_LCCL
+try:
+ from lcalib.functional import lcal_all2allvc
+except:
+ lcal_all2allvc = None
+
+def broadcast(input_: torch.Tensor):
+ sp_size = hccl_info.world_size
+ src = hccl_info.rank // sp_size * sp_size
+ dist.broadcast(input_, src=src, group=hccl_info.group)
+
+_COUNT = 0
+def _all_to_all(
+ input_: torch.Tensor,
+ scatter_dim: int,
+ gather_dim: int,
+):
+ group = hccl_info.group
+ sp_size = hccl_info.world_size
+ input_list = [t.contiguous() for t in torch.tensor_split(input_, sp_size, scatter_dim)]
+ output_list = [torch.empty_like(input_list[0]) for _ in range(sp_size)]
+ dist.all_to_all(output_list, input_list, group=group)
+ return torch.cat(output_list, dim=gather_dim).contiguous()
+
+def _single_all_to_all(
+ input_: torch.Tensor,
+ scatter_dim: int,
+ gather_dim: int,
+ enable_HCCL=False,
+):
+ if enable_LCCL:
+ sp_size = lccl_info.world_size
+ else:
+ sp_size = hccl_info.world_size
+ inp_shape = list(input_.shape)
+ inp_shape[scatter_dim] = inp_shape[scatter_dim] // sp_size
+ if scatter_dim < 1:
+ input_t = input_.reshape(
+ [sp_size, inp_shape[scatter_dim]] + \
+ inp_shape[scatter_dim + 1:]
+ )
+ else:
+ # transpose groups of heads with the seq-len parallel dimension, so that we can scatter them!
+ input_t = input_.reshape(
+ [-1, sp_size, inp_shape[scatter_dim]] + \
+ inp_shape[scatter_dim + 1:]
+ ).transpose(0, 1).contiguous()
+
+ output = torch.empty_like(input_t)
+ if enable_LCCL and not enable_HCCL:
+ matrix_count = torch.ones([sp_size, sp_size], dtype=torch.int64, device=input_t.device) * (
+ input_t.numel() // sp_size)
+ lcal_all2allvc(input_t, output, matrix_count, lccl_info.group)
+ else:
+ dist.all_to_all_single(output, input_t, group=hccl_info.group)
+ # if scattering the seq-dim, transpose the heads back to the original dimension
+ if scatter_dim < 1:
+ output = output.transpose(0, 1).contiguous()
+
+ return output.reshape(
+ inp_shape[: gather_dim] + [inp_shape[gather_dim] * sp_size, ] + inp_shape[gather_dim + 1:])
+
+
+class _AllToAll(torch.autograd.Function):
+ """All-to-all communication.
+
+ Args:
+ input_: input matrix
+ process_group: communication group
+ scatter_dim: scatter dimension
+ gather_dim: gather dimension
+ """
+
+ @staticmethod
+ def forward(ctx, input_, scatter_dim, gather_dim, all_to_all_func):
+ ctx.scatter_dim = scatter_dim
+ ctx.gather_dim = gather_dim
+ ctx.all_to_all = all_to_all_func
+ output = ctx.all_to_all(input_, scatter_dim, gather_dim)
+ return output
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ grad_output = ctx.all_to_all(
+ grad_output,
+ ctx.gather_dim,
+ ctx.scatter_dim,
+ )
+ return (
+ grad_output,
+ None,
+ None,
+ None,
+ )
+
+def all_to_all_SBH(
+ input_: torch.Tensor,
+ scatter_dim: int = 1,
+ gather_dim: int = 0,
+):
+ return _AllToAll.apply(input_, scatter_dim, gather_dim, _single_all_to_all)
+
+def all_to_all_BSND(
+ input_: torch.Tensor,
+ scatter_dim: int = 2,
+ gather_dim: int = 1,
+):
+ return _AllToAll.apply(input_, scatter_dim, gather_dim, _all_to_all)
+
+
+def prepare_parallel_data(hidden_states, encoder_hidden_states, attention_mask, encoder_attention_mask, use_image_num):
+ def all_to_all(hidden_states, encoder_hidden_states, attention_mask, encoder_attention_mask):
+ hidden_states = _single_all_to_all(hidden_states, scatter_dim=2, gather_dim=0, enable_HCCL=True)
+ encoder_hidden_states = _single_all_to_all(encoder_hidden_states, scatter_dim=1, gather_dim=0, enable_HCCL=True)
+ attention_mask = _single_all_to_all(attention_mask, scatter_dim=1, gather_dim=0, enable_HCCL=True)
+ encoder_attention_mask = _single_all_to_all(encoder_attention_mask, scatter_dim=1, gather_dim=0, enable_HCCL=True)
+ return hidden_states, encoder_hidden_states, attention_mask, encoder_attention_mask
+
+ sp_size = hccl_info.world_size
+ frame = hidden_states.shape[2]
+ assert frame % sp_size == 0, "frame should be a multiple of sp_size"
+
+ encoder_hidden_states = rearrange(encoder_hidden_states, 'b 1 (n x) h -> b n x h',
+ n=sp_size, x=encoder_hidden_states.shape[2]//sp_size).contiguous()
+ hidden_states, encoder_hidden_states, attention_mask, encoder_attention_mask = all_to_all(hidden_states,
+ encoder_hidden_states,
+ attention_mask.repeat(1, sp_size, 1, 1),
+ encoder_attention_mask.repeat(1, sp_size, 1))
+
+ return hidden_states, encoder_hidden_states, attention_mask, encoder_attention_mask, use_image_num
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/acceleration/parallel_states.py b/One-to-All-Animation/video-generation/opensora/acceleration/parallel_states.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3f96e121ce523605af55fddc963db0d85acde8b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/acceleration/parallel_states.py
@@ -0,0 +1,57 @@
+import torch
+import torch_npu
+import torch.distributed as dist
+import os
+try:
+ from lcalib.functional import lcal_initialize
+ enable_LCCL = True
+except:
+ lcal_initialize = None
+ enable_LCCL = False
+class COMM_INFO:
+ def __init__(self):
+ self.group = None
+ self.world_size = 0
+ self.rank = -1
+
+lccl_info = COMM_INFO()
+hccl_info = COMM_INFO()
+_SEQUENCE_PARALLEL_STATE = False
+def initialize_sequence_parallel_state(sequence_parallel_size):
+ global _SEQUENCE_PARALLEL_STATE
+ if sequence_parallel_size > 1:
+ _SEQUENCE_PARALLEL_STATE = True
+ initialize_sequence_parallel_group(sequence_parallel_size)
+
+def set_sequence_parallel_state(state):
+ global _SEQUENCE_PARALLEL_STATE
+ _SEQUENCE_PARALLEL_STATE = state
+
+def get_sequence_parallel_state():
+ return _SEQUENCE_PARALLEL_STATE
+
+def initialize_sequence_parallel_group(sequence_parallel_size):
+ """Initialize the sequence parallel group."""
+ rank = int(os.getenv('RANK', '0'))
+ world_size = int(os.getenv("WORLD_SIZE", '1'))
+ assert world_size % sequence_parallel_size == 0, "world_size must be divisible by sequence_parallel_size"
+ # hccl
+ hccl_info.world_size = sequence_parallel_size
+ hccl_info.rank = rank
+ num_sequence_parallel_groups: int = world_size // sequence_parallel_size
+ for i in range(num_sequence_parallel_groups):
+ ranks = range(i * sequence_parallel_size, (i + 1) * sequence_parallel_size)
+ group = dist.new_group(ranks)
+ if rank in ranks:
+ hccl_info.group = group
+
+ if enable_LCCL:
+ assert sequence_parallel_size == 8, "sequence_parallel_size should be 8 when enable_LCCL is True"
+ rank %= sequence_parallel_size
+ lccl_info.world_size = sequence_parallel_size
+ lccl_info.group = lcal_initialize(rank, sequence_parallel_size)
+ lccl_info.rank = rank
+
+def destroy_sequence_parallel_group():
+ """Destroy the sequence parallel group."""
+ dist.destroy_process_group()
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/__init__.py b/One-to-All-Animation/video-generation/opensora/adaptor/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/bf16_optimizer.py b/One-to-All-Animation/video-generation/opensora/adaptor/bf16_optimizer.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0401c0b3a4701c30d3d910668cc1460ee20c369
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/bf16_optimizer.py
@@ -0,0 +1,458 @@
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: Apache-2.0
+
+# DeepSpeed Team
+
+from collections import OrderedDict
+import torch
+import sys
+import os
+from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
+from deepspeed import comm as dist
+from deepspeed.runtime.constants import PIPE_REPLICATED
+from deepspeed.runtime import ZeROOptimizer
+from packaging import version as pkg_version
+
+from deepspeed.git_version_info import version
+from deepspeed.runtime.utils import (get_global_norm_of_tensors, clip_tensors_by_global_norm, DummyOptim,
+ align_dense_tensors, all_gather_dp_groups, bwc_tensor_model_parallel_rank,
+ is_model_parallel_parameter, see_memory_usage, graph_process)
+
+from deepspeed.utils import link_hp_params, fragment_address
+from deepspeed.checkpoint import enable_universal_checkpoint
+from deepspeed.checkpoint.constants import (DS_VERSION, PARTITION_COUNT, BASE_OPTIMIZER_STATE,
+ SINGLE_PARTITION_OF_FP32_GROUPS, CLIP_GRAD, GROUP_PADDINGS,
+ PARAM_SLICE_MAPPINGS)
+
+setattr(sys.modules[__name__], 'fragment_address', fragment_address)
+
+
+def contigous_flatten(tensors):
+ return _flatten_dense_tensors([tensor.contiguous() for tensor in tensors])
+
+
+class BF16_Optimizer(ZeROOptimizer):
+
+ def __init__(self,
+ init_optimizer,
+ param_names,
+ mpu=None,
+ clip_grad=0.0,
+ norm_type=2,
+ allgather_bucket_size=5000000000,
+ dp_process_group=None,
+ timers=None,
+ grad_acc_dtype=None,
+ graph_harvesting=False):
+ # super().__init__()
+ # base_class = ZeROOptimizer.__bases__[0]
+ # # 直接调用基类的 __init__ 方法
+ # base_class.__init__()
+ see_memory_usage('begin bf16_optimizer', force=True)
+ self.timers = timers
+ self.optimizer = init_optimizer
+ self.param_names = param_names
+ self.using_real_optimizer = not isinstance(self.optimizer, DummyOptim)
+
+ assert grad_acc_dtype in [torch.float32, torch.bfloat16
+ ], f"BF16Optimizer: Unsupported gradient accumulation data type: {grad_acc_dtype}"
+ self.grad_acc_dtype = grad_acc_dtype
+
+ self.clip_grad = clip_grad
+ self.norm_type = norm_type
+ self.mpu = mpu
+ self.allgather_bucket_size = int(allgather_bucket_size)
+ self.dp_process_group = dp_process_group
+ self.dp_rank = dist.get_rank(group=self.dp_process_group)
+ self.real_dp_process_group = [dp_process_group for i in range(len(self.optimizer.param_groups))]
+
+ # Use torch (un)flatten ops
+ self.flatten = contigous_flatten
+ self.unflatten = _unflatten_dense_tensors
+
+ #align nccl all-gather send buffers to 4-bye boundary
+ self.nccl_start_alignment_factor = 16
+
+ # Build BF16/FP32 groups
+ self.bf16_groups = []
+ self.bf16_groups_flat = []
+ self.bf16_partitioned_groups = []
+
+ self.fp32_groups_flat_partition = []
+
+ # Maintain different fp32 gradients views for convenience
+ self.fp32_groups_gradients = []
+ self.fp32_groups_gradient_dict = {}
+ self.fp32_groups_gradients_flat = []
+ self.fp32_groups_actual_gradients_flat = []
+ self.fp32_groups_gradient_flat_partition = []
+ self.fp32_groups_has_gradients = []
+
+ self.group_paddings = []
+ self.graph_harvesting = graph_harvesting
+ if self.using_real_optimizer:
+ self._setup_for_real_optimizer()
+
+ see_memory_usage('end bf16_optimizer', force=True)
+
+ def _setup_for_real_optimizer(self):
+ dp_world_size = dist.get_world_size(group=self.dp_process_group)
+ self.partition_count = [dp_world_size for i in range(len(self.optimizer.param_groups))]
+
+ for i, param_group in enumerate(self.optimizer.param_groups):
+ see_memory_usage(f'before initializing group {i}', force=True)
+
+ partition_id = dist.get_rank(group=self.real_dp_process_group[i])
+
+ # grab the original list
+ trainable_parameters = [param for param in param_group['params'] if param.requires_grad]
+ self.bf16_groups.append(trainable_parameters)
+
+ # create flat bf16 params
+ self.bf16_groups_flat.append(
+ self._flatten_dense_tensors_aligned(self.bf16_groups[i],
+ self.nccl_start_alignment_factor * dp_world_size))
+
+ # Make bf16 params point to flat tensor storage
+ self._update_storage_to_flattened_tensor(tensor_list=self.bf16_groups[i],
+ flat_tensor=self.bf16_groups_flat[i])
+
+ # divide flat weights into equal sized partitions
+ partition_size = self.bf16_groups_flat[i].numel() // dp_world_size
+ bf16_dp_partitions = [
+ self.bf16_groups_flat[i].narrow(0, dp_index * partition_size, partition_size)
+ for dp_index in range(dp_world_size)
+ ]
+ self.bf16_partitioned_groups.append(bf16_dp_partitions)
+
+ # create fp32 params partition
+ self.fp32_groups_flat_partition.append(bf16_dp_partitions[partition_id].clone().float().detach())
+ self.fp32_groups_flat_partition[i].requires_grad = True
+
+ num_elem_list = [t.numel() for t in self.bf16_groups[i]]
+
+ # create fp32 gradients
+ self.fp32_groups_gradients_flat.append(
+ torch.zeros_like(self.bf16_groups_flat[i], dtype=self.grad_acc_dtype))
+
+ # track individual fp32 gradients for entire model
+ fp32_gradients = self._split_flat_tensor(flat_tensor=self.fp32_groups_gradients_flat[i],
+ num_elem_list=num_elem_list)
+ self.fp32_groups_gradients.append(fp32_gradients)
+ self.fp32_groups_gradient_dict[i] = fp32_gradients
+
+ # flat tensor corresponding to actual fp32 gradients (i.e., minus alignment padding)
+ length_without_padding = sum(num_elem_list)
+ self.fp32_groups_actual_gradients_flat.append(
+ torch.narrow(self.fp32_groups_gradients_flat[i], 0, 0, length_without_padding))
+
+ # flat tensor corresponding to gradient partition
+ self.fp32_groups_gradient_flat_partition.append(
+ torch.narrow(self.fp32_groups_gradients_flat[i], 0, partition_id * partition_size, partition_size))
+
+ # track fp32 gradient updates
+ self.fp32_groups_has_gradients.append([False] * len(self.bf16_groups[i]))
+
+ # Record padding required for alignment
+ if partition_id == dist.get_world_size(group=self.real_dp_process_group[i]) - 1:
+ padding = self.bf16_groups_flat[i].numel() - length_without_padding
+ else:
+ padding = 0
+
+ self.group_paddings.append(padding)
+
+ # update optimizer param groups to reference fp32 params partition
+ param_group['params'] = [self.fp32_groups_flat_partition[i]]
+
+ see_memory_usage(f'after initializing group {i}', force=True)
+
+ see_memory_usage('before initialize_optimizer', force=True)
+ self.initialize_optimizer_states()
+ see_memory_usage('end initialize_optimizer', force=True)
+
+ # Need optimizer states initialized before linking lp to optimizer state
+ self._link_all_hp_params()
+ self._enable_universal_checkpoint()
+ self._param_slice_mappings = self._create_param_mapping()
+
+ def _enable_universal_checkpoint(self):
+ for lp_param_group in self.bf16_groups:
+ enable_universal_checkpoint(param_list=lp_param_group)
+
+ def _create_param_mapping(self):
+ param_mapping = []
+ for i, _ in enumerate(self.optimizer.param_groups):
+ param_mapping_per_group = OrderedDict()
+ for lp in self.bf16_groups[i]:
+ if lp._hp_mapping is not None:
+ lp_name = self.param_names[lp]
+ param_mapping_per_group[lp_name] = lp._hp_mapping.get_hp_fragment_address()
+ param_mapping.append(param_mapping_per_group)
+
+ return param_mapping
+
+ def _link_all_hp_params(self):
+ dp_world_size = dist.get_world_size(group=self.dp_process_group)
+ for i, _ in enumerate(self.optimizer.param_groups):
+ # Link bf16 and fp32 params in partition
+ partition_id = dist.get_rank(group=self.real_dp_process_group[i])
+ partition_size = self.bf16_groups_flat[i].numel() // dp_world_size
+ flat_hp_partition = self.fp32_groups_flat_partition[i]
+ link_hp_params(lp_param_list=self.bf16_groups[i],
+ flat_hp_partition=flat_hp_partition,
+ gradient_dict=self.fp32_groups_gradient_dict,
+ offload_gradient_dict=None,
+ use_offload=False,
+ param_group_index=i,
+ partition_start=partition_id * partition_size,
+ partition_size=partition_size,
+ partition_optimizer_state=self.optimizer.state[flat_hp_partition],
+ dp_group=self.real_dp_process_group[i])
+
+ def initialize_optimizer_states(self):
+ """Take an optimizer step with zero-valued gradients to allocate internal
+ optimizer state.
+
+ This helps prevent memory fragmentation by allocating optimizer state at the
+ beginning of training instead of after activations have been allocated.
+ """
+ for param_partition, grad_partition in zip(self.fp32_groups_flat_partition,
+ self.fp32_groups_gradient_flat_partition):
+ # In case of grad acc dtype different than FP32, need to cast to high precision.
+ param_partition.grad = grad_partition.to(
+ param_partition.dtype) if grad_partition.dtype != param_partition.dtype else grad_partition
+
+ self.optimizer.step()
+
+ if self.grad_acc_dtype is not torch.float32:
+ for param_partition in self.fp32_groups_flat_partition:
+ param_partition.grad = None
+
+ self.clear_hp_grads()
+
+ def _split_flat_tensor(self, flat_tensor, num_elem_list):
+ assert sum(num_elem_list) <= flat_tensor.numel()
+ tensor_list = []
+ offset = 0
+ for num_elem in num_elem_list:
+ dense_tensor = torch.narrow(flat_tensor, 0, offset, num_elem)
+ tensor_list.append(dense_tensor)
+ offset += num_elem
+
+ return tensor_list
+
+ def _update_storage_to_flattened_tensor(self, tensor_list, flat_tensor):
+ updated_params = self.unflatten(flat_tensor, tensor_list)
+ for p, q in zip(tensor_list, updated_params):
+ p.data = q.data
+
+ def _flatten_dense_tensors_aligned(self, tensor_list, alignment):
+ return self.flatten(align_dense_tensors(tensor_list, alignment))
+
+ @torch.no_grad()
+ def step(self, closure=None):
+ if closure is not None:
+ raise NotImplementedError(f'{self.__class__} does not support closure.')
+
+ all_groups_norm = get_global_norm_of_tensors(input_tensors=self.get_grads_for_norm(),
+ mpu=self.mpu,
+ norm_type=self.norm_type,
+ use_graph=self.graph_harvesting)
+ self._global_grad_norm = all_groups_norm
+
+ assert all_groups_norm > 0.
+ if self.clip_grad > 0.:
+ clip_tensors_by_global_norm(input_tensors=self.get_grads_for_norm(for_clipping=True),
+ max_norm=self.clip_grad,
+ global_norm=all_groups_norm,
+ mpu=self.mpu,
+ use_graph=self.graph_harvesting)
+
+ self.optimizer.step()
+
+ self.update_lp_params()
+
+ self.clear_hp_grads()
+
+ def backward(self, loss, update_hp_grads=True, clear_lp_grads=False, **bwd_kwargs):
+ """Perform a backward pass and copy the low-precision gradients to the
+ high-precision copy.
+
+ We copy/accumulate to the high-precision grads now to prevent accumulating in the
+ bf16 grads after successive backward() calls (i.e., grad accumulation steps > 1)
+
+ The low-precision grads are deallocated during this procedure.
+ """
+ self.clear_lp_grads()
+ loss.backward(**bwd_kwargs)
+
+ if update_hp_grads:
+ self.update_hp_grads(clear_lp_grads=clear_lp_grads)
+
+ @torch.no_grad()
+ def update_hp_grads(self, clear_lp_grads=False):
+
+ def _update_hp_grads_func(clear_lp_grads=False):
+ for i, group in enumerate(self.bf16_groups):
+ for j, lp in enumerate(group):
+ if lp.grad is None:
+ continue
+ hp_grad = self.fp32_groups_gradients[i][j]
+ assert hp_grad is not None, \
+ f'high precision param has no gradient, lp param_id = {id(lp)} group_info = [{i}][{j}]'
+ hp_grad.data.add_(lp.grad.data.to(hp_grad.dtype).view(hp_grad.shape))
+ lp._hp_grad = hp_grad
+ self.fp32_groups_has_gradients[i][j] = True
+ # clear gradients
+ if clear_lp_grads:
+ lp.grad._zero()
+
+ if self.graph_harvesting:
+ graph_process(False, _update_hp_grads_func, clear_lp_grads)
+ else:
+ _update_hp_grads_func(clear_lp_grads)
+ #cpu op
+ for i, group in enumerate(self.bf16_groups):
+ for j, lp in enumerate(group):
+ if lp.grad is None:
+ continue
+ self.fp32_groups_has_gradients[i][j] = True
+
+ @torch.no_grad()
+ def get_grads_for_reduction(self):
+ return self.fp32_groups_gradients_flat
+
+ @torch.no_grad()
+ def get_grads_for_norm(self, for_clipping=False):
+ grads = []
+ tensor_mp_rank = bwc_tensor_model_parallel_rank(mpu=self.mpu)
+ for i, group in enumerate(self.bf16_groups):
+ for j, lp in enumerate(group):
+ if not for_clipping:
+ if hasattr(lp, PIPE_REPLICATED) and lp.ds_pipe_replicated:
+ continue
+
+ if not (tensor_mp_rank == 0 or is_model_parallel_parameter(lp)):
+ continue
+
+ if not self.fp32_groups_has_gradients[i][j]:
+ continue
+
+ grads.append(self.fp32_groups_gradients[i][j])
+
+ return grads
+
+ @torch.no_grad()
+ def update_lp_params(self):
+ for i, (bf16_partitions,
+ fp32_partition) in enumerate(zip(self.bf16_partitioned_groups, self.fp32_groups_flat_partition)):
+ partition_id = dist.get_rank(group=self.real_dp_process_group[i])
+ bf16_partitions[partition_id].data.copy_(fp32_partition.data)
+ # print_rank_0(f'update_lp_params {i=} {partition_id=}', force=True)
+ # if i == 0:
+ # print_rank_0(f'{fp32_partition[:10]=}', force=True)
+
+ all_gather_dp_groups(groups_flat=self.bf16_groups_flat,
+ partitioned_param_groups=self.bf16_partitioned_groups,
+ dp_process_group=self.real_dp_process_group,
+ start_alignment_factor=self.nccl_start_alignment_factor,
+ allgather_bucket_size=self.allgather_bucket_size)
+
+ def clear_hp_grads(self):
+ for flat_gradients in self.fp32_groups_gradients_flat:
+ flat_gradients.zero_()
+
+ for i, group in enumerate(self.fp32_groups_gradients):
+ self.fp32_groups_has_gradients[i] = [False] * len(group)
+
+ def clear_lp_grads(self):
+ for group in self.bf16_groups:
+ for param in group:
+ if param.grad is not None:
+ # Using zero_() fixed memory address for graph replay
+ param.grad.zero_()
+
+ def state_dict(self):
+ state_dict = {}
+ state_dict[CLIP_GRAD] = self.clip_grad
+ state_dict[BASE_OPTIMIZER_STATE] = self.optimizer.state_dict()
+ state_dict[SINGLE_PARTITION_OF_FP32_GROUPS] = self.fp32_groups_flat_partition
+ state_dict[GROUP_PADDINGS] = self.group_paddings
+ state_dict[PARTITION_COUNT] = self.partition_count
+ state_dict[DS_VERSION] = version
+ state_dict[PARAM_SLICE_MAPPINGS] = self._param_slice_mappings
+
+ return state_dict
+
+ # Restore base optimizer fp32 weights bfloat16 weights
+ def _restore_from_bit16_weights(self):
+ for i, group in enumerate(self.bf16_groups):
+ partition_id = dist.get_rank(group=self.real_dp_process_group[i])
+ for bf16_partitions, fp32_partition in zip(self.bf16_partitioned_groups, self.fp32_groups_flat_partition):
+ fp32_partition.data.copy_(bf16_partitions[partition_id].data)
+
+ def refresh_fp32_params(self):
+ self._restore_from_bit16_weights()
+
+ def load_state_dict(self,
+ state_dict_list,
+ checkpoint_folder,
+ load_optimizer_states=True,
+ load_from_fp32_weights=False,
+ load_serial=None):
+ if checkpoint_folder:
+ self._load_universal_checkpoint(checkpoint_folder, load_optimizer_states, load_from_fp32_weights)
+ else:
+ self._load_legacy_checkpoint(state_dict_list, load_optimizer_states, load_from_fp32_weights)
+
+ def _load_legacy_checkpoint(self, state_dict_list, load_optimizer_states=True, load_from_fp32_weights=False):
+
+ dp_rank = dist.get_rank(group=self.dp_process_group)
+ current_rank_sd = state_dict_list[dp_rank]
+
+ ckpt_version = current_rank_sd.get(DS_VERSION, False)
+ assert ckpt_version, f"Empty ds_version in checkpoint, not clear how to proceed"
+ ckpt_version = pkg_version.parse(ckpt_version)
+
+ self.clip_grad = current_rank_sd.get(CLIP_GRAD, self.clip_grad)
+
+ if load_optimizer_states:
+ self.optimizer.load_state_dict(current_rank_sd[BASE_OPTIMIZER_STATE])
+
+ if load_from_fp32_weights:
+ for current, saved in zip(self.fp32_groups_flat_partition,
+ current_rank_sd[SINGLE_PARTITION_OF_FP32_GROUPS]):
+ src_tensor = _get_padded_tensor(saved, current.numel())
+ current.data.copy_(src_tensor.data)
+
+ if load_optimizer_states:
+ self._link_all_hp_params()
+
+ def _load_universal_checkpoint(self, checkpoint_folder, load_optimizer_states, load_from_fp32_weights):
+ self._load_hp_checkpoint_state(checkpoint_folder)
+
+ @property
+ def param_groups(self):
+ """Forward the wrapped optimizer's parameters."""
+ return self.optimizer.param_groups
+
+ def _load_hp_checkpoint_state(self, checkpoint_dir):
+ checkpoint_dir = os.path.join(checkpoint_dir, "zero")
+ tp_rank = bwc_tensor_model_parallel_rank(mpu=self.mpu)
+ tp_world_size = self.mpu.get_slice_parallel_world_size()
+
+ for i, _ in enumerate(self.optimizer.param_groups):
+ for lp in self.bf16_groups[i]:
+ if lp._hp_mapping is not None:
+ #print(f"Loading {self.param_names[lp]} {tp_rank=} {tp_world_size=}")
+ lp.load_hp_checkpoint_state(os.path.join(checkpoint_dir, self.param_names[lp]), tp_rank,
+ tp_world_size)
+
+
+def _get_padded_tensor(src_tensor, size):
+ if src_tensor.numel() >= size:
+ return src_tensor
+ padded_tensor = torch.zeros(size, dtype=src_tensor.dtype, device=src_tensor.device)
+ slice_tensor = torch.narrow(padded_tensor, 0, 0, src_tensor.numel())
+ slice_tensor.data.copy_(src_tensor.data)
+ return padded_tensor
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/engine.py b/One-to-All-Animation/video-generation/opensora/adaptor/engine.py
new file mode 100644
index 0000000000000000000000000000000000000000..5208a9e4133edb9d52fd642568e33782f852dc46
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/engine.py
@@ -0,0 +1,3568 @@
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: Apache-2.0
+
+# DeepSpeed Team
+
+import os
+import re
+import stat
+import torch
+import hashlib
+from collections import defaultdict, OrderedDict, deque
+from shutil import copyfile
+import gc
+
+from torch.nn.modules import Module
+from torch.nn.parameter import Parameter
+from torch.optim import Optimizer
+from torch.optim.lr_scheduler import _LRScheduler
+from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
+
+from typing import Callable, Dict, Union, Iterable
+
+import deepspeed
+
+from deepspeed import comm as dist
+from deepspeed.runtime.utils import see_memory_usage, DummyOptim
+from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum
+from deepspeed.runtime.zero.stage_1_and_2 import DeepSpeedZeroOptimizer
+from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
+from deepspeed.runtime.zero.utils import is_zero_supported_optimizer, ZeRORuntimeException
+from deepspeed.runtime.zero.parameter_offload import DeepSpeedZeRoOffload
+from deepspeed.runtime.zero.config import ZERO_OPTIMIZATION
+
+from deepspeed.runtime.fp16.fused_optimizer import FP16_Optimizer
+from deepspeed.runtime.fp16.unfused_optimizer import FP16_UnfusedOptimizer
+from deepspeed.runtime.bf16_optimizer import BF16_Optimizer
+
+from deepspeed.runtime.config import DEEPSPEED_OPTIMIZERS, \
+ ADAGRAD_OPTIMIZER, ADAM_OPTIMIZER, ADAMW_OPTIMIZER, LAMB_OPTIMIZER, ONEBIT_ADAM_OPTIMIZER, ONEBIT_LAMB_OPTIMIZER, \
+ TORCH_ADAM_PARAM, ADAM_W_MODE, ADAM_W_MODE_DEFAULT, ZERO_ONE_ADAM_OPTIMIZER, MUADAM_OPTIMIZER, MUADAMW_OPTIMIZER, \
+ MUSGD_OPTIMIZER, LION_OPTIMIZER
+
+from deepspeed.runtime.dataloader import DeepSpeedDataLoader
+from deepspeed.runtime.constants import \
+ ROUTE_TRAIN, ROUTE_PREDICT, ROUTE_EVAL, \
+ PLD_THETA, PLD_GAMMA, BFLOAT16, FP16, AMP, GRADIENT_ACCUMULATION_STEPS, \
+ DATA_PARALLEL_GROUP, GLOBAL_RANK
+from deepspeed.runtime.zero.config import ZeroStageEnum
+from deepspeed.compression import compression_scheduler
+from deepspeed.compression.constants import \
+ WEIGHT_QUANTIZE_IN_FORWARD_ENABLED, \
+ WEIGHT_QUANTIZATION, SHARED_PARAMETERS, \
+ WEIGHT_QUANTIZE_ENABLED, \
+ WEIGHT_QUANTIZE_GROUPS, \
+ WEIGHT_QUANTIZE_FP16_MIXED_QUANTIZE, \
+ WEIGHT_QUANTIZE_CHANGE_RATIO, \
+ WEIGHT_QUANTIZE_TYPE, \
+ WEIGHT_QUANTIZE_ROUNDING, \
+ WEIGHT_QUANTIZE_VERBOSE, \
+ WEIGHT_QUANTIZE_KERNEL
+from deepspeed.checkpoint.constants import OPTIMIZER_STATE_DICT, FROZEN_PARAM_FRAGMENTS
+from deepspeed.runtime.sparse_tensor import SparseTensor
+
+from deepspeed.runtime import lr_schedules
+from deepspeed.utils import groups
+from deepspeed.utils import logger, log_dist, instrument_w_nvtx
+from deepspeed.utils.timer import NoopTimer, ThroughputTimer, SynchronizedWallClockTimer, \
+ FORWARD_MICRO_TIMER, BACKWARD_MICRO_TIMER, BACKWARD_INNER_MICRO_TIMER, BACKWARD_REDUCE_MICRO_TIMER, \
+ STEP_MICRO_TIMER, \
+ FORWARD_GLOBAL_TIMER, BACKWARD_GLOBAL_TIMER, BACKWARD_INNER_GLOBAL_TIMER, BACKWARD_REDUCE_GLOBAL_TIMER, \
+ STEP_GLOBAL_TIMER
+from deepspeed.utils.debug import debug_extract_module_and_param_names
+from deepspeed.monitor.monitor import MonitorMaster
+from deepspeed.runtime.progressive_layer_drop import ProgressiveLayerDrop
+from deepspeed.runtime.utils import clip_grad_norm_
+from deepspeed.runtime.eigenvalue import Eigenvalue
+from deepspeed.runtime.data_pipeline.constants import DATA_SAMPLING, \
+ DATA_ROUTING, DATA_SAMPLING_ENABLED, CURRICULUM_LEARNING, \
+ CURRICULUM_LEARNING_ENABLED, DATA_SAMPLING_NUM_WORKERS, RANDOM_LTD, \
+ RANDOM_LTD_ENABLED, RANDOM_LTD_LAYER_ID, RANDOM_LTD_LAYER_NUM, \
+ RANDOM_LTD_LAYER_TOKEN_LR_SCHEDULE, RANDOM_LTD_LAYER_TOKEN_LR_ENABLED, \
+ RANDOM_LTD_GLOBAL_BATCH_SIZE, RANDOM_LTD_MICRO_BATCH_SIZE, DATA_EFFICIENCY
+from deepspeed.runtime.data_pipeline.curriculum_scheduler import CurriculumScheduler
+from deepspeed.runtime.data_pipeline.data_routing.scheduler import RandomLTDScheduler
+from deepspeed.runtime.data_pipeline.data_routing.helper import remove_random_ltd_state_dict
+from deepspeed.runtime.data_pipeline.data_routing.basic_layer import RandomLayerTokenDrop
+
+from deepspeed.runtime.checkpoint_engine.torch_checkpoint_engine import TorchCheckpointEngine
+from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint
+
+from deepspeed.runtime.pipe.module import PipelineModule
+from deepspeed.runtime.utils import get_ma_status
+from deepspeed.ops.adam import FusedAdam
+from deepspeed.moe.sharded_moe import TopKGate, MOELayer
+from deepspeed.moe.layer import MoE
+from deepspeed.moe.utils import is_moe_param
+from deepspeed.git_version_info import version
+
+from deepspeed.profiling.flops_profiler.profiler import FlopsProfiler
+from deepspeed.utils.logging import print_json_dist, print_configuration
+
+from deepspeed.accelerator import get_accelerator
+
+from deepspeed.runtime.config import DtypeEnum
+
+from opensora.adaptor.zp_manager import zp_manager
+
+MEMORY_OPT_ALLREDUCE_SIZE = 500000000
+
+DeepSpeedOptimizerCallable = \
+ Callable[[Union[Iterable[Parameter], Dict[str, Iterable]]], Optimizer]
+DeepSpeedSchedulerCallable = Callable[[Optimizer], _LRScheduler]
+
+try:
+ import apex
+ from apex import amp
+ APEX_INSTALLED = True
+except ImportError:
+ # Fail silently so we don't spam logs unnecessarily if user isn't using amp
+ APEX_INSTALLED = False
+
+
+def split_half_float_double_sparse(tensors):
+ device_type = get_accelerator().device_name()
+ supported_types = [
+ "torch.{}.HalfTensor".format(device_type), "torch.{}.FloatTensor".format(device_type),
+ "torch.{}.DoubleTensor".format(device_type), "torch.{}.BFloat16Tensor".format(device_type),
+ SparseTensor.type()
+ ]
+
+ for t in tensors:
+ assert t.type() in supported_types, f"attempting to reduce an unsupported grad type: {t.type()}"
+
+ buckets = []
+ for i, dtype in enumerate(supported_types):
+ bucket = [t for t in tensors if t.type() == dtype]
+ if bucket:
+ buckets.append((dtype, bucket))
+ return buckets
+
+
+class EngineTimers(object):
+ r"""Wallclock timers for DeepSpeedEngine"""
+
+ def __init__(self, enable_micro_timers, enable_global_timers):
+ self.forward_timers = []
+ self.backward_timers = []
+ self.backward_inner_timers = []
+ self.backward_reduce_timers = []
+ self.step_timers = []
+ self.global_timers = []
+ self.micro_timers = []
+
+ if enable_micro_timers:
+ self.forward_timers += [FORWARD_MICRO_TIMER]
+ self.backward_timers += [BACKWARD_MICRO_TIMER]
+ self.backward_inner_timers += [BACKWARD_INNER_MICRO_TIMER]
+ self.backward_reduce_timers += [BACKWARD_REDUCE_MICRO_TIMER]
+ self.step_timers += [STEP_MICRO_TIMER]
+ self.micro_timers += [
+ FORWARD_MICRO_TIMER, BACKWARD_MICRO_TIMER, BACKWARD_INNER_MICRO_TIMER, BACKWARD_REDUCE_MICRO_TIMER,
+ STEP_MICRO_TIMER
+ ]
+
+ if enable_global_timers:
+ self.forward_timers += [FORWARD_GLOBAL_TIMER]
+ self.backward_timers += [BACKWARD_GLOBAL_TIMER]
+ self.backward_inner_timers += [BACKWARD_INNER_GLOBAL_TIMER]
+ self.backward_reduce_timers += [BACKWARD_REDUCE_GLOBAL_TIMER]
+ self.step_timers += [STEP_GLOBAL_TIMER]
+ self.global_timers += [
+ FORWARD_GLOBAL_TIMER, BACKWARD_GLOBAL_TIMER, BACKWARD_INNER_GLOBAL_TIMER, BACKWARD_REDUCE_GLOBAL_TIMER,
+ STEP_GLOBAL_TIMER
+ ]
+
+
+class DeepSpeedEngine(Module):
+ r"""DeepSpeed engine for training."""
+
+ def __init__(
+ self,
+ args,
+ model,
+ optimizer=None,
+ model_parameters=None,
+ training_data=None,
+ lr_scheduler=None,
+ mpu=None,
+ dist_init_required=None,
+ collate_fn=None,
+ config=None,
+ config_class=None,
+ dont_change_device=False,
+ ):
+ super(DeepSpeedEngine, self).__init__()
+ self.dont_change_device = dont_change_device
+ self.client_optimizer = optimizer
+ self.client_lr_scheduler = lr_scheduler
+ self.training_data = training_data
+ self.collate_fn = collate_fn
+ self.mpu = mpu
+ self.all_to_all_group = None
+ self.data_parallel_group = None
+ self.global_steps = 0
+ self.global_samples = 0
+ self.micro_steps = 0
+ self.skipped_steps = 0
+ self.gradient_average = True
+ self.warn_unscaled_loss = True
+ self.config = config
+ self._config = config_class
+ self.loaded_checkpoint_mp_world_size = None
+ self.loaded_checkpoint_dp_world_size = None
+ self.loaded_checkpoint_zp_world_size = None
+ self.enable_backward_allreduce = True
+ self.progressive_layer_drop = None
+ self.eigenvalue = None
+ self.block_eigenvalue = None
+ self.gas_boundary_ctr = 0
+ self.dist_backend = get_accelerator().communication_backend_name()
+ self.has_moe_layers = False
+ self.num_experts = []
+ self.gate_modules = []
+ self.moe_layers = []
+ self._step_applied = False
+ self._global_grad_norm = None
+ self.use_ds_comm = False # False --> Use torch.dist, True --> Use ds.comm backend.
+
+ self.checkpoint_engine = None
+
+ self._is_gradient_accumulation_boundary = None
+ self.scale_wrt_gas = None
+ self.losses = 0.0
+
+ # for debug purposes - can then debug print: debug_get_module_name(module)
+ debug_extract_module_and_param_names(model)
+
+ self._do_args_sanity_check(args)
+ self._configure_with_arguments(args, mpu)
+ self._do_sanity_check()
+ see_memory_usage(f"DeepSpeed Engine: After args sanity test", force=self.memory_breakdown())
+ if mpu is not None:
+ if self.elasticity_enabled():
+ if not self.is_elastic_model_parallel_supported():
+ assert not self.elasticity_enabled(), ("Elasticity is not currently supported"
+ " with model parallelism.")
+
+ self._set_distributed_vars(args)
+
+ dist.configure(self._config)
+
+ self.monitor = MonitorMaster(self._config.monitor_config)
+
+ see_memory_usage(
+ f"DeepSpeed Engine: Before configure distributed model",
+ force=self.memory_breakdown(),
+ )
+
+ self.pipeline_parallelism = isinstance(model, PipelineModule)
+
+ # Configure distributed model
+ self._configure_distributed_model(model)
+
+ # needed for zero_to_fp32 weights reconstruction to remap nameless data to state_dict
+ self.param_names = {param: name for name, param in model.named_parameters()}
+
+ self._get_model_parameters()
+
+ see_memory_usage(f"DeepSpeed Engine: After configure distributed model")
+
+ # Configure wall clock timers
+ self.timers = SynchronizedWallClockTimer()
+ # Throughput timer
+ self.tput_timer = ThroughputTimer(
+ batch_size=self.train_batch_size(),
+ steps_per_output=self.steps_per_print(),
+ monitor_memory=False,
+ )
+
+ log_dist(f"DeepSpeed Flops Profiler Enabled: {self.flops_profiler_enabled()}", ranks=[0])
+
+ if self.flops_profiler_enabled():
+ self.flops_profiler = FlopsProfiler(self.module, self, self.flops_profiler_recompute_fwd_factor())
+
+ if training_data:
+ self.training_dataloader = self.deepspeed_io(training_data)
+ else:
+ self.training_dataloader = None
+
+ # Configure optimizer and scheduler
+ self.optimizer = None
+ self.basic_optimizer = None
+ self.lr_scheduler = None
+ has_optimizer = False
+
+ if optimizer or self.optimizer_name():
+ has_optimizer = True
+ # If no parameters given by init default to module parameters
+ if model_parameters is None:
+ model_parameters = self.module.parameters()
+
+ # Convert model parameters from generator to list
+ if not isinstance(model_parameters, list):
+ model_parameters = list(model_parameters)
+
+ if has_optimizer:
+ self._configure_optimizer(optimizer, model_parameters)
+ self._configure_lr_scheduler(lr_scheduler)
+ self._report_progress(0)
+ elif self.zero_optimization():
+ # no optim selected but zero is enabled
+ self.optimizer = self._configure_zero_optimizer(optimizer=None)
+ elif self.bfloat16_enabled():
+ self.optimizer = self._configure_bf16_optimizer(optimizer=None)
+
+ # Hook optimizer for snip_momentum pruning
+ if hasattr(model, 'pruners'):
+ from deepspeed.compression.helper import rewrite_optimizer_step
+ self.optimizer.pruners = model.pruners
+ rewrite_optimizer_step(self.optimizer)
+
+ # Bookkeeping for sparse support
+ self.sparse_tensor_module_names = set()
+ # if self.sparse_gradients_enabled():
+ for name, module in self.module.named_modules():
+ if isinstance(module, (torch.nn.Embedding, torch.nn.EmbeddingBag)) and self.sparse_gradients_enabled():
+ self.sparse_tensor_module_names.add(name + ".weight")
+ logger.info("Will convert {} to sparse tensor during training".format(name))
+
+ self.save_non_zero_checkpoint = False
+ self.save_zero_checkpoint = False
+ if not isinstance(self.optimizer, DeepSpeedZeRoOffload):
+ self._configure_checkpointing(dist_init_required)
+
+ if self.eigenvalue_enabled():
+ self.eigenvalue = self._configure_eigenvalue()
+
+ if self.pld_enabled():
+ self.progressive_layer_drop = self._configure_progressive_layer_drop()
+
+ if self.curriculum_enabled_legacy():
+ self.curriculum_scheduler_legacy = self._configure_curriculum_scheduler_legacy()
+
+ if self.random_ltd_enabled():
+ random_ltd_config = self.random_ltd_config()
+ random_ltd_config[RANDOM_LTD_GLOBAL_BATCH_SIZE] = self.train_batch_size()
+ random_ltd_config[RANDOM_LTD_MICRO_BATCH_SIZE] = self.train_micro_batch_size_per_gpu()
+ self.random_ltd_scheduler = self._configure_random_ltd_scheduler(random_ltd_config)
+
+ # Engine timers
+
+ self.engine_timers = EngineTimers(enable_micro_timers=self.wall_clock_breakdown(),
+ enable_global_timers=self.wall_clock_breakdown()
+ or self.flops_profiler_enabled())
+
+ if self.global_rank == 0:
+ self._config.print("DeepSpeedEngine configuration")
+ if self.dump_state():
+ print_configuration(self, "DeepSpeedEngine")
+
+ # Use torch (un)flatten ops
+ self.flatten = _flatten_dense_tensors
+ self.unflatten = _unflatten_dense_tensors
+
+ def destroy(self):
+ if self.optimizer is not None and hasattr(self.optimizer, 'destroy'):
+ self.optimizer.destroy()
+
+ def _get_model_parameters(self):
+ if self.autotuning_profile_model_info():
+ self.autotuning_model_info = {}
+ num_params = 0
+ trainable_num_params = 0
+
+ for p in self.module.parameters():
+ # since user code might call deepspeed.zero.Init() before deepspeed.initialize(), need to check the attribute to check if the parameter is partitioned in zero 3 already or not
+ n = 0
+ if hasattr(p, "ds_tensor"): # if the parameter is partitioned in zero 3
+ n += p.ds_numel
+ else: # if the parameter is not partitioned in zero 3 yet
+ n += p.numel()
+ num_params += n
+ if p.requires_grad:
+ trainable_num_params += n
+ if self.global_rank == 0:
+ self.autotuning_model_info["num_params"] = num_params * self.mp_world_size
+ self.autotuning_model_info["trainable_num_params"] = trainable_num_params * self.mp_world_size
+
+ logger.info(f"model parameter = {num_params}")
+
+ def get_batch_info(self):
+ """Get all training batch related settings.
+ Returns:
+ train_batch_size (int): The effective training batch size. This is the amount of data
+ samples that leads to one step of model update.
+ train_micro_batch_size_per_gpu (int): Batch size to be processed by one GPU in one
+ step (without gradient accumulation).
+ gradient_accumulation_steps (int): Number of training steps to accumulate gradients
+ before averaging and applying them.
+ """
+ return (
+ self.train_batch_size,
+ self.train_micro_batch_size_per_gpu,
+ self.gradient_accumulation_steps,
+ )
+
+ def set_train_batch_size(self, train_batch_size):
+ """Adjust the global batch size by increasing or decreasing the number of
+ micro-batches (i.e., gradient accumulation steps). The size of each micro-batch
+ (i.e., ``train_micro_batch_size_per_gpu``) is not changed.
+ Args:
+ train_batch_size (int): The new global batch size for training.
+ Raises:
+ ValueError: if ``train_batch_size`` is not divisible by the
+ configured micro-batch size and data parallelism.
+ """
+ if train_batch_size % (self.train_micro_batch_size_per_gpu() * self.dp_world_size) != 0:
+ #print(f'{train_batch_size=} {self.train_micro_batch_size_per_gpu()=} {self.dp_world_size=}')
+ raise ValueError(f'Train batch size must be divisible by micro-batch data parallelism')
+ new_gas = train_batch_size // (self.train_micro_batch_size_per_gpu() * self.dp_world_size)
+ # overwrite config
+ self._config.train_batch_size = train_batch_size
+ self._config.gradient_accumulation_steps = new_gas
+
+ def set_train_micro_batch_size(self, micro_batch_size):
+ """Adjust the micro batch size(i.e., the micro batch size in every data parallel group),
+ while keep the gradient accumulation steps the same.
+ Args:
+ micro_batch_size (int): The new micro batch size for training.
+ """
+ # overwrite config
+ new_global_batch_size = micro_batch_size * self._config.gradient_accumulation_steps * self.dp_world_size
+ self._config.train_batch_size = new_global_batch_size
+ self._config.train_micro_batch_size_per_gpu = micro_batch_size
+
+ def set_data_post_process_func(self, post_process_func):
+ if self.training_dataloader is not None:
+ self.training_dataloader.post_process_func = post_process_func
+
+ def set_custom_curriculum_learning_schedule(self, schedule_func_dict):
+ if self.training_dataloader is not None and self.curriculum_learning_enabled():
+ self.training_dataloader.data_sampler.set_custom_curriculum_learning_schedule(schedule_func_dict)
+
+ def get_global_grad_norm(self) -> float:
+ """Return the 2-norm of all gradients. If there is model parallelism,
+ the norm will be global.
+ The computed norm will be cached and reused until the next step() pass.
+ .. note::
+ In the presence of model parallelism, this is a collective call
+ and acts as a barrier among ``mpu.get_model_parallel_group()``.
+ Returns:
+ float: norm
+ """
+ return self._global_grad_norm
+
+ def __getattr__(self, name):
+ """
+ Pass through attributes defined in the model if they are not overridden by ds-engine.
+ """
+
+ _module = {}
+ if "module" in self.__dict__:
+ _module = self.__dict__['module']
+ if name in dir(self):
+ return getattr(self, name)
+ elif name in dir(_module):
+ return getattr(_module, name)
+ else:
+ raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'")
+
+ def checkpoint_tag_validation_enabled(self):
+ return self._config.checkpoint_tag_validation_enabled
+
+ def checkpoint_tag_validation_fail(self):
+ return self._config.checkpoint_tag_validation_fail
+
+ def elasticity_enabled(self):
+ return self._config.elasticity_enabled
+
+ def is_elastic_model_parallel_supported(self):
+ if self.elasticity_enabled():
+ # Add code for finding number of GPUs per node automatically
+ if self._config.num_gpus_per_node % self._config.elastic_model_parallel_size == 0:
+ return True
+ else:
+ return False
+
+ def pld_enabled(self):
+ return self._config.pld_enabled
+
+ def pld_params(self):
+ return self._config.pld_params
+
+ def pld_theta(self):
+ return self.pld_params()[PLD_THETA]
+
+ def pld_gamma(self):
+ return self.pld_params()[PLD_GAMMA]
+
+ def eigenvalue_enabled(self):
+ return self._config.eigenvalue_enabled
+
+ def eigenvalue_verbose(self):
+ return self._config.eigenvalue_verbose
+
+ def eigenvalue_max_iter(self):
+ return self._config.eigenvalue_max_iter
+
+ def eigenvalue_tol(self):
+ return self._config.eigenvalue_tol
+
+ def eigenvalue_stability(self):
+ return self._config.eigenvalue_stability
+
+ def eigenvalue_gas_boundary_resolution(self):
+ return self._config.eigenvalue_gas_boundary_resolution
+
+ def eigenvalue_layer_name(self):
+ return self._config.eigenvalue_layer_name
+
+ def eigenvalue_layer_num(self):
+ return self._config.eigenvalue_layer_num
+
+ def curriculum_enabled_legacy(self):
+ return self._config.curriculum_enabled_legacy
+
+ def curriculum_params_legacy(self):
+ return self._config.curriculum_params_legacy
+
+ def data_efficiency_enabled(self):
+ return self._config.data_efficiency_enabled
+
+ def data_efficiency_config(self):
+ return self._config.data_efficiency_config
+
+ def data_sampling_enabled(self):
+ return self._config.data_efficiency_config[DATA_SAMPLING][DATA_SAMPLING_ENABLED]
+
+ def data_sampling_config(self):
+ return self._config.data_efficiency_config[DATA_SAMPLING]
+
+ def curriculum_learning_enabled(self):
+ return self._config.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING][CURRICULUM_LEARNING_ENABLED]
+
+ def curriculum_learning_config(self):
+ return self._config.data_efficiency_config[DATA_SAMPLING][CURRICULUM_LEARNING]
+
+ def random_ltd_enabled(self):
+ return self._config.data_efficiency_config[DATA_ROUTING][RANDOM_LTD][RANDOM_LTD_ENABLED]
+
+ def random_ltd_config(self):
+ return self._config.data_efficiency_config[DATA_ROUTING][RANDOM_LTD]
+
+ def random_ltd_initialize(self):
+ assert self.random_ltd_enabled()
+ random_ltd_config = self.random_ltd_config()
+ random_ltd_queue = deque([x for x in sorted(random_ltd_config[RANDOM_LTD_LAYER_ID])])
+ count = 0
+ for name, layer in self.module.named_modules():
+ if isinstance(layer, RandomLayerTokenDrop):
+ if len(random_ltd_queue) != 0 and str(random_ltd_queue[0]) in name: ###[1,2,3]
+ layer.init_config(random_ltd_config, self.random_ltd_scheduler, count)
+ random_ltd_queue.popleft()
+ count += 1
+
+ if random_ltd_config[RANDOM_LTD_LAYER_NUM] != count:
+ raise ValueError(f'random_ltd_layer_num {random_ltd_config[RANDOM_LTD_LAYER_NUM]} must be \
+ equivalent to the len of random_ltd_layer_id {count}')
+
+ if random_ltd_config[RANDOM_LTD_LAYER_TOKEN_LR_SCHEDULE][RANDOM_LTD_LAYER_TOKEN_LR_ENABLED]:
+ assert self.client_lr_scheduler is None
+ raise ValueError(f'not yet support')
+ #self.lr_scheduler = lr_schedules.WarmupLayerTokenDecayLR(self.optimizer, self.random_ltd_scheduler)
+
+ def wall_clock_breakdown(self):
+ return self._config.wall_clock_breakdown
+
+ def flops_profiler_enabled(self):
+ return self._config.flops_profiler_config.enabled or self.autotuning_enabled()
+
+ def flops_profiler_recompute_fwd_factor(self):
+ return self._config.flops_profiler_config.recompute_fwd_factor
+
+ def flops_profiler_profile_step(self):
+ step = self._config.flops_profiler_config.profile_step
+ if self._config.autotuning_config.enabled:
+ step = self.autotuning_start_profile_step()
+ return step
+
+ def flops_profiler_module_depth(self):
+ return self._config.flops_profiler_config.module_depth
+
+ def flops_profiler_top_modules(self):
+ return self._config.flops_profiler_config.top_modules
+
+ def flops_profiler_detailed(self):
+ if self._config.autotuning_config.enabled:
+ return False
+ return self._config.flops_profiler_config.detailed
+
+ def flops_profiler_output_file(self):
+ return self._config.flops_profiler_config.output_file
+
+ def memory_breakdown(self):
+ return self._config.memory_breakdown
+
+ def autotuning_enabled(self):
+ return self._config.autotuning_config.enabled
+
+ def autotuning_start_profile_step(self):
+ return self._config.autotuning_config.start_profile_step
+
+ def autotuning_end_profile_step(self):
+ return self._config.autotuning_config.end_profile_step
+
+ def autotuning_metric_path(self):
+ path = self._config.autotuning_config.metric_path
+ if not path:
+ path = os.path.join(os.getcwd(), "autotuning_metric.json")
+ return path
+
+ def autotuning_model_info_path(self):
+ path = self._config.autotuning_config.model_info_path
+ if not path:
+ path = os.path.join(os.getcwd(), "autotuning_model_info.json")
+ return path
+
+ def autotuning_metric(self):
+ return self._config.autotuning_config.metric
+
+ def autotuning_profile_model_info(self):
+ return self.autotuning_enabled(
+ ) and self._config.autotuning_config.model_info and self._config.autotuning_config.model_info.get(
+ "profile", False)
+
+ def sparse_gradients_enabled(self):
+ return self._config.sparse_gradients_enabled
+
+ def train_batch_size(self):
+ return self._config.train_batch_size
+
+ def train_micro_batch_size_per_gpu(self):
+ return self._config.train_micro_batch_size_per_gpu
+
+ def optimizer_name(self):
+ return (self.client_optimizer.__class__.__name__ if self.client_optimizer else self._config.optimizer_name)
+
+ def optimizer_params(self):
+ return self._config.optimizer_params
+
+ def optimizer_legacy_fusion(self):
+ return self._config.optimizer_legacy_fusion
+
+ def scheduler_name(self):
+ return self._config.scheduler_name
+
+ def scheduler_params(self):
+ return self._config.scheduler_params
+
+ def quantize_training(self):
+ return (
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS]
+ [WEIGHT_QUANTIZE_IN_FORWARD_ENABLED],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_ENABLED],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_GROUPS],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS]
+ [WEIGHT_QUANTIZE_FP16_MIXED_QUANTIZE],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_CHANGE_RATIO],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_TYPE],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_ROUNDING],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_VERBOSE],
+ self._config.compression_config[WEIGHT_QUANTIZATION][SHARED_PARAMETERS][WEIGHT_QUANTIZE_KERNEL],
+ )
+
+ def zero_optimization(self):
+ return self._config.zero_enabled
+
+ def zero_allow_untested_optimizer(self):
+ return self._config.zero_allow_untested_optimizer
+
+ def zero_force_ds_cpu_optimizer(self):
+ return self._config.zero_force_ds_cpu_optimizer
+
+ def zero_reduce_scatter(self):
+ return self._config.zero_config.reduce_scatter
+
+ def zero_overlap_comm(self):
+ return self._config.zero_config.overlap_comm
+
+ def zero_offload_optimizer(self):
+ return self._config.zero_config.offload_optimizer
+
+ def zero_offload_param(self):
+ return self._config.zero_config.offload_param
+
+ def zero_use_cpu_optimizer(self):
+ if self._config.zero_config.offload_optimizer is not None:
+ return self._config.zero_config.offload_optimizer.device in [OffloadDeviceEnum.cpu, OffloadDeviceEnum.nvme]
+ return False
+
+ def zero_cpu_offload(self):
+ if self._config.zero_config.offload_optimizer is not None:
+ return self._config.zero_config.offload_optimizer.device == OffloadDeviceEnum.cpu
+ return False
+
+ def zero_partial_offload(self):
+ return getattr(self._config.zero_config.offload_optimizer, "ratio", 1.0)
+
+ def zero_sub_group_size(self):
+ return self._config.zero_config.sub_group_size
+
+ def zero_optimization_stage(self):
+ return self._config.zero_optimization_stage
+
+ def mics_shard_size(self):
+ return self._config.mics_shard_size
+
+ def zero_reduce_bucket_size(self):
+ return self._config.zero_config.reduce_bucket_size
+
+ def zero_multi_rank_bucket_allreduce(self):
+ return self._config.zero_config.use_multi_rank_bucket_allreduce
+
+ def zero_allgather_bucket_size(self):
+ return self._config.zero_config.allgather_bucket_size
+
+ def zero_optimization_partition_gradients(self):
+ return self.zero_optimization_stage() >= ZeroStageEnum.gradients
+
+ def zero_optimization_partition_weights(self):
+ return self.zero_optimization_stage() >= ZeroStageEnum.weights
+
+ def is_first_weights_partition_group(self):
+ ret = True if self.mics_shard_size() < 0 \
+ and self.zero_optimization_partition_weights() else False
+ if self.mics_shard_size() > 0 and self.global_rank < self.mics_shard_size():
+ ret = True
+ return ret
+
+ def zero_contiguous_gradients(self):
+ return self._config.zero_config.contiguous_gradients
+
+ def zero_load_from_fp32_weights(self):
+ return self._config.zero_config.load_from_fp32_weights
+
+ def zero_elastic_checkpoint(self):
+ return self._config.zero_config.elastic_checkpoint
+
+ def zero_max_live_parameters(self):
+ return self._config.zero_config.max_live_parameters
+
+ def zero_max_reuse_distance(self):
+ return self._config.zero_config.max_reuse_distance
+
+ def zero_prefetch_bucket_size(self):
+ return self._config.zero_config.prefetch_bucket_size
+
+ def zero_param_persistence_threshold(self):
+ return self._config.zero_config.param_persistence_threshold
+
+ def zero_model_persistence_threshold(self):
+ return self._config.zero_config.model_persistence_threshold
+
+ def zero_gather_16bit_weights_on_model_save(self):
+ return self._config.zero_config.gather_16bit_weights_on_model_save
+
+ def zero_grad_hooks(self):
+ return self._config.zero_config.grad_hooks
+
+ def zero_legacy_stage1(self):
+ return self._config.zero_config.legacy_stage1
+
+ def zero_ignore_unused_parameters(self):
+ return self._config.zero_config.ignore_unused_parameters
+
+ def graph_harvesting(self):
+ return self._config.graph_harvesting
+
+ def fp16_enabled(self):
+ return self._config.fp16_enabled
+
+ def bfloat16_enabled(self):
+ return self._config.bfloat16_enabled
+
+ def fp16_master_weights_and_gradients(self):
+ return self._config.fp16_master_weights_and_gradients
+
+ def amp_enabled(self):
+ return self._config.amp_enabled
+
+ def amp_params(self):
+ return self._config.amp_params
+
+ def fp16_auto_cast(self):
+ return self._config.fp16_auto_cast
+
+ def loss_scale(self):
+ return self._config.loss_scale
+
+ def gradient_accumulation_steps(self):
+ return self._config.gradient_accumulation_steps
+
+ def use_node_local_storage(self):
+ return self._config.use_node_local_storage
+
+ def load_universal_checkpoint(self):
+ return self._config.load_universal_checkpoint
+
+ @property
+ def communication_data_type(self):
+ res = self._config.communication_data_type
+ if res is not None:
+ return res
+
+ if self.fp16_enabled():
+ return torch.float16
+
+ if self.bfloat16_enabled():
+ return torch.bfloat16
+
+ return torch.float32
+
+ @communication_data_type.setter
+ def communication_data_type(self, value):
+ self._config.communication_data_type = value
+
+ def postscale_gradients(self):
+ return not self._config.prescale_gradients
+
+ def gradient_predivide_factor(self):
+ return self._config.gradient_predivide_factor
+
+ def steps_per_print(self):
+ return self._config.steps_per_print
+
+ def zero_allgather_partitions(self):
+ return self._config.zero_config.allgather_partitions
+
+ def zero_round_robin_gradients(self):
+ return self._config.zero_config.round_robin_gradients
+
+ def zero_hpz_partition_size(self):
+ return self._config.zero_config.zero_hpz_partition_size
+
+ def zero_quantized_weights(self):
+ return self._config.zero_config.zero_quantized_weights
+
+ def zero_quantized_nontrainable_weights(self):
+ return self._config.zero_config.zero_quantized_nontrainable_weights
+
+ def zero_quantized_gradients(self):
+ return self._config.zero_config.zero_quantized_gradients
+
+ def dump_state(self):
+ return self._config.dump_state
+
+ def gradient_clipping(self):
+ return self._config.gradient_clipping
+
+ def dynamic_loss_scale(self):
+ return self._config.loss_scale == 0
+
+ def initial_dynamic_scale(self):
+ return self._config.initial_dynamic_scale
+
+ def dynamic_loss_scale_args(self):
+ return self._config.dynamic_loss_scale_args
+
+ def swap_tensor_config(self):
+ return self._config.swap_tensor_config
+
+ def aio_config(self):
+ return self._config.aio_config
+
+ def get_data_types(self):
+ model_dtype = torch.float32
+ if self.fp16_enabled():
+ model_dtype = torch.float16
+ elif self.bfloat16_enabled():
+ model_dtype = torch.bfloat16
+
+ if self._config.grad_accum_dtype is None:
+ if model_dtype == torch.bfloat16 and not self.zero_optimization():
+ grad_accum_dtype = torch.float32
+ else:
+ grad_accum_dtype = model_dtype
+ else:
+ grad_accum_dtype = DtypeEnum(self._config.grad_accum_dtype).value
+
+ return (model_dtype, grad_accum_dtype)
+
+ def _optimizer_has_ckpt_event_prologue(self):
+ return self.optimizer is not None and hasattr(self.optimizer, 'checkpoint_event_prologue')
+
+ def _optimizer_has_ckpt_event_epilogue(self):
+ return self.optimizer is not None and hasattr(self.optimizer, 'checkpoint_event_epilogue')
+
+ def _configure_lr_scheduler(self, client_lr_scheduler):
+ # First check for scheduler in json configuration
+ lr_scheduler = self._scheduler_from_config(self.optimizer)
+ if lr_scheduler:
+ log_dist(f"DeepSpeed using configured LR scheduler = {self.scheduler_name()}", ranks=[0])
+ self.lr_scheduler = lr_scheduler
+ else:
+ if isinstance(client_lr_scheduler, Callable):
+ log_dist('DeepSpeed using client callable to create LR scheduler', ranks=[0])
+ self.lr_scheduler = client_lr_scheduler(self.basic_optimizer)
+ else:
+ log_dist('DeepSpeed using client LR scheduler', ranks=[0])
+ self.lr_scheduler = client_lr_scheduler
+
+ log_dist(f'DeepSpeed LR Scheduler = {self.lr_scheduler}', ranks=[0])
+
+ def _configure_checkpointing(self, dist_init_required):
+ self.checkpoint_engine = TorchCheckpointEngine()
+
+ if self._config is not None and self._config.nebula_config.enabled:
+ try:
+ from deepspeed.runtime.checkpoint_engine.nebula_checkpoint_engine import \
+ NebulaCheckpointEngine
+ self.checkpoint_engine = NebulaCheckpointEngine(config_params=self._config.nebula_config)
+ except ImportError as err:
+ logger.error(f"No torch_nebula was found! Will fall back to torch.save. Details: {err}")
+ self.checkpoint_engine = TorchCheckpointEngine()
+
+ dp_rank = groups._get_sequence_data_parallel_rank()
+
+ rank = self.local_rank if self.use_node_local_storage() else dp_rank
+
+ # only the first data parallel process needs to store the model checkpoint
+ # if you want to use node local storage this must be done by rank 0 on each
+ # node
+ self.save_non_zero_checkpoint = (rank == 0) or (self.zero_optimization_partition_weights()
+ and self.is_first_weights_partition_group())
+
+ if self.zero_optimization() or self.bfloat16_enabled():
+ param_rank = dist.get_rank(group=self.optimizer.zp_process_group)
+
+ # Only the first parameter parallel process needs to store the
+ # optimizer state checkpoints for zero
+ self.save_zero_checkpoint = param_rank == dp_rank
+
+ def _scheduler_from_config(self, optimizer):
+ scheduler_name = self.scheduler_name()
+ if scheduler_name is not None:
+ if hasattr(lr_schedules, scheduler_name):
+ scheduler = getattr(lr_schedules, scheduler_name)
+ else:
+ assert hasattr(torch.optim.lr_scheduler,
+ scheduler_name), f"DeepSpeed does not recognize LR scheduler {scheduler_name}"
+
+ scheduler = getattr(torch.optim.lr_scheduler, scheduler_name)
+
+ scheduler_params = self.scheduler_params()
+ instantiated_scheduler = scheduler(optimizer, **scheduler_params)
+ return instantiated_scheduler
+ else:
+ return None
+
+ def _set_distributed_vars(self, args):
+ device_rank = args.device_rank if args is not None and hasattr(args, 'device_rank') else self.local_rank
+ if device_rank >= 0:
+ get_accelerator().set_device(device_rank)
+ self.device = torch.device(get_accelerator().device_name(), device_rank)
+ self.world_size = dist.get_world_size()
+ self.global_rank = dist.get_rank()
+ else:
+ self.world_size = 1
+ self.global_rank = 0
+ self.device = torch.device(get_accelerator().device_name())
+
+ # Configure based on command line arguments
+ def _configure_with_arguments(self, args, mpu):
+ # After the distributed backend is initialized we are guaranteed the LOCAL_RANK
+ # environment variable is set. We must align args.local_rank to this value for
+ # backwards compatibility with scripts relying on [args|self].local_rank containing
+ # the correct local rank info. _do_args_sanity_check will ensure this is the case.
+
+ if "OMPI_COMM_WORLD_LOCAL_RANK" in os.environ:
+ ompi_local_rank = os.environ.get("OMPI_COMM_WORLD_LOCAL_RANK")
+ local_rank = os.environ.get('LOCAL_RANK', ompi_local_rank)
+ assert ompi_local_rank == local_rank, f"LOCAL_RANK ({local_rank}) != OMPI_COMM_WORLD_LOCAL_RANK ({ompi_local_rank}), " \
+ "not sure how to proceed as we're seeing conflicting local rank info."
+ os.environ['LOCAL_RANK'] = local_rank
+
+ self.local_rank = int(os.environ['LOCAL_RANK'])
+ if hasattr(args, 'local_rank'):
+ args.local_rank = self.local_rank
+
+ # Validate command line arguments
+ def _do_args_sanity_check(self, args):
+ assert "LOCAL_RANK" in os.environ or "OMPI_COMM_WORLD_LOCAL_RANK" in os.environ, "DeepSpeed requires the LOCAL_RANK environment " \
+ "variable, it is set by the deepspeed launcher, deepspeed.init_distributed, or the torch's launcher. If using a " \
+ "different launcher please ensure LOCAL_RANK is set prior to initializing deepspeed."
+
+ if hasattr(args, 'local_rank') and args.local_rank is not None:
+ assert isinstance(args.local_rank,
+ int), f"args.local_rank of {args.local_rank} is an unknown type {type(args.local_rank)}"
+ if args.local_rank >= 0:
+ env_local_rank = int(os.environ.get("LOCAL_RANK"))
+ assert (
+ env_local_rank == args.local_rank
+ ), f"Mismatch in local rank setting, args.local_rank={args.local_rank} but env['LOCAL_RANK']={env_local_rank}."
+
+ def _is_supported_optimizer(self, optimizer_name):
+ return (optimizer_name in DEEPSPEED_OPTIMIZERS or getattr(torch.optim, optimizer_name, None) is not None)
+
+ def _supported_optims(self):
+ FairseqOptimizer = None
+ try:
+ from fairseq.optim.fairseq_optimizer import FairseqOptimizer
+ except ImportError:
+ pass
+
+ expected_optim_types = [Optimizer]
+ if FairseqOptimizer:
+ # fairseq optims are not torch.optim objects
+ expected_optim_types.append(FairseqOptimizer)
+ return expected_optim_types
+
+ # Validate configuration based on command line arguments
+ def _do_sanity_check(self):
+ expected_optim_types = self._supported_optims()
+ expected_optim_types += [type(None), Callable]
+ assert isinstance(self.client_optimizer, tuple(expected_optim_types)), \
+ f'Client Optimizer is of unexpected type {type(self.client_optimizer)}'
+
+ if not self.client_optimizer:
+ if self.optimizer_name() is not None:
+ assert self._is_supported_optimizer(
+ self.optimizer_name()), "{} is not a supported DeepSpeed Optimizer".format(self.optimizer_name())
+
+ if (self.optimizer_name() == LAMB_OPTIMIZER or self.optimizer_name() == ONEBIT_LAMB_OPTIMIZER):
+ assert (self.dynamic_loss_scale()), "DeepSpeed {} optimizer requires dynamic loss scaling".format(
+ self.optimizer_name())
+
+ # Detect invalid combinations of client optimizer and client scheduler
+ if isinstance(self.client_lr_scheduler, _LRScheduler):
+ assert isinstance(self.client_optimizer, Optimizer), \
+ f'Client Optimizer (type = {type(self.client_optimizer)} is not instantiated but Client LR Scheduler is instantiated'
+
+ def _broadcast_model(self):
+
+ def is_replicated(p):
+ if hasattr(p, "ds_status") and p.ds_status is not ZeroParamStatus.AVAILABLE:
+ return False
+ return True
+
+ for p in self.module.parameters():
+ # Broadcast the model for different parameters
+ if is_moe_param(p):
+ if torch.is_tensor(p) and is_replicated(p):
+ dist.broadcast(p,
+ groups._get_expert_broadcast_src_rank(p.group_name),
+ group=self.expert_data_parallel_group[p.group_name])
+ else:
+ if torch.is_tensor(p) and is_replicated(p):
+ dist.broadcast(p, groups._get_broadcast_src_rank(), group=self.seq_data_parallel_group)
+
+ @staticmethod
+ def __check_params(model: Module, dtype: torch.dtype) -> None:
+ return
+ if not all(param.dtype == dtype for param in model.parameters()) and dist.get_rank() == 0:
+ raise ValueError(f"{dtype} is enabled but the following parameters have dtype that is "
+ f"not {dtype}: "
+ f"{[(n, p.dtype) for n, p in model.named_parameters() if p.dtype != dtype]}")
+
+ def _set_client_model(self, model):
+ # register client model in _modules so that nn.module methods work correctly
+ modules = self.__dict__.get('_modules')
+ modules['module'] = model
+ # register module attribute in engine but avoid getattr
+ self.__dict__['module'] = model
+
+ def _configure_distributed_model(self, model):
+ self._set_client_model(model)
+ is_zero_init_model = self.zero_optimization_partition_weights() and any(
+ [hasattr(param, "ds_id") for param in self.module.parameters()])
+
+ if self.fp16_enabled():
+ if is_zero_init_model:
+ self.__check_params(self.module, torch.half)
+ self.module.half()
+ elif self.bfloat16_enabled():
+ if is_zero_init_model:
+ self.__check_params(self.module, torch.bfloat16)
+ self.module.bfloat16()
+ else:
+ self.__check_params(self.module, torch.float)
+
+ # zero.Init() handles device placement of model
+ if not (self.dont_change_device or is_zero_init_model):
+ self.module.to(self.device)
+
+ # MoE related initialization
+ for _, module in self.module.named_modules():
+ if isinstance(module, MoE):
+ self.has_moe_layers = True
+ self.num_experts.append(module.num_experts)
+
+ if self.has_moe_layers:
+ for _, module in self.module.named_modules():
+ if isinstance(module, TopKGate):
+ self.gate_modules.append(module)
+ if self.wall_clock_breakdown():
+ module.wall_clock_breakdown = True
+ if isinstance(module, MOELayer):
+ self.moe_layers.append(module)
+ if self.wall_clock_breakdown():
+ module.wall_clock_breakdown = True
+
+ # Pass the mpu from here to groups. For subsequent use, just query groups
+ if self.mpu is not None:
+ groups.mpu = self.mpu
+
+ # Set deepspeed parallelism spec. for the model including expert parallelism
+ for _, module in self.module.named_modules():
+ if hasattr(module, 'set_deepspeed_parallelism'):
+ module.set_deepspeed_parallelism(self._config.use_data_before_expert_parallel_)
+
+ # Query the groups module to get information about various parallel groups
+ self.local_all_to_all_group = None
+ if self.zero_quantized_gradients():
+ log_dist("Using quantized gradients", ranks=[0])
+ self.local_all_to_all_group = groups._get_local_all_to_all_group()
+ self.data_parallel_group = groups._get_data_parallel_group()
+ self.dp_world_size = groups._get_data_parallel_world_size()
+ self.zp_world_size = zp_manager.zp_size
+ self.seq_data_parallel_group = groups._get_sequence_data_parallel_group()
+ self.seq_dp_world_size = groups._get_sequence_data_parallel_world_size()
+ self.mp_world_size = groups._get_model_parallel_world_size()
+ self.expert_parallel_group = groups._get_expert_parallel_group_dict()
+ self.expert_data_parallel_group = groups._get_expert_data_parallel_group_dict()
+ self.sequence_parallel_size = groups._get_sequence_parallel_world_size()
+ if self.sequence_parallel_size > 1:
+ self.communication_data_type = self._config.seq_parallel_communication_data_type
+
+ if not (self.amp_enabled() or is_zero_init_model):
+ self._broadcast_model()
+
+ # check if parameters are duplicated in optimizer param_groups
+ def _check_for_duplicates(self, optimizer):
+ for name, param in self.module.named_parameters():
+ param_id = id(param)
+
+ def ids_list(group):
+ return [id(param) for param in group]
+
+ occurrence = sum([
+ ids_list(group['params']).count(param_id) if param_id in ids_list(group['params']) else 0
+ for group in optimizer.param_groups
+ ])
+ assert occurrence <= 1, f"Parameter with name: {name} occurs multiple times in optimizer.param_groups. Make sure it only appears once to prevent undefined behavior."
+
+ def _do_optimizer_sanity_check(self, basic_optimizer):
+ model_dtype, grad_accum_dtype = self.get_data_types()
+ zero_enabled = self.zero_optimization()
+ amp_enabled = self.amp_enabled()
+ # config based assertions
+ assert (
+ not (amp_enabled and zero_enabled)
+ ), "Amp and ZeRO are not currently compatible, please use (legacy) fp16 mode which performs similar to amp opt_mode=O2"
+ if zero_enabled:
+ if not is_zero_supported_optimizer(basic_optimizer):
+ assert (
+ self.zero_allow_untested_optimizer()
+ ), 'You are using an untested ZeRO Optimizer. Please add <"zero_allow_untested_optimizer": true> in the configuration file to use it.'
+
+ if self.global_rank == 0:
+ logger.warning("**** You are using ZeRO with an untested optimizer, proceed with caution *****")
+ if model_dtype == torch.bfloat16 and grad_accum_dtype == torch.float32 and self.zero_optimization_stage(
+ ) == 1 and not self.zero_cpu_offload():
+ return BFLOAT16
+ return ZERO_OPTIMIZATION
+ elif amp_enabled:
+ if model_dtype != grad_accum_dtype:
+ raise NotImplementedError(
+ "Model data type and gradient accumulation data type must be equal to use Amp")
+ if model_dtype == torch.bfloat16 or model_dtype == torch.float16:
+ raise NotImplementedError("Cannot enable both amp with (legacy) fp16 or bfloat16 mode")
+ try:
+ logger.info("Initializing Apex amp from: {}".format(amp.__path__))
+ except NameError:
+ # If apex/amp is available it will be imported above
+ raise RuntimeError("Unable to import apex/amp, please make sure it is installed")
+ return AMP
+ # data type checks
+ elif model_dtype == grad_accum_dtype:
+ if model_dtype == torch.bfloat16:
+ if self.pipeline_parallelism:
+ logger.warning(
+ "**** BF16 gradient accumulation is not safe numerically with large number of accumulation steps, proceed with caution *****"
+ )
+ return BFLOAT16
+ else:
+ raise NotImplementedError(
+ "Bfloat16 wrapper must use a gradient accumulation type of fp32, enable ZeRO to use Bfloat16 gradient accumulation"
+ )
+ if model_dtype == torch.float16:
+ return FP16
+ # else optimizer_wrapper = None
+ elif model_dtype == torch.bfloat16 and grad_accum_dtype == torch.float32:
+ return BFLOAT16
+ else:
+ raise NotImplementedError("unsupported mix of model dtype and gradient accumulation type")
+
+ return None
+
+ # Configure optimizer
+ def _configure_optimizer(self, client_optimizer, model_parameters):
+ if client_optimizer is None:
+ basic_optimizer = self._configure_basic_optimizer(model_parameters)
+ log_dist(f"Using DeepSpeed Optimizer param name {self.optimizer_name()} as basic optimizer", ranks=[0])
+ else:
+ if isinstance(client_optimizer, tuple(self._supported_optims())):
+ basic_optimizer = client_optimizer
+ log_dist('Using client Optimizer as basic optimizer', ranks=[0])
+ else:
+ basic_optimizer = client_optimizer(model_parameters)
+ log_dist('Using client callable to create basic optimizer', ranks=[0])
+
+ if self.zero_use_cpu_optimizer() and not isinstance(basic_optimizer, deepspeed.ops.adam.DeepSpeedCPUAdam):
+ if self.zero_force_ds_cpu_optimizer():
+ msg = f'You are using ZeRO-Offload with a client provided optimizer ({type(basic_optimizer)}) which in most cases will yield poor performance. Please either use deepspeed.ops.adam.DeepSpeedCPUAdam or set an optimizer in your ds-config (https://www.deepspeed.ai/docs/config-json/#optimizer-parameters). If you really want to use a custom optimizer w. ZeRO-Offload and understand the performance impacts you can also set <"zero_force_ds_cpu_optimizer": false> in your configuration file.'
+ raise ZeRORuntimeException(msg)
+
+ basic_optimizer.param_groups[:] = [pg for pg in basic_optimizer.param_groups if len(pg["params"]) != 0]
+ log_dist("Removing param_group that has no 'params' in the basic Optimizer", ranks=[0])
+
+ self._check_for_duplicates(basic_optimizer)
+
+ self.basic_optimizer = basic_optimizer
+ log_dist("DeepSpeed Basic Optimizer = {}".format(basic_optimizer.__class__.__name__), ranks=[0])
+
+ optimizer_wrapper = self._do_optimizer_sanity_check(basic_optimizer)
+
+ if optimizer_wrapper == ZERO_OPTIMIZATION:
+ self.optimizer = self._configure_zero_optimizer(basic_optimizer)
+ elif optimizer_wrapper == AMP:
+ amp_params = self.amp_params()
+ log_dist(f"Initializing AMP with these params: {amp_params}", ranks=[0])
+ model, self.optimizer = amp.initialize(self.module, basic_optimizer, **amp_params)
+ self._set_client_model(model)
+ self._broadcast_model()
+ # TODO: maybe need to broadcast experts differently?
+ elif optimizer_wrapper == FP16:
+ self.optimizer = self._configure_fp16_optimizer(basic_optimizer)
+ elif optimizer_wrapper == BFLOAT16:
+ self.optimizer = self._configure_bf16_optimizer(basic_optimizer)
+ else:
+ self.optimizer = basic_optimizer
+
+ log_dist("DeepSpeed Final Optimizer = {}".format(self.optimizer_name()), ranks=[0])
+
+ self.compression_scheduler = self._configure_compression_scheduler()
+ self.quantizer = self._configure_quantization()
+
+ def _configure_basic_optimizer(self, model_parameters):
+ optimizer_parameters = self.optimizer_params()
+ if optimizer_parameters is None:
+ optimizer_parameters = {}
+ # print(optimizer_parameters.keys())
+ if "max_grad_norm" in optimizer_parameters.keys():
+ raise ValueError(
+ "'max_grad_norm' is not supported as an optimizer parameter, please switch to using the deepspeed parameter 'gradient_clipping' see: https://www.deepspeed.ai/docs/config-json/#gradient-clipping for more details"
+ )
+
+ if self.optimizer_name() in [ADAM_OPTIMIZER, ADAMW_OPTIMIZER]:
+ torch_adam = optimizer_parameters.pop(TORCH_ADAM_PARAM, False)
+ adam_w_mode = optimizer_parameters.pop(ADAM_W_MODE, ADAM_W_MODE_DEFAULT)
+
+ # Optimizer name of Adam forces AdamW logic unless adam_w_mode is explicitly set
+ effective_adam_w_mode = self.optimizer_name() == ADAMW_OPTIMIZER or adam_w_mode
+
+ if torch_adam:
+ if not effective_adam_w_mode:
+ optimizer = torch.optim.Adam(model_parameters, **optimizer_parameters)
+ else:
+ optimizer = torch.optim.AdamW(model_parameters, **optimizer_parameters)
+ else:
+ if self.zero_use_cpu_optimizer():
+ from deepspeed.ops.adam import DeepSpeedCPUAdam
+ optimizer = DeepSpeedCPUAdam(model_parameters,
+ **optimizer_parameters,
+ adamw_mode=effective_adam_w_mode)
+ else:
+ from deepspeed.ops.adam import FusedAdam
+
+ optimizer = FusedAdam(
+ model_parameters,
+ **optimizer_parameters,
+ adam_w_mode=effective_adam_w_mode,
+ )
+
+ elif self.optimizer_name() == ADAGRAD_OPTIMIZER:
+ if self.zero_use_cpu_optimizer():
+ from deepspeed.ops.adagrad import DeepSpeedCPUAdagrad
+ optimizer = DeepSpeedCPUAdagrad(model_parameters, **optimizer_parameters)
+ else:
+ optimizer = torch.optim.Adagrad(model_parameters, **optimizer_parameters)
+ elif self.optimizer_name() == LAMB_OPTIMIZER:
+ from deepspeed.ops.lamb import FusedLamb
+
+ optimizer = FusedLamb(model_parameters, **optimizer_parameters)
+ elif self.optimizer_name() == ONEBIT_ADAM_OPTIMIZER:
+ assert not self.zero_optimization(), "1bit-Adam is not compatible with ZeRO"
+ from deepspeed.runtime.fp16.onebit.adam import OnebitAdam
+
+ optimizer = OnebitAdam(model_parameters, self, **optimizer_parameters)
+ if not self.fp16_enabled():
+ logger.warning(f"Currently the convergence of 1-bit Adam is only verified under FP16")
+ elif self.optimizer_name() == ZERO_ONE_ADAM_OPTIMIZER:
+ assert not self.zero_optimization(), "0/1 Adam is not compatible with ZeRO"
+ from deepspeed.runtime.fp16.onebit.zoadam import ZeroOneAdam
+
+ optimizer = ZeroOneAdam(model_parameters, self, **optimizer_parameters)
+ if not self.fp16_enabled():
+ logger.warning(f'Currently the convergence of 0/1 Adam is only verified under FP16')
+ elif self.optimizer_name() == ONEBIT_LAMB_OPTIMIZER:
+ assert not self.zero_optimization(), "1bit-Lamb is not compatible with ZeRO"
+ from deepspeed.runtime.fp16.onebit.lamb import OnebitLamb
+
+ optimizer = OnebitLamb(model_parameters, self, **optimizer_parameters)
+ if not self.fp16_enabled():
+ logger.warning(f"Currently the convergence of 1-bit Lamb is only verified under FP16")
+ elif self.optimizer_name() == LION_OPTIMIZER:
+ if self.zero_use_cpu_optimizer():
+ from deepspeed.ops.lion import DeepSpeedCPULion
+ optimizer = DeepSpeedCPULion(model_parameters, **optimizer_parameters)
+ else:
+ from deepspeed.ops.lion import FusedLion
+ optimizer = FusedLion(model_parameters, **optimizer_parameters)
+ elif self.optimizer_name() == MUADAM_OPTIMIZER:
+ try:
+ from mup import MuAdam
+ except ImportError:
+ logger.error(f"Install mup to use MuAdam optimizer")
+ optimizer = MuAdam(model_parameters, **optimizer_parameters)
+ elif self.optimizer_name() == MUADAMW_OPTIMIZER:
+ try:
+ from mup import MuAdamW
+ except ImportError:
+ logger.error(f"Install mup to use MuAdamW optimizer")
+ optimizer = MuAdamW(model_parameters, **optimizer_parameters)
+ elif self.optimizer_name() == MUSGD_OPTIMIZER:
+ try:
+ from mup import MuSGD
+ except ImportError:
+ logger.error(f"Install mup to use MuSGD optimizer")
+ optimizer = MuSGD(model_parameters, **optimizer_parameters)
+ else:
+ torch_optimizer = getattr(torch.optim, self.optimizer_name())
+ optimizer = torch_optimizer(model_parameters, **optimizer_parameters)
+ return optimizer
+
+ def _configure_compression_scheduler(self):
+ return compression_scheduler(self.module, self._config.compression_config)
+
+ def _configure_random_ltd_scheduler(self, configs):
+ return RandomLTDScheduler(configs)
+
+ def _configure_quantization(self):
+ (
+ quantize_weight_in_forward,
+ quantize_enabled,
+ q_groups,
+ q_mixed_fp16,
+ q_change_ratio,
+ q_type,
+ q_rounding,
+ q_verbose,
+ use_quantizer_kernel,
+ ) = self.quantize_training()
+ if quantize_enabled and not quantize_weight_in_forward:
+ assert self.fp16_enabled(
+ ), "MoQ (quantize in optimization step) weight quantization is only supported for FP16"
+ quantizer = None
+ if quantize_enabled and not quantize_weight_in_forward:
+ from deepspeed.runtime.quantize import Quantizer
+
+ quantizer = Quantizer(
+ q_groups,
+ q_mixed_fp16,
+ q_change_ratio,
+ q_type,
+ q_rounding,
+ q_verbose,
+ self.eigenvalue_enabled(),
+ use_quantizer_kernel,
+ self.eigenvalue_layer_num() if self.eigenvalue_enabled() else 0,
+ )
+ return quantizer
+
+ def _configure_fp16_optimizer(self, optimizer):
+ initial_dynamic_scale = self.initial_dynamic_scale()
+ dynamic_loss_args = self.dynamic_loss_scale_args()
+ clip_grad = self.gradient_clipping()
+ if APEX_INSTALLED:
+ fused_opts = (apex.optimizers.FusedAdam, FusedAdam)
+ else:
+ fused_opts = FusedAdam
+ if isinstance(optimizer, fused_opts) \
+ or self.optimizer_name() in [ONEBIT_ADAM_OPTIMIZER, ZERO_ONE_ADAM_OPTIMIZER]:
+ if self.dynamic_loss_scale():
+ log_dist(f'Creating fp16 optimizer with dynamic loss scale', ranks=[0])
+ timers = self.timers if self.wall_clock_breakdown() else NoopTimer()
+ optimizer = FP16_Optimizer(
+ optimizer,
+ deepspeed=self,
+ dynamic_loss_scale=True,
+ initial_dynamic_scale=initial_dynamic_scale,
+ dynamic_loss_args=dynamic_loss_args,
+ mpu=self.mpu,
+ clip_grad=clip_grad,
+ fused_adam_legacy=self.optimizer_legacy_fusion(),
+ timers=timers,
+ has_moe_layers=self.has_moe_layers,
+ )
+ else:
+ log_dist(f'Creating fp16 optimizer with static loss scale: {self.loss_scale()}', ranks=[0])
+ optimizer = FP16_Optimizer(
+ optimizer,
+ deepspeed=self,
+ static_loss_scale=self.loss_scale(),
+ mpu=self.mpu,
+ clip_grad=clip_grad,
+ fused_adam_legacy=self.optimizer_legacy_fusion(),
+ has_moe_layers=self.has_moe_layers,
+ )
+ else:
+ log_dist(f'Creating fp16 unfused optimizer with dynamic loss scale', ranks=[0])
+ optimizer = FP16_UnfusedOptimizer(
+ optimizer,
+ deepspeed=self,
+ static_loss_scale=self.loss_scale(),
+ dynamic_loss_scale=self.dynamic_loss_scale(),
+ dynamic_loss_args=dynamic_loss_args,
+ mpu=self.mpu,
+ clip_grad=clip_grad,
+ fused_lamb_legacy=self.optimizer_name() == LAMB_OPTIMIZER,
+ )
+
+ return optimizer
+
+ def _configure_bf16_optimizer(self, optimizer):
+ clip_grad = self.gradient_clipping()
+
+ if optimizer is None:
+ optimizer = DummyOptim(list(self.module.parameters()))
+
+ log_dist('Creating BF16 optimizer', ranks=[0])
+
+ timers = self.timers if self.wall_clock_breakdown() else NoopTimer()
+ optimizer = BF16_Optimizer(optimizer,
+ self.param_names,
+ mpu=self.mpu,
+ clip_grad=clip_grad,
+ allgather_bucket_size=self.zero_allgather_bucket_size(),
+ dp_process_group=self.seq_data_parallel_group,
+ timers=timers,
+ grad_acc_dtype=self.get_data_types()[1],
+ graph_harvesting=self.graph_harvesting())
+
+ return optimizer
+
+ def _configure_zero_optimizer(self, optimizer):
+ zero_stage = self.zero_optimization_stage()
+
+ mics_shard_size = self.mics_shard_size()
+ model_dtype, gradient_accumulation_dtype = self.get_data_types()
+
+ timers = self.timers if self.wall_clock_breakdown() else NoopTimer()
+
+ if optimizer is None:
+ optimizer = DummyOptim(list(self.module.parameters()))
+
+ if self.zero_legacy_stage1():
+ raise Exception(
+ "The deprecated version of ZeRO Stage 1 is not supported in deepspeed >= 0.5.9. Please downgrade to a version less than 0.5.9 if you need to use this deprecated version of ZeRO."
+ )
+
+ if zero_stage <= ZeroStageEnum.gradients:
+ overlap_comm = self.zero_overlap_comm()
+ contiguous_gradients = self.zero_contiguous_gradients()
+ round_robin_gradients = self.zero_round_robin_gradients()
+ assert not isinstance(optimizer, DummyOptim), "zero stage {} requires an optimizer".format(zero_stage)
+
+ log_dist(f'Creating {model_dtype} ZeRO stage {zero_stage} optimizer', ranks=[0])
+ # Overlap and contiguous grads are meaningless in stage 1 and are ignored
+ if zero_stage == ZeroStageEnum.optimizer_states:
+ overlap_comm = False
+ round_robin_gradients = False
+ # Non-MoE requires contiguous grads to be disabled w. stage 1
+ if not self.has_moe_layers:
+ contiguous_gradients = False
+
+ if isinstance(self.module, PipelineModule):
+ if overlap_comm:
+ logger.warning("Pipeline parallelism does not support overlapped communication, will be disabled.")
+ overlap_comm = False
+ optimizer = DeepSpeedZeroOptimizer(
+ optimizer,
+ self.param_names,
+ timers=timers,
+ static_loss_scale=self.loss_scale(),
+ dynamic_loss_scale=self.dynamic_loss_scale(),
+ dynamic_loss_args=self.dynamic_loss_scale_args(),
+ clip_grad=self.gradient_clipping(),
+ contiguous_gradients=contiguous_gradients,
+ reduce_bucket_size=self.zero_reduce_bucket_size(),
+ use_multi_rank_bucket_allreduce=self.zero_multi_rank_bucket_allreduce(),
+ allgather_bucket_size=self.zero_allgather_bucket_size(),
+ dp_process_group=self.seq_data_parallel_group,
+ expert_parallel_group=self.expert_parallel_group if self.has_moe_layers else None,
+ expert_data_parallel_group=self.expert_data_parallel_group if self.has_moe_layers else None,
+ reduce_scatter=self.zero_reduce_scatter(),
+ overlap_comm=overlap_comm,
+ offload_optimizer_config=self.zero_offload_optimizer(),
+ mpu=self.mpu,
+ postscale_gradients=self.postscale_gradients(),
+ gradient_predivide_factor=self.gradient_predivide_factor(),
+ gradient_accumulation_steps=self.gradient_accumulation_steps(),
+ ignore_unused_parameters=self.zero_ignore_unused_parameters(),
+ partition_grads=zero_stage == ZeroStageEnum.gradients,
+ round_robin_gradients=round_robin_gradients,
+ has_moe_layers=self.has_moe_layers,
+ fp16_master_weights_and_gradients=self.fp16_master_weights_and_gradients(),
+ gradient_accumulation_dtype=gradient_accumulation_dtype,
+ communication_data_type=self.communication_data_type,
+ elastic_checkpoint=self.zero_elastic_checkpoint())
+
+ elif zero_stage == ZeroStageEnum.weights:
+ assert not self.has_moe_layers, "MoE not supported with Stage 3"
+ if isinstance(optimizer, DummyOptim):
+ log_dist("Creating ZeRO Offload", ranks=[0])
+ zero_param_parallel_group = groups._get_zero_param_intra_parallel_group()
+ if self.zero_hpz_partition_size() > 1 and zero_param_parallel_group is None:
+ self._set_zero_group_parallelism()
+ zero_param_parallel_group = groups._get_zero_param_intra_parallel_group()
+ optimizer = DeepSpeedZeRoOffload(
+ self.module,
+ timers=timers,
+ ds_config=self.config,
+ overlap_comm=self.zero_overlap_comm(),
+ prefetch_bucket_size=self.zero_prefetch_bucket_size(),
+ max_reuse_distance=self.zero_max_reuse_distance(),
+ max_live_parameters=self.zero_max_live_parameters(),
+ param_persistence_threshold=self.zero_param_persistence_threshold(),
+ model_persistence_threshold=self.zero_model_persistence_threshold(),
+ offload_param_config=self.zero_offload_param(),
+ mpu=self.mpu,
+ zero_param_parallel_group=zero_param_parallel_group,
+ zero_quantized_weights=self.zero_quantized_weights(),
+ zero_quantized_nontrainable_weights=self.zero_quantized_nontrainable_weights(),
+ )
+ else:
+ log_dist(
+ f'Creating fp16 ZeRO stage {zero_stage} optimizer,'
+ f' MiCS is enabled {mics_shard_size>0},'
+ f' Hierarchical params gather {self._config.mics_hierarchial_params_gather}',
+ ranks=[0])
+ if mics_shard_size > 0:
+ return self._return_mics_optimizer(optimizer, timers)
+
+ log_dist(f'Creating {model_dtype} ZeRO stage {zero_stage} optimizer', ranks=[0])
+ from deepspeed.runtime.zero.stage3 import DeepSpeedZeroOptimizer_Stage3
+ optimizer = DeepSpeedZeroOptimizer_Stage3(
+ self.module,
+ optimizer,
+ timers=timers,
+ ds_config=self.config,
+ static_loss_scale=self.loss_scale(),
+ dynamic_loss_scale=self.dynamic_loss_scale(),
+ dynamic_loss_args=self.dynamic_loss_scale_args(),
+ clip_grad=self.gradient_clipping(),
+ contiguous_gradients=self.zero_contiguous_gradients(),
+ reduce_bucket_size=self.zero_reduce_bucket_size(),
+ prefetch_bucket_size=self.zero_prefetch_bucket_size(),
+ max_reuse_distance=self.zero_max_reuse_distance(),
+ max_live_parameters=self.zero_max_live_parameters(),
+ param_persistence_threshold=self.zero_param_persistence_threshold(),
+ model_persistence_threshold=self.zero_model_persistence_threshold(),
+ dp_process_group=self.seq_data_parallel_group,
+ all2all_process_group=self.local_all_to_all_group,
+ reduce_scatter=self.zero_reduce_scatter(),
+ overlap_comm=self.zero_overlap_comm(),
+ offload_optimizer_config=self.zero_offload_optimizer(),
+ offload_param_config=self.zero_offload_param(),
+ sub_group_size=self.zero_sub_group_size(),
+ offload_ratio=self.zero_partial_offload(),
+ mpu=self.mpu,
+ postscale_gradients=self.postscale_gradients(),
+ gradient_predivide_factor=self.gradient_predivide_factor(),
+ gradient_accumulation_steps=self.gradient_accumulation_steps(),
+ aio_config=self.aio_config(),
+ gradient_accumulation_dtype=gradient_accumulation_dtype,
+ communication_data_type=self.communication_data_type,
+ zero_hpz_partition_size=self.zero_hpz_partition_size(),
+ zero_quantized_weights=self.zero_quantized_weights(),
+ zero_quantized_nontrainable_weights=self.zero_quantized_nontrainable_weights(),
+ )
+
+ else:
+ raise NotImplementedError("ZeRO stage {} not implemented".format(zero_stage))
+
+ return optimizer
+
+ def _return_mics_optimizer(self, basic_optimizer, timers):
+ from deepspeed.runtime.zero.mics import MiCS_Optimizer
+ model_dtype, gradient_accumulation_dtype = self.get_data_types()
+ optimizer = MiCS_Optimizer(self.module,
+ basic_optimizer,
+ timers=timers,
+ ds_config=self.config,
+ static_loss_scale=self.loss_scale(),
+ dynamic_loss_scale=self.dynamic_loss_scale(),
+ dynamic_loss_args=self.dynamic_loss_scale_args(),
+ clip_grad=self.gradient_clipping(),
+ contiguous_gradients=self.zero_contiguous_gradients(),
+ reduce_bucket_size=self.zero_reduce_bucket_size(),
+ prefetch_bucket_size=self.zero_prefetch_bucket_size(),
+ max_reuse_distance=self.zero_max_reuse_distance(),
+ max_live_parameters=self.zero_max_live_parameters(),
+ param_persistence_threshold=self.zero_param_persistence_threshold(),
+ model_persistence_threshold=self.zero_model_persistence_threshold(),
+ dp_process_group=self.seq_data_parallel_group,
+ reduce_scatter=self.zero_reduce_scatter(),
+ overlap_comm=self.zero_overlap_comm(),
+ offload_optimizer_config=self.zero_offload_optimizer(),
+ offload_param_config=self.zero_offload_param(),
+ sub_group_size=self.zero_sub_group_size(),
+ mpu=self.mpu,
+ postscale_gradients=self.postscale_gradients(),
+ gradient_predivide_factor=self.gradient_predivide_factor(),
+ gradient_accumulation_steps=self.gradient_accumulation_steps(),
+ aio_config=self.aio_config(),
+ gradient_accumulation_dtype=gradient_accumulation_dtype,
+ communication_data_type=self.communication_data_type)
+ return optimizer
+
+ def _configure_eigenvalue(self):
+ eigenvalue = Eigenvalue(
+ verbose=self.eigenvalue_verbose(),
+ max_iter=self.eigenvalue_max_iter(),
+ tol=self.eigenvalue_tol(),
+ stability=self.eigenvalue_stability(),
+ gas_boundary_resolution=self.eigenvalue_gas_boundary_resolution(),
+ layer_name=self.eigenvalue_layer_name(),
+ layer_num=self.eigenvalue_layer_num(),
+ )
+
+ return eigenvalue
+
+ def _configure_progressive_layer_drop(self):
+ pld = ProgressiveLayerDrop(theta=self.pld_theta(), gamma=self.pld_gamma())
+
+ return pld
+
+ def _configure_curriculum_scheduler_legacy(self):
+ scheduler = CurriculumScheduler(self.curriculum_params_legacy())
+ return scheduler
+
+ @staticmethod
+ def is_map_style_dataset(obj):
+ return hasattr(obj, "__getitem__") and hasattr(obj, "__len__")
+
+ @staticmethod
+ def is_iterable_style_dataset(obj):
+ return isinstance(obj, torch.utils.data.IterableDataset) # hasattr(obj, "__iter__") should work as well
+
+ def dataloader_drop_last(self):
+ return self._config.dataloader_drop_last
+
+ def was_step_applied(self) -> bool:
+ """Returns True if the latest ``step()`` produced in parameter updates.
+ Note that a ``False`` return is not an error condition. Steps are frequently
+ no-ops, such as between gradient accumulation boundaries or when overflows
+ occur.
+ Returns:
+ bool: Whether the latest ``step()`` modified model parameters.
+ """
+ return self._step_applied
+
+ def deepspeed_io(self,
+ dataset,
+ batch_size=None,
+ route=ROUTE_TRAIN,
+ pin_memory=True,
+ data_sampler=None,
+ collate_fn=None,
+ num_local_io_workers=None):
+ if not (self.is_map_style_dataset(dataset) or self.is_iterable_style_dataset(dataset)):
+ raise ValueError("Training data must be a torch Dataset")
+
+ if batch_size is None:
+ batch_size = self.train_micro_batch_size_per_gpu()
+
+ if collate_fn is None:
+ collate_fn = self.collate_fn
+
+ # Currently we only use timer in train route
+ deepspeed_io_timer = None
+ if route == ROUTE_TRAIN:
+ deepspeed_io_timer = self.tput_timer
+
+ # If mpu is provided, forward world size and parallel rank to sampler.
+ data_parallel_world_size = self.dp_world_size
+ data_parallel_rank = self.global_rank
+ if self.mpu is not None:
+ data_parallel_world_size = self.mpu.get_data_parallel_world_size()
+ data_parallel_rank = self.mpu.get_data_parallel_rank()
+
+ if data_sampler is None and (route == ROUTE_PREDICT or route == ROUTE_EVAL):
+ data_sampler = torch.utils.data.DistributedSampler(
+ dataset,
+ num_replicas=data_parallel_world_size,
+ rank=data_parallel_rank,
+ shuffle=False,
+ )
+
+ deepspeed_dataloader_config = {}
+ if self.curriculum_learning_enabled():
+ deepspeed_dataloader_config = {
+ CURRICULUM_LEARNING: self.curriculum_learning_enabled(),
+ DATA_EFFICIENCY: self.data_efficiency_config(),
+ DATA_PARALLEL_GROUP: self.data_parallel_group,
+ GRADIENT_ACCUMULATION_STEPS: self.gradient_accumulation_steps(),
+ GLOBAL_RANK: self.global_rank,
+ DATA_SAMPLING_NUM_WORKERS: self.data_sampling_config()[DATA_SAMPLING_NUM_WORKERS]
+ }
+
+ return DeepSpeedDataLoader(dataset=dataset,
+ batch_size=batch_size,
+ pin_memory=pin_memory,
+ collate_fn=collate_fn,
+ local_rank=self.local_rank,
+ tput_timer=deepspeed_io_timer,
+ num_local_io_workers=num_local_io_workers,
+ data_sampler=data_sampler,
+ data_parallel_world_size=data_parallel_world_size,
+ data_parallel_rank=data_parallel_rank,
+ dataloader_drop_last=self.dataloader_drop_last(),
+ deepspeed_dataloader_config=deepspeed_dataloader_config)
+
+ def train(self, mode=True):
+ r""""""
+
+ self.warn_unscaled_loss = True
+ self.module.train(mode)
+
+ def eval(self):
+ r""""""
+
+ self.warn_unscaled_loss = True
+ self.module.train(False)
+
+ def _scale_loss_by_gas(self, prescaled_loss):
+ if isinstance(prescaled_loss, torch.Tensor):
+ scaled_loss = prescaled_loss / self.gradient_accumulation_steps()
+ elif isinstance(prescaled_loss, tuple) or isinstance(prescaled_loss, list):
+ scaled_loss = []
+ for l in prescaled_loss:
+ if isinstance(l, torch.Tensor):
+ scaled_loss.append(l / self.gradient_accumulation_steps())
+ else:
+ scaled_loss.append(l)
+ else:
+ scaled_loss = prescaled_loss
+ if self.warn_unscaled_loss:
+ logger.warning(f"DeepSpeed unable to scale loss because of type: {type(prescaled_loss)}")
+ self.warn_unscaled_loss = False
+
+ return scaled_loss
+
+ @instrument_w_nvtx
+ def forward(self, *inputs, **kwargs):
+ r"""Execute forward propagation
+ Arguments:
+ *inputs: Variable length input list
+ **kwargs: variable length keyword arguments
+ """
+
+ if self.autotuning_profile_model_info():
+ ma = get_ma_status()
+ else:
+ see_memory_usage("Engine before forward", force=self.memory_breakdown())
+
+ flops_profiler_active = (self.flops_profiler_enabled()
+ and self.global_steps == self.flops_profiler_profile_step() and self.global_rank == 0)
+
+ # used to check quantization happens at step 0!
+ if self.global_steps == 0 and hasattr(self, "compression_scheduler"):
+ self.compression_scheduler.step(step_zero_check=True)
+ if self.quantizer:
+ tensor_to_quantize = self.optimizer.bit16_groups if self.zero_optimization_stage(
+ ) == 2 else self.optimizer.fp16_groups
+ if self.compression_scheduler.weight_quantization_enabled:
+ self.quantizer.quantize(
+ tensor_to_quantize,
+ (self.optimizer.overflow if self.fp16_enabled() else False),
+ self.eigenvalue_enabled(),
+ None,
+ )
+
+ if flops_profiler_active:
+ self.flops_profiler.start_profile(ignore_list=None)
+
+ if self.module.training:
+ if self.progressive_layer_drop:
+ kwargs.update(self.progressive_layer_drop.get_state())
+
+ if self.__class__.__name__ != "PipelineEngine":
+ # TODO: The above if condition is a HACK since for PipelineEngine
+ # it's difficult to inject argument in forward pass.
+ if self.module.training and self.curriculum_enabled_legacy():
+ self.curriculum_scheduler_legacy.update_difficulty(self.global_steps + 1)
+ if self.curriculum_params_legacy()["curriculum_type"] == "seqlen":
+ kwargs.update({"curriculum_seqlen": self.curriculum_scheduler_legacy.get_current_difficulty()})
+
+ if self.module.training and self.random_ltd_enabled():
+ self.random_ltd_scheduler.update_seq(self.global_steps)
+
+ if self.zero_optimization_partition_weights():
+ # Enable automated discovery of external parameters by indicating that
+ # we are in a forward pass.
+ for module in self.module.modules():
+ module._parameters._in_forward = True
+
+ self._start_timers(self.engine_timers.forward_timers)
+
+ if self.training_dataloader is None:
+ self.tput_timer.start()
+
+ if self.fp16_auto_cast():
+ inputs = self._cast_inputs_half(inputs)
+ # print(f"RANK[{self.global_rank}] self.fp16_auto_cast() is {self.fp16_auto_cast()}")
+
+ loss = self.module(*inputs, **kwargs)
+
+ # print(f"RANK[{self.global_rank}]'s loss is {loss}")
+
+ if self.zero_optimization_partition_weights():
+ # Disable automated discovery of external parameters
+ for module in self.module.modules():
+ module._parameters._in_forward = False
+
+ self._stop_timers(self.engine_timers.forward_timers)
+
+ if flops_profiler_active:
+ self.flops_profiler.stop_profile()
+
+ if self.autotuning_profile_model_info():
+ activation_mem = get_ma_status() - ma
+ self.autotuning_model_info["activation_mem_per_gpu"] = activation_mem
+ print_json_dist(self.autotuning_model_info, [0], path=self.autotuning_model_info_path())
+ exit()
+ else:
+ see_memory_usage("Engine after forward", force=self.memory_breakdown())
+ return loss
+
+ def _cast_inputs_half(self, inputs):
+ if isinstance(inputs, (list, tuple)):
+ new_inputs = []
+ for v in inputs:
+ new_inputs.append(self._cast_inputs_half(v))
+ return inputs.__class__(new_inputs)
+ elif isinstance(inputs, dict):
+ new_inputs = {}
+ for k, v in inputs.items():
+ new_inputs[k] = self._cast_inputs_half(v)
+ return new_inputs
+ elif hasattr(inputs, 'half'):
+ return inputs.half()
+ else:
+ return inputs
+
+ def print_forward_breakdown(self, fwd_time):
+ gate_time = 0.0
+ moe_time = 0.0
+ falltoall = 0.0
+ salltoall = 0.0
+
+ for gate in self.gate_modules:
+ #logger.info(f"Individual TopK gate time: {gate.gate_time:.2f} ms")
+ gate_time += gate.gate_time
+
+ for l in self.moe_layers:
+ #logger.info(f"MoE layer; total: {l.time_moe:.2f} ms, first alltoall: {l.time_falltoall:.2f}, second alltoall: {l.time_salltoall:.2f}")
+ moe_time += l.time_moe
+ falltoall += l.time_falltoall
+ salltoall += l.time_salltoall
+
+ # TODO: Allreduce/average them across ranks for more accurate timing.
+
+ # if deepspeed.comm.get_rank() == 0:
+ log_dist(
+ f"time (ms) | fwd: {fwd_time:.2f} (fwd_moe: {moe_time:.2f}, 1st_a2a: {falltoall:.2f}, 2nd_a2a: {salltoall:.2f}, top_k: {gate_time:.2f})",
+ ranks=[0])
+
+ @instrument_w_nvtx
+ def allreduce_gradients(self, bucket_size=MEMORY_OPT_ALLREDUCE_SIZE):
+ assert not (self.bfloat16_enabled() and self.pipeline_parallelism), \
+ f'allreduce_gradients() is not valid when bfloat+pipeline_parallelism is enabled'
+
+ # Pass (PP) gas boundary flag to optimizer (required for zero)
+ self.optimizer.is_gradient_accumulation_boundary = self.is_gradient_accumulation_boundary()
+ # ZeRO stage >= 2 communicates during non gradient accumulation boundaries as well
+ if self.zero_optimization_partition_gradients():
+ self.optimizer.overlapping_partition_gradients_reduce_epilogue()
+
+ # Communicate only at gradient accumulation boundaries
+ elif self.is_gradient_accumulation_boundary():
+ if self.zero_optimization_stage() == ZeroStageEnum.optimizer_states and hasattr(
+ self.optimizer, 'reduce_gradients'):
+ self.optimizer.reduce_gradients(pipeline_parallel=self.pipeline_parallelism)
+ else:
+ self.buffered_allreduce_fallback(elements_per_buffer=bucket_size)
+
+ @instrument_w_nvtx
+ def backward(self, loss, allreduce_gradients=True, release_loss=False, retain_graph=False, scale_wrt_gas=True):
+ r"""Execute backward pass on the loss
+ Arguments:
+ loss: Torch tensor on which to execute backward propagation
+ allreduce_gradients: is deprecated, ignored, and will soon be removed'
+ retain_graph: bool, default: false
+ forward on user defined choice of retain_graph
+ """
+
+ see_memory_usage("Engine before backward", force=self.memory_breakdown())
+
+ if self.scale_wrt_gas is not None:
+ scale_wrt_gas = self.scale_wrt_gas
+
+ if not allreduce_gradients:
+ logger.warning(f"Argument `allreduce_gradients` is deprecated, ignored, and will soon be removed")
+
+ # scale loss w.r.t. gradient accumulation if needed
+ if self.gradient_accumulation_steps() > 1 and scale_wrt_gas:
+ loss = self._scale_loss_by_gas(loss.float())
+
+ # Log training loss
+ self.losses += loss.mean().item()
+ if self.monitor.enabled:
+ if self.is_gradient_accumulation_boundary():
+ if self.global_rank == 0:
+ self.summary_events = [(
+ f"Train/Samples/train_loss",
+ self.losses,
+ self.global_samples,
+ )]
+ self.monitor.write_events(self.summary_events)
+
+ self._start_timers(self.engine_timers.backward_timers)
+
+ assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
+ "must provide optimizer during init in order to use backward"
+
+ self._start_timers(self.engine_timers.backward_inner_timers)
+
+ if self.zero_optimization():
+ self.optimizer.is_gradient_accumulation_boundary = self.is_gradient_accumulation_boundary()
+ self.optimizer.backward(loss, retain_graph=retain_graph)
+ elif self.amp_enabled():
+ # AMP requires delaying unscale when inside gradient accumulation boundaries
+ # https://nvidia.github.io/apex/advanced.html#gradient-accumulation-across-iterations
+ delay_unscale = not self.is_gradient_accumulation_boundary()
+ with amp.scale_loss(loss, self.optimizer, delay_unscale=delay_unscale) as scaled_loss:
+ scaled_loss.backward(retain_graph=retain_graph)
+ elif self.fp16_enabled():
+ if self.eigenvalue_enabled():
+ self.optimizer.backward(loss, create_graph=True, retain_graph=True)
+ else:
+ self.optimizer.backward(loss, retain_graph=retain_graph)
+ elif self.bfloat16_enabled():
+ self.optimizer.backward(loss)
+ else:
+ if self.eigenvalue_enabled():
+ loss.backward(create_graph=True, retain_graph=True)
+ else:
+ loss.backward(retain_graph=retain_graph)
+
+ self._stop_timers(self.engine_timers.backward_inner_timers)
+
+ self._start_timers(self.engine_timers.backward_reduce_timers)
+
+ if allreduce_gradients and self.enable_backward_allreduce:
+ # Traditional code path that allreduces the module parameter grads
+ self.allreduce_gradients()
+
+ self._stop_timers(self.engine_timers.backward_reduce_timers)
+
+ self._stop_timers(self.engine_timers.backward_timers)
+
+ if release_loss:
+ # loss.data = None
+ pass
+
+ see_memory_usage("Engine after backward", force=self.memory_breakdown())
+
+ return loss
+
+ def is_gradient_accumulation_boundary(self):
+ """
+ Query whether the current micro-batch is at the boundary of
+ gradient accumulation, and thus will trigger gradient reductions and
+ an optimizer step.
+
+ Returns:
+ bool: if the current step is a gradient accumulation boundary.
+
+ """
+ if self._is_gradient_accumulation_boundary is None:
+ return (self.micro_steps + 1) % \
+ self.gradient_accumulation_steps() == 0
+ else:
+ return self._is_gradient_accumulation_boundary
+
+ def set_gradient_accumulation_boundary(self, is_boundary):
+ """
+ Manually overrides the DeepSpeed engine's gradient accumulation boundary state, this is an optional
+ feature and should be used with care. The state should be set before to the intended
+ value before each forward/backward. The final forward/backward should have the
+ boundary state set to True. This style allows client code to only call engine.step() once after all
+ the gradient accumulation passes are complete. See example below:
+ .. code-block:: python
+ engine.set_gradient_accumulation_boundary(False)
+ for _ in range(gradient_accumulation_steps - 1):
+ micro_batch = next(data_loader)
+ loss = engine(micro_batch)
+ engine.backward(loss)
+ engine.set_gradient_accumulation_boundary(True)
+ micro_batch = next(data_loader)
+ loss = engine(micro_batch)
+ engine.backward(loss)
+ engine.step()
+ Arguments:
+ is_boundary (bool): are we at a gradient accumulation boundary or not?
+ """
+ self._is_gradient_accumulation_boundary = is_boundary
+ self.optimizer.is_gradient_accumulation_boundary = is_boundary
+
+ def zero_grad(self):
+ """
+ Zero parameter grads.
+ """
+ for param_name, param in self.module.named_parameters():
+ param.grad = None
+
+ def clip_fp32_gradients(self):
+ clip_grad_norm_(parameters=self.module.parameters(), max_norm=self.gradient_clipping(), mpu=self.mpu)
+
+ def _take_model_step(self, lr_kwargs, block_eigenvalue={}):
+ if self.gradient_clipping() > 0.0:
+ if not (self.fp16_enabled() or self.bfloat16_enabled() or self.amp_enabled() or self.zero_optimization()):
+ self.clip_fp32_gradients()
+ elif self.amp_enabled():
+ # AMP's recommended way of doing clipping
+ # https://nvidia.github.io/apex/advanced.html#gradient-clipping
+ master_params = amp.master_params(self.optimizer)
+ clip_grad_norm_(parameters=master_params, max_norm=self.gradient_clipping(), mpu=self.mpu)
+ self.optimizer.step()
+
+ if hasattr(self.optimizer, '_global_grad_norm'):
+ self._global_grad_norm = self.optimizer._global_grad_norm
+
+ # Quantize the updated parameter if there is no overflow
+ if self.quantizer:
+ tensor_to_quantize = self.optimizer.bit16_groups if self.zero_optimization_stage(
+ ) == 2 else self.optimizer.fp16_groups
+ if self.compression_scheduler.weight_quantization_enabled:
+ self.quantizer.quantize(
+ tensor_to_quantize,
+ (self.optimizer.overflow if self.fp16_enabled() else False),
+ self.eigenvalue_enabled(),
+ block_eigenvalue,
+ )
+ # zero grad in basic optimizer could be unreliable and may not exhibit
+ # the behavior that we want
+ if self.bfloat16_enabled():
+ # TODO: Temporary until bf16_optimizer and zero_optimizer are integrated
+ if self.zero_optimization() and hasattr(self.optimizer, "zero_grad"):
+ self.optimizer.zero_grad()
+ else:
+ pass
+ elif self.zero_optimization() or self.fp16_enabled() or self.amp_enabled():
+ self.optimizer.zero_grad()
+ else:
+ self.zero_grad()
+
+ report_progress = self.global_rank == 0 if self.global_rank else True
+
+ # Check overflow here since in DS fp16 optimizer, the overflow is updated in above step() function.
+ overflow = False
+ if hasattr(self.optimizer, "overflow"):
+ overflow = self.optimizer.overflow
+ self._step_applied = not overflow
+
+ if overflow:
+ self.skipped_steps += 1
+ else:
+ self.compression_scheduler.step()
+ if self.lr_scheduler is not None:
+ try:
+ self.lr_scheduler.step(**(lr_kwargs or {}))
+ except TypeError:
+ # XXX Hack to work with Megatron 2.0 and DeepSpeed pipelines.
+ # We don't currently have a way to specify lr_kwargs from
+ # pipe_engine.train_batch()
+ self.lr_scheduler.step(self.train_batch_size())
+
+ if report_progress and (self.global_steps + 1) % self.steps_per_print() == 0:
+ self._report_progress(self.global_steps + 1)
+
+ self.losses = 0.0
+ self.global_steps += 1
+ self.global_samples += self.train_batch_size()
+
+ def step(self, lr_kwargs=None):
+ r"""Execute the weight update step after forward and backward propagation
+ on effective_train_batch.
+ """
+ see_memory_usage("Engine before step", force=self.memory_breakdown())
+
+ # Check early because self.global_steps is incremented at some point here.
+ # TODO: Delay self.global_steps increment until very end of this function.
+ flops_profiler_active = self.flops_profiler_enabled(
+ ) and self.global_steps == self.flops_profiler_profile_step() and self.global_rank == 0
+
+ self._start_timers(self.engine_timers.step_timers)
+
+ assert self.optimizer is not None and not isinstance(self.optimizer, DummyOptim), \
+ "must provide optimizer during init in order to use step"
+
+ report_progress = False
+
+ self._step_applied = False # assume False, will flip to True
+
+ # Update the model when we reach gradient accumulation boundaries
+ if self.is_gradient_accumulation_boundary():
+ self.gas_boundary_ctr += 1
+
+ if (self.eigenvalue_enabled() and (self.gas_boundary_ctr % self.eigenvalue_gas_boundary_resolution() == 0)
+ and self.quantizer.any_precision_switch()):
+ log_dist(f"computing eigenvalue...", ranks=[0])
+ self.block_eigenvalue = self.eigenvalue.compute_eigenvalue(self.module, self.device,
+ self.optimizer.cur_scale)
+
+ if self.progressive_layer_drop:
+ self.progressive_layer_drop.update_state(self.global_steps)
+
+ if (self.eigenvalue_enabled() and not self.gas_boundary_ctr % self.eigenvalue_gas_boundary_resolution()
+ and self.quantizer.any_precision_switch()):
+ self._take_model_step(lr_kwargs, self.block_eigenvalue)
+ else:
+ self._take_model_step(lr_kwargs)
+
+ report_progress = self.global_rank == 0 if self.global_rank else True
+
+ self.tput_timer.stop(global_step=self.is_gradient_accumulation_boundary(), report_speed=report_progress)
+
+ self._stop_timers(self.engine_timers.step_timers)
+
+ # Log learning rate
+ if self.monitor.enabled:
+ if self.is_gradient_accumulation_boundary():
+ if self.global_rank == 0:
+ self.summary_events = [(f"Train/Samples/lr", self.get_lr()[0], self.global_samples)]
+
+ if self.fp16_enabled() and hasattr(self.optimizer, "cur_scale"):
+ self.summary_events.append((
+ f"Train/Samples/loss_scale",
+ self.optimizer.cur_scale,
+ self.global_samples,
+ ))
+
+ if (self.eigenvalue_enabled()
+ and not self.gas_boundary_ctr % self.eigenvalue_gas_boundary_resolution()):
+ ev_values = self.block_eigenvalue.values()
+ for i in range(len(ev_values)):
+ self.summary_events.append((
+ f"Train/Eigenvalues/ModelBlockParam_{i}",
+ self.ev_values[i][0],
+ self.global_samples,
+ ))
+ self.monitor.write_events(self.summary_events)
+
+ # Check flops profiling
+ if flops_profiler_active:
+ if self.autotuning_enabled():
+ self.flops = self.flops_profiler.get_total_flops() * 3
+ self.fwd_duration = self.flops_profiler.get_total_duration()
+ else:
+ self.flops_profiler.print_model_profile(
+ profile_step=self.global_steps,
+ module_depth=self.flops_profiler_module_depth(),
+ top_modules=self.flops_profiler_top_modules(),
+ detailed=self.flops_profiler_detailed(),
+ output_file=self.flops_profiler_output_file(),
+ )
+ self.flops_profiler.end_profile()
+
+ if self.autotuning_enabled() and self.global_steps == (self.autotuning_end_profile_step() + 1):
+ self._autotuning_exit()
+
+ if self.wall_clock_breakdown():
+ # Log micro timing and reset
+ self.timers.log(names=self.engine_timers.micro_timers, memory_breakdown=self.memory_breakdown())
+
+ if self.wall_clock_breakdown() or self.flops_profiler_enabled():
+ # Log global timing and reset
+ if self.is_gradient_accumulation_boundary():
+ if self.monitor.enabled:
+ self._write_monitor()
+
+ if self.has_moe_layers:
+ fwd_time = self.timers(FORWARD_GLOBAL_TIMER).elapsed(reset=False)
+ self.print_forward_breakdown(fwd_time=fwd_time)
+
+ self.timers.log(self.engine_timers.global_timers)
+
+ self.micro_steps += 1
+ see_memory_usage("Engine after step", force=self.memory_breakdown())
+
+ def _start_timers(self, timer_names):
+ for name in timer_names:
+ self.timers(name).start()
+
+ def _stop_timers(self, timer_names):
+ record = self.is_gradient_accumulation_boundary() and \
+ self.flops_profiler_enabled() and \
+ (self.global_steps >= self.flops_profiler_profile_step())
+ for name in timer_names:
+ self.timers(name).stop(record=record)
+
+ def _autotuning_exit(self):
+ if self.global_rank == 0:
+ msg = self.timers.get_mean([
+ FORWARD_GLOBAL_TIMER,
+ BACKWARD_GLOBAL_TIMER,
+ STEP_GLOBAL_TIMER,
+ ], reset=False)
+ titer = 0.0
+ titer += msg[FORWARD_GLOBAL_TIMER] if FORWARD_GLOBAL_TIMER in msg else 0
+ titer += msg[BACKWARD_GLOBAL_TIMER] if BACKWARD_GLOBAL_TIMER in msg else 0
+ titer += msg[STEP_GLOBAL_TIMER] if STEP_GLOBAL_TIMER in msg else 0
+ titer *= self.gradient_accumulation_steps()
+ msg["latency"] = titer
+ msg["FLOPS_per_gpu"] = self.flops * 1_000_000 * self.gradient_accumulation_steps() / titer
+ msg["throughput"] = self.train_batch_size() * 1_000_000 / \
+ msg["latency"]
+ print_json_dist(msg, [0], path=self.autotuning_metric_path())
+ log_dist(
+ f"Wrote metrics to {self.autotuning_metric_path()}, {os.path.abspath(self.autotuning_metric_path())}",
+ ranks=[0])
+ import atexit
+ atexit.register(print, "Autotuning: done with running current ds config.")
+ exit()
+
+ def _write_monitor(self):
+ if self.global_rank == 0:
+ self.summary_events = [
+ (
+ f"Train/Samples/elapsed_time_ms_forward",
+ self.timers(FORWARD_GLOBAL_TIMER).elapsed(reset=False),
+ self.global_samples,
+ ),
+ (
+ f"Train/Samples/elapsed_time_ms_backward",
+ self.timers(BACKWARD_GLOBAL_TIMER).elapsed(reset=False),
+ self.global_samples,
+ ),
+ (
+ f"Train/Samples/elapsed_time_ms_backward_inner",
+ self.timers(BACKWARD_INNER_GLOBAL_TIMER).elapsed(reset=False),
+ self.global_samples,
+ ),
+ (
+ f"Train/Samples/elapsed_time_ms_backward_allreduce",
+ self.timers(BACKWARD_REDUCE_GLOBAL_TIMER).elapsed(reset=False),
+ self.global_samples,
+ ),
+ (
+ f"Train/Samples/elapsed_time_ms_step",
+ self.timers(STEP_GLOBAL_TIMER).elapsed(reset=False),
+ self.global_samples,
+ ),
+ ]
+ self.monitor.write_events(self.summary_events)
+
+ def _get_optimizer_param(self, param_name):
+ result = []
+ if not self.optimizer:
+ return result
+ for group in self.optimizer.param_groups:
+ if param_name in group:
+ result.append(group[param_name])
+ else:
+ result.append(0.0)
+ return result
+
+ def get_lr(self):
+ return self._get_optimizer_param("lr")
+
+ def get_type(self):
+ return self._get_optimizer_param("type")
+
+ def get_mom(self):
+ if self.optimizer_name() in ["SGD", "RMSprop"]:
+ return self._get_optimizer_param("momentum")
+ else:
+ return self._get_optimizer_param("betas")
+
+ def get_pld_theta(self):
+ if self.progressive_layer_drop:
+ return self.progressive_layer_drop.get_theta()
+ else:
+ return None
+
+ def _report_progress(self, step):
+ lr = self.get_lr()
+ mom = self.get_mom()
+ log_dist(f"step={step}, skipped={self.skipped_steps}, lr={lr}, mom={mom}", ranks=[0])
+
+ def allreduce_bucket(self, bucket, dp_group):
+ tensor = self.flatten(bucket)
+
+ tensor_to_allreduce = tensor
+
+ if self.communication_data_type != tensor.dtype:
+ tensor_to_allreduce = tensor.to(self.communication_data_type)
+
+ if self.postscale_gradients():
+ if self.gradient_predivide_factor() != 1.0:
+ tensor_to_allreduce.mul_(1.0 / self.gradient_predivide_factor())
+
+ dist.all_reduce(tensor_to_allreduce, group=dp_group)
+ if self.gradient_average:
+ if self.gradient_predivide_factor() != dist.get_world_size(group=dp_group):
+ tensor_to_allreduce.mul_(self.gradient_predivide_factor() / dist.get_world_size(group=dp_group))
+ else:
+ tensor_to_allreduce.mul_(1. / dist.get_world_size(group=dp_group))
+ dist.all_reduce(tensor_to_allreduce, group=dp_group)
+
+ if self.communication_data_type != tensor.dtype and tensor is not tensor_to_allreduce:
+ tensor.copy_(tensor_to_allreduce)
+
+ return tensor
+
+ def allreduce_and_copy(self, small_bucket, dp_group):
+ allreduced = self.allreduce_bucket(small_bucket, dp_group)
+ for buf, synced in zip(small_bucket, self.unflatten(allreduced, small_bucket)):
+ buf.copy_(synced)
+
+ def allreduce_no_retain(self, bucket, dp_group, numel_per_bucket=500000000):
+ small_bucket = []
+ numel = 0
+ for tensor in bucket:
+ small_bucket.append(tensor)
+ numel = numel + tensor.numel()
+ if numel > numel_per_bucket:
+ self.allreduce_and_copy(small_bucket, dp_group)
+ small_bucket = []
+ numel = 0
+ if len(small_bucket) > 0:
+ self.allreduce_and_copy(small_bucket, dp_group)
+
+ def _get_gradients_for_reduction(self):
+ non_expert_grads = []
+ expert_grads = {}
+ if self.has_moe_layers:
+ for key in self.expert_data_parallel_group.keys():
+ expert_grads[key] = []
+
+ for param_name, param in self.module.named_parameters():
+ if not param.requires_grad:
+ continue
+
+ if param.grad is None:
+ # In cases where there is an imbalance of empty grads across
+ # ranks we must create empty grads, this will ensure that every
+ # rank is reducing the same size. In some cases it may make
+ # sense in the future to support the ability to average not
+ # w.r.t. world size but with a different value.
+ param.grad = torch.zeros(param.size(), dtype=param.dtype, device=param.device)
+
+ grad_data = param.grad.data
+ if param_name in self.sparse_tensor_module_names or grad_data.is_sparse:
+ # Call param.grad without data to avoid problem with setting of updated grads
+ grad_data = SparseTensor(param.grad)
+
+ if is_moe_param(param):
+ expert_grads[param.group_name].append(grad_data)
+ else:
+ non_expert_grads.append(grad_data)
+
+ return non_expert_grads, expert_grads
+
+ def _reduce_non_expert_gradients(self, grads, elements_per_buffer):
+ split_buckets = split_half_float_double_sparse(grads)
+ for _, bucket_tuple in enumerate(split_buckets):
+ bucket_type, bucket = bucket_tuple
+
+ if self.pipeline_parallelism:
+ dp_group = self.mpu.get_data_parallel_group()
+ else:
+ dp_group = groups._get_sequence_data_parallel_group()
+
+ if bucket_type == SparseTensor.type():
+ self.sparse_allreduce_no_retain(bucket, dp_group=dp_group)
+ else:
+ self.allreduce_no_retain(bucket, dp_group=dp_group, numel_per_bucket=elements_per_buffer)
+
+ def _reduce_expert_gradients(self, expert_grads, elements_per_buffer):
+ for ep_name, expert_grads_group in expert_grads.items():
+ expert_split_buckets = split_half_float_double_sparse(expert_grads_group)
+ for i, bucket_tuple in enumerate(expert_split_buckets):
+ bucket_type, bucket = bucket_tuple
+ if bucket_type == SparseTensor.type():
+ self.sparse_allreduce_no_retain(bucket, groups._get_expert_data_parallel_group(ep_name))
+ else:
+ # Separate between diff groups
+ self.allreduce_no_retain(bucket,
+ dp_group=groups._get_expert_data_parallel_group(ep_name),
+ numel_per_bucket=elements_per_buffer)
+
+ def buffered_allreduce_fallback(self, grads=None, elements_per_buffer=500000000):
+ if grads is None:
+ non_expert_grads, expert_grads = self._get_gradients_for_reduction()
+ else:
+ assert not self.has_moe_layers, "attempting to reduce grads in unsupported way w.r.t. MoE"
+ non_expert_grads = grads
+
+ self._reduce_non_expert_gradients(non_expert_grads, elements_per_buffer)
+
+ if self.has_moe_layers:
+ self._reduce_expert_gradients(expert_grads, elements_per_buffer)
+
+ def sparse_allreduce_no_retain(self, bucket, dp_group):
+ allreduced_sparses = self.sparse_allreduce_bucket(bucket, dp_group)
+ # Densify sparse tensor and copy back to original location
+ for tensor in allreduced_sparses:
+ if tensor.is_sparse:
+ tensor.orig_dense_tensor.data = tensor.to_coo_tensor()
+ else:
+ tensor.orig_dense_tensor.copy_(tensor.to_dense())
+
+ def sparse_allreduce_bucket(self, bucket, dp_group):
+ sparse_list = []
+ for sparse in bucket:
+ sparse_list.append(self.sparse_allreduce(sparse, dp_group))
+ return sparse_list
+
+ def sparse_allreduce(self, sparse, dp_group):
+ original_data_type = sparse.values.dtype
+ if self.communication_data_type != sparse.values.dtype:
+ if self.communication_data_type in (torch.float16, torch.bfloat16):
+ indices = sparse.indices.to(torch.int32)
+ else:
+ indices = sparse.indices
+ values = sparse.values.to(self.communication_data_type)
+ else:
+ indices = sparse.indices
+ values = sparse.values
+
+ if self.postscale_gradients():
+ if self.gradient_average:
+ values.mul_(self.gradient_predivide_factor() /
+ (dist.get_world_size(group=dp_group) / float(self.sequence_parallel_size)))
+ else:
+ values.mul_(1. / (dist.get_world_size(group=dp_group) / float(self.sequence_parallel_size)))
+
+ indices_device_list = self.sparse_all_gather(indices, dp_group)
+ values_device_list = self.sparse_all_gather(values, dp_group)
+
+ sparse.indices = torch.cat(indices_device_list).to(torch.long)
+ sparse.values = torch.cat(values_device_list).to(original_data_type)
+ return sparse
+
+ def sparse_all_gather(self, value, dp_group):
+ my_size = torch.LongTensor([value.size()[0]]).to(self.device)
+ all_sizes = self.all_gather_scalar(my_size, dp_group)
+ max_size = torch.cat(all_sizes).max()
+ fill_size = max_size - my_size
+
+ assert value.dim() in [1, 2]
+ if value.dim() == 1:
+ if fill_size > 0:
+ value = torch.cat([value, value.new_empty(fill_size)])
+ tensor_list = [value.new_empty(max_size) for _ in range(dist.get_world_size(group=dp_group))]
+ else:
+ if fill_size > 0:
+ value = torch.cat([value, value.new_empty(fill_size, value.size()[1])])
+ tensor_list = [
+ value.new_empty(max_size,
+ value.size()[1]) for _ in range(dist.get_world_size(group=dp_group))
+ ]
+
+ dist.all_gather(tensor_list, value, group=dp_group)
+ tensors = []
+ for dev_idx, t in enumerate(tensor_list):
+ size = all_sizes[dev_idx][0]
+ tensors.append(t.index_select(0, torch.arange(size, dtype=torch.long, device=self.device)))
+
+ return tensors
+
+ def all_gather_scalar(self, value, dp_group):
+ tensor_list = [value.new_zeros(value.size()) for _ in range(dist.get_world_size(group=dp_group))]
+ dist.all_gather(tensor_list, value, group=dp_group)
+ return tensor_list
+
+ def module_state_dict(self, destination=None, prefix="", keep_vars=False, exclude_frozen_parameters=False):
+ sd = self.module.state_dict(destination, prefix, keep_vars)
+
+ # Remove frozen parameter weights from state_dict if specified
+ if exclude_frozen_parameters:
+ for n, p in self.module.named_parameters():
+ if not p.requires_grad and n in sd:
+ del sd[n]
+
+ if self.random_ltd_enabled():
+ sd = remove_random_ltd_state_dict(sd)
+ return sd
+
+ @staticmethod
+ def load_moe_state_dict(checkpoint_path,
+ tag,
+ state_dict,
+ old_moe_load,
+ model=None,
+ mpu=None,
+ num_experts=1,
+ checkpoint_engine=TorchCheckpointEngine()):
+ if old_moe_load:
+ expp_rank = groups._get_expert_data_parallel_rank(groups._get_max_expert_size_name())
+
+ num_local_experts = max(num_experts) // groups._get_expert_parallel_world_size(
+ groups._get_max_expert_size_name())
+ for local_expert_id in range(num_local_experts):
+ global_expert_id = expp_rank * num_local_experts + local_expert_id
+ expert_state_dict = checkpoint_engine.load(
+ DeepSpeedEngine._get_expert_ckpt_name(
+ checkpoint_path,
+ -1, # -1 means ignore layer_id
+ global_expert_id,
+ tag,
+ mpu),
+ map_location=torch.device('cpu'))
+
+ # Updating global -> local expert ids
+ moe_str_prefix = '.deepspeed_moe.experts.deepspeed_experts.'
+ for key in list(expert_state_dict.keys()):
+ local_key = key.replace(f'{moe_str_prefix}{global_expert_id}',
+ f'{moe_str_prefix}{local_expert_id}')
+ expert_state_dict[local_key] = expert_state_dict.pop(key)
+ state_dict.update(expert_state_dict)
+
+ else:
+ moe_layer_id = 0
+ for n_module, module in model.named_modules():
+ if isinstance(module, MoE): # and deepspeed.comm.get_rank() == 0:
+ group_name = module.expert_group_name
+ num_local_experts = module.num_local_experts
+ expp_rank = groups._get_expert_parallel_rank(group_name)
+ # loop all local_experts
+ for local_expert_id in range(num_local_experts):
+ global_expert_id = expp_rank * num_local_experts + local_expert_id
+ expert_state_dict = checkpoint_engine.load(DeepSpeedEngine._get_expert_ckpt_name(
+ checkpoint_path, moe_layer_id, global_expert_id, tag, mpu),
+ map_location=torch.device('cpu'))
+ # print(expert_state_dict.keys())
+ # Updating global -> local expert ids
+ moe_str_prefix = '.deepspeed_moe.experts.deepspeed_experts.'
+ for key in list(expert_state_dict.keys()):
+ local_key = key.replace(f'{moe_str_prefix}{global_expert_id}',
+ f'{moe_str_prefix}{local_expert_id}')
+ expert_state_dict[local_key] = expert_state_dict.pop(key)
+ state_dict.update(expert_state_dict)
+ moe_layer_id += 1
+
+ def load_module_state_dict(self, checkpoint, strict=True, custom_load_fn=None, fetch_z3_params=False):
+ if fetch_z3_params:
+ params_to_fetch = [
+ p for p in self.module.parameters()
+ if hasattr(p, 'ds_id') and p.ds_status == ZeroParamStatus.NOT_AVAILABLE
+ ]
+ else:
+ params_to_fetch = []
+
+ with deepspeed.zero.GatheredParameters(params_to_fetch, modifier_rank=0):
+ module_state_dict = checkpoint['module']
+ if custom_load_fn:
+ custom_load_fn(src=module_state_dict, dst=self.module)
+ else:
+ self.module.load_state_dict(
+ module_state_dict, # TODO
+ strict=strict)
+
+ if checkpoint.get(FROZEN_PARAM_FRAGMENTS, None) is not None:
+ saved_frozen_params = checkpoint[FROZEN_PARAM_FRAGMENTS]
+ for param in self.module.parameters():
+ if param.requires_grad:
+ continue
+ if param not in self.param_names:
+ raise ValueError(f"failed to find frozen {param} in named params")
+ name = self.param_names[param]
+ if hasattr(param, 'ds_id'):
+ param.ds_tensor.data.copy_(saved_frozen_params[name].data)
+ else:
+ param.data.copy_(saved_frozen_params[name].data)
+
+ def _get_zero_ckpt_prefix(self, dp_rank, bf16_mode):
+ return f'{"bf16_" if bf16_mode else ""}zero_pp_rank_{dp_rank}'
+
+ def _get_rank_zero_ckpt_name(self, checkpoints_path, tag, mp_rank, dp_rank, bf16_mode):
+ file_prefix = self._get_zero_ckpt_prefix(dp_rank, bf16_mode=bf16_mode)
+ zero_ckpt_name = os.path.join(
+ checkpoints_path,
+ str(tag),
+ f"{file_prefix}_mp_rank_{mp_rank:02d}_optim_states.pt",
+ )
+ return zero_ckpt_name
+
+ def _get_zero_ckpt_name(self, checkpoints_path, tag):
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
+ pp_rank = dist.get_rank(group=self.optimizer.zp_process_group)
+ bf16_mode = self.bfloat16_enabled()
+ return self._get_rank_zero_ckpt_name(checkpoints_path, tag, mp_rank, pp_rank, bf16_mode)
+
+ def _get_ckpt_name(self, checkpoints_path, tag, mp_placeholder=None):
+ if mp_placeholder is not None:
+ mp_rank_str = mp_placeholder
+ else:
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
+ mp_rank_str = f"{mp_rank:02d}"
+
+ if self.zero_optimization_partition_weights():
+ filename = "zero_pp_rank_{}".format(dist.get_rank(group=self.optimizer.zp_process_group))
+ ckpt_name = os.path.join(
+ checkpoints_path,
+ str(tag),
+ f"{filename}_mp_rank_{mp_rank_str}_model_states.pt",
+ )
+ else:
+ ckpt_name = os.path.join(
+ checkpoints_path,
+ str(tag),
+ "mp_rank_" + mp_rank_str + "_model_states.pt",
+ )
+ return ckpt_name
+
+ def _get_optimizer_ckpt_name(self, checkpoints_path, tag, expp_rank):
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
+ ckpt_name = os.path.join(checkpoints_path, str(tag),
+ f'expp_rank_{expp_rank}_mp_rank_{mp_rank:02d}_optim_states.pt')
+ return ckpt_name
+
+ @staticmethod
+ def _get_expert_ckpt_name(checkpoints_path, layer_id, expert_id, tag, mpu=None):
+ mp_rank = 0 if mpu is None else mpu.get_model_parallel_rank()
+ if layer_id <= -1:
+ # Used to support old checkpoint loading
+ ckpt_name = os.path.join(checkpoints_path, '' if tag is None else str(tag),
+ f'expert_{expert_id}_mp_rank_{mp_rank:02d}_model_states.pt')
+ else:
+ # Used to support new checkpoint loading
+ ckpt_name = os.path.join(checkpoints_path, '' if tag is None else str(tag),
+ f'layer_{layer_id}_expert_{expert_id}_mp_rank_{mp_rank:02d}_model_states.pt')
+ return ckpt_name
+
+ def _get_all_ckpt_names(self, checkpoints_path, tag):
+ # It is required that (checkpoints_path, tag) are consistent among all ranks.
+ ckpt_file_pattern = self._get_ckpt_name(checkpoints_path, tag, mp_placeholder="*")
+ import glob
+
+ ckpt_files = glob.glob(ckpt_file_pattern)
+ ckpt_files.sort()
+ return ckpt_files
+
+ def load_checkpoint(self,
+ load_dir,
+ tag=None,
+ load_module_strict=True,
+ load_optimizer_states=True,
+ load_lr_scheduler_states=True,
+ load_module_only=False,
+ custom_load_fn=None):
+ """
+ Load training checkpoint
+
+ Arguments:
+ load_dir: Required. Directory to load the checkpoint from
+ tag: Checkpoint tag used as a unique identifier for checkpoint, if not provided will attempt to load tag in 'latest' file
+ load_module_strict: Optional. Boolean to strictly enforce that the keys in state_dict of module and checkpoint match.
+ load_optimizer_states: Optional. Boolean to load the training optimizer states from Checkpoint. Ex. ADAM's momentum and variance
+ load_lr_scheduler_states: Optional. Boolean to add the learning rate scheduler states from Checkpoint.
+ load_module_only: Optional. Boolean to load only the model weights from the checkpoint. Ex. warmstarting.
+ custom_load_fn: Optional. Custom model load function.
+
+ Returns:
+ A tuple of ``load_path`` and ``client_state``.
+ *``load_path``: Path of the loaded checkpoint. ``None`` if loading the checkpoint failed.
+ *``client_state``: State dictionary used for loading required training states in the client code.
+
+ Important: under ZeRO3, one cannot load checkpoint with ``engine.load_checkpoint()`` right
+ after ``engine.save_checkpoint()``. It is because ``engine.module`` is partitioned, and
+ ``load_checkpoint()`` wants a pristine model. If insisting to do so, please reinitialize engine
+ before ``load_checkpoint()``.
+
+ """
+
+ if tag is None:
+ latest_tag = "latest_universal" if self.load_universal_checkpoint() else "latest"
+ latest_path = os.path.join(load_dir, latest_tag)
+ if os.path.isfile(latest_path):
+ with open(latest_path, "r") as fd:
+ tag = fd.read().strip()
+ else:
+ if self.load_universal_checkpoint():
+ raise ValueError(f'Invalid for universal checkpoint: {latest_path} does not exist')
+ else:
+ logger.warning(
+ f"Unable to find latest file at {latest_path}, if trying to load latest "
+ "checkpoint please ensure this file exists or pass an explicit checkpoint tag when loading a checkpoint."
+ )
+ return None, None
+
+ if self._optimizer_has_ckpt_event_prologue():
+ # Prepare for checkpoint load by ensuring all parameters are partitioned
+ self.optimizer.checkpoint_event_prologue()
+
+ load_path, client_states = self._load_checkpoint(load_dir,
+ tag,
+ load_module_strict=load_module_strict,
+ load_optimizer_states=load_optimizer_states,
+ load_lr_scheduler_states=load_lr_scheduler_states,
+ load_module_only=load_module_only,
+ custom_load_fn=custom_load_fn)
+
+ load_zero_checkpoint = load_optimizer_states and load_path is not None and (self.zero_optimization()
+ or self.bfloat16_enabled())
+ if load_zero_checkpoint:
+ success = self._load_zero_checkpoint(load_dir, tag, load_optimizer_states=load_optimizer_states)
+ if not success:
+ self.optimizer._restore_from_bit16_weights()
+
+ if self._optimizer_has_ckpt_event_epilogue():
+ self.optimizer.checkpoint_event_epilogue()
+
+ if self.load_universal_checkpoint():
+ self.optimizer.update_lp_params()
+ if load_zero_checkpoint:
+ self.update_optimizer_step(step=client_states['iteration'] + 1)
+
+ return load_path, client_states
+
+ def _load_checkpoint(self,
+ load_dir,
+ tag,
+ load_module_strict=True,
+ load_optimizer_states=True,
+ load_lr_scheduler_states=True,
+ load_module_only=False,
+ custom_load_fn=None):
+
+ from deepspeed.runtime.state_dict_factory import SDLoaderFactory
+
+ ckpt_list = self._get_all_ckpt_names(load_dir, tag)
+ sd_loader = SDLoaderFactory.get_sd_loader(ckpt_list, checkpoint_engine=self.checkpoint_engine)
+
+ is_pipe_parallel = isinstance(self.module, PipelineModule)
+
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
+ load_path, checkpoint, _ = sd_loader.load(self.mp_world_size, mp_rank, is_pipe_parallel=is_pipe_parallel)
+
+ if checkpoint is None:
+ return None, None
+
+ fetch_z3_params = False
+ if self.zero_optimization_partition_weights() and not load_optimizer_states:
+ checkpoint['module'] = get_fp32_state_dict_from_zero_checkpoint(load_dir)
+ fetch_z3_params = True
+
+ if is_pipe_parallel:
+ # Pipeline parallelism uses this to load its own checkpoint files.
+ self._curr_ckpt_path = os.path.join(load_dir, tag)
+
+ if self.has_moe_layers:
+ # print(checkpoint.keys())
+ old_moe_load = False
+ if not isinstance(checkpoint['num_experts'], list):
+ old_moe_load = True
+ DeepSpeedEngine.load_moe_state_dict(load_dir,
+ tag,
+ state_dict=checkpoint['module'],
+ old_moe_load=old_moe_load,
+ model=self.module,
+ mpu=self.mpu,
+ num_experts=self.num_experts,
+ checkpoint_engine=self.checkpoint_engine)
+ if not self.load_universal_checkpoint():
+ self.load_module_state_dict(checkpoint=checkpoint,
+ strict=load_module_strict,
+ custom_load_fn=custom_load_fn,
+ fetch_z3_params=fetch_z3_params)
+
+ self.loaded_checkpoint_dp_world_size = checkpoint['dp_world_size']
+ if 'zp_world_size' not in checkpoint:
+ checkpoint['zp_world_size'] = self.zp_world_size
+ self.loaded_checkpoint_zp_world_size = checkpoint['zp_world_size']
+
+ optim_checkpoint = None
+ if load_module_only:
+ deepspeed_states = ['module']
+ if self.optimizer is not None and self.fp16_enabled():
+ self.optimizer.refresh_fp32_params()
+ else:
+ has_zero_optimizer_state = self.zero_optimization() or self.bfloat16_enabled()
+ if load_optimizer_states and self.optimizer is not None and not has_zero_optimizer_state:
+ if self.has_moe_layers:
+ largest_group_name = groups._get_max_expert_size_name()
+ expp_rank = groups._get_expert_parallel_rank(largest_group_name)
+ optim_load_path = self._get_optimizer_ckpt_name(load_dir, tag, expp_rank)
+ optim_checkpoint = self.checkpoint_engine.load(optim_load_path, map_location=torch.device('cpu'))
+ else:
+ optim_checkpoint = checkpoint
+
+ if self.fp16_enabled() or self.bfloat16_enabled():
+ self.optimizer.load_state_dict(optim_checkpoint['optimizer'],
+ load_optimizer_states=load_optimizer_states)
+ else:
+ optim_checkpoint = checkpoint
+
+ self.optimizer.load_state_dict(optim_checkpoint['optimizer'])
+
+ if load_lr_scheduler_states and self.lr_scheduler is not None:
+ self.lr_scheduler.load_state_dict(checkpoint['lr_scheduler'])
+
+ if self.random_ltd_enabled() and self.random_ltd_scheduler is not None and 'random_ltd' in checkpoint:
+ self.random_ltd_scheduler.load_state_dict(checkpoint['random_ltd'])
+
+ if self.training_dataloader is not None and self.curriculum_learning_enabled(
+ ) and 'data_sampler' in checkpoint:
+ self.training_dataloader.data_sampler.load_state_dict(checkpoint['data_sampler'])
+
+ def get_sparse_tensor_module_names(original_set, loaded_set, original_parameters, loaded_parameters):
+ result = set()
+
+ for name in original_set:
+ if name in loaded_parameters and name not in loaded_set:
+ continue # parameter existed in previous model and was not sparse
+ result.add(name)
+
+ for name in loaded_set:
+ if name in original_parameters:
+ result.add(name) # parameter exists in both configs and it was sparse
+
+ return result
+
+ if 'sparse_tensor_module_names' in checkpoint:
+ sparse_tensor_module_names = checkpoint['sparse_tensor_module_names']
+ elif 'csr_tensor_module_names' in checkpoint:
+ sparse_tensor_module_names = checkpoint['csr_tensor_module_names']
+ else:
+ sparse_tensor_module_names = None
+ if sparse_tensor_module_names is not None:
+ if load_module_strict:
+ self.sparse_tensor_module_names = sparse_tensor_module_names
+ else:
+ self.sparse_tensor_module_names = get_sparse_tensor_module_names(
+ self.sparse_tensor_module_names, sparse_tensor_module_names,
+ dict(self.module.named_parameters()), checkpoint["module"])
+
+ self.global_steps = checkpoint['global_steps']
+ self.global_samples = checkpoint.get('global_samples', self.global_steps * self.train_batch_size())
+ self.skipped_steps = checkpoint['skipped_steps']
+ self.loaded_checkpoint_mp_world_size = checkpoint['mp_world_size']
+ deepspeed_states = [
+ 'module', 'sparse_tensor_module_names', 'skipped_steps', 'global_steps', 'zp_world_size',
+ 'mp_world_size', 'data_sampler', 'random_ltd', 'dp_world_size',
+ ]
+ client_state = {}
+
+ if load_lr_scheduler_states:
+ deepspeed_states.append('lr_scheduler')
+ if load_optimizer_states:
+ deepspeed_states.append('optimizer')
+
+ client_state = {key: value for key, value in checkpoint.items() if not key in deepspeed_states}
+
+ if optim_checkpoint is not None:
+ client_state['optimizer'] = optim_checkpoint['optimizer']
+
+ return load_path, client_state
+
+ def _load_zero_checkpoint(self, load_dir, tag, load_optimizer_states=True):
+
+ load_serial = None
+ # When use loading checkpoint serial, checkpoint loading start from local rank 0,
+ # all other local rank would be paused, waiting for its rank-1 peer ready and its notification.
+ if self._config.zero_config.pipeline_loading_checkpoint:
+ assert self.zero_optimization_stage(
+ ) == ZeroStageEnum.weights, "Only stage3 support for pipeline checkpoint loading"
+ load_serial = torch.zeros(1).to(self.device)
+ if dist.get_local_rank() != 0:
+ dist.recv(tensor=load_serial, src=dist.get_rank() - 1)
+ if self.load_universal_checkpoint():
+ zero_sd_list = None
+ checkpoint_folder = f'{os.path.join(load_dir, tag)}'
+ else:
+ if load_optimizer_states and self.zp_world_size != self.loaded_checkpoint_zp_world_size:
+ raise ZeRORuntimeException("The checkpoint being loaded used a DP " \
+ f"world size of {self.loaded_checkpoint_zp_world_size} but the " \
+ f"current world size is {self.zp_world_size}. Automatic adjustment " \
+ "of ZeRO's optimizer state partitioning with a new world size is not " \
+ "currently supported.")
+ checkpoint_folder = None
+ zero_sd_list = self._get_all_zero_checkpoints(load_dir, tag)
+ if zero_sd_list is None:
+ return False
+
+ self.optimizer.load_state_dict(state_dict_list=zero_sd_list,
+ load_optimizer_states=load_optimizer_states,
+ load_from_fp32_weights=self.zero_load_from_fp32_weights(),
+ checkpoint_folder=checkpoint_folder,
+ load_serial=load_serial)
+
+ if self.load_universal_checkpoint():
+ logger.info(f'loaded universal zero checkpoints from {checkpoint_folder} for rank {self.global_rank}')
+ else:
+ logger.info(f"loading {len(zero_sd_list)} zero partition checkpoints for rank {self.global_rank}")
+ return True
+
+ def update_optimizer_step(self, step):
+
+ def set_step(d):
+ if isinstance(d['step'], torch.Tensor):
+ d['step'] = torch.tensor(step, dtype=d['step'].dtype, device=d['step'].device)
+ else:
+ d['step'] = step
+
+ optimizer = self.optimizer
+ base_optimizer = optimizer.optimizer
+ state = base_optimizer.state
+ for group in optimizer.param_groups:
+ if 'step' in group:
+ set_step(group)
+ for p in group['params']:
+ if p in state and len(state[p]) > 0 and 'step' in state[p]:
+ set_step(state[p])
+
+ def _get_mp_rank_zero_checkpoint_names(self, load_dir, tag, mp_rank, dp_world_size, bf16_mode):
+ zero_ckpt_names = []
+ for dp_rank in range(dp_world_size):
+ ckpt_name = self._get_rank_zero_ckpt_name(checkpoints_path=load_dir,
+ tag=tag,
+ mp_rank=mp_rank,
+ dp_rank=dp_rank,
+ bf16_mode=bf16_mode)
+ zero_ckpt_names.append(ckpt_name)
+
+ return zero_ckpt_names
+
+ def _get_all_zero_checkpoint_names(self, load_dir, tag, bf16_mode):
+ mp_rank = 0 if self.mpu is None else self.mpu.get_model_parallel_rank()
+ zero_ckpt_names = self._get_mp_rank_zero_checkpoint_names(load_dir=load_dir,
+ tag=tag,
+ mp_rank=mp_rank,
+ dp_world_size=self.loaded_checkpoint_dp_world_size,
+ bf16_mode=bf16_mode)
+ for i, ckpt_name in enumerate(zero_ckpt_names):
+ if not os.path.exists(ckpt_name):
+ # transparently handle the old file pattern for optim_states
+ if "optim_states.pt" in ckpt_name:
+ ckpt_name_try = ckpt_name.replace("_optim_states.pt", "optim_states.pt")
+ if os.path.exists(ckpt_name_try):
+ zero_ckpt_names[i] = ckpt_name_try
+ continue
+
+ return zero_ckpt_names
+
+ def _get_all_zero_checkpoint_state_dicts(self, zero_ckpt_names):
+ zero_sd_list = []
+ for i, ckpt_name in enumerate(zero_ckpt_names):
+ _state = None
+ if ckpt_name is None:
+ _state = {OPTIMIZER_STATE_DICT: None}
+ # Fully load state for current rank
+ elif self.zero_elastic_checkpoint() or dist.get_rank(group=self.optimizer.zp_process_group) == i:
+ _state = self.checkpoint_engine.load(
+ ckpt_name,
+ map_location='cpu',
+ )
+ else:
+ _state = {OPTIMIZER_STATE_DICT: None}
+ zero_sd_list.append(_state)
+
+ zero_optimizer_sd = [sd[OPTIMIZER_STATE_DICT] for sd in zero_sd_list]
+ logger.info(f"successfully read {len(zero_optimizer_sd)} ZeRO state_dicts for rank {self.global_rank}")
+ return zero_optimizer_sd
+
+ def _get_all_zero_checkpoints(self, load_dir, tag):
+ for bf16_mode in [self.bfloat16_enabled(), not self.bfloat16_enabled()]:
+ zero_ckpt_names = self._get_all_zero_checkpoint_names(load_dir, tag, bf16_mode)
+ if zero_ckpt_names is not None:
+ # Warn if loading checkpoint of different bit16 type
+ if bf16_mode is not self.bfloat16_enabled():
+ checkpoint_bit16 = BFLOAT16 if bf16_mode else FP16
+ engine_bit16 = BFLOAT16 if self.bfloat16_enabled() else FP16
+ logger.warn(f'Loading {checkpoint_bit16} zero checkpoints into {engine_bit16} training engine')
+ return self._get_all_zero_checkpoint_state_dicts(zero_ckpt_names)
+
+ return None
+
+ def _checkpoint_tag_validation(self, tag):
+ if self.checkpoint_tag_validation_enabled():
+ s_hash = hashlib.sha1(tag.encode())
+ bhash = torch.ByteTensor([s_hash.digest()]).flatten().to(self.device)
+ max_bhash = bhash.clone()
+ min_bhash = bhash.clone()
+ dist.all_reduce(max_bhash, op=dist.ReduceOp.MAX)
+ dist.all_reduce(min_bhash, op=dist.ReduceOp.MIN)
+ valid = all(min_bhash == bhash) and all(max_bhash == bhash)
+ msg = (f"[rank={dist.get_rank()}] The checkpoint tag name '{tag}' is not consistent across "
+ "all ranks. Including rank unique information in checkpoint tag could cause issues when "
+ "restoring with different world sizes.")
+ if self.checkpoint_tag_validation_fail():
+ assert valid, msg
+ elif not valid:
+ logger.warning(msg)
+
+ def save_checkpoint(self, save_dir, tag=None, client_state={}, save_latest=True, exclude_frozen_parameters=False):
+ """Save training checkpoint
+
+ Arguments:
+ save_dir: Required. Directory for saving the checkpoint
+ tag: Optional. Checkpoint tag used as a unique identifier for the checkpoint, global step is
+ used if not provided. Tag name must be the same across all ranks.
+ client_state: Optional. State dictionary used for saving required training states in the client code.
+ save_latest: Optional. Save a file 'latest' pointing to the latest saved checkpoint.
+ exclude_frozen_parameters: Optional. Exclude frozen parameters from checkpointed state.
+ Important: all processes must call this method and not just the process with rank 0. It is
+ because each process needs to save its master weights and scheduler+optimizer states. This
+ method will hang waiting to synchronize with other processes if it's called just for the
+ process with rank 0.
+
+ """
+ if self._optimizer_has_ckpt_event_prologue():
+ # Custom preparation for checkpoint save, if applicable
+ self.optimizer.checkpoint_event_prologue()
+
+ rank = self.local_rank if self.use_node_local_storage() else self.global_rank
+
+ # This is to make sure the checkpoint names are created without collision
+ # There seems to be issue creating them in parallel
+
+ # Ensure save_dir directory exists
+ if rank == 0:
+ self.checkpoint_engine.makedirs(save_dir, exist_ok=True)
+ dist.barrier()
+
+ if tag is None:
+ tag = f"global_step{self.global_steps}"
+
+ # Ensure tag is a string
+ tag = str(tag)
+ self.checkpoint_engine.create(tag)
+
+ # Ensure checkpoint tag is consistent across ranks
+ self._checkpoint_tag_validation(tag)
+
+ if self.has_moe_layers:
+ self.save_non_zero_checkpoint = False
+ self._create_checkpoint_file(save_dir, tag, False)
+ self._save_moe_checkpoint(save_dir,
+ tag,
+ client_state=client_state,
+ exclude_frozen_parameters=exclude_frozen_parameters)
+
+ # We distribute the task of saving layer checkpoint files among
+ # data parallel instances, so all procs should call _save_checkpoint.
+ # All procs then call module_state_dict(), but only procs of data
+ # parallel rank 0 save the general model params.
+ if not self.has_moe_layers:
+ self._create_checkpoint_file(save_dir, tag, False)
+ self._save_checkpoint(save_dir,
+ tag,
+ client_state=client_state,
+ exclude_frozen_parameters=exclude_frozen_parameters)
+
+ if self.save_zero_checkpoint:
+ self._create_zero_checkpoint_files(save_dir, tag)
+ self._save_zero_checkpoint(save_dir, tag)
+
+ if self._optimizer_has_ckpt_event_epilogue():
+ self.optimizer.checkpoint_event_epilogue()
+
+ # Save latest checkpoint tag
+ self.checkpoint_engine.commit(tag)
+ if save_latest and rank == 0:
+ with open(os.path.join(save_dir, 'latest'), 'w') as fd:
+ fd.write(tag)
+
+ dist.barrier()
+
+ return True
+
+ def _get_non_moe_state_dict(self, full_state_dict):
+ """
+ Get the state dict of the non-moe layers
+ """
+ for key in list(full_state_dict.keys()):
+ if 'expert' in key and 'moe.gate.wg.weight' not in key:
+ full_state_dict.pop(key)
+
+ return full_state_dict
+
+ def _save_moe_checkpoint(self, save_dir, tag, client_state={}, exclude_frozen_parameters=False):
+ save_path = self._get_ckpt_name(save_dir, tag)
+ # A hack to save the checkpointing directory. Pipeline parallelism overrides
+ # module_state_dict() and uses this path to save the model. module_state_dict()
+ # then instead just returns None.
+
+ # Using layer_#_export_# to save the model's expert state_dict
+ moe_layer_id = 0
+ for n_module, module in self.module.named_modules():
+ if isinstance(module, MoE): # and deepspeed.comm.get_rank() == 0:
+ group_name = module.expert_group_name
+ num_local_experts = module.num_local_experts
+ expp_rank = groups._get_expert_parallel_rank(group_name)
+ exp_dp_rank = groups._get_expert_data_parallel_rank(group_name)
+ # print(expp_rank, exp_dp_rank)
+ if exp_dp_rank != 0:
+ moe_layer_id += 1
+ continue
+
+ # get all moe parameters
+ moe_state_dict = {}
+ for n, p in module.state_dict().items():
+ if 'expert' in n and 'moe.gate.wg.weight' not in n:
+ moe_state_dict[n_module + '.' + n] = p
+ moe_str_prefix = '.deepspeed_moe.experts.deepspeed_experts.'
+ # print(moe_state_dict.keys()) # until now, everything is fine. So the bug happens at next few lines
+ # Reorder the moe name rank, so that each checkpoint only has one expert
+ experts_state_dict = defaultdict(dict)
+ for key in list(moe_state_dict.keys()):
+ m = re.match(f".*{moe_str_prefix}([0-9]+).*", key)
+
+ local_expert_id = None
+ if not m:
+ logger.warn(f'No expert found in key {key}.')
+ else:
+ local_expert_id = m.group(1)
+
+ global_expert_id = expp_rank * \
+ num_local_experts + int(local_expert_id)
+ expert_key = key.replace(f'{moe_str_prefix}{local_expert_id}',
+ f'{moe_str_prefix}{global_expert_id}')
+ # truncating extra tensor (shared) storage
+ truncated = moe_state_dict.pop(key).clone().detach()
+ experts_state_dict[str(global_expert_id)][expert_key] = truncated
+
+ # let save the moe parameters
+ for global_expert_id, expert_state_dict in experts_state_dict.items():
+ # save the moe parameters
+ moe_save_path = self._get_expert_ckpt_name(save_dir, moe_layer_id, global_expert_id, tag, self.mpu)
+ if self.random_ltd_enabled():
+ expert_state_dict = remove_random_ltd_state_dict(expert_state_dict)
+ self.checkpoint_engine.save(expert_state_dict, moe_save_path)
+ moe_layer_id += 1
+
+ self._curr_ckpt_path = os.path.join(save_dir, tag)
+
+ largest_group_name = groups._get_max_expert_size_name()
+ expp_rank = groups._get_expert_parallel_rank(largest_group_name)
+ exp_dp_rank = groups._get_expert_data_parallel_rank(largest_group_name)
+
+ # In the case of E + D parallelism, only the
+ # first expert parallel group should save the expert weights
+ # since each expert parallel group is a copy of the model's experts
+ if exp_dp_rank != 0:
+ return
+
+ # Save optimizer states. They are different across each exp parallel rank.
+ optimizer_state = {
+ 'optimizer': self.optimizer.state_dict() if self.optimizer and not self.zero_optimization() else None
+ }
+ # TODO: why use BufferedWriter not the path
+ file_path = self._get_optimizer_ckpt_name(save_dir, tag, expp_rank)
+ self.checkpoint_engine.save(optimizer_state, file_path)
+
+ # get non-moe parameters
+ model_state_dict = self._get_non_moe_state_dict(
+ self.module_state_dict(exclude_frozen_parameters=exclude_frozen_parameters))
+
+ if expp_rank == 0:
+ # TODO: update num experts info,.. in checkpoint
+ state = {
+ 'module':
+ model_state_dict,
+ 'lr_scheduler':
+ self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None,
+ 'data_sampler':
+ self.training_dataloader.data_sampler.state_dict() if
+ (self.training_dataloader is not None and self.curriculum_learning_enabled()) else None,
+ 'random_ltd':
+ self.random_ltd_scheduler.state_dict() if self.random_ltd_enabled() else None,
+ 'sparse_tensor_module_names':
+ self.sparse_tensor_module_names,
+ 'skipped_steps':
+ self.skipped_steps,
+ 'global_steps':
+ self.global_steps,
+ 'global_samples':
+ self.global_samples,
+ 'zp_world_size':
+ self.zp_world_size,
+ 'dp_world_size':
+ self.dp_world_size,
+ 'mp_world_size':
+ self.mp_world_size,
+ 'num_experts':
+ self.num_experts
+ }
+ state.update(client_state)
+ logger.info(f'Saving model checkpoint: {save_path}')
+ self.checkpoint_engine.save(state, save_path)
+
+ def _create_checkpoint_file(self, save_dir, tag, zero_checkpoint):
+ name_function = (self._get_zero_ckpt_name if zero_checkpoint else self._get_ckpt_name)
+ try:
+ checkpoint_name = name_function(save_dir, tag)
+ path = os.path.dirname(checkpoint_name)
+ self.checkpoint_engine.makedirs(path, exist_ok=True)
+ except:
+ logger.error(f"Failed saving model checkpoint to {save_dir} with tag {tag}")
+ return False
+
+ return True
+
+ def _create_zero_checkpoint_files(self, save_dir, tag):
+ success = True
+ # zero checkpoint files are created sequentially
+ for rank in range(dist.get_world_size(self.optimizer.zp_process_group)):
+ if rank == self.global_rank:
+ success = self._create_checkpoint_file(save_dir, tag, True)
+
+ dist.barrier(group=self.optimizer.zp_process_group)
+
+ return success
+
+ def _save_checkpoint(self, save_dir, tag, client_state={}, exclude_frozen_parameters=False):
+
+ save_path = self._get_ckpt_name(save_dir, tag)
+
+ zero_optimizer_state = self.zero_optimization() or self.bfloat16_enabled()
+
+ save_frozen_param = self.zero_optimization_partition_gradients() and not exclude_frozen_parameters
+
+ # A hack to save the checkpointing directory. Pipeline parallelism overrides
+ # module_state_dict() and uses this path to save the model. module_state_dict()
+ # then instead just returns None. The module_state_dict() implementation in
+ # PipelineEngine expects the save path to be set in self._curr_ckpt_path.
+ self._curr_ckpt_path = os.path.join(save_dir, tag)
+ module = self.module_state_dict(exclude_frozen_parameters=exclude_frozen_parameters)
+ self._curr_ckpt_path = None
+
+ state = dict(module=module,
+ buffer_names=self._get_buffer_names(),
+ optimizer=self.optimizer.state_dict() if self.optimizer and not zero_optimizer_state else None,
+ param_shapes=self._get_zero_param_shapes() if self.optimizer and zero_optimizer_state else None,
+ frozen_param_shapes=self._get_zero_frozen_param_attributes(self._get_param_shape_func)
+ if save_frozen_param else None,
+ shared_params=self._get_shared_params() if self.optimizer and zero_optimizer_state else None,
+ frozen_param_fragments=self._get_zero_frozen_param_attributes(self._get_param_fragment_func)
+ if save_frozen_param else None,
+ lr_scheduler=self.lr_scheduler.state_dict() if self.lr_scheduler is not None else None,
+ data_sampler=self.training_dataloader.data_sampler.state_dict() if
+ (self.training_dataloader is not None and self.curriculum_learning_enabled()) else None,
+ random_ltd=self.random_ltd_scheduler.state_dict() if self.random_ltd_enabled() else None,
+ sparse_tensor_module_names=self.sparse_tensor_module_names,
+ skipped_steps=self.skipped_steps,
+ global_steps=self.global_steps,
+ global_samples=self.global_samples,
+ dp_world_size=self.seq_dp_world_size,
+ mp_world_size=self.mp_world_size,
+ ds_config=self.config,
+ ds_version=version)
+ state.update(client_state)
+
+ if self.save_non_zero_checkpoint:
+ log_dist(message=f'Saving model checkpoint: {save_path}', ranks=[0, 1])
+ self.checkpoint_engine.save(state, save_path)
+
+ def _get_buffer_names(self):
+ buffer_names = []
+
+ # we save buffer names so that we could extract later the real buffers from the saved
+ # state_dict["module"] in the non-zero checkpoint - the buffers are already there but they
+ # are intermixed with param placeholders
+
+ # have to traverse the tree to be able to skip non-persistent buffers
+ def get_layer_named_buffers(module, prefix=""):
+ for name, buf in module.named_buffers(recurse=False):
+ if buf is not None and name not in module._non_persistent_buffers_set:
+ buffer_names.append(prefix + name)
+
+ for name, child in module.named_children():
+ if child is not None:
+ get_layer_named_buffers(child, prefix + name + ".")
+
+ get_layer_named_buffers(self.module, prefix="")
+
+ return buffer_names
+
+ def _get_param_shape_func(self, param):
+ return param.ds_shape if hasattr(param, 'ds_id') else param.shape
+
+ def _get_param_fragment_func(self, param):
+ return param.ds_tensor.detach().cpu() if hasattr(param, 'ds_id') else param.detach().cpu()
+
+ def _get_zero_frozen_param_attributes(self, attr_func):
+ frozen_param_fragments = OrderedDict()
+
+ for param in self.module.parameters():
+ if param.requires_grad:
+ continue
+ if param not in self.param_names:
+ raise ValueError(f"failed to find frozen {param} in named params")
+ name = self.param_names[param]
+ frozen_param_fragments[name] = attr_func(param)
+
+ return frozen_param_fragments
+
+ def _get_zero_param_shapes(self):
+ """Returns a dict of name to shape mapping, only for the flattened fp32 weights saved by the
+ optimizer. the names are exactly as in state_dict. The order is absolutely important, since
+ the saved data is just flattened data with no identifiers and requires reconstruction in the
+ same order it was saved.
+ We can't rely on self.module.named_parameters() to get the saved tensors, as some params
+ will be missing and others unsaved and then it'd be impossible to reconstruct state_dict
+ from the flattened weights.
+ optimizer.bit16_groups seems to be the easiest to use as it's in all zeroX versions.
+ """
+ param_group_shapes = []
+ cnt = 0
+ numel = 0
+
+ # zero2 started using a round_robin_bit16_groups which is a shuffled version of bit16_groups -
+ # if we don't use it, we get parameters ordered incorrectly
+ if hasattr(self.optimizer, "round_robin_bit16_groups"):
+ bit16_groups = self.optimizer.round_robin_bit16_groups
+ elif self.bfloat16_enabled() and hasattr(self.optimizer, "bf16_groups"):
+ bit16_groups = self.optimizer.bf16_groups
+ else:
+ bit16_groups = self.optimizer.bit16_groups if self.zero_optimization_stage(
+ ) == 2 else self.optimizer.fp16_groups
+
+ for bit16_group in bit16_groups:
+ param_shapes = OrderedDict()
+ for param in bit16_group:
+ cnt += 1
+ numel += param.ds_numel if hasattr(param, "ds_numel") else param.numel()
+ shape = param.ds_shape if hasattr(param, "ds_shape") else param.shape
+ if param not in self.param_names:
+ raise ValueError(f"failed to find optimizer param in named params")
+ name = self.param_names[param]
+ param_shapes[name] = shape
+
+ # uncomment to debug zero_to_fp32.py problems
+ # if self.global_rank == 0: print(f"saving param {name} {shape} (numel={shape.numel()})")
+ param_group_shapes.append(param_shapes)
+ # if self.global_rank == 0: print(f"Total saved {numel} numels in {cnt} params")
+
+ return param_group_shapes
+
+ def _get_shared_params(self):
+ """
+ Returns a dict of shared params, which can later be used to reconstruct the original state dict,
+ e.g. in `zero_to_fp32`. Each dict entry is a pair of param names, where the key is the name
+ of the variable that isn't stored and the value is the actual param holding data.
+ """
+ shared_index = {}
+ shared_params_by_full_name = {}
+
+ is_zero3_model = (self.zero_optimization_partition_weights()
+ and any(hasattr(param, "ds_id") for param in self.module.parameters()))
+
+ def get_layer_state_dict(module, prefix=""):
+ # handle params
+ for name, param in module.named_parameters(recurse=False):
+ if param is None or (is_zero3_model and not hasattr(param, "ds_id")):
+ continue
+ key = prefix + name
+
+ # When weights are manged by stage 3, we can't rely on param.data_ptr() as it will be reused
+ # as weights get gathered and reduced, but param.ds_id is unique across all zero weights
+ # (and shared params will have the same param.ds_id)
+ param_id = param.ds_id if is_zero3_model else param.data_ptr()
+
+ if param_id in shared_index:
+ # shared weights
+ #print(f"`{key}` is shared with `{shared_index[param_id]}`")
+ shared_params_by_full_name[key] = shared_index[param_id]
+ else:
+ shared_index[param_id] = key
+
+ for name, child in module.named_children():
+ if child is not None:
+ get_layer_state_dict(child, prefix + name + ".")
+
+ if dist.get_rank() == 0:
+ get_layer_state_dict(self.module, prefix="")
+
+ return shared_params_by_full_name
+
+ def _copy_recovery_script(self, save_path):
+ base_dir = os.path.dirname(os.path.dirname(__file__))
+ script = "zero_to_fp32.py"
+ src = os.path.join(base_dir, "utils", script)
+ dst = os.path.join(save_path, script)
+ #logger.info(f"creating recovery script {dst}")
+ copyfile(src, dst)
+ self._change_recovery_script_permissions(dst)
+
+ def _change_recovery_script_permissions(self, dst):
+ # make executable (safeguard for file shares - Azure as example)
+ try:
+ os.chmod(dst, os.stat(dst).st_mode | stat.S_IEXEC)
+ except (FileNotFoundError, PermissionError) as e:
+ #this message is used in unit test TestZeRONonDistributed
+ logger.info(
+ f'Warning: Could not change permissions for {dst} due to error: {e}. Continuing without changing permissions.'
+ )
+
+ def _save_zero_checkpoint(self, save_path, tag):
+ zero_checkpoint_name = self._get_zero_ckpt_name(save_path, tag)
+ zero_sd = dict(optimizer_state_dict=self.optimizer.state_dict(), ds_config=self.config, ds_version=version)
+ self.checkpoint_engine.save(zero_sd, zero_checkpoint_name)
+
+ if self.global_rank == 0:
+ self._copy_recovery_script(save_path)
+ ckpt_type = 'zero' if self.zero_optimization() else 'bf16_zero'
+ logger.info(f'{ckpt_type} checkpoint saved {zero_checkpoint_name}')
+
+ def _zero3_consolidated_16bit_state_dict(self):
+ """
+ Get a full non-partitioned state_dict with fp16 weights on cpu.
+ Important: this function must be called on all ranks and not just rank 0.
+ This is similar to nn.Module.state_dict (modelled after _save_to_state_dict), but:
+ 1. consolidates the weights from different partitions on gpu0
+ 2. works on one layer at a time to require as little gpu0 memory as possible, by
+ moving the already consolidated weights to cpu
+ 3. takes care to keep the shared params shared when gradually copying the params to cpu
+ Returns:
+ a consolidated fp16 ``state_dict`` on cpu on rank 0, ``None`` on other ranks
+ """
+ if not self.zero_optimization_partition_weights():
+ raise ValueError("this function requires ZeRO-3 mode")
+
+ state_dict = OrderedDict() if dist.get_rank() == 0 else None
+ shared_params = {}
+
+ def get_layer_state_dict(module, prefix=""):
+ # gather one layer at a time to be memory-efficient
+ # must use modifier_rank=0 to release GPU memory after each layer gathered
+ #see_memory_usage("before GatheredParameters", force=True)
+ with deepspeed.zero.GatheredParameters(list(module.parameters(recurse=False)), modifier_rank=0):
+ if dist.get_rank() == 0:
+ # handle params
+ for name, param in module.named_parameters(recurse=False):
+ if param is None:
+ continue
+ key = prefix + name
+ # can't rely on param.data_ptr() as it will be reused as weights gets
+ # gathered and reduced, but param.ds_id is unique across all zero weights
+ # (and shared params will have the same param.ds_id)
+ if param.ds_id in shared_params:
+ # shared weights
+ #print(f"`{key}` is shared with `{shared_params[param.ds_id]}`")
+ state_dict[key] = state_dict[shared_params[param.ds_id]]
+ else:
+ state_dict[key] = param.detach().cpu()
+ shared_params[param.ds_id] = key
+ #print(f"param {param.ds_id} {param.shape} {key} ")
+
+ # now buffers - not sure if need to take care of potentially shared weights here
+ for name, buf in module.named_buffers(recurse=False):
+ if (buf is not None and name not in module._non_persistent_buffers_set):
+ state_dict[prefix + name] = buf.detach().cpu()
+ #see_memory_usage("after GatheredParameters", force=True)
+
+ for name, child in module.named_children():
+ if child is not None:
+ get_layer_state_dict(child, prefix + name + ".")
+
+ # Prepare for checkpoint save by ensuring all parameters are partitioned
+ if self._optimizer_has_ckpt_event_prologue():
+ self.optimizer.checkpoint_event_prologue()
+
+ see_memory_usage("before get_layer_state_dict", force=False)
+ get_layer_state_dict(self.module, prefix="")
+ see_memory_usage("after get_layer_state_dict", force=False)
+
+ if self._optimizer_has_ckpt_event_epilogue():
+ self.optimizer.checkpoint_event_epilogue()
+
+ return state_dict
+
+ def save_fp16_model(self, save_dir, save_filename="pytorch_model.bin"):
+ """has been renamed to save_16bit_model, keeping this around for backwards
+ compatibility"""
+ return self.save_16bit_model(save_dir, save_filename)
+
+ def save_16bit_model(self, save_dir, save_filename="pytorch_model.bin"):
+ """
+ Save 16bit model weights
+
+ This method saves the 16bit model weights at the desired destination.
+
+ Arguments:
+ save_dir: Required. Directory for saving the model
+ save_filename: Optional. Filename to save to. Defaults to ``pytorch_model.bin``
+
+ Returns:
+ ``True`` when a model has been saved, ``False`` otherwise. It will not be saved if
+ stage3_gather_16bit_weights_on_model_save is ``False``.
+
+ Important: all processes must call this method and not just the process with rank 0. It is
+ because the processes need to work in sync to gather the weights. This method will hang
+ waiting to synchronize with other processes if it's called just for the process with rank 0.
+
+ """
+
+ path = os.path.join(save_dir, save_filename)
+
+ if self.zero_optimization_partition_weights():
+ if self.zero_gather_16bit_weights_on_model_save():
+ # consolidation is expensive in time and memory and therefore isn't a default
+ state_dict = self._zero3_consolidated_16bit_state_dict()
+ else:
+ # the model will be bogus if not consolidated so don't confuse the user by saving it
+ logger.info(
+ f"Did not save the model {path} because `stage3_gather_16bit_weights_on_model_save` is False")
+ return False
+ else:
+ state_dict = self.module.state_dict()
+
+ tag = f"global_step{self.global_steps}"
+ tag = str(tag)
+ self.checkpoint_engine.create(tag)
+
+ if dist.get_rank() == 0:
+ self.checkpoint_engine.makedirs(save_dir, exist_ok=True)
+ logger.info(f"Saving model weights to {path}, tag: {tag}")
+ self.checkpoint_engine.save(state_dict, path)
+
+ self.checkpoint_engine.commit(tag)
+
+ return True
+
+ def empty_partition_cache(self):
+ """
+ Release GPU memory consumed by offloaded model parameters.
+ """
+ if hasattr(self.optimizer, 'empty_partition_cache'):
+ self.optimizer.empty_partition_cache()
+ gc.collect()
+ get_accelerator().empty_cache()
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/modules.py b/One-to-All-Animation/video-generation/opensora/adaptor/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..e53599d553b19249bbb76b469d03202f9999db46
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/modules.py
@@ -0,0 +1,23 @@
+import torch
+from torch import nn
+from torch.nn import functional as F
+
+
+def fp32_layer_norm_forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ origin_dtype = inputs.dtype
+ return F.layer_norm(inputs.float(), self.normalized_shape, self.weight.float() if self.weight is not None else None,
+ self.bias.float() if self.bias is not None else None, self.eps).to(origin_dtype)
+
+
+def fp32_silu_forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.silu(inputs.float(), inplace=self.inplace).to(inputs.dtype)
+
+
+def fp32_gelu_forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.gelu(inputs.float(), approximate=self.approximate).to(inputs.dtype)
+
+
+def replace_with_fp32_forwards():
+ nn.GELU.forward = fp32_gelu_forward
+ nn.SiLU.forward = fp32_silu_forward
+ nn.LayerNorm.forward = fp32_layer_norm_forward
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/stage_1_and_2.py b/One-to-All-Animation/video-generation/opensora/adaptor/stage_1_and_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..35f9a6d55d7b49cfecfb313520a31ead32fe1613
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/stage_1_and_2.py
@@ -0,0 +1,2522 @@
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: Apache-2.0
+
+# DeepSpeed Team
+
+import torch
+import os
+import pdb
+from deepspeed import comm as dist
+from packaging import version as pkg_version
+from collections import OrderedDict
+from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
+
+from deepspeed.runtime import ZeROOptimizer
+from deepspeed.runtime.fp16.loss_scaler import CreateLossScaler
+from deepspeed.runtime.utils import (bwc_tensor_model_parallel_rank, get_global_norm, empty_cache, see_memory_usage,
+ inf, is_model_parallel_parameter, align_dense_tensors, all_gather_dp_groups)
+
+from deepspeed.runtime.zero.config import ZeroStageEnum
+from deepspeed.runtime.zero.offload_config import OffloadDeviceEnum
+from deepspeed.ops.adam import DeepSpeedCPUAdam
+from deepspeed.utils import logger
+from deepspeed.moe.utils import is_moe_param
+from deepspeed.git_version_info import version
+
+from deepspeed.runtime.constants import PIPE_REPLICATED
+from deepspeed.accelerator import get_accelerator
+
+from deepspeed.checkpoint.constants import (DS_VERSION, GROUP_PADDINGS, PARTITION_COUNT, LOSS_SCALER,
+ SINGLE_PARTITION_OF_FP32_GROUPS, BASE_OPTIMIZER_STATE,
+ BASE_OPTIMIZER_STATE_STEP, CLIP_GRAD, ZERO_STAGE, PARAM_SLICE_MAPPINGS)
+from deepspeed.utils import link_hp_params
+from deepspeed.checkpoint import enable_universal_checkpoint
+
+from deepspeed.utils import groups
+
+from opensora.adaptor.zp_manager import zp_manager
+
+# Toggle this to true to enable correctness test
+# with gradient partitioning and without
+pg_correctness_test = False
+
+OPTIMIZER_ALLGATHER_TIMER = 'optimizer_allgather'
+OPTIMIZER_GRADIENTS_TIMER = 'optimizer_gradients'
+OPTIMIZER_STEP_TIMER = 'optimizer_step'
+OPTIMIZER_TIMERS = [OPTIMIZER_ALLGATHER_TIMER, OPTIMIZER_GRADIENTS_TIMER, OPTIMIZER_STEP_TIMER]
+
+
+def input(msg):
+ return
+
+
+def split_half_float_double(tensors):
+ device_type = get_accelerator().device_name()
+ dtypes = [
+ "torch.{}.HalfTensor".format(device_type), "torch.{}.FloatTensor".format(device_type),
+ "torch.{}.DoubleTensor".format(device_type), "torch.{}.BFloat16Tensor".format(device_type)
+ ]
+ buckets = []
+ for i, dtype in enumerate(dtypes):
+ bucket = [t for t in tensors if t.type() == dtype]
+ if bucket:
+ buckets.append(bucket)
+ return buckets
+
+
+def isclose(a, b, rtol=1e-09, atol=0.0):
+ return abs(a - b) <= max(rtol * max(abs(a), abs(b)), atol)
+
+
+def lcm(x, y):
+ from fractions import gcd # or can import gcd from `math` in Python 3
+ return x * y // gcd(x, y)
+
+
+def get_alignment_padding(tensor_list, alignment):
+ num_elements = sum([tensor.numel() for tensor in tensor_list])
+ remainder = num_elements % alignment
+ return (alignment - remainder) if remainder else remainder
+
+
+def move_to_cpu(tensor_list):
+ for tensor in tensor_list:
+ tensor.data = tensor.data.cpu()
+
+
+def print_rank_msg(msg):
+ print(f"rank {dist.get_rank()} - {msg}")
+
+
+def _get_padded_tensor(src_tensor, size):
+ if src_tensor.numel() >= size:
+ return src_tensor
+ padded_tensor = torch.zeros(size, dtype=src_tensor.dtype, device=src_tensor.device)
+ slice_tensor = torch.narrow(padded_tensor, 0, 0, src_tensor.numel())
+ slice_tensor.data.copy_(src_tensor.data)
+ return padded_tensor
+
+
+def contigous_flatten(tensors):
+ return _flatten_dense_tensors([tensor.contiguous() for tensor in tensors])
+
+
+def all_gather_into_tensor_dp_groups(groups_flat, partitioned_param_groups, zp_process_group):
+ for group_id, (group_flat, partitioned_params) in enumerate(zip(groups_flat, partitioned_param_groups)):
+ partition_id = dist.get_rank(group=zp_process_group[group_id])
+ dp_world_size = dist.get_world_size(group=zp_process_group[group_id])
+ if dp_world_size == 1:
+ # no groups share optimizer states
+ # pipeline parallel with bf16 will default call this even if dp size = 1.
+ continue
+ input_tensor = partitioned_params[partition_id].contiguous()
+ # print(f"call all_gather_into_tensor_dp_groups, input size is {input_tensor.size()}, "
+ # f"output size is {group_flat.size()}")
+ #
+ # print(f"groups_flat.size = {groups_flat.numel()}")
+ # print(f"partitioned_param_groups = {sum([v.numel() for v in partitioned_param_groups])}")
+ dist.all_gather_into_tensor(group_flat, input_tensor, zp_process_group[group_id])
+
+
+class DeepSpeedZeroOptimizer(ZeROOptimizer):
+ """
+ DeepSpeedZeroOptimizer designed to reduce the memory footprint
+ required for training large deep learning models.
+
+ For more details please see ZeRO: Memory Optimization Towards Training A Trillion Parameter Models
+ https://arxiv.org/abs/1910.02054
+
+ For usage examples, refer to TODO: DeepSpeed Tutorial
+
+ """
+
+ def __init__(self,
+ init_optimizer,
+ param_names,
+ timers,
+ static_loss_scale=1.0,
+ dynamic_loss_scale=False,
+ dynamic_loss_args=None,
+ verbose=True,
+ contiguous_gradients=True,
+ reduce_bucket_size=500000000,
+ use_multi_rank_bucket_allreduce=True,
+ allgather_bucket_size=5000000000,
+ dp_process_group=None,
+ expert_parallel_group=None,
+ expert_data_parallel_group=None,
+ reduce_scatter=True,
+ overlap_comm=False,
+ offload_optimizer_config=None,
+ mpu=None,
+ clip_grad=0.0,
+ gradient_accumulation_dtype=torch.float32,
+ communication_data_type=torch.float16,
+ postscale_gradients=True,
+ gradient_predivide_factor=1.0,
+ gradient_accumulation_steps=1,
+ ignore_unused_parameters=True,
+ partition_grads=True,
+ round_robin_gradients=False,
+ has_moe_layers=False,
+ fp16_master_weights_and_gradients=False,
+ elastic_checkpoint=False):
+
+ if offload_optimizer_config is not None and offload_optimizer_config.device != OffloadDeviceEnum.none:
+ self.cpu_offload = True
+ self.cpu_offload_pin_memory = offload_optimizer_config.pin_memory
+ else:
+ self.cpu_offload = False
+ self.cpu_offload_pin_memory = False
+
+ if dist.get_rank() == 0:
+ logger.info(f"Reduce bucket size {reduce_bucket_size}")
+ logger.info(f"Allgather bucket size {allgather_bucket_size}")
+ logger.info(f"CPU Offload: {self.cpu_offload}")
+ logger.info(f'Round robin gradient partitioning: {round_robin_gradients}')
+ # The fused optimizer does all the work. We need this layer for two reason:
+ # 1. maintain same user API from apex.fp16_utils
+ # 2. keep common stuff here in case we need to add ne552w fused optimizer later
+
+ self.elastic_checkpoint = elastic_checkpoint
+ self.param_names = param_names
+ self.mpu = mpu
+ # differences from apex.fp16_utils:
+ # - assume all model params in fp16
+ # - assume all params requires grad
+ # - flat by groups, not keeping state. TODO: remove state explicitly?
+ # - master grad and unflat master weight never exist. TODO: a way to save out unflat master?
+ if not get_accelerator().is_available():
+ raise SystemError("Accelerator is not detected, cannot perform low precision training (e.g., fp16, bf16).")
+ self.optimizer = init_optimizer
+
+ # Use torch (un)flatten ops
+ self.flatten = contigous_flatten
+ self.unflatten = _unflatten_dense_tensors
+
+ # ZeRO stage 1 (False) or 2 (True)
+ self.partition_gradients = partition_grads
+ self.zero_stage_string = "ZeRO-2" if partition_grads else "ZeRO-1"
+
+ self.timers = timers
+
+ self.reduce_scatter = reduce_scatter
+
+ self.overlap_comm = overlap_comm
+
+ self.deepspeed_adam_offload = self.cpu_offload
+
+ self.device = get_accelerator().current_device_name() if not self.cpu_offload else 'cpu'
+
+ zp_manager.init_group()
+ self.zp_process_group = zp_manager.zp_group
+ zp_rank = dist.get_rank(group=self.zp_process_group)
+ zp_size = dist.get_world_size(group=self.zp_process_group)
+ print(f"zp rank is {zp_rank}, zp_size={zp_size}")
+
+ self.dp_process_group = dp_process_group
+
+ self.sequence_parallel_size = groups._get_sequence_parallel_world_size()
+ # expert parallel group
+ self.ep_process_group = expert_parallel_group
+
+ # data parallel group for experts
+ self.expert_dp_process_group = expert_data_parallel_group
+
+ # data parallel size for non-experts
+ dp_size = dist.get_world_size(group=self.dp_process_group)
+
+ # For MoE models this maybe different for different param group
+ # It will be modified during MoE setup later in the init
+ self.real_zp_process_group = [self.zp_process_group for i in range(len(self.optimizer.param_groups))]
+ self.real_dp_process_group = [self.dp_process_group for i in range(len(self.optimizer.param_groups))]
+ self.partition_count = [zp_manager.zp_size for i in range(len(self.optimizer.param_groups))]
+
+ self.is_gradient_accumulation_boundary = True
+
+ # CPU-Offload requires contiguous gradients
+ self.contiguous_gradients = contiguous_gradients or self.cpu_offload
+
+ self.has_moe_layers = has_moe_layers
+ if self.has_moe_layers:
+ self._configure_moe_settings()
+ self._global_grad_norm = 0.
+
+ if mpu is None:
+ self.model_parallel_group = None
+ self.model_parallel_world_size = 1
+ self.model_parallel_rank = 0
+ else:
+ self.model_parallel_group = mpu.get_model_parallel_group()
+ self.model_parallel_world_size = mpu.get_model_parallel_world_size()
+ self.model_parallel_rank = bwc_tensor_model_parallel_rank(mpu)
+
+ self.overflow = False
+ self.clip_grad = clip_grad
+ self.communication_data_type = communication_data_type
+ self.gradient_predivide_factor = gradient_predivide_factor
+ self.postscale_gradients = postscale_gradients
+ self.gradient_accumulation_steps = gradient_accumulation_steps
+ self.micro_step_id = 0
+ self.ignore_unused_parameters = ignore_unused_parameters
+ self.round_robin_gradients = round_robin_gradients
+
+ self.extra_large_param_to_reduce = None
+ self.fp16_master_weights_and_gradients = fp16_master_weights_and_gradients
+
+ if self.fp16_master_weights_and_gradients:
+ assert self.cpu_offload and type(self.optimizer) in [DeepSpeedCPUAdam], \
+ f"fp16_master_and_gradients requires optimizer to support keeping fp16 master and gradients while keeping the optimizer states in fp32." \
+ f"Currently only supported using ZeRO-Offload with DeepSpeedCPUAdam. But current setting is ZeRO-Offload:{self.cpu_offload} and optimizer type {type(self.optimizer)}." \
+ f"Either disable fp16_master_weights_and_gradients or enable {self.zero_stage_string} Offload with DeepSpeedCPUAdam."
+
+ if self.reduce_scatter:
+ valid_reduce_scatter_dtypes = (torch.float16, torch.bfloat16, torch.float32)
+ assert self.communication_data_type in valid_reduce_scatter_dtypes, f"{self.zero_stage_string} supports {valid_reduce_scatter_dtypes} communication_data_type with reduce scatter enabled. Got: '{self.communication_data_type}'"
+ assert self.gradient_predivide_factor == 1.0, "gradient_predivide_factor != 1.0 is not yet supported with {self.zero_stage_string} with reduce scatter enabled"
+ assert self.postscale_gradients, "pre-scale gradients is not yet supported with {self.zero_stage_string} with reduce scatter enabled"
+
+ # param flattened by groups
+ self.bit16_groups = []
+ self.bit16_groups_flat = []
+
+ # param partitioned by data parallel degree
+ # this will contain a list of equal sized tensors
+ # each of which will be updated by a different process
+ self.parallel_partitioned_bit16_groups = []
+
+ # a single 32-bit partition of the parallel partitioned parameters
+ # that this process will update
+ self.single_partition_of_fp32_groups = []
+
+ # param partition info
+
+ # These are the parameters in each group that will not be updated by this process directly
+ self.params_not_in_partition = []
+
+ # These are the parameters that will be updated by this process directly
+ self.params_in_partition = []
+
+ # Offset from the first parameter in the self.params_in_partition
+ # the parameter boundaries may not align with partition boundaries
+ # so we need to keep track of the offset
+ self.first_offset = []
+
+ # number of elements per partition in each group
+ self.partition_size = []
+
+ # align nccl all-gather send buffers to 4-byte boundary
+ self.nccl_start_alignment_factor = 16 # 4-byte alignment/sizeof(fp16) = 2
+
+ assert (
+ allgather_bucket_size % self.nccl_start_alignment_factor == 0
+ ), f"allgather_bucket_size must be a multiple of nccl_start_alignment_factor, {self.nccl_start_alignment_factor} "
+
+ self.all_reduce_print = False
+ self.dtype = self.optimizer.param_groups[0]['params'][0].dtype
+ self.gradient_accumulation_dtype = gradient_accumulation_dtype
+
+ if self.dtype != self.gradient_accumulation_dtype:
+ self.use_separate_grad_accum = True
+ else:
+ self.use_separate_grad_accum = False
+ if self.use_separate_grad_accum and not self.partition_gradients:
+ self.use_grad_accum_attribute = True
+ else:
+ self.use_grad_accum_attribute = False
+
+ self.round_robin_bit16_groups = []
+ self.round_robin_bit16_indices = []
+
+ # Use different parallel to do all_to_all_reduce related things
+ # padding on each partition for alignment purposes
+ self.groups_padding = []
+ # loop to deal with groups
+ for i, param_group in enumerate(self.optimizer.param_groups):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+
+ # push this group to list before modify
+ # TODO: Explore simplification that avoids the extra book-keeping by pushing the reordered group
+ trainable_parameters = []
+ for param in param_group['params']:
+ if param.requires_grad:
+ param.grad_accum = None
+ trainable_parameters.append(param)
+ self.bit16_groups.append(trainable_parameters)
+
+ # not sure why apex was cloning the weights before flattening
+ # removing cloning here
+
+ see_memory_usage(f"Before moving param group {i} to CPU")
+ # move all the parameters to cpu to free up GPU space for creating flat buffer
+ move_to_cpu(self.bit16_groups[i])
+ empty_cache()
+ see_memory_usage(f"After moving param group {i} to CPU", force=False)
+
+ # Reorder group parameters for load balancing of gradient partitioning during backward among ranks.
+ # This ensures that gradients are reduced in a fashion such that ownership round robins among the ranks.
+ # For example, rather than 3 gradients (g_n+2, g_n+1, g_n) that are reduced consecutively belonging
+ # to the same rank, instead they will belong to 3 ranks (r_m+2, r_m+1, r_m).
+ if self.round_robin_gradients:
+ round_robin_tensors, round_robin_indices = self._round_robin_reorder(
+ self.bit16_groups[i], dist.get_world_size(group=self.real_zp_process_group[i]))
+ else:
+ round_robin_tensors = self.bit16_groups[i]
+ round_robin_indices = list(range(len(self.bit16_groups[i])))
+
+ self.round_robin_bit16_groups.append(round_robin_tensors)
+ self.round_robin_bit16_indices.append(round_robin_indices)
+
+ # create flat buffer in CPU and move to GPU
+ self.bit16_groups_flat.append(
+ self.flatten_dense_tensors_aligned(
+ self.round_robin_bit16_groups[i],
+ self.nccl_start_alignment_factor * dist.get_world_size(group=self.real_zp_process_group[i])).to(
+ get_accelerator().current_device_name()))
+ see_memory_usage(f"After flattening and moving param group {i} to GPU", force=False)
+
+ # Record padding required for alignment
+ if partition_id == dist.get_world_size(group=self.real_zp_process_group[i]) - 1:
+ padding = self.bit16_groups_flat[i].numel() - sum(
+ [t.numel() for t in self.round_robin_bit16_groups[i]])
+ else:
+ padding = 0
+ self.groups_padding.append(padding)
+
+ if dist.get_rank(group=self.real_zp_process_group[i]) == 0:
+ see_memory_usage(f"After Flattening and after emptying param group {i} cache", force=False)
+
+ # set model bit16 weight to slices of flattened buffer
+ self._update_model_bit16_weights(i)
+
+ # divide the flat weights into near equal partition equal to the data parallel degree
+ # each process will compute on a different part of the partition
+ data_parallel_partitions = self.get_data_parallel_partitions(self.bit16_groups_flat[i], i)
+ self.parallel_partitioned_bit16_groups.append(data_parallel_partitions)
+
+ # print(f"self.bit16_groups_flat[i].size = {self.bit16_groups_flat[i].numel()}")
+ # print(f"data_parallel_partitions = {sum([v.numel() for v in data_parallel_partitions])}")
+
+ # verify that data partition start locations are 4-byte aligned
+ for partitioned_data in data_parallel_partitions:
+ assert (partitioned_data.data_ptr() % (2 * self.nccl_start_alignment_factor) == 0)
+
+ # A partition of the fp32 master weights that will be updated by this process.
+ # Note that the params in single_partition_of_fp32_groups is cloned and detached
+ # from the origin params of the model.
+ if not fp16_master_weights_and_gradients:
+ self.single_partition_of_fp32_groups.append(self.parallel_partitioned_bit16_groups[i][partition_id].to(
+ self.device).clone().float().detach())
+ else:
+ self.single_partition_of_fp32_groups.append(self.parallel_partitioned_bit16_groups[i][partition_id].to(
+ self.device).clone().half().detach())
+
+ # Set local optimizer to have flat params of its own partition.
+ # After this, the local optimizer will only contain its own partition of params.
+ # In that case, the local optimizer only saves the states(momentum, variance, etc.) related to its partition's params(zero stage1).
+ self.single_partition_of_fp32_groups[
+ i].requires_grad = True # keep this in case internal optimizer uses it
+ param_group['params'] = [self.single_partition_of_fp32_groups[i]]
+
+ partition_size = len(self.bit16_groups_flat[i]) / dist.get_world_size(group=self.real_zp_process_group[i])
+ params_in_partition, params_not_in_partition, first_offset = self.get_partition_info(
+ self.round_robin_bit16_groups[i], partition_size, partition_id)
+
+ self.partition_size.append(partition_size)
+ self.params_in_partition.append(params_in_partition)
+ self.params_not_in_partition.append(params_not_in_partition)
+ self.first_offset.append(first_offset)
+
+ self.reduce_bucket_size = int(reduce_bucket_size)
+ self.use_multi_rank_bucket_allreduce = use_multi_rank_bucket_allreduce
+ self.allgather_bucket_size = int(allgather_bucket_size)
+
+ self.reduction_stream = None if get_accelerator().is_synchronized_device() else get_accelerator().Stream()
+ # self.copy_grad_stream = get_accelerator().Stream()
+ self.callback_queued = False
+
+ self.param_dict = {}
+
+ # map between param_id and bool to specify if a param is in this partition
+ self.is_param_in_current_partition = {}
+
+ self.grads_in_ipg_bucket = []
+ self.params_in_ipg_bucket = []
+ self.elements_in_ipg_bucket = 0
+ self.params_already_reduced = []
+ self._release_ipg_buffers()
+ self.previous_reduced_grads = None
+ self.ipg_bucket_has_moe_params = False
+
+ # simplified param id
+ self.param_id = {}
+
+ # interesting code: unique ids being assigned to individual parameters
+ largest_param_numel = 0
+ count = 0
+ for i, params_group in enumerate(self.bit16_groups):
+ for param in params_group:
+ unique_id = id(param)
+ self.param_id[unique_id] = count
+ self.param_dict[count] = param
+ self.params_already_reduced.append(False)
+ if param.numel() > largest_param_numel:
+ largest_param_numel = param.numel()
+ count = count + 1
+
+ for param_group in self.params_in_partition:
+ for param in param_group:
+ self.is_param_in_current_partition[self.get_param_id(param)] = True
+
+ for param_group in self.params_not_in_partition:
+ for param in param_group:
+ self.is_param_in_current_partition[self.get_param_id(param)] = False
+
+ if self.cpu_offload:
+ self.accumulated_grads_in_cpu = {}
+ self.norm_for_param_grads = {}
+ self.local_overflow = False
+ self.grad_position = {}
+ self.temp_grad_buffer_for_cpu_offload = torch.zeros(largest_param_numel,
+ device=self.device,
+ dtype=self.dtype)
+ if self.cpu_offload_pin_memory:
+ self.temp_grad_buffer_for_cpu_offload = get_accelerator().pin_memory(
+ self.temp_grad_buffer_for_cpu_offload)
+ self.temp_grad_buffer_for_gpu_offload = torch.zeros(largest_param_numel,
+ device=get_accelerator().current_device_name(),
+ dtype=self.dtype)
+ for i, params_group in enumerate(self.bit16_groups):
+ self.get_grad_position(i, self.params_in_partition[i], self.first_offset[i], self.partition_size[i])
+
+ # mapping from parameter to partition that it belongs to
+ self.param_to_partition_ids = {}
+
+ # stores if a partition has been reduced in this step
+ self.is_partition_reduced = {}
+
+ # number of grads in partition that still need to be computed
+ self.remaining_grads_in_partition = {}
+
+ # total number of grads in partition
+ self.total_grads_in_partition = {}
+
+ # stores if a grad in a partition has been computed or not
+ self.is_grad_computed = {}
+
+ # stores the offset at which a parameter gradient needs to be inserted in a partition
+ self.grad_partition_insertion_offset = {}
+
+ # the offset in the gradient at which it must be inserted at the beginning of the partition
+ self.grad_start_offset = {}
+
+ # will store the averaged gradients required by this partition
+ self.averaged_gradients = {}
+
+ # For cpu_offload, will store the averaged gradients required by this partition
+ self.offload_gradient_dict = {}
+
+ # store index of first parameter in each partition
+ self.first_param_index_in_partition = {}
+
+ # initializes all data structures for implementing gradient partitioning
+ self.initialize_gradient_partitioning_data_structures()
+
+ # resets the data structure value for the next backward propagation
+ self.reset_partition_gradient_structures()
+
+ # creates backward hooks for gradient partitioning
+ if self.partition_gradients or self.overlap_comm:
+ self.create_reduce_and_remove_grad_hooks()
+
+ self.custom_loss_scaler = False
+ self.external_loss_scale = None
+
+ # we may have a way of fusing dynamic scale. Do not support for now
+ self.loss_scaler = CreateLossScaler(dtype=self.dtype,
+ static_loss_scale=static_loss_scale,
+ dynamic_scaling=dynamic_loss_scale,
+ dynamic_loss_args=dynamic_loss_args)
+ self.dynamic_loss_scale = self.loss_scaler.dynamic
+
+ if self.dtype != torch.float16:
+ # Only fp16 should use dynamic loss scaling
+ assert self.loss_scaler.cur_scale == 1.0
+ assert not self.dynamic_loss_scale
+
+ see_memory_usage("Before initializing optimizer states", force=True)
+ self.initialize_optimizer_states()
+ see_memory_usage("After initializing optimizer states", force=True)
+
+ if dist.get_rank() == 0:
+ logger.info(f"optimizer state initialized")
+
+ if dist.get_rank(group=self.zp_process_group) == 0:
+ see_memory_usage(f"After initializing ZeRO optimizer", force=True)
+
+ self._link_all_hp_params()
+ self._enable_universal_checkpoint()
+ self._param_slice_mappings = self._create_param_mapping()
+
+ def _enable_universal_checkpoint(self):
+ for lp_param_group in self.bit16_groups:
+ enable_universal_checkpoint(param_list=lp_param_group)
+
+ def _create_param_mapping(self):
+ param_mapping = []
+ for i, _ in enumerate(self.optimizer.param_groups):
+ param_mapping_per_group = OrderedDict()
+ for lp in self.bit16_groups[i]:
+ if lp._hp_mapping is not None:
+ lp_name = self.param_names[lp]
+ param_mapping_per_group[lp_name] = lp._hp_mapping.get_hp_fragment_address()
+ param_mapping.append(param_mapping_per_group)
+
+ return param_mapping
+
+ def _link_all_hp_params(self):
+ dp_world_size = dist.get_world_size(group=self.zp_process_group)
+ if self.cpu_offload:
+ self._get_offload_gradient_dict()
+
+ for i, _ in enumerate(self.optimizer.param_groups):
+ # Link bit16 and fp32 params in partition
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+ partition_size = self.bit16_groups_flat[i].numel() // dp_world_size
+ flat_hp_partition = self.single_partition_of_fp32_groups[i]
+ link_hp_params(lp_param_list=self.bit16_groups[i],
+ flat_hp_partition=flat_hp_partition,
+ gradient_dict=self.averaged_gradients,
+ offload_gradient_dict=self.offload_gradient_dict,
+ use_offload=self.cpu_offload,
+ param_group_index=i,
+ partition_start=partition_id * partition_size,
+ partition_size=partition_size,
+ partition_optimizer_state=self.optimizer.state[flat_hp_partition],
+ dp_group=self.real_zp_process_group[i])
+
+ def is_moe_group(self, group):
+ return 'moe' in group and group['moe']
+
+ def _configure_moe_settings(self):
+ # if we're using ZeRO stage 2, ensure contiguous gradients are used
+ if self.partition_gradients:
+ assert self.contiguous_gradients, "Contiguous Gradients in ZeRO Stage 2 must be set to True for MoE. Other code paths are not tested with MoE"
+ # NOTE: To run ZeRO stage 1 with MoE, we need to set self.contiguous_gradients to True or ignore the assertion
+ if not self.partition_gradients and not self.contiguous_gradients:
+ logger.warn(
+ "ZeRO Stage 1 has not been thoroughly tested with MoE. This configuration is still experimental.")
+ assert self.reduce_scatter, "Reduce Scatter in ZeRO Stage 2 must be set to True for MoE. Other code paths are not tested with MoE"
+
+ assert any(
+ [self.is_moe_group(group) for group in self.optimizer.param_groups]
+ ), "The model has moe layers, but None of the param groups are marked as MoE. Create a param group with 'moe' key set to True before creating optimizer"
+ self.is_moe_param_group = []
+ for i, group in enumerate(self.optimizer.param_groups):
+ if self.is_moe_group(group):
+ assert all([is_moe_param(param)
+ for param in group['params']]), "All params in MoE group must be MoE params"
+ self.real_zp_process_group[i] = self.expert_dp_process_group[group['name']]
+ self.partition_count[i] = dist.get_world_size(group=self.expert_dp_process_group[group['name']])
+ self.is_moe_param_group.append(True)
+ else:
+ self.is_moe_param_group.append(False)
+
+ assert self.expert_dp_process_group is not None, "Expert data parallel group should be configured with MoE"
+ assert self.ep_process_group is not None, "Expert parallel group should be configured with MoE"
+
+ def _update_model_bit16_weights(self, group_index):
+ updated_params = self.unflatten(self.bit16_groups_flat[group_index],
+ self.round_robin_bit16_groups[group_index])
+ for p, q in zip(self.round_robin_bit16_groups[group_index], updated_params):
+ p.data = q.data
+
+ # set model fp16 weight to slices of reordered flattened buffer
+ for param_index, param in enumerate(self.bit16_groups[group_index]):
+ new_index = self.round_robin_bit16_indices[group_index][param_index]
+ param.data = self.round_robin_bit16_groups[group_index][new_index].data
+
+ def _round_robin_reorder(self, tensor_list, num_partitions):
+
+ # disable round robin if need to debug something
+ # return tensor_list, list(range(len(tensor_list)))
+
+ partition_tensors = {}
+
+ for i, tensor in enumerate(tensor_list):
+ j = i % num_partitions
+ if not j in partition_tensors:
+ partition_tensors[j] = []
+ partition_tensors[j].append((i, tensor))
+
+ reordered_tensors = []
+ reordered_indices = {}
+
+ for partition_index in partition_tensors.keys():
+ for i, (original_index, tensor) in enumerate(partition_tensors[partition_index]):
+ reordered_indices[original_index] = len(reordered_tensors)
+ reordered_tensors.append(tensor)
+
+ return reordered_tensors, reordered_indices
+
+ def _release_ipg_buffers(self):
+ if self.contiguous_gradients:
+ self.ipg_buffer = None
+ self.grads_in_partition = None
+ self.grads_in_partition_offset = 0
+
+ def initialize_optimizer_states(self):
+
+ for i, group in enumerate(self.bit16_groups):
+ single_grad_partition = torch.zeros(int(self.partition_size[i]),
+ dtype=self.single_partition_of_fp32_groups[i].dtype,
+ device=self.device)
+ self.single_partition_of_fp32_groups[i].grad = get_accelerator().pin_memory(
+ single_grad_partition) if self.cpu_offload_pin_memory else single_grad_partition
+
+ # Initialize the optimizer states with the flattened fp32 partition.
+ # State initialization for the Adagrad optimizer occurs at construction as opposed to other optimizers
+ # which do lazy initialization of the state at the first call to step.
+ if isinstance(self.optimizer, torch.optim.Adagrad):
+ self.optimizer = torch.optim.Adagrad(self.single_partition_of_fp32_groups, **self.optimizer.defaults)
+ else:
+ self.optimizer.step()
+
+ if not self.cpu_offload:
+ for group in self.single_partition_of_fp32_groups:
+ group.grad = None # class init
+
+ return
+
+ #########################################################################
+ #################### ZeRO Stage 1 - reduce gradients ####################
+ #########################################################################
+ def reduce_gradients(self, pipeline_parallel=False):
+ world_size = dist.get_world_size(self.zp_process_group)
+ my_rank = dist.get_rank(self.zp_process_group)
+
+ # with PP we must create ipg buffer, since backward is handled outside zero
+ if pipeline_parallel and self.contiguous_gradients:
+ self.ipg_buffer = []
+ buf_0 = torch.empty(int(self.reduce_bucket_size),
+ dtype=self.dtype,
+ device=get_accelerator().current_device_name())
+ self.ipg_buffer.append(buf_0)
+ self.ipg_index = 0
+
+ if not self.overlap_comm:
+ for i, group in enumerate(self.bit16_groups):
+ for param in group:
+ grad_reduc = self.get_gradient_for_reduction(param)
+ if grad_reduc is not None:
+ self.reduce_ready_partitions_and_remove_grads(param, i)
+ # reduce any pending grads in either hook/non-hook case
+ self.overlapping_partition_gradients_reduce_epilogue()
+
+ #########################################################################
+ #########################ZeRO Partition Gradients########################
+ #########################################################################
+
+ def get_first_param_index(self, group_id, param_group, partition_id):
+ for index, param in enumerate(param_group):
+ param_id = self.get_param_id(param)
+ if partition_id in self.param_to_partition_ids[group_id][param_id]:
+ return index
+ return None
+
+ def initialize_gradient_partitioning_data_structures(self):
+
+ for i, param_group in enumerate(self.round_robin_bit16_groups):
+ total_partitions = dist.get_world_size(group=self.real_zp_process_group[i])
+
+ self.param_to_partition_ids[i] = {}
+ self.is_partition_reduced[i] = {}
+ self.total_grads_in_partition[i] = {}
+ self.remaining_grads_in_partition[i] = {}
+ self.is_grad_computed[i] = {}
+ self.grad_partition_insertion_offset[i] = {}
+ self.grad_start_offset[i] = {}
+ self.first_param_index_in_partition[i] = {}
+
+ for partition_id in range(total_partitions):
+ self.is_grad_computed[i][partition_id] = {}
+ self.grad_partition_insertion_offset[i][partition_id] = {}
+ self.grad_start_offset[i][partition_id] = {}
+ self.total_grads_in_partition[i][partition_id] = 0
+ self.initialize_gradient_partition(i, param_group, partition_id)
+ self.is_partition_reduced[i][partition_id] = False
+ self.first_param_index_in_partition[i][partition_id] = self.get_first_param_index(
+ i, param_group, partition_id)
+
+ def independent_gradient_partition_epilogue(self):
+ self.report_ipg_memory_usage(f"In ipg_epilogue before reduce_ipg_grads", 0)
+ self.reduce_ipg_grads()
+ self.report_ipg_memory_usage(f"In ipg_epilogue after reduce_ipg_grads", 0)
+
+ # if dist.get_rank() == 0:
+ # logger.info("Params already reduced %s", self.params_already_reduced)
+ for i in range(len(self.params_already_reduced)):
+ self.params_already_reduced[i] = False
+
+ if self.overlap_comm:
+ get_accelerator().synchronize()
+ # It is safe to clear previously reduced grads of other partitions
+ self._clear_previous_reduced_grads()
+
+ if self.cpu_offload is False:
+ for i, _ in enumerate(self.bit16_groups):
+
+ if not i in self.averaged_gradients or self.averaged_gradients[i] is None:
+ self.averaged_gradients[i] = self.get_flat_partition(
+ self.params_in_partition[i],
+ self.first_offset[i],
+ self.partition_size[i],
+ dtype=self.gradient_accumulation_dtype,
+ device=get_accelerator().current_device_name(),
+ return_tensor_list=True)
+ else:
+ avg_new = self.get_flat_partition(self.params_in_partition[i],
+ self.first_offset[i],
+ self.partition_size[i],
+ dtype=self.gradient_accumulation_dtype,
+ device=get_accelerator().current_device_name(),
+ return_tensor_list=True)
+
+ for accumulated_grad, new_avg_grad in zip(self.averaged_gradients[i], avg_new):
+ accumulated_grad.add_(new_avg_grad)
+
+ self._release_ipg_buffers()
+
+ # No need to keep the gradients anymore.
+ # All gradients required by the step
+ # are in self.averaged_gradients
+ self.zero_grad(set_to_none=True)
+ see_memory_usage(f"End ipg_epilogue")
+
+ # resets all partition to no reduced
+ # sets remaining grads to the total number of grads in each partition
+ # set is grad computed to false for all grads in partition
+ def reset_partition_gradient_structures(self):
+ for i, _ in enumerate(self.bit16_groups):
+ total_partitions = dist.get_world_size(group=self.real_zp_process_group[i])
+ for partition_id in range(total_partitions):
+ self.is_partition_reduced[i][partition_id] = False
+ self.remaining_grads_in_partition[i][partition_id] = self.total_grads_in_partition[i][partition_id]
+
+ for param_id in self.is_grad_computed[i][partition_id]:
+ self.is_grad_computed[i][partition_id][param_id] = False
+
+ def initialize_gradient_partition(self, i, param_group, partition_id):
+
+ def set_key_value_list(dictionary, key, value):
+ if key in dictionary:
+ dictionary[key].append(value)
+ else:
+ dictionary[key] = [value]
+
+ def increment_value(dictionary, key):
+ if key in dictionary:
+ dictionary[key] += 1
+ else:
+ dictionary[key] = 1
+
+ partition_size = self.partition_size[i]
+
+ start_index = partition_size * partition_id
+ end_index = partition_size * (partition_id + 1)
+
+ current_index = 0
+ first_offset = 0
+
+ for param in param_group:
+
+ param_size = param.numel()
+ param_id = self.get_param_id(param)
+
+ if start_index <= current_index < end_index:
+ set_key_value_list(self.param_to_partition_ids[i], param_id, partition_id)
+ increment_value(self.total_grads_in_partition[i], partition_id)
+
+ self.is_grad_computed[i][partition_id][param_id] = False
+
+ self.grad_partition_insertion_offset[i][partition_id][param_id] = current_index - start_index
+ self.grad_start_offset[i][partition_id][param_id] = 0
+
+ elif current_index < start_index < (current_index + param_size):
+ assert (first_offset == 0
+ ), "This can happen either zero or only once as this must be the first tensor in the partition"
+ first_offset = start_index - current_index
+
+ set_key_value_list(self.param_to_partition_ids[i], param_id, partition_id)
+ increment_value(self.total_grads_in_partition[i], partition_id)
+
+ self.is_grad_computed[i][partition_id][param_id] = False
+
+ self.grad_partition_insertion_offset[i][partition_id][param_id] = 0
+ self.grad_start_offset[i][partition_id][param_id] = first_offset
+
+ current_index = current_index + param_size
+
+ def overlapping_partition_gradients_reduce_epilogue(self):
+ self.independent_gradient_partition_epilogue()
+
+ def fill_grad_accum_attribute(self):
+ for group in self.bit16_groups:
+ for param in group:
+ if param.grad is not None:
+ if param.grad_accum is None:
+ param.grad_accum = param.grad.to(self.gradient_accumulation_dtype)
+ else:
+ param.grad_accum.add_(
+ param.grad.to(self.gradient_accumulation_dtype).view(param.grad_accum.shape))
+ param.grad = None
+
+ def get_gradient_for_reduction(self, param):
+ if self.use_grad_accum_attribute:
+ return param.grad_accum.to(self.dtype) if param.grad_accum is not None else None
+ else:
+ return param.grad
+
+ def get_param_gradient_attribute(self, param):
+ return param.grad_accum if self.use_grad_accum_attribute else param.grad
+
+ # Clear the tensor the reduction gradient attribute is pointing to
+ def clear_grad_attribute(self, param):
+ if self.use_grad_accum_attribute:
+ param.grad_accum = None
+ else:
+ param.grad = None
+
+ def create_reduce_and_remove_grad_hooks(self):
+ self.grad_accs = []
+ for i, param_group in enumerate(self.bit16_groups):
+ for param in param_group:
+ if param.requires_grad:
+ def wrapper(param, i):
+ param_tmp = param.expand_as(param)
+ grad_acc = param_tmp.grad_fn.next_functions[0][0]
+
+ def reduce_partition_and_remove_grads(*notneeded):
+ self.reduce_ready_partitions_and_remove_grads(param, i)
+
+ grad_acc.register_hook(reduce_partition_and_remove_grads)
+ self.grad_accs.append(grad_acc)
+
+ wrapper(param, i)
+
+ def get_param_id(self, param):
+ unique_id = id(param)
+ return self.param_id[unique_id]
+
+ def report_ipg_memory_usage(self, tag, param_elems):
+ elem_count = self.elements_in_ipg_bucket + param_elems
+ percent_of_bucket_size = (100.0 * elem_count) // self.reduce_bucket_size
+ see_memory_usage(
+ f"{tag}: elems in_bucket {self.elements_in_ipg_bucket} param {param_elems} max_percent {percent_of_bucket_size}"
+ )
+
+ # create a flat tensor aligned at the alignment boundary
+ def flatten_dense_tensors_aligned(self, tensor_list, alignment):
+ return self.flatten(align_dense_tensors(tensor_list, alignment))
+
+ ############### Independent Partition Gradient ########################
+ def reduce_independent_p_g_buckets_and_remove_grads(self, param, i):
+
+ grad_reduc = self.get_gradient_for_reduction(param)
+ if self.elements_in_ipg_bucket + param.numel() > self.reduce_bucket_size:
+ self.report_ipg_memory_usage("In ipg_remove_grads before reduce_ipg_grads", param.numel())
+ self.reduce_ipg_grads()
+ if self.contiguous_gradients and self.overlap_comm:
+ # Swap ipg_index between 0 and 1
+ self.ipg_index = 1 - self.ipg_index
+ self.report_ipg_memory_usage("In ipg_remove_grads after reduce_ipg_grads", param.numel())
+
+ param_id = self.get_param_id(param)
+ assert self.params_already_reduced[param_id] == False, \
+ f"The parameter {param_id} has already been reduced. \
+ Gradient computed twice for this partition. \
+ Multiple gradient reduction is currently not supported"
+
+ if self.contiguous_gradients:
+ if param.numel() > self.reduce_bucket_size:
+ self.extra_large_param_to_reduce = param
+ else:
+ # keeping the gradients contiguous to prevent memory fragmentation, and avoid flattening
+ new_grad_tensor = self.ipg_buffer[self.ipg_index].narrow(0, self.elements_in_ipg_bucket, param.numel())
+ new_grad_tensor.copy_(grad_reduc.view(-1))
+ grad_reduc.data = new_grad_tensor.data.view_as(grad_reduc)
+
+ self.elements_in_ipg_bucket += param.numel()
+
+ assert grad_reduc is not None, f"rank {dist.get_rank()} - Invalid to reduce Param {param_id} with None gradient"
+
+ self.grads_in_ipg_bucket.append(grad_reduc)
+ self.params_in_ipg_bucket.append((i, param, param_id))
+
+ # make sure the average tensor function knows how to average the gradients
+ if is_moe_param(param):
+ self.ipg_bucket_has_moe_params = True
+
+ self.report_ipg_memory_usage("End ipg_remove_grads", 0)
+
+ def print_rank_0(self, message):
+ if dist.get_rank() == 0:
+ logger.info(message)
+
+ def gradient_reduction_w_predivide(self, tensor):
+
+ dp_world_size = dist.get_world_size(group=self.dp_process_group)
+
+ tensor_to_allreduce = tensor
+
+ if self.communication_data_type != tensor.dtype:
+ tensor_to_allreduce = tensor.to(self.communication_data_type)
+
+ if self.postscale_gradients:
+ if self.gradient_predivide_factor != 1.0:
+ tensor_to_allreduce.mul_(1. / self.gradient_predivide_factor)
+
+ dist.all_reduce(tensor_to_allreduce, group=self.dp_process_group)
+
+ if self.gradient_predivide_factor != dp_world_size:
+ tensor_to_allreduce.mul_(self.gradient_predivide_factor /
+ (dp_world_size / float(self.sequence_parallel_size)))
+ else:
+ tensor_to_allreduce.div_(dp_world_size / float(self.sequence_parallel_size))
+ dist.all_reduce(tensor_to_allreduce, group=self.dp_process_group)
+
+ if self.communication_data_type != tensor.dtype and tensor is not tensor_to_allreduce:
+ tensor.copy_(tensor_to_allreduce)
+
+ return tensor
+
+ def allreduce_and_copy_with_multiple_ranks(self,
+ small_bucket,
+ log=None,
+ divide=True,
+ process_group=None,
+ bucket_ranks=None):
+ process_group = self.zp_process_group if process_group is None else process_group
+ allreduced = self.allreduce_bucket(small_bucket, log=log, divide=divide, process_group=process_group)
+ for buf, synced, bucket_rank in zip(small_bucket, self.unflatten(allreduced, small_bucket), bucket_ranks):
+ if dist.get_rank(group=process_group) == bucket_rank:
+ buf.copy_(synced)
+
+ def allreduce_and_scatter(self, bucket, numel_per_bucket=500000000, log=None, divide=True, process_group=None):
+ small_bucket = []
+ small_bucket_ranks = []
+ numel = 0
+ allreduce_sizes = []
+
+ for i, bucket_elem in enumerate(bucket):
+ rank, tensor = bucket_elem
+ small_bucket.append(tensor)
+ small_bucket_ranks.append(rank)
+ numel = numel + tensor.numel()
+ if numel > numel_per_bucket:
+ self.allreduce_and_copy_with_multiple_ranks(small_bucket,
+ log=None,
+ divide=divide,
+ process_group=process_group,
+ bucket_ranks=small_bucket_ranks)
+ small_bucket = []
+ small_bucket_ranks = []
+ numel = 0
+
+ if len(small_bucket) > 0:
+ self.allreduce_and_copy_with_multiple_ranks(small_bucket,
+ log=None,
+ divide=divide,
+ process_group=process_group,
+ bucket_ranks=small_bucket_ranks)
+
+ def average_tensor(self, tensor):
+ if self.overlap_comm:
+ stream = self.reduction_stream
+ if not get_accelerator().is_synchronized_device():
+ stream.wait_stream(get_accelerator().current_stream())
+ else:
+ stream = get_accelerator().current_stream()
+
+ with get_accelerator().stream(stream):
+ if not self.reduce_scatter:
+ self.gradient_reduction_w_predivide(tensor)
+ return
+
+ # Accumulate destination ranks and bucket offsets for each gradient slice.
+ # Note: potential future optimization, record access pattern of parameters
+ # in backward pass and partition gradients w.r.t. access pattern so that our
+ # bucket is guaranteed to be contiguous w.r.t. ranks
+ rank_and_offsets = []
+ real_dp_process_group = []
+ curr_size = 0
+ prev_id, prev_process_group = -1, None
+
+ process_group = self.zp_process_group
+ # count = 0
+ for i, param, param_id in self.params_in_ipg_bucket:
+
+ process_group = self.zp_process_group
+ grad_reduc = self.get_gradient_for_reduction(param)
+ # Averages gradients at parameter level if ipg has a moe param
+ # Otherwise averaging is done at the entire buffer level at the end of the loop
+ # MoE param have different groups
+ if self.ipg_bucket_has_moe_params:
+ process_group = self.expert_dp_process_group[param.group_name] if is_moe_param(
+ param) else self.zp_process_group
+ grad_reduc.data.div_(dist.get_world_size(group=process_group) / float(self.sequence_parallel_size))
+
+ partition_ids = self.param_to_partition_ids[i][param_id]
+ assert all([p_id < dist.get_world_size(group=process_group) for p_id in partition_ids
+ ]), f"world size {dist.get_world_size(group=process_group)} and p_ids: {partition_ids}"
+ partition_size = self.partition_size[i]
+ # Get all partition ids + their offsets
+ partition_ids_w_offsets = []
+ for partition_id in partition_ids:
+ offset = self.grad_start_offset[i][partition_id][param_id]
+ partition_ids_w_offsets.append((partition_id, offset))
+ partition_ids_w_offsets.sort(key=lambda t: t[1])
+
+ # Calculate rank and offsets for grad slices
+ for idx in range(len(partition_ids_w_offsets)):
+ partition_id, offset = partition_ids_w_offsets[idx]
+
+ # if dist.get_rank() == 0 and count < 100:
+ # print(f"Rank {dist.get_rank()} rank offset id {idx} calculated dp size {dist.get_world_size(group=process_group)} real dp size {dist.get_world_size(self.real_dp_process_group[i])} and dst: {partition_id}")
+ # count += 1
+
+ # Calculate numel for grad slice depending on partition location
+ if idx == len(partition_ids_w_offsets) - 1:
+ # Last partition_id uses its own offset
+ numel = param.numel() - offset
+ else:
+ # Set numel to next partition's offset
+ numel = partition_ids_w_offsets[idx + 1][1] - offset
+
+ # Merge bucket ranges if they belong to the same rank
+ if partition_id == prev_id and process_group == prev_process_group:
+ prev_pid, prev_size, prev_numel = rank_and_offsets[-1]
+ rank_and_offsets[-1] = (prev_pid, prev_size, prev_numel + numel)
+ else:
+ rank_and_offsets.append((partition_id, curr_size, numel))
+ real_dp_process_group.append(process_group)
+ curr_size += numel
+ prev_id, prev_process_group = partition_id, process_group
+
+ if not self.ipg_bucket_has_moe_params:
+ tensor.div_(dist.get_world_size(group=self.dp_process_group) / float(self.sequence_parallel_size))
+
+ buckets = {}
+ for i, (dst, bucket_offset, numel) in enumerate(rank_and_offsets):
+ grad_slice = tensor.narrow(0, int(bucket_offset), int(numel))
+ bucket_key = real_dp_process_group[i] if self.use_multi_rank_bucket_allreduce else (
+ dst, real_dp_process_group[i])
+ if bucket_key not in buckets:
+ buckets[bucket_key] = []
+ if self.use_multi_rank_bucket_allreduce:
+ buckets[bucket_key].append((dst, grad_slice))
+ else:
+ buckets[bucket_key].append(grad_slice)
+
+ for bucket_key in buckets:
+ if self.use_multi_rank_bucket_allreduce:
+ self.allreduce_and_scatter(buckets[bucket_key],
+ numel_per_bucket=self.reduce_bucket_size,
+ divide=self.ipg_bucket_has_moe_params,
+ process_group=bucket_key)
+ else:
+ dst, process_group = bucket_key
+ self.allreduce_no_retain(buckets[bucket_key],
+ numel_per_bucket=self.reduce_bucket_size,
+ rank=dst,
+ divide=self.ipg_bucket_has_moe_params,
+ process_group=process_group)
+
+ ##############################################################################
+ ############################# CPU Offload Methods#############################
+ ##############################################################################
+ def get_grad_position(self, group_id, tensor_list, first_offset, partition_size):
+ current_offset = 0
+
+ for i, tensor in enumerate(tensor_list):
+ param_id = self.get_param_id(tensor)
+ param_start_offset = 0
+
+ num_elements = tensor.numel()
+
+ # we need to offset to get to the right element
+ if i == 0 and first_offset > 0:
+ tensor_offset = first_offset
+ num_elements = num_elements - tensor_offset
+ param_start_offset = first_offset
+
+ # we dont need all elements of the tensor
+ if num_elements > (partition_size - current_offset):
+ num_elements = partition_size - current_offset
+
+ self.grad_position[param_id] = [
+ int(group_id), int(param_start_offset),
+ int(current_offset), int(num_elements)
+ ]
+ current_offset += num_elements
+
+ def update_overflow_tracker_for_param_grad(self, param):
+ grad_accum = self.get_param_gradient_attribute(param)
+ if grad_accum is not None and self._has_inf_or_nan(grad_accum.data):
+ self.local_overflow = True
+
+ def _get_offload_gradient_dict(self):
+ for param_group_index, _ in enumerate(self.optimizer.param_groups):
+ self.offload_gradient_dict[param_group_index] = []
+ for lp_param in self.params_in_partition[param_group_index]:
+ param_id = self.get_param_id(lp_param)
+ [_, _, dest_offset, num_elements] = self.grad_position[param_id]
+ dest_tensor = self.single_partition_of_fp32_groups[param_group_index].grad.view(-1).narrow(
+ 0, dest_offset, num_elements)
+ self.offload_gradient_dict[param_group_index].append(dest_tensor)
+
+ def async_accumulate_grad_in_cpu_via_gpu(self, param):
+ param_id = self.get_param_id(param)
+
+ [i, source_offset, dest_offset, num_elements] = self.grad_position[param_id]
+
+ # copy to a preexisiting buffer to avoid memory allocation penalty
+ dest_buffer = self.temp_grad_buffer_for_gpu_offload.view(-1).narrow(0, 0, param.numel())
+
+ # buffer for storing gradients for this parameter in CPU
+ def buffer_to_accumulate_to_in_cpu():
+ if not self.fp16_master_weights_and_gradients:
+ buffer = torch.zeros(param.numel(), dtype=param.dtype, device=self.device)
+ return get_accelerator().pin_memory(buffer) if self.cpu_offload_pin_memory else buffer
+ else:
+ return self.single_partition_of_fp32_groups[i].grad.view(-1).narrow(0, dest_offset, num_elements)
+
+ # accumulate gradients into param.grad_accum or parts of it that belongs to this partition
+ def accumulate_gradients():
+ grad_accum = self.get_param_gradient_attribute(param)
+ if not self.fp16_master_weights_and_gradients:
+ dest_buffer.copy_(self.accumulated_grads_in_cpu[param_id].view(-1), non_blocking=True)
+ grad_accum.data.view(-1).add_(dest_buffer)
+ else:
+ dest_buffer.narrow(0, source_offset,
+ num_elements).copy_(self.accumulated_grads_in_cpu[param_id].view(-1),
+ non_blocking=True)
+ grad_accum.data.view(-1).narrow(0, source_offset,
+ num_elements).add_(dest_buffer.narrow(0, source_offset, num_elements))
+
+ # move accumulated gradients back to CPU
+ def copy_gradients_to_cpu():
+ grad_accum = self.get_param_gradient_attribute(param)
+ if not self.fp16_master_weights_and_gradients:
+ self.accumulated_grads_in_cpu[param_id].data.copy_(grad_accum.data.view(-1), non_blocking=True)
+ else:
+ self.accumulated_grads_in_cpu[param_id].data.copy_(grad_accum.data.view(-1).narrow(
+ 0, source_offset, num_elements),
+ non_blocking=True)
+
+ if param_id not in self.accumulated_grads_in_cpu:
+ self.accumulated_grads_in_cpu[param_id] = buffer_to_accumulate_to_in_cpu()
+
+ if self.micro_step_id > 0:
+ accumulate_gradients()
+
+ # at the boundary we will send 32bit directly
+ if not self.is_gradient_accumulation_boundary:
+ copy_gradients_to_cpu()
+
+ def set_norm_for_param_grad(self, param):
+ param_id = self.get_param_id(param)
+ grad_accum = self.get_param_gradient_attribute(param)
+ accumulated_grad = self.accumulated_grads_in_cpu[
+ param_id] if self.gradient_accumulation_steps > 1 else grad_accum
+
+ [i, source_offset, dest_offset, num_elements] = self.grad_position[param_id]
+
+ start = source_offset
+ accumulated_grad = accumulated_grad.view(-1).narrow(0, start, num_elements)
+
+ self.norm_for_param_grads[param_id] = accumulated_grad.data.double().norm(2)
+
+ def set_norm_for_param_grad_in_gpu(self, param):
+ param_id = self.get_param_id(param)
+ grad_accum = self.get_param_gradient_attribute(param)
+ if grad_accum is None:
+ accumulated_grad = param.grad
+ else:
+ accumulated_grad = grad_accum
+
+ [i, source_offset, dest_offset, num_elements] = self.grad_position[param_id]
+
+ start = source_offset
+ accumulated_grad = accumulated_grad.view(-1).narrow(0, start, num_elements)
+
+ self.norm_for_param_grads[param_id] = accumulated_grad.data.double().norm(2)
+
+ def async_inplace_copy_grad_to_fp32_buffer_from_gpu(self, param):
+ param_id = self.get_param_id(param)
+
+ [i, source_offset, dest_offset, num_elements] = self.grad_position[param_id]
+
+ dest_tensor = self.single_partition_of_fp32_groups[i].grad.view(-1).narrow(0, dest_offset, num_elements)
+
+ grad_accum = self.get_param_gradient_attribute(param)
+ if grad_accum is None:
+ src_tensor = grad_accum.view(-1).narrow(0, source_offset, num_elements)
+ else:
+ src_tensor = grad_accum.view(-1).narrow(0, source_offset, num_elements)
+ if not self.fp16_master_weights_and_gradients:
+ src_tensor = src_tensor.float()
+
+ dest_tensor.copy_(src_tensor, non_blocking=True)
+ param.grad = None # offload only
+
+ def complete_grad_norm_calculation_for_cpu_offload(self, params):
+ total_norm = 0.0
+ norm_type = 2.0
+ for p in params:
+ # Pipeline parallelism may replicate parameters. Avoid multi-counting.
+ if hasattr(p, PIPE_REPLICATED) and p.ds_pipe_replicated:
+ continue
+
+ if is_model_parallel_parameter(p) or (self.model_parallel_rank == 0):
+ param_id = self.get_param_id(p)
+ # as some model have trainable parameters but skipped in training,
+ # their backward hooks in self.create_reduce_and_remove_grad_hooks() will not run,
+ # so they have no norm_for_param_grads
+ if param_id in self.norm_for_param_grads:
+ param_norm = self.norm_for_param_grads[param_id]
+ total_norm += param_norm.item() ** 2
+ else:
+ # As unused parameters in modules may not be expected sometimes,
+ # add an explicit error msg when it occurred and an option to
+ # avoid the error
+ assert self.ignore_unused_parameters, """
+ This assert indicates that your module has parameters that
+ were not used in producing loss.
+ You can avoid this assert by
+ (1) enable ignore_unused_parameters option in zero_optimization config;
+ (2) making sure all trainable parameters and `forward` function
+ outputs participate in calculating loss.
+ """
+
+ # Sum across all model parallel GPUs.
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=self.dp_process_group)
+
+ self._model_parallel_all_reduce(tensor=total_norm_cuda, op=dist.ReduceOp.SUM)
+
+ total_norm = total_norm_cuda[0].item() ** (1. / norm_type)
+
+ if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm:
+ total_norm = -1
+
+ return total_norm
+
+ ############################################################################################
+ def copy_grads_in_partition(self, param):
+ if self.cpu_offload:
+
+ if self.gradient_accumulation_steps > 1:
+ self.async_accumulate_grad_in_cpu_via_gpu(param)
+
+ if self.is_gradient_accumulation_boundary:
+ self.set_norm_for_param_grad_in_gpu(param)
+
+ self.update_overflow_tracker_for_param_grad(param)
+
+ self.async_inplace_copy_grad_to_fp32_buffer_from_gpu(param)
+
+ return
+ # print(f"ID {self.get_param_id(param)} grad norm {param.grad.norm()}")
+ if self.grads_in_partition is None:
+ self.grads_in_partition_offset = 0
+ total_size = 0
+ for group in self.params_in_partition:
+ for param_in_partition in group:
+ total_size += param_in_partition.numel()
+
+ see_memory_usage(f"before copying {total_size} gradients into partition")
+ self.grads_in_partition = torch.empty(int(total_size),
+ dtype=self.dtype,
+ device=get_accelerator().current_device_name())
+ see_memory_usage(f"after copying {total_size} gradients into partition")
+
+ grad_reduc = self.get_gradient_for_reduction(param)
+ # The allreduce buffer will be rewritten. Copy the gradients in partition to a new buffer
+ new_grad_tensor = self.grads_in_partition.view(-1).narrow(0, self.grads_in_partition_offset, param.numel())
+ new_grad_tensor.copy_(grad_reduc.view(-1))
+ grad_reduc.data = new_grad_tensor.data.view_as(grad_reduc)
+ # print(f"Grad norm after copy to contiguous_buffer {param.grad.data.norm()}")
+ self.grads_in_partition_offset += param.numel()
+
+ def reduce_ipg_grads(self):
+ if self.contiguous_gradients:
+ if self.extra_large_param_to_reduce is not None:
+ assert len(self.params_in_ipg_bucket) == 1, "more than 1 param in ipg bucket, this shouldn't happen"
+ _, _, param_id = self.params_in_ipg_bucket[0]
+ assert self.get_param_id(self.extra_large_param_to_reduce
+ ) == param_id, "param in ipg bucket does not match extra-large param"
+ extra_large_grad_reduc = self.get_gradient_for_reduction(self.extra_large_param_to_reduce)
+ self.average_tensor(extra_large_grad_reduc.view(-1))
+ self.extra_large_param_to_reduce = None
+ else:
+ self.average_tensor(self.ipg_buffer[self.ipg_index])
+ else:
+ self.buffered_reduce_fallback(None,
+ self.grads_in_ipg_bucket,
+ elements_per_buffer=self.elements_in_ipg_bucket)
+
+ if self.overlap_comm:
+ stream = self.reduction_stream
+ elif self.cpu_offload:
+ # TODO: copy_grad_stream is disabled because of race with reduce. This hurts perf and should be fixed.
+ # get_accelerator().synchronize()
+ # stream = self.copy_grad_stream
+ stream = get_accelerator().current_stream()
+ else:
+ stream = get_accelerator().current_stream()
+
+ with get_accelerator().stream(stream):
+ for _, param, param_id in self.params_in_ipg_bucket:
+
+ assert self.params_already_reduced[param_id] == False, \
+ f"The parameter {param_id} has already been reduced. \
+ Gradient computed twice for this partition. \
+ Multiple gradient reduction is currently not supported"
+
+ self.params_already_reduced[param_id] = True
+ if self.partition_gradients:
+ if not self.is_param_in_current_partition[param_id]:
+ if self.overlap_comm and self.contiguous_gradients is False:
+ # Clear grads of other partitions during the next reduction
+ # to avoid clearing them before the reduction is complete.
+ if self.previous_reduced_grads is None:
+ self.previous_reduced_grads = []
+ self.previous_reduced_grads.append(param)
+ else:
+ self.clear_grad_attribute(param)
+ elif self.contiguous_gradients:
+ self.copy_grads_in_partition(param)
+ else: # zero stage 1 - partition only optimizer state
+ if self.contiguous_gradients and self.is_param_in_current_partition[param_id]:
+ self.copy_grads_in_partition(param)
+
+ self.grads_in_ipg_bucket = []
+ self.params_in_ipg_bucket = []
+ self.ipg_bucket_has_moe_params = False
+ self.elements_in_ipg_bucket = 0
+ #####################################################################
+
+ def reduce_ready_partitions_and_remove_grads(self, param, i):
+ if self.partition_gradients or self.is_gradient_accumulation_boundary:
+ self.reduce_independent_p_g_buckets_and_remove_grads(param, i)
+
+ def zero_reduced_gradients(self, partition_id, i):
+
+ def are_all_related_partitions_reduced(params_id):
+ for partition_id in self.param_to_partition_ids[i][params_id]:
+ if not self.is_partition_reduced[i][partition_id]:
+ return False
+ return True
+
+ for params_id in self.is_grad_computed[i][partition_id]:
+ if are_all_related_partitions_reduced(params_id):
+ self.param_dict[params_id].grad = None # dead code
+
+ def flatten_and_print(self, message, tensors, start=0, n=5):
+ flatten_tensor = self.flatten(tensors)
+
+ def print_func():
+ logger.info(flatten_tensor.contiguous().view(-1).narrow(0, start, n))
+
+ self.sequential_execution(print_func, message)
+
+ def get_grads_to_reduce(self, i, partition_id):
+
+ def get_reducible_portion(key):
+ grad = self.param_dict[key].grad
+ total_elements = grad.numel()
+ start = self.grad_start_offset[i][partition_id][key]
+ num_elements = min(total_elements - start,
+ self.partition_size[i] - self.grad_partition_insertion_offset[i][partition_id][key])
+ if not pg_correctness_test:
+ if num_elements == total_elements:
+ return grad
+ else:
+ return grad.contiguous().view(-1).narrow(0, int(start), int(num_elements))
+ else:
+ if num_elements == total_elements:
+ return grad.clone()
+ else:
+ return grad.clone().contiguous().view(-1).narrow(0, int(start), int(num_elements))
+
+ grads_to_reduce = []
+ for key in self.is_grad_computed[i][partition_id]:
+ grad = get_reducible_portion(key)
+ grads_to_reduce.append(grad)
+ return grads_to_reduce
+
+ def sequential_execution(self, function, message, group=None):
+ if group is None:
+ group = self.zp_process_group
+ if dist.get_rank(group=group) == 0:
+ logger.info(message)
+ for id in range(dist.get_world_size(group=group)):
+ if id == dist.get_rank(group=group):
+ function()
+ dist.barrier(group=group)
+
+ def set_none_gradients_to_zero(self, i, partition_id):
+ for param_id in self.is_grad_computed[i][partition_id]:
+ param = self.param_dict[param_id]
+ if param.grad is None:
+ param.grad = torch.zero_like(param)
+
+ ######################Reduction Related Methods##############################
+ def allreduce_bucket(self, bucket, rank=None, log=None, divide=True, process_group=None):
+ rank = None
+ tensor = self.flatten(bucket)
+
+ process_group = self.zp_process_group if process_group is None else process_group
+
+ tensor_to_allreduce = tensor
+
+ if pg_correctness_test or self.sequence_parallel_size > 1:
+ communication_data_type = torch.float32
+ else:
+ communication_data_type = self.communication_data_type
+
+ if communication_data_type != tensor.dtype:
+ tensor_to_allreduce = tensor.to(communication_data_type)
+
+ if divide:
+ tensor_to_allreduce.div_(
+ dist.get_world_size(group=self.dp_process_group) / float(self.sequence_parallel_size))
+
+ tensor_to_allreduce = tensor_to_allreduce.contiguous()
+ if rank is None:
+ # "All Reducing"
+ dist.all_reduce(tensor_to_allreduce, group=self.dp_process_group)
+ else:
+ global_rank = dist.get_global_rank(self.dp_process_group, rank)
+ dist.reduce(tensor_to_allreduce, global_rank, group=self.dp_process_group)
+
+ if communication_data_type != tensor.dtype and tensor is not tensor_to_allreduce:
+ if rank is None or rank == dist.get_rank(group=process_group):
+ tensor.copy_(tensor_to_allreduce)
+
+ return tensor
+
+ def _clear_previous_reduced_grads(self):
+ if self.previous_reduced_grads is not None:
+ for param in self.previous_reduced_grads:
+ self.clear_grad_attribute(param)
+ self.previous_reduced_grads = None
+
+ # if rank is specified do a reduction instead of an allreduce
+ def allreduce_and_copy(self, small_bucket, rank=None, log=None, divide=True, process_group=None):
+ process_group = self.zp_process_group if process_group is None else process_group
+ if self.overlap_comm:
+ get_accelerator().synchronize()
+ # It is safe to clear the previously reduced grads of other partitions
+ self._clear_previous_reduced_grads()
+ stream = self.reduction_stream
+ else:
+ stream = get_accelerator().current_stream()
+
+ with get_accelerator().stream(stream):
+ allreduced = self.allreduce_bucket(
+ small_bucket,
+ rank=rank,
+ log=log,
+ divide=divide,
+ process_group=process_group,
+ )
+ if rank is None or rank == dist.get_rank(group=self.zp_process_group):
+ for buf, synced in zip(small_bucket, self.unflatten(allreduced, small_bucket)):
+ buf.copy_(synced)
+
+ def allreduce_no_retain(
+ self,
+ bucket,
+ numel_per_bucket=500000000,
+ rank=None,
+ log=None,
+ divide=True,
+ process_group=None,
+ ):
+ small_bucket = []
+ numel = 0
+ for tensor in bucket:
+ small_bucket.append(tensor)
+ numel = numel + tensor.numel()
+ if numel > numel_per_bucket:
+ self.allreduce_and_copy(small_bucket, rank=rank, log=None, divide=divide, process_group=process_group)
+ small_bucket = []
+ numel = 0
+
+ if len(small_bucket) > 0:
+ self.allreduce_and_copy(small_bucket, rank=rank, log=log, divide=divide, process_group=process_group)
+
+ # allows using reduction of gradients instead of using all_reduce
+
+ def buffered_reduce_fallback(self, rank, grads, elements_per_buffer=500000000, log=None):
+ split_buckets = split_half_float_double(grads)
+
+ for i, bucket in enumerate(split_buckets):
+ self.allreduce_no_retain(bucket, numel_per_bucket=elements_per_buffer, rank=rank, log=log)
+
+ #############################################################################
+ #############################################################################
+ #############################################################################
+
+ # views the tensor as multiple partitions and returns
+ # those partitions
+ def get_data_parallel_partitions(self, tensor, group_id):
+ partitions = []
+
+ dp = dist.get_world_size(group=self.real_zp_process_group[group_id])
+ # dp_id = dist.get_rank(group=self.real_dp_process_group[group_id])
+
+ total_num_elements = tensor.numel()
+
+ base_size = total_num_elements // dp
+ remaining = total_num_elements % dp
+
+ start = 0
+ for id in range(dp):
+ partition_size = base_size
+ if id < remaining:
+ partition_size = partition_size + 1
+ partitions.append(tensor.narrow(0, start, partition_size))
+ start = start + partition_size
+ return partitions
+
+ def get_partition_info(self, tensor_list, partition_size, partition_id):
+ params_in_partition = []
+ params_not_in_partition = []
+
+ start_index = partition_size * partition_id
+ end_index = partition_size * (partition_id + 1)
+
+ current_index = 0
+ first_offset = 0
+
+ for tensor in tensor_list:
+
+ tensor_size = tensor.numel()
+
+ if start_index <= current_index < end_index:
+ params_in_partition.append(tensor)
+
+ elif current_index < start_index < (current_index + tensor_size):
+ params_in_partition.append(tensor)
+
+ assert (first_offset == 0
+ ), "This can happen either zero or only once as this must be the first tensor in the partition"
+ first_offset = start_index - current_index
+
+ else:
+ params_not_in_partition.append(tensor)
+
+ current_index = current_index + tensor_size
+
+ return params_in_partition, params_not_in_partition, first_offset
+
+ def zero_grad(self, set_to_none=True):
+ """
+ Zero FP16 parameter grads.
+ """
+ # FP32 grad should never exist.
+ # For speed, set model fp16 grad to None by default
+ # zero all pointers to grad tensors
+ for group in self.bit16_groups:
+ for p in group:
+ if set_to_none:
+ p.grad = None # epilogue and in step
+ p.grad_accum = None
+ else:
+ if p.grad is not None:
+ p.grad.detach_()
+ p.grad.zero_()
+
+ def _model_parallel_all_reduce(self, tensor, op):
+ """ Perform all reduce within model parallel group, if any.
+ """
+ if self.model_parallel_group is None or self.model_parallel_world_size == 1:
+ pass
+ else:
+ dist.all_reduce(tensor=tensor, op=op, group=self.model_parallel_group)
+
+ def get_grad_norm_direct(self, gradients, params, norm_type=2):
+ """Clips gradient norm of an iterable of parameters.
+
+ This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
+ added functionality to handle model parallel parameters. Note that
+ the gradients are modified in place.
+
+ Arguments:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ max_norm (float or int): max norm of the gradients
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+
+ Returns:
+ Total norm of the parameters (viewed as a single vector).
+ """
+ norm_type = float(norm_type)
+ if norm_type == inf:
+ total_norm = max(g.data.abs().max() for g in gradients)
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=self.dp_process_group)
+
+ # Take max across all GPUs.
+ self._model_parallel_all_reduce(tensor=total_norm_cuda, op=dist.ReduceOp.MAX)
+ total_norm = total_norm_cuda[0].item()
+ else:
+ total_norm = 0.0
+ # if dist.get_rank() == 0:
+ # logger.info(f"Total Norm beginning {total_norm}")
+ for g, p in zip(gradients, params):
+ # Pipeline parallelism may replicate parameters. Avoid multi-counting.
+ if hasattr(p, PIPE_REPLICATED) and p.ds_pipe_replicated:
+ continue
+ if is_model_parallel_parameter(p) or (self.model_parallel_rank == 0):
+ param_norm = g.data.double().norm(2)
+ total_norm += param_norm.item() ** 2
+ # Sum across all model parallel GPUs.
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=self.dp_process_group)
+
+ self._model_parallel_all_reduce(tensor=total_norm_cuda, op=dist.ReduceOp.SUM)
+
+ total_norm = total_norm_cuda[0].item() ** (1. / norm_type)
+
+ if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm:
+ total_norm = -1
+
+ return total_norm
+
+ # creates a flat fused tensor from the tensor list starting at the first_offset
+ # in the first tensor of the list. If there are not enough elements in the tensor
+ # list then the flat tensor will be padded with zeros
+ def get_flat_partition(self, tensor_list, first_offset, partition_size, dtype, device, return_tensor_list=False):
+ flat_tensor_list = []
+ current_size = 0
+
+ for i, tensor in enumerate(tensor_list):
+ grad_accum = self.get_param_gradient_attribute(tensor)
+ if grad_accum is None:
+ grad_accum = torch.zeros_like(tensor, dtype=dtype)
+
+ tensor = grad_accum
+ num_elements = tensor.numel()
+ tensor_offset = 0
+
+ # we need to offset to get to the right element
+ if i == 0 and first_offset > 0:
+ tensor_offset = first_offset
+ num_elements = num_elements - tensor_offset
+
+ # we dont need all elements of the tensor
+ if num_elements > (partition_size - current_size):
+ num_elements = partition_size - current_size
+
+ # we need a narrow view of the tensor based on the tensor offset and number of elements that
+ # we need from this tensor
+ if tensor_offset > 0 or num_elements < tensor.numel():
+ flat_tensor_list.append(tensor.contiguous().view(-1).narrow(0, int(tensor_offset), int(num_elements)))
+ else:
+ flat_tensor_list.append(tensor)
+
+ current_size = current_size + num_elements
+
+ # this means its the last partition and does not align with the dp boundary. We need to pad before flattening
+ if current_size < partition_size:
+ flat_tensor_list.append(torch.zeros(int(partition_size - current_size), dtype=dtype, device=device))
+
+ if return_tensor_list:
+ return flat_tensor_list
+
+ return self.flatten(flat_tensor_list)
+
+ def free_grad_in_param_list(self, param_list):
+ for p in param_list:
+ p.grad = None # in step
+ p.grad_accum = None
+
+ def reset_cpu_buffers(self):
+ self.norm_for_param_grads = {}
+ self.local_overflow = False
+
+ def set_lr(self, lr):
+ """Set the learning rate."""
+ for param_group in self.optimizer.param_groups:
+ param_group["lr"] = lr
+
+ def get_lr(self):
+ """Return the current learning rate."""
+ return self.optimizer.param_groups[0]["lr"]
+
+ def override_loss_scale(self, loss_scale):
+ if loss_scale != self.external_loss_scale:
+ logger.info(f'[deepspeed] setting loss scale from {self.external_loss_scale} -> {loss_scale}')
+ self.custom_loss_scaler = True
+ self.external_loss_scale = loss_scale
+
+ def scaled_global_norm(self, norm_type=2):
+ assert norm_type == 2, "only L2 norm supported"
+ norm_groups = []
+ for i, group in enumerate(self.bit16_groups):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+ if self.cpu_offload:
+ norm_groups.append(self.complete_grad_norm_calculation_for_cpu_offload(self.params_in_partition[i]))
+ single_grad_partition = self.single_partition_of_fp32_groups[i].grad
+ else:
+ norm_groups.append(self.get_grad_norm_direct(self.averaged_gradients[i], self.params_in_partition[i]))
+
+ if self.has_moe_layers:
+ self._average_expert_grad_norms(norm_groups)
+
+ # note that the get_global_norm function only supports l2 norm
+ return get_global_norm(norm_list=norm_groups)
+
+ def get_bit16_param_group(self, group_no):
+ bit16_partitions = self.parallel_partitioned_bit16_groups[group_no]
+ partition_id = dist.get_rank(group=self.real_zp_process_group[group_no])
+ return [bit16_partitions[dist.get_rank(group=self.real_zp_process_group[group_no])]]
+
+ def _optimizer_step(self, group_no):
+ original_param_groups = self.optimizer.param_groups
+ self.optimizer.param_groups = [original_param_groups[group_no]]
+ # Disabling this as the C++ side copy & synchronize is not working correctly
+ # from deepspeed.ops.adam import DeepSpeedCPUAdam
+ # if type(self.optimizer) == DeepSpeedCPUAdam and self.dtype == torch.half:
+ # self.optimizer.step(fp16_param_groups=[self.get_bit16_param_group(group_no)])
+ # else:
+ # self.optimizer.step()
+ self.optimizer.step()
+ self.optimizer.param_groups = original_param_groups
+
+ def step(self, closure=None):
+ """
+ Not supporting closure.
+ """
+ self.micro_step_id = -1
+
+ see_memory_usage(f"In step before checking overflow")
+
+ # First compute norm for all group so we know if there is overflow
+ if self.dtype == torch.float16:
+ self.check_overflow()
+
+ prev_scale = self.loss_scale
+ self._update_scale(self.overflow)
+ if self.overflow:
+ see_memory_usage('After overflow before clearing gradients')
+ self.zero_grad(set_to_none=True)
+ if self.cpu_offload:
+ self.reset_cpu_buffers()
+ else:
+ self.averaged_gradients = {}
+
+ see_memory_usage('After overflow after clearing gradients')
+
+ for timer in OPTIMIZER_TIMERS:
+ self.timers(timer).start()
+ self.timers(timer).stop()
+ return
+
+ # Step 1:- Calculate gradient norm using bit-16 grads
+ see_memory_usage('Before norm calculation')
+ scaled_global_grad_norm = self.scaled_global_norm()
+ self._global_grad_norm = scaled_global_grad_norm / prev_scale
+ see_memory_usage('After norm before optimizer')
+
+ # Step 2:- run optimizer and upscaling simultaneously
+ for i, group in enumerate(self.bit16_groups):
+ self.timers(OPTIMIZER_GRADIENTS_TIMER).start()
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+ if self.cpu_offload:
+ single_grad_partition = self.single_partition_of_fp32_groups[i].grad
+ self.unscale_and_clip_grads([single_grad_partition], scaled_global_grad_norm)
+
+ self.timers(OPTIMIZER_GRADIENTS_TIMER).stop()
+ self.timers(OPTIMIZER_STEP_TIMER).start()
+ self._optimizer_step(i)
+
+ # Disabled, this is not currently working
+ # from deepspeed.ops.adam import DeepSpeedCPUAdam
+ # if not (type(self.optimizer) == DeepSpeedCPUAdam and self.dtype == torch.half):
+ # bit16_partitions = self.parallel_partitioned_bit16_groups[i]
+ # fp32_partition = self.single_partition_of_fp32_groups[i]
+ # bit16_partitions[partition_id].data.copy_(fp32_partition.data)
+ bit16_partitions = self.parallel_partitioned_bit16_groups[i]
+ fp32_partition = self.single_partition_of_fp32_groups[i]
+ bit16_partitions[partition_id].data.copy_(fp32_partition.data)
+
+ self.timers(OPTIMIZER_STEP_TIMER).stop()
+ else:
+ # free gradients for all the parameters that are not updated by this process(ZeRO stage2)
+ self.free_grad_in_param_list(self.params_not_in_partition[i])
+
+ # create a flat gradients for parameters updated by this process
+ # If we are last partition, ensure we have same size grads and partition size, if not pad with zero tensors
+ if partition_id == dist.get_world_size(group=self.real_zp_process_group[i]) - 1:
+ single_grad_partition = self.flatten_dense_tensors_aligned(
+ self.averaged_gradients[i],
+ int(self.partition_size[i])).to(self.single_partition_of_fp32_groups[i].dtype)
+ else:
+ single_grad_partition = self.flatten(self.averaged_gradients[i]).to(
+ self.single_partition_of_fp32_groups[i].dtype)
+ assert single_grad_partition.numel() == self.partition_size[i], \
+ "averaged gradients have different number of elements that partition size {} {} {} {}".format(
+ single_grad_partition.numel(), self.partition_size[i], i, partition_id)
+
+ self.single_partition_of_fp32_groups[i].grad = single_grad_partition
+ # release all the gradient since we have already created a necessary copy in dp_grad_partition(ZeRO stage2)
+ self.free_grad_in_param_list(self.params_in_partition[i])
+
+ self.averaged_gradients[i] = None
+
+ self.unscale_and_clip_grads([single_grad_partition], scaled_global_grad_norm)
+
+ self.timers(OPTIMIZER_GRADIENTS_TIMER).stop()
+
+ # Step 3:- run the optimizer if no offloading
+ self.timers(OPTIMIZER_STEP_TIMER).start()
+ self._optimizer_step(i)
+ # Step 4:- get rid of the fp32 gradients. Not needed anymore
+ self.single_partition_of_fp32_groups[i].grad = None
+ del single_grad_partition
+ bit16_partitions = self.parallel_partitioned_bit16_groups[i]
+ fp32_partition = self.single_partition_of_fp32_groups[i]
+ bit16_partitions[partition_id].data.copy_(fp32_partition.data)
+ self.timers(OPTIMIZER_STEP_TIMER).stop()
+
+ see_memory_usage('After optimizer before all-gather')
+ if self.cpu_offload:
+ self.reset_cpu_buffers()
+
+ self.timers(OPTIMIZER_ALLGATHER_TIMER).start()
+
+ # if dist.get_rank(group=self.dp_process_group) == 0:
+ # pdb.set_trace() # 或者使用其他调试工具
+
+ # Gather the updated weights from everyone.
+ # Then all partitions of the model parameters are updated and ready for next round forward.
+ all_gather_into_tensor_dp_groups(groups_flat=self.bit16_groups_flat,
+ partitioned_param_groups=self.parallel_partitioned_bit16_groups,
+ zp_process_group=self.real_zp_process_group)
+ self.timers(OPTIMIZER_ALLGATHER_TIMER).stop()
+
+ # TODO: we probably don't need this? just to be safe
+ for i in range(len(self.bit16_groups)):
+ self._update_model_bit16_weights(i)
+
+ self.timers.log(OPTIMIZER_TIMERS)
+ see_memory_usage('After zero_optimizer step')
+
+ return
+
+ @torch.no_grad()
+ def update_lp_params(self):
+ for i, (bit16_partitions, fp32_partition) in enumerate(
+ zip(self.parallel_partitioned_bit16_groups, self.single_partition_of_fp32_groups)):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+ bit16_partitions[partition_id].data.copy_(fp32_partition.data)
+ # print_rank_0(f'update_lp_params {i=} {partition_id=}', force=True)
+ # if i == 0:
+ # print_rank_0(f'{fp32_partition[:10]=}', force=True)
+ all_gather_into_tensor_dp_groups(groups_flat=self.bit16_groups_flat,
+ partitioned_param_groups=self.parallel_partitioned_bit16_groups,
+ zp_process_group=self.real_zp_process_group)
+
+ def _average_expert_grad_norms(self, norm_groups):
+ for i, norm in enumerate(norm_groups):
+ if self.is_moe_param_group[i]:
+ scaled_norm = norm * 1.0 / float(dist.get_world_size(group=self.dp_process_group))
+ scaled_norm_tensor = torch.tensor(scaled_norm,
+ device=get_accelerator().device_name(),
+ dtype=torch.float)
+ dist.all_reduce(scaled_norm_tensor, group=self.dp_process_group)
+ norm_groups[i] = scaled_norm_tensor.item()
+
+ def unscale_and_clip_grads(self, grad_groups_flat, total_norm):
+ # compute combined scale factor for this group
+ combined_scale = self.loss_scale
+ if self.clip_grad > 0.:
+ # norm is in fact norm*scale
+ clip = ((total_norm / self.loss_scale) + 1e-6) / self.clip_grad
+ if clip > 1:
+ combined_scale = clip * self.loss_scale
+
+ for grad in grad_groups_flat:
+ if isinstance(grad, list):
+ sub_partitions = grad
+ for g in sub_partitions:
+ g.data.mul_(1. / combined_scale)
+ else:
+ grad.data.mul_(1. / combined_scale)
+
+ def _check_overflow(self, partition_gradients=True):
+ self.overflow = self.has_overflow(partition_gradients)
+
+ # `params` is a list / generator of torch.Variable
+ def has_overflow_serial(self, params, is_grad_list=False):
+ for p in params:
+ if p.grad is not None and self._has_inf_or_nan(p.grad.data):
+ return True
+
+ return False
+
+ def has_overflow_partitioned_grads_serial(self):
+ for i in range(len(self.bit16_groups)):
+ for j, grad in enumerate(self.averaged_gradients[i]):
+ if grad is not None and self._has_inf_or_nan(grad.data, j):
+ return True
+ return False
+
+ def has_overflow(self, partition_gradients=True):
+ if partition_gradients:
+ overflow = self.local_overflow if self.cpu_offload else self.has_overflow_partitioned_grads_serial()
+ overflow_gpu = get_accelerator().ByteTensor([overflow])
+ '''This will capture overflow across all data parallel and expert parallel process
+ Since expert parallel process are a subset of data parallel process'''
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.dp_process_group)
+
+ else:
+ params = []
+ for group in self.bit16_groups:
+ for param in group:
+ params.append(param)
+
+ overflow = self.has_overflow_serial(params, is_grad_list=partition_gradients)
+ overflow_gpu = get_accelerator().ByteTensor([overflow])
+
+ # Since each model parallel GPU carries only part of the model,
+ # make sure overflow flag is synced across all the model parallel GPUs
+ self._model_parallel_all_reduce(tensor=overflow_gpu, op=dist.ReduceOp.MAX)
+
+ overflow = overflow_gpu[0].item()
+ return bool(overflow)
+
+ # `x` is a torch.Tensor
+ @staticmethod
+ def _has_inf_or_nan(x, j=None):
+ try:
+ # if x is half, the .float() incurs an additional deep copy, but it's necessary if
+ # Pytorch's .sum() creates a one-element tensor of the same type as x
+ # (which is true for some recent version of pytorch).
+ cpu_sum = float(x.float().sum())
+ # More efficient version that can be used if .sum() returns a Python scalar
+ # cpu_sum = float(x.sum())
+ except RuntimeError as instance:
+ # We want to check if inst is actually an overflow exception.
+ # RuntimeError could come from a different error.
+ # If so, we still want the exception to propagate.
+ if "value cannot be converted" not in instance.args[0]:
+ raise
+ return True
+ else:
+ if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
+ return True
+ return False
+
+ def backward(self, loss, retain_graph=False):
+ """
+ :attr:`backward` performs the following steps:
+
+ 1. fp32_loss = loss.float()
+ 2. scaled_loss = fp32_loss*loss_scale
+ 3. scaled_loss.backward(), which accumulates scaled gradients into the ``.grad`` attributes of the model's fp16 leaves
+ """
+ self.micro_step_id += 1
+
+ if self.contiguous_gradients:
+ self.ipg_buffer = []
+ buf_0 = torch.empty(int(self.reduce_bucket_size),
+ dtype=self.dtype,
+ device=get_accelerator().current_device_name())
+ self.ipg_buffer.append(buf_0)
+
+ # Use double buffers to avoid data access conflict when overlap_comm is enabled.
+ if self.overlap_comm:
+ buf_1 = torch.empty(int(self.reduce_bucket_size),
+ dtype=self.dtype,
+ device=get_accelerator().current_device_name())
+ self.ipg_buffer.append(buf_1)
+ self.ipg_index = 0
+
+ if self.custom_loss_scaler:
+ scaled_loss = self.external_loss_scale * loss
+ scaled_loss.backward()
+ else:
+ self.loss_scaler.backward(loss.float(), retain_graph=retain_graph)
+
+ # Only for Stage 1, Mode 2
+ if self.use_grad_accum_attribute:
+ self.fill_grad_accum_attribute()
+
+ def check_overflow(self, partition_gradients=True):
+ self._check_overflow(partition_gradients)
+
+ def _update_scale(self, has_overflow=False):
+ self.loss_scaler.update_scale(has_overflow)
+
+ # Promote state so it can be retrieved or set via "fp16_optimizer_instance.state"
+ def _get_state(self):
+ return self.optimizer.state
+
+ def _set_state(self, value):
+ self.optimizer.state = value
+
+ state = property(_get_state, _set_state)
+
+ # Promote param_groups so it can be retrieved or set via "fp16_optimizer_instance.param_groups"
+ # (for example, to adjust the learning rate)
+ def _get_param_groups(self):
+ return self.optimizer.param_groups
+
+ def _set_param_groups(self, value):
+ self.optimizer.param_groups = value
+
+ param_groups = property(_get_param_groups, _set_param_groups)
+
+ # Promote loss scale so it can be retrieved or set via "fp16_optimizer_instance.loss_scale"
+ def _get_loss_scale(self):
+ if self.custom_loss_scaler:
+ return self.external_loss_scale
+ else:
+ return self.loss_scaler.cur_scale
+
+ def _set_loss_scale(self, value):
+ self.loss_scaler.cur_scale = value
+
+ loss_scale = property(_get_loss_scale, _set_loss_scale)
+ cur_scale = property(_get_loss_scale, _set_loss_scale)
+
+ # Return group tensor after removing paddings that are added for alignment to DP world size.
+ # This method works on the assumption that each group contains a single flattened tensor.
+ def _get_groups_without_padding(self, groups_with_padding):
+ groups_without_padding = []
+ for i, group in enumerate(groups_with_padding):
+ lean_length = group.numel() - self.groups_padding[i]
+ groups_without_padding.append(group[:lean_length])
+
+ return groups_without_padding
+
+ # Return optimizer state after removing paddings that are added for alignment.
+ def _get_state_without_padding(self, state_with_padding, padding):
+ lean_state = {}
+ for key, value in state_with_padding.items():
+ if torch.is_tensor(value):
+ lean_length = value.numel() - padding
+ lean_state[key] = value[:lean_length]
+ else:
+ lean_state[key] = value
+
+ return lean_state
+
+ # Return base optimizer states.
+ # This method assumes that each param group contains a single flattened tensor.
+ def _get_base_optimizer_state(self):
+ optimizer_groups_state = []
+ for i, group in enumerate(self.optimizer.param_groups):
+ p = group['params'][0]
+ lean_optimizer_state = self._get_state_without_padding(self.optimizer.state[p], self.groups_padding[i])
+ optimizer_groups_state.append(lean_optimizer_state)
+
+ return optimizer_groups_state
+
+ def state_dict(self):
+ """
+ Returns a dict containing the current state of this :class:`FP16_Optimizer` instance.
+ This dict contains attributes of :class:`FP16_Optimizer`, as well as the state_dict
+ of the contained Pytorch optimizer.
+ Example::
+ checkpoint = {}
+ checkpoint['model'] = model.state_dict()
+ checkpoint['optimizer'] = optimizer.state_dict()
+ torch.save(checkpoint, "saved.pth")
+ """
+ state_dict = {}
+ state_dict[LOSS_SCALER] = self.loss_scaler
+ state_dict['dynamic_loss_scale'] = self.dynamic_loss_scale
+ state_dict['overflow'] = self.overflow
+ state_dict[CLIP_GRAD] = self.clip_grad
+
+ if self.elastic_checkpoint:
+ state_dict[BASE_OPTIMIZER_STATE] = self._get_base_optimizer_state()
+
+ if "step" in self.optimizer.param_groups[0]:
+ # Assuming "step" is the only item that changes through training iterations
+ assert all(group["step"] == self.optimizer.param_groups[0]["step"]
+ for group in self.optimizer.param_groups), "All param groups must have the same step value"
+ state_dict[BASE_OPTIMIZER_STATE_STEP] = self.optimizer.param_groups[0]["step"]
+ else:
+ state_dict[BASE_OPTIMIZER_STATE] = self.optimizer.state_dict()
+
+ # Remove paddings for DP alignment to enable loading for other alignment values
+ fp32_groups_without_padding = self._get_groups_without_padding(self.single_partition_of_fp32_groups)
+ state_dict[SINGLE_PARTITION_OF_FP32_GROUPS] = fp32_groups_without_padding
+
+ state_dict[
+ ZERO_STAGE] = ZeroStageEnum.gradients if self.partition_gradients else ZeroStageEnum.optimizer_states
+ state_dict[GROUP_PADDINGS] = self.groups_padding
+ state_dict[PARTITION_COUNT] = self.partition_count
+
+ state_dict[DS_VERSION] = version
+ state_dict[PARAM_SLICE_MAPPINGS] = self._param_slice_mappings
+
+ return state_dict
+
+ # Restore base optimizer fp32 weights from elastic checkpoint by:
+ # 1) Merging fp32 weights from checkpoints of all partitions
+ # 2) Extracting fp32 weights for current partition from merged weights
+ # 3) Using extracted weights to update base optimizer weights directly.
+ def _restore_from_elastic_fp32_weights(self, all_state_dict):
+ merged_single_partition_of_fp32_groups = []
+
+ for i in range(len(self.single_partition_of_fp32_groups)):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[i])
+ merged_partitions = [sd[SINGLE_PARTITION_OF_FP32_GROUPS][i] for sd in all_state_dict]
+ if self.is_moe_group(self.optimizer.param_groups[i]):
+ ranks = self.get_ep_ranks(group_name=self.optimizer.param_groups[i]['name'])
+ merged_partitions = [merged_partitions[i] for i in ranks]
+ flat_merged_partitions = self.flatten_dense_tensors_aligned(
+ merged_partitions,
+ self.nccl_start_alignment_factor * dist.get_world_size(group=self.real_zp_process_group[i]))
+ dp_partitions = self.get_data_parallel_partitions(flat_merged_partitions, i)
+ merged_single_partition_of_fp32_groups.append(dp_partitions[partition_id])
+
+ for current, saved in zip(self.single_partition_of_fp32_groups, merged_single_partition_of_fp32_groups):
+ current.data.copy_(saved.data)
+
+ # Restore base optimizer fp32 weights from ZeRO fp16 or bfloat16 weights
+ def _restore_from_bit16_weights(self):
+ for group_id, (bit16_partitions, fp32_partition) in enumerate(
+ zip(self.parallel_partitioned_bit16_groups, self.single_partition_of_fp32_groups)):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[group_id])
+ fp32_partition.data.copy_(bit16_partitions[partition_id].data)
+
+ # Refresh the fp32 master params from the fp16 or bfloat16 copies.
+ def refresh_fp32_params(self):
+ self._restore_from_bit16_weights()
+
+ # Extract optimizer state for current partition from merged states of all partitions
+ def _partition_base_optimizer_state(self, state_key, all_partition_states, group_id):
+ partition_id = dist.get_rank(group=self.real_zp_process_group[group_id])
+ alignment = dist.get_world_size(group=self.real_zp_process_group[group_id])
+ if torch.is_tensor(all_partition_states[0]):
+ flat_merged_partitions = self.flatten_dense_tensors_aligned(all_partition_states, alignment)
+ dp_partitions = self.get_data_parallel_partitions(flat_merged_partitions, group_id)
+ return dp_partitions[partition_id]
+ else:
+ # Assume non-tensor states are not partitioned and equal across ranks, so return first one
+ return all_partition_states[0]
+
+ def _restore_base_optimizer_state(self, base_optimizer_group_states):
+ if type(base_optimizer_group_states) == dict:
+ base_optimizer_group_states = base_optimizer_group_states['state']
+ for i, group in enumerate(self.optimizer.param_groups):
+ p = group['params'][0]
+ for key, saved in base_optimizer_group_states[i].items():
+ if torch.is_tensor(self.optimizer.state[p][key]):
+ dst_tensor = self.optimizer.state[p][key]
+ src_tensor = _get_padded_tensor(saved, dst_tensor.numel())
+ self.optimizer.state[p][key].data.copy_(src_tensor.data)
+ else:
+ self.optimizer.state[p][key] = saved
+
+ def get_ep_ranks(self, rank=0, group_name=None):
+ from deepspeed.utils import groups
+ expert_parallel_size_ = groups._get_expert_parallel_world_size(group_name)
+ world_size = groups._get_data_parallel_world_size()
+ rank = groups._get_expert_parallel_rank(group_name)
+ ranks = range(rank, world_size, expert_parallel_size_)
+ return list(ranks)
+
+ # Restore base optimizer state from elastic checkpoint by
+ # 1) Merging optimizer state from checkpoints of all partitions
+ # 2) Extracting optimizer state for current partition from the merged state
+ # 3) Using the extracted value to directly update the base optimizer.
+ def _restore_elastic_base_optimizer_state(self, all_state_dict):
+ base_optimizer_group_states = []
+ for i in range(len(self.optimizer.param_groups)):
+ partition_states = {}
+ all_partition_group_states = [sd[BASE_OPTIMIZER_STATE][i] for sd in all_state_dict]
+
+ if self.is_moe_group(self.optimizer.param_groups[i]):
+ ranks = self.get_ep_ranks(group_name=self.optimizer.param_groups[i]['name'])
+ all_partition_group_states = [all_partition_group_states[i] for i in ranks]
+
+ for key in all_partition_group_states[0].keys():
+ all_partition_states = [all_states[key] for all_states in all_partition_group_states]
+ partition_states[key] = self._partition_base_optimizer_state(key, all_partition_states, i)
+ base_optimizer_group_states.append(partition_states)
+
+ self._restore_base_optimizer_state(base_optimizer_group_states)
+
+ # Restore step
+ if BASE_OPTIMIZER_STATE_STEP in all_state_dict[0]:
+ assert all(sd[BASE_OPTIMIZER_STATE_STEP] == all_state_dict[0][BASE_OPTIMIZER_STATE_STEP]
+ for sd in all_state_dict), "State dicts of all partitions must have the same step value"
+ loaded_param_groups_step = all_state_dict[0][BASE_OPTIMIZER_STATE_STEP]
+ for param_group in self.optimizer.param_groups:
+ param_group['step'] = loaded_param_groups_step
+
+ def load_state_dict(self,
+ state_dict_list,
+ load_optimizer_states=True,
+ load_from_fp32_weights=False,
+ checkpoint_folder=None,
+ load_serial=None):
+ if checkpoint_folder:
+ self._load_universal_checkpoint(checkpoint_folder, load_optimizer_states, load_from_fp32_weights)
+ else:
+ self._load_legacy_checkpoint(state_dict_list, load_optimizer_states, load_from_fp32_weights)
+
+ def _load_universal_checkpoint(self, checkpoint_folder, load_optimizer_states, load_from_fp32_weights):
+ self._load_hp_checkpoint_state(checkpoint_folder)
+
+ @property
+ def param_groups(self):
+ """Forward the wrapped optimizer's parameters."""
+ return self.optimizer.param_groups
+
+ def _load_hp_checkpoint_state(self, checkpoint_dir):
+ checkpoint_dir = os.path.join(checkpoint_dir, "zero")
+ optim_state_path = os.path.join(checkpoint_dir, "optimizer_state.pt")
+ assert os.path.isfile(
+ optim_state_path), f'{optim_state_path} containing optimizer global state is missing! Cannot proceed.'
+ optim_sd = torch.load(optim_state_path)
+ self._load_global_state(optim_sd)
+
+ tp_rank = bwc_tensor_model_parallel_rank(mpu=self.mpu)
+ tp_world_size = self.mpu.get_slice_parallel_world_size() if hasattr(self.mpu, "get_slice_parallel_world_size") \
+ else self.mpu.get_tensor_model_parallel_world_size()
+
+ for i, _ in enumerate(self.optimizer.param_groups):
+ for lp in self.bit16_groups[i]:
+ if lp._hp_mapping is not None:
+ # print(f"Loading {self.param_names[lp]} {tp_rank=} {tp_world_size=}")
+ lp.load_hp_checkpoint_state(os.path.join(checkpoint_dir, self.param_names[lp]), tp_rank,
+ tp_world_size)
+
+ def _load_global_state(self, sd):
+ self.loss_scaler = sd.get(LOSS_SCALER, self.loss_scaler)
+ self.dynamic_loss_scale = sd.get('dynamic_loss_scale', self.dynamic_loss_scale)
+ self.overflow = sd.get('overflow', self.overflow)
+ self.clip_grad = sd.get(CLIP_GRAD, self.clip_grad)
+
+ ckpt_version = sd.get(DS_VERSION, False)
+ assert ckpt_version, f"Empty ds_version in checkpoint, not clear how to proceed"
+ ckpt_version = pkg_version.parse(ckpt_version)
+
+ # zero stage 1 mode
+ if not self.partition_gradients:
+ required_version = pkg_version.parse("0.3.17")
+ error_str = f"ZeRO stage 1 changed in {required_version} and is not backwards compatible " \
+ "with older stage 1 checkpoints. If you'd like to load an old ZeRO-1 checkpoint " \
+ "please use an older version of DeepSpeed (<= 0.5.8) and set 'legacy_stage1': true in your zero config json."
+ assert required_version <= ckpt_version, f"Old version: {ckpt_version} {error_str}"
+
+ def _load_legacy_checkpoint(self, state_dict_list, load_optimizer_states=True, load_from_fp32_weights=False):
+ r"""Loading ZeRO checkpoint
+
+ Arguments:
+ state_dict_list: List of all saved ZeRO checkpoints, one for each saved partition.
+ Note that the number of saved partitions may differ from number of loading partitions to support
+ changing GPU count, specifically DP world size, between saving and loading checkpoints.
+ load_optimizer_states: Boolean indicating whether or not to load base optimizer states
+ load_from_fp32_weights: Boolean indicating whether to initialize fp32 master weights from fp32
+ copies in checkpoints (no precision loss) or from model's fp16 copies (with precision loss).
+ """
+ """
+ Loads a state_dict created by an earlier call to state_dict().
+ If ``fp16_optimizer_instance`` was constructed from some ``init_optimizer``,
+ whose parameters in turn came from ``model``, it is expected that the user
+ will call ``model.load_state_dict()`` before
+ ``fp16_optimizer_instance.load_state_dict()`` is called.
+ Example::
+ model = torch.nn.Linear(D_in, D_out).to(get_accelerator().device_name()).half()
+ optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
+ optimizer = FP16_Optimizer(optimizer, static_loss_scale = 128.0)
+ ...
+ checkpoint = torch.load("saved.pth")
+ model.load_state_dict(checkpoint['model'])
+ optimizer.load_state_dict(checkpoint['optimizer'])
+ """
+
+ # I think it should actually be ok to reload the optimizer before the model.
+ dp_rank = dist.get_rank(group=self.zp_process_group)
+ current_rank_sd = state_dict_list[dp_rank]
+ self._load_global_state(current_rank_sd)
+
+ ckpt_is_rigid = isinstance(current_rank_sd[BASE_OPTIMIZER_STATE], dict)
+
+ # padding is always at the last rank/partition
+ # if DP=1024 and param-group elems=16 -> padding will be 1024-16 across all but one rank
+ # scenario-1 (shrink): saving w. 4 gpus -> loading w. 2 gpus
+ # scenario-2 (expand): saving w. 2 gpus -> loading w. 4 gpus
+ # if load_optimizer_states:
+ # if new_dp_size:
+ # self.strip_padding()
+ # self.add_padding_w_new_dp_size()
+ # self.optimizer.load_state_dict(current_rank_sd[BASE_OPTIMIZER_STATE])
+
+ if load_optimizer_states:
+ if ckpt_is_rigid:
+ # loading rigid ckpt into either rigid or elastic exec
+ self.optimizer.load_state_dict(current_rank_sd[BASE_OPTIMIZER_STATE])
+ else:
+ if self.elastic_checkpoint:
+ # loading elastic into elastic exec
+ self._restore_elastic_base_optimizer_state(state_dict_list)
+ else:
+ # loading an elastic checkpoint into rigid exec
+ self._restore_base_optimizer_state(current_rank_sd[BASE_OPTIMIZER_STATE])
+
+ # At this point, the optimizer's references to the model's fp32 parameters are up to date.
+ # The optimizer's hyperparameters and internal buffers are also up to date.
+ # However, the fp32 master copies of the model's fp16 params stored by the optimizer are still
+ # out of date. There are two options.
+ # 1: Refresh the master params from the model's fp16 params.
+ # This requires less storage but incurs precision loss.
+ # 2: Save and restore the fp32 master copies separately.
+ # We choose option 1 if changing DP degree and option 2 otherwise.
+ #
+ # Pytorch Optimizer.load_state_dict casts saved buffers (e.g. momentum) to the type and device
+ # of their associated parameters, because it's possible those buffers might not exist yet in
+ # the current optimizer instance. In our case, as long as the current FP16_Optimizer has been
+ # constructed in the same way as the one whose state_dict we are loading, the same master params
+ # are guaranteed to exist, so we can just copy_() from the saved master params.
+
+ if load_from_fp32_weights:
+ # option 2 from above
+ if self.elastic_checkpoint and not ckpt_is_rigid:
+ self._restore_from_elastic_fp32_weights(state_dict_list)
+ else:
+ # For non-elastic checkpoint, simply copying from saved weights of current rank is sufficient.
+ for current, saved in zip(self.single_partition_of_fp32_groups,
+ current_rank_sd[SINGLE_PARTITION_OF_FP32_GROUPS]):
+ src_tensor = _get_padded_tensor(saved, current.numel())
+ current.data.copy_(src_tensor.data)
+ else:
+ # option 1 from above
+ self._restore_from_bit16_weights()
+
+ if load_optimizer_states:
+ self._link_all_hp_params()
+
+
+def _handle_overflow(cpu_sum, x, i):
+ import math
+ rank = dist.get_rank()
+ if rank == 0:
+ t_i = -1
+ for v_i, v in enumerate(x.data.contiguous().view(-1)):
+ if not math.isfinite(float(v)):
+ t_i = v_i
+ break
+ logger.info(f"rank {rank} detected overflow {cpu_sum} in tensor {i}:{t_i} shape {x.shape}")
+
+
+def estimate_zero2_model_states_mem_needs(total_params,
+ num_gpus_per_node=1,
+ num_nodes=1,
+ cpu_offload=True,
+ additional_buffer_factor=1.5):
+ total_gpus = num_nodes * num_gpus_per_node
+
+ if cpu_offload:
+ gpu_mem = 2 * total_params
+ cpu_mem = total_params * max(4 * total_gpus, 16) * additional_buffer_factor
+ else:
+ gpu_mem = 4 * total_params + int(16 * total_params / total_gpus)
+ cpu_mem = total_params * 4 * num_gpus_per_node * additional_buffer_factor
+
+ return int(cpu_mem), int(gpu_mem)
+
+
+def model_to_params(model):
+ # shared params calculated only once
+ total_params = sum(dict((p.data_ptr(), p.numel()) for p in model.parameters()).values())
+ return total_params
+
+
+def estimate_zero2_model_states_mem_needs_all_live(model,
+ num_gpus_per_node=1,
+ num_nodes=1,
+ additional_buffer_factor=1.5):
+ """
+ Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients
+ for a given ``model`` and hardware setup.
+
+ If you have an actual model object, use this function and everything will be derived
+ automatically.
+
+ If it's a hypothetical model, use ``estimate_zero2_model_states_mem_needs_all_cold`` where you have to pass
+ the ``total_params`` explicitly.
+
+ Args:
+ - ``model``: ``nn.Module`` object
+ - ``num_gpus_per_node``: how many gpus per node (defaults to 1)
+ - ``num_nodes``: how many nodes (defaults to 1),
+ - ``additional_buffer_factor``: estimation factor (defaults to 1.5):
+
+ """
+
+ total_params = model_to_params(model)
+
+ estimate_zero2_model_states_mem_needs_all_cold(total_params=total_params,
+ num_gpus_per_node=num_gpus_per_node,
+ num_nodes=num_nodes,
+ additional_buffer_factor=additional_buffer_factor)
+
+
+def estimate_zero2_model_states_mem_needs_all_cold(total_params,
+ num_gpus_per_node=1,
+ num_nodes=1,
+ additional_buffer_factor=1.5):
+ """
+ Print out estimates on memory usage requirements for ZeRO 2 params, optim states and gradients
+ for a given ``model`` and hardware setup.
+
+ If it's a hypothetical model, use this function where you have to pass
+ the ``total_params`` and ``largest_layer_params`` explicitly.
+
+ If you have an actual model object, use ``estimate_zero2_model_states_mem_needs_all_live`` and everything
+ will be derived automatically.
+
+ Args:
+ - ``total_params``: total model params
+ - ``num_gpus_per_node``: how many gpus per node (defaults to 1)
+ - ``num_nodes``: how many nodes (defaults to 1),
+ - ``additional_buffer_factor``: estimation factor (defaults to 1.5):
+
+ """
+
+ def format_options(cpu_offload):
+ enabled = []
+ device = f'{OffloadDeviceEnum.cpu:4}' if cpu_offload else "none"
+ enabled.append(f"offload_optimizer={device}")
+ return ", ".join(enabled)
+
+ nodes_str = "nodes" if num_nodes > 1 else "node"
+ gpus_str = "GPUs" if num_gpus_per_node > 1 else "GPU"
+ print("Estimated memory needed for params, optim states and gradients for a:\n"
+ f"HW: Setup with {num_nodes} {nodes_str}, {num_gpus_per_node} {gpus_str} per node.\n"
+ f"SW: Model with {int(total_params / 1e6)}M total params.")
+ print(" per CPU | per GPU | Options")
+ for cpu_offload in [True, False]:
+ cpu_mem, gpu_mem = estimate_zero2_model_states_mem_needs(total_params=total_params,
+ num_gpus_per_node=num_gpus_per_node,
+ num_nodes=num_nodes,
+ cpu_offload=cpu_offload,
+ additional_buffer_factor=additional_buffer_factor)
+
+ options_str = format_options(cpu_offload=cpu_offload)
+ print(f" {cpu_mem / 2 ** 30:7.2f}GB | {gpu_mem / 2 ** 30:6.2f}GB | {options_str}")
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/utils.py b/One-to-All-Animation/video-generation/opensora/adaptor/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c32ff6efcc21cc1881531ee5cf2e57d30a3c9b32
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/utils.py
@@ -0,0 +1,1042 @@
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: Apache-2.0
+
+# DeepSpeed Team
+"""
+Copyright NVIDIA/Megatron
+
+Helper functions and classes from multiple sources.
+"""
+
+from collections.abc import Iterable
+from deepspeed.moe.utils import is_moe_param
+import os
+import psutil
+import gc
+from math import sqrt
+from packaging import version as pkg_version
+
+import torch
+from deepspeed import comm as dist
+
+try:
+ from torch._six import inf
+except ModuleNotFoundError:
+ from torch import inf
+
+from deepspeed.utils import groups, logger
+from deepspeed.runtime.constants import PIPE_REPLICATED
+from numpy import prod
+from deepspeed.accelerator import get_accelerator
+
+from deepspeed.module_inject.policy import transpose
+from torch.nn import functional as F
+
+torch_memory_reserved = get_accelerator().memory_reserved
+torch_max_memory_reserved = get_accelerator().max_memory_reserved
+
+
+class DummyOptim():
+ """
+ Dummy optimizer presents model parameters as a param group, this is
+ primarily used to allow ZeRO-3 without an optimizer
+ """
+
+ def __init__(self, params):
+ self.param_groups = []
+ self.param_groups.append({'params': params})
+
+
+graph_cache = {}
+
+
+def graph_process(replay_first_step, func, *args, **kwargs):
+ # `func` should only contain operations on the GPU
+ # Please ensure that the memory address of the data required by 'func' remains constant
+ if func.__name__ not in graph_cache:
+ cuda_stream = get_accelerator().Stream()
+ cuda_stream.wait_stream(get_accelerator().current_stream())
+ with get_accelerator().stream(cuda_stream):
+ func(*args, **kwargs)
+ get_accelerator().current_stream().wait_stream(cuda_stream)
+ graph_cache[func.__name__] = get_accelerator().create_graph()
+ with get_accelerator().capture_to_graph(graph_cache[func.__name__]):
+ func(*args, **kwargs)
+ if replay_first_step:
+ get_accelerator().replay_graph(graph_cache[func.__name__])
+ else:
+ get_accelerator().replay_graph(graph_cache[func.__name__])
+
+
+def noop_decorator(func):
+ return func
+
+
+class noop_context(object):
+
+ def __init__(self):
+ pass
+
+ def __enter__(self):
+ pass
+
+ def __exit__(self, exc_type, exc_val, exc_tb):
+ pass
+
+
+def ensure_directory_exists(filename):
+ """Create the directory path to ``filename`` if it does not already exist.
+
+ Args:
+ filename (str): A file path.
+ """
+ dirname = os.path.dirname(filename)
+ os.makedirs(dirname, exist_ok=True)
+
+
+def set_random_seed(seed):
+ """Set the random seed for common PRNGs used during training: random, numpy, and torch.
+
+ Args:
+ seed (int): the seed to use
+ """
+ import numpy
+ import random
+ random.seed(seed)
+ numpy.random.seed(seed)
+ torch.manual_seed(seed)
+
+
+def is_model_parallel_parameter(p) -> bool:
+ if hasattr(p, 'model_parallel') and p.model_parallel:
+ return True
+
+ if hasattr(p, 'tensor_model_parallel') and p.tensor_model_parallel:
+ return True
+
+ return False
+
+
+def bwc_tensor_model_parallel_rank(mpu=None):
+ """Backwards-compatible way of querying the tensor model parallel rank from
+ an ``mpu`` object.
+
+ *Tensor* model parallelism means that tensors are physically split across
+ processes. This contrasts with *pipeline* model parallelism, in which the
+ layers are partitioned but tensors left intact.
+
+ The API for tensor model parallelism has changed across versions and this
+ helper provides a best-effort implementation across versions of ``mpu``
+ objects. The preferred mechanism is
+ ``mpu.get_tensor_model_parallel_rank()``.
+
+ This should "just work" with both Megatron-LM and DeepSpeed's pipeline
+ parallelism.
+
+ Args:
+ mpu (model parallel unit, optional): The tensor model parallel rank.
+ If ``mpu=None``, returns 0. Defaults to ``None``.
+
+ Returns:
+ int: the rank
+ """
+ if mpu is None:
+ # No model parallelism in easy :)
+ return 0
+
+ if hasattr(mpu, 'get_tensor_model_parallel_rank'):
+ # New Megatron and DeepSpeed convention (post pipeline-parallelism release)
+ return mpu.get_tensor_model_parallel_rank()
+ elif hasattr(mpu, 'get_slice_parallel_rank'):
+ # Some DeepSpeed + pipeline parallelism versions
+ return mpu.get_slice_parallel_rank()
+ else:
+ # Deprecated Megatron and DeepSpeed convention
+ return mpu.get_model_parallel_rank()
+
+
+def copy_to_device(item, device, criterion_func):
+ """
+ Return a copy of tensor on specified device.
+ Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts.
+ Parameters:
+ item: tensor to copy or (possibly nested) container of tensors to copy.
+ device: target device
+ criterion_func: Function to restrict copy operation to items meet criterion
+
+ Returns:
+ None
+ """
+ if criterion_func(item):
+ return item.to(device)
+ elif isinstance(item, list):
+ return [copy_to_device(v, device, criterion_func) for v in item]
+ elif isinstance(item, tuple):
+ return tuple([copy_to_device(v, device, criterion_func) for v in item])
+ elif isinstance(item, dict):
+ return {k: copy_to_device(v, device, criterion_func) for k, v in item.items()}
+ else:
+ return item
+
+
+def move_to_device(item, device, criterion_func):
+ """
+ Move tensor on to specified device by changing the storage.
+ Works on individual tensors, and tensors contained/nested in lists, tuples, and dicts.
+ Parameters:
+ item: tensor to move or (possibly nested) container of tensors to move.
+ device: target device
+ criterion_func: Function to restrict move operation to items meet criterion
+
+ Returns:
+ None
+ """
+ if criterion_func(item):
+ device_copy = item.to(device)
+ item.data = device_copy.data
+ return item
+ elif isinstance(item, list):
+ return [move_to_device(v, device, criterion_func) for v in item]
+ elif isinstance(item, tuple):
+ return tuple([move_to_device(v, device, criterion_func) for v in item])
+ elif isinstance(item, dict):
+ return {k: move_to_device(v, device, criterion_func) for k, v in item.items()}
+ else:
+ return item
+
+
+class CheckOverflow(object):
+ '''Checks for overflow in gradient across parallel process'''
+
+ def __init__(self, param_groups=None, mpu=None, zero_reduce_scatter=False, deepspeed=None):
+ self.mpu = mpu
+ self.params = [] if param_groups else None
+ self.zero_reduce_scatter = zero_reduce_scatter
+ self.deepspeed = deepspeed
+ self.has_moe_params = False
+ if param_groups:
+ for group in param_groups:
+ for param in group:
+ self.params.append(param)
+ if is_moe_param(param):
+ self.has_moe_params = True
+
+ def check_using_norm(self, norm_group, reduce_overflow=True):
+ # TODO: I don't think reduce_overflow is needed if mpu is None
+ overflow = -1 in norm_group
+ overflow_gpu = get_accelerator().FloatTensor([overflow])
+ if self.has_moe_params:
+ # In this case, we need to do an all_reduce across
+ # the expert_parallel_group, so that if there was
+ # an overflow due to expert weights, we detect it
+
+ # Only need to check groups.get_largest_expert_parallel_group()
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=groups._get_max_expert_parallel_group())
+ if self.mpu is not None:
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.mpu.get_model_parallel_group())
+ elif reduce_overflow:
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX)
+ dist.barrier()
+ overflow = overflow_gpu[0].item()
+ return bool(overflow)
+
+ def check(self, param_groups=None):
+ params = []
+ has_moe_params = False
+ if param_groups is None:
+ params = self.params
+ has_moe_params = self.has_moe_params
+ else:
+ assert param_groups is not None, \
+ "self.params and param_groups both cannot be none"
+
+ for group in param_groups:
+ for param in group:
+ params.append(param)
+ if is_moe_param(param):
+ has_moe_params = True
+
+ return self.has_overflow(params, has_moe_params=has_moe_params)
+
+ # `params` is a list / generator of torch.Variable
+ def has_overflow_serial(self, params):
+ for i, p in enumerate(params):
+ if p.grad is not None and self._has_inf_or_nan(p.grad.data, i):
+ return True
+ return False
+
+ def has_overflow(self, params, has_moe_params=None):
+ if has_moe_params is None:
+ has_moe_params = self.has_moe_params
+ overflow = self.has_overflow_serial(params)
+ # Since each model parallel GPU carries only part of the model,
+ # make sure overflow flag is synced across all the model parallel GPUs
+ overflow_gpu = get_accelerator().ByteTensor([overflow])
+ # deepspeed.comm.all_reduce(overflow_gpu,
+ # op=deepspeed.comm.ReduceOp.MAX,
+ # group=mpu.get_model_parallel_group())
+ if has_moe_params:
+ # All reduce this across expert_parallel_group, so that if an expert
+ # overflows, we detect it here
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=groups._get_max_expert_parallel_group())
+ if self.zero_reduce_scatter:
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=dist.get_world_group())
+ elif self.mpu is not None:
+ if self.deepspeed is not None:
+ using_pipeline = hasattr(self.deepspeed, 'pipeline_enable_backward_allreduce')
+ if (using_pipeline and self.deepspeed.pipeline_enable_backward_allreduce is False) or (
+ not using_pipeline and self.deepspeed.enable_backward_allreduce is False):
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.mpu.get_data_parallel_group())
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=self.mpu.get_model_parallel_group())
+ elif self.deepspeed is not None and self.deepspeed.enable_backward_allreduce is False:
+ dist.all_reduce(overflow_gpu, op=dist.ReduceOp.MAX, group=dist.get_world_group())
+
+ overflow = overflow_gpu[0].item()
+ return bool(overflow)
+
+ # `x` is a torch.Tensor
+ @staticmethod
+ def _has_inf_or_nan(x, i):
+ try:
+ # if x is half, the .float() incurs an additional deep copy, but it's necessary if
+ # Pytorch's .sum() creates a one-element tensor of the same type as x
+ # (which is true for some recent version of pytorch).
+ cpu_sum = float(x.float().sum())
+ # More efficient version that can be used if .sum() returns a Python scalar
+ # cpu_sum = float(x.sum())
+ except RuntimeError as instance:
+ # We want to check if inst is actually an overflow exception.
+ # RuntimeError could come from a different error.
+ # If so, we still want the exception to propagate.
+ if "value cannot be converted" not in instance.args[0]:
+ raise
+ return True
+ else:
+ if cpu_sum == float('inf') or cpu_sum == -float('inf') or cpu_sum != cpu_sum:
+ return True
+ return False
+
+
+def _handle_overflow(cpu_sum, x, i):
+ import math
+ rank = dist.get_rank()
+ if rank == 0:
+ t_i = -1
+ for v_i, v in enumerate(x.data.contiguous().view(-1)):
+ if not math.isfinite(float(v)):
+ t_i = v_i
+ break
+ logger.info(f"rank {rank} detected overflow {cpu_sum} in tensor {i}:{t_i} shape {x.shape}")
+
+
+def get_global_norm(norm_list):
+ """ Compute total from a list of norms
+ """
+ total_norm = 0.0
+ for norm in norm_list:
+ total_norm += norm**2.0
+ # logger.info(f'norm_list = {norm_list} global = {sqrt(total_norm)}')
+ return sqrt(total_norm)
+
+
+def clip_grad_norm_(parameters, max_norm, norm_type=2, mpu=None):
+ """Clips gradient norm of an iterable of parameters.
+
+ This has been adapted from Nvidia megatron. We add norm averaging
+ to consider MoE params when calculating norm as they will result
+ in different norms across different ranks.
+
+ This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
+ added functionality to handle model parallel parameters. Note that
+ the gradients are modified in place.
+
+ Arguments:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ max_norm (float or int): max norm of the gradients
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+
+ Returns:
+ Total norm of the parameters (viewed as a single vector).
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
+ max_norm = float(max_norm)
+ norm_type = float(norm_type)
+ if norm_type == inf:
+ total_norm = max(p.grad.data.abs().max() for p in parameters)
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ # Take max across all GPUs.
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()
+ else:
+ total_norm = 0
+ for p in parameters:
+ if mpu is not None:
+ if (mpu.get_model_parallel_rank() == 0) or is_model_parallel_parameter(p):
+ param_norm = p.grad.data.norm(norm_type)
+ total_norm += param_norm.item()**norm_type
+ else:
+ param_norm = p.grad.data.float().norm(norm_type)
+ total_norm += param_norm.item()**norm_type
+
+ # Sum across all model parallel GPUs.
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()**(1. / norm_type)
+
+ # Need to average total_norm across different GPUs due to the presence of moe params
+ pg = groups._get_data_parallel_group()
+ scaled_norm = total_norm * 1.0 / float(dist.get_world_size(group=pg))
+
+ scaled_norm_tensor = get_accelerator().FloatTensor([float(scaled_norm)])
+ dist.all_reduce(scaled_norm_tensor, group=pg)
+ total_norm = scaled_norm_tensor.item()
+
+ clip_coef = max_norm / (total_norm + 1e-6)
+ if clip_coef < 1:
+ for p in parameters:
+ p.grad.data.mul_(clip_coef)
+ return total_norm
+
+
+def get_grad_norm(parameters, norm_type=2, mpu=None):
+ """Get grad norm of an iterable of parameters.
+
+ This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
+ added functionality to handle model parallel parameters. Note that
+ the gradients are modified in place. Taken from Nvidia Megatron.
+
+ Arguments:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+
+ Returns:
+ Total norm of the parameters (viewed as a single vector).
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
+
+ norm_type = float(norm_type)
+ if norm_type == inf:
+ total_norm = max(p.grad.data.abs().max() for p in parameters)
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ # Take max across all GPUs.
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()
+ else:
+ total_norm = 0.
+ tensor_mp_rank = bwc_tensor_model_parallel_rank(mpu=mpu)
+ for p in parameters:
+ # Pipeline parallelism may replicate parameters. Avoid multi-counting.
+ if hasattr(p, PIPE_REPLICATED) and p.ds_pipe_replicated:
+ continue
+
+ # Filter to avoid over-counting replicated tensors from tensor
+ # model parallelism
+ if (tensor_mp_rank > 0) and not is_model_parallel_parameter(p):
+ continue
+
+ param_norm = p.grad.data.float().norm(norm_type)
+ total_norm += param_norm.item()**norm_type
+
+ # Sum across all model parallel GPUs.
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()**(1. / norm_type)
+
+ if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm:
+ total_norm = -1
+
+ return total_norm
+
+
+def get_grad_zeros(parameters, mpu=None):
+ """Compute the number of grads with zero values.
+
+ This is adapted from get_grad_norm
+
+ Arguments:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+
+ Returns:
+ Total number of params with zero values (viewed as a single vector).
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ parameters = list(filter(lambda p: p.grad is not None, parameters))
+
+ total_zeros = 0.
+ tensor_mp_rank = bwc_tensor_model_parallel_rank(mpu=mpu)
+ for p in parameters:
+ # Pipeline parallelism may replicate parameters. Avoid multi-counting.
+ if hasattr(p, PIPE_REPLICATED) and p.ds_pipe_replicated:
+ continue
+
+ # Filter to avoid over-counting replicated tensors from tensor
+ # model parallelism
+ if (tensor_mp_rank > 0) and not is_model_parallel_parameter(p):
+ continue
+
+ count_zeros = p.grad.numel() - torch.count_nonzero(p.grad)
+ total_zeros += count_zeros.item()
+
+ # Sum across all model parallel GPUs.
+ total_zeros_cuda = get_accelerator().FloatTensor([float(total_zeros)])
+ if mpu is not None:
+ dist.all_reduce(total_zeros_cuda, op=dist.ReduceOp.SUM, group=mpu.get_model_parallel_group())
+ total_zeros = total_zeros_cuda[0].item()
+
+ return total_zeros
+
+
+def get_weight_norm(parameters, norm_type=2, mpu=None):
+ """Get norm of an iterable of parameters.
+
+ This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
+ added functionality to handle model parallel parameters. Note that
+ the gradients are modified in place. Taken from Nvidia Megatron.
+
+ Arguments:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+
+ Returns:
+ Total norm of the parameters (viewed as a single vector).
+ -1 if the norm value is NaN or Inf.
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+
+ norm_type = float(norm_type)
+ if norm_type == inf:
+ total_norm = max(p.data.abs().max() for p in parameters)
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ # Take max across all GPUs.
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()
+ else:
+ total_norm = 0.
+ tensor_mp_rank = bwc_tensor_model_parallel_rank(mpu=mpu)
+ for p in parameters:
+ # Pipeline parallelism may replicate parameters. Avoid multi-counting.
+ if hasattr(p, PIPE_REPLICATED) and p.ds_pipe_replicated:
+ continue
+
+ # Filter to avoid over-counting replicated tensors from tensor
+ # model parallelism
+ if (tensor_mp_rank > 0) and not is_model_parallel_parameter(p):
+ continue
+
+ param_norm = p.data.float().norm(norm_type)
+ total_norm += param_norm**norm_type
+
+ # Sum across all model parallel GPUs.
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()**(1. / norm_type)
+
+ if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm:
+ total_norm = -1
+
+ return total_norm
+
+
+def prefix_sum_inc(weights):
+ """ Compute an inclusive prefix sum.
+
+ Example:
+ >>> prefix_sum_inc([3,4,5])
+ [3, 7, 12]
+ """
+ weights_ = [w for w in weights]
+ for x in range(1, len(weights_)):
+ weights_[x] += weights_[x - 1]
+ return weights_
+
+
+def partition_uniform(num_items, num_parts):
+ import numpy
+ parts = [0] * (num_parts + 1)
+ # First check for the trivial edge case
+ if num_items <= num_parts:
+ for p in range(num_parts + 1):
+ parts[p] = min(p, num_items)
+ return parts
+
+ chunksize = num_items // num_parts
+ residual = num_items - (chunksize * num_parts)
+
+ parts = numpy.arange(0, (num_parts + 1) * chunksize, chunksize)
+
+ for i in range(residual):
+ parts[i + 1:] += 1
+ parts = parts.tolist()
+
+ return parts
+
+
+def partition_balanced(weights, num_parts):
+ """
+ use dynamic programming solve `The Linear Partition Problem`.
+ see https://www8.cs.umu.se/kurser/TDBAfl/VT06/algorithms/BOOK/BOOK2/NODE45.HTM
+ """
+ import numpy as np
+ n = len(weights)
+ m = num_parts
+
+ if n <= m:
+ return partition_uniform(n, m)
+
+ dp_max = np.full((n + 1, m + 1), np.inf)
+ dp_min = np.full((n + 1, m + 1), np.inf)
+ dp_cost = np.full((n + 1, m + 1), np.inf)
+ position = np.zeros((n + 1, m + 1), dtype=int)
+ prefix_sum = np.zeros((n + 1))
+ prefix_sum[1:] = np.cumsum(weights)
+
+ dp_max[0, 0] = 0
+ dp_cost[0, 0] = 0
+ for i in range(1, n + 1):
+ for j in range(1, min(i, m) + 1):
+ for k in range(i):
+ max_sum = max(dp_max[k, j - 1], prefix_sum[i] - prefix_sum[k])
+ min_sum = min(dp_min[k, j - 1], prefix_sum[i] - prefix_sum[k])
+ cost = max_sum - min_sum
+ if dp_cost[i, j] >= cost:
+ dp_cost[i, j] = cost
+ dp_max[i, j] = max_sum
+ dp_min[i, j] = min_sum
+ position[i, j] = k
+
+ parts = [n]
+ for i in reversed(range(1, m + 1)):
+ parts.append(position[parts[-1], i])
+ parts.reverse()
+
+ return parts
+
+
+class PartitionedTensor:
+
+ def __init__(self, tensor, group, partition_meta=None):
+ super().__init__()
+
+ self.group = group
+ self.num_parts = dist.get_world_size(group=self.group)
+ self.rank = dist.get_rank(group=self.group)
+ self.orig_size = list(tensor.size())
+ self.orig_device = tensor.device
+ self.local_data, self.partition = self._partition_tensor(tensor)
+ self.even_split = tensor.numel() % self.num_parts == 0
+
+ @classmethod
+ def from_meta(cls, meta, local_part, group, device=get_accelerator().device_name()):
+ assert meta.dtype == torch.long
+ dummy = torch.ones(dist.get_world_size(group=group))
+ part_obj = cls(tensor=dummy, group=group)
+
+ meta = meta.tolist()
+
+ # [N, list0, ..., listN-1]
+ part_obj.orig_size = meta[1:(1 + meta[0])]
+ meta = meta[1 + meta[0]:]
+
+ part_obj.orig_device = device
+ part_obj.local_data = local_part.detach()
+
+ part_obj.group = group
+
+ # Partition is encoded like the rowptr of a CSR matrix:
+ # [num_parts, rank, 0, part_1, ..., part_num_parts]
+ # TODO: support shuffle between different partition granularities
+ assert part_obj.num_parts == meta[0]
+ assert part_obj.rank == meta[1]
+ part_obj.partition = meta[2:] # length num_parts+1
+
+ return part_obj
+
+ def _partition_tensor(self, tensor):
+ partition = partition_uniform(num_items=tensor.numel(), num_parts=self.num_parts)
+ start = partition[self.rank]
+ length = partition[self.rank + 1] - start
+ tensor_part = tensor.detach().contiguous().view(-1).narrow(0, start=start, length=length).clone()
+
+ return tensor_part, partition
+
+ def full(self, device=None):
+ if device is None:
+ device = self.orig_device
+
+ # Allocate the full tensor as a flat buffer.
+ full_numel = prod(self.full_size())
+ flat_tensor = torch.zeros([full_numel], dtype=self.local_data.dtype, device=device)
+ if self.even_split:
+ # Collect the full tensor
+ dist.all_gather_into_tensor(flat_tensor, self.local_data, group=self.group)
+ else:
+ for part_id in range(self.num_parts):
+ part_size = self.partition[part_id + 1] - self.partition[part_id]
+ buf = flat_tensor.narrow(0, start=self.partition[part_id], length=part_size)
+ if part_id == self.rank:
+ buf.copy_(self.local_data)
+ dist.broadcast(buf, part_id, self.group)
+ return flat_tensor.view(self.full_size()).clone().detach()
+
+ def to_meta(self):
+ """Returns a torch.LongTensor that encodes partitioning information.
+
+ Can be used along with ``data()`` to serialize a ``PartitionedTensor`` for
+ communication.
+
+ Returns:
+ torch.LongTensor: a tensor encoding the meta-information for the partitioning
+ """
+ meta = []
+ meta.append(len(self.orig_size))
+ meta += list(self.orig_size)
+ meta.append(self.num_parts)
+ meta.append(self.rank)
+ meta += self.partition
+ return torch.LongTensor(data=meta).to(self.orig_device)
+
+ def data(self):
+ return self.local_data
+
+ def local_size(self):
+ return self.local_data.size()
+
+ def full_size(self):
+ return self.orig_size
+
+
+mem_alloced = 0
+mem_cached = 0
+
+
+def memory_status(msg, print_rank=-1, reset_max=False):
+ global mem_alloced, mem_cached
+
+ rank = dist.get_rank()
+ if print_rank != -1 and rank != print_rank:
+ return
+
+ get_accelerator().synchronize()
+
+ if reset_max:
+ get_accelerator().reset_max_memory_cached()
+ get_accelerator().reset_max_memory_allocated()
+
+ new_alloced = get_accelerator().memory_allocated()
+ new_cached = get_accelerator().memory_cached()
+
+ delta_alloced = new_alloced - mem_alloced
+ delta_cached = new_cached - mem_cached
+
+ mem_cached = new_cached
+ mem_alloced = new_alloced
+
+ max_alloced = get_accelerator().max_memory_allocated()
+ max_cached = get_accelerator().max_memory_cached()
+
+ # convert to GB for printing
+ new_alloced /= 1024**3
+ new_cached /= 1024**3
+ delta_alloced /= 1024**3
+ delta_cached /= 1024**3
+ max_alloced /= 1024**3
+ max_cached /= 1024**3
+
+ print(
+ f'RANK={rank} MEMSTATS', msg, f'device={get_accelerator().current_device_name()} '
+ f'current alloc={new_alloced:0.4f}GB (delta={delta_alloced:0.4f}GB max={max_alloced:0.4f}GB) '
+ f'current cache={new_cached:0.4f}GB (delta={delta_cached:0.4f}GB max={max_cached:0.4f}GB)')
+
+
+def get_ma_status():
+ if dist.is_initialized() and not dist.get_rank() == 0:
+ return 0
+ return get_accelerator().memory_allocated()
+
+
+def empty_cache():
+ get_accelerator().empty_cache()
+ get_accelerator().reset_peak_memory_stats()
+
+
+def see_memory_usage(message, force=False):
+ if not force:
+ return
+ if dist.is_initialized() and not dist.get_rank() == 0:
+ return
+
+ # python doesn't do real-time garbage collection so do it explicitly to get the correct RAM reports
+ gc.collect()
+
+ # Print message except when distributed but not rank 0
+ logger.info(message)
+ logger.info(f"MA {round(get_accelerator().memory_allocated() / (1024 * 1024 * 1024),2 )} GB \
+ Max_MA {round(get_accelerator().max_memory_allocated() / (1024 * 1024 * 1024),2)} GB \
+ CA {round(torch_memory_reserved() / (1024 * 1024 * 1024),2)} GB \
+ Max_CA {round(torch_max_memory_reserved() / (1024 * 1024 * 1024))} GB ")
+
+ vm_stats = psutil.virtual_memory()
+ used_GB = round(((vm_stats.total - vm_stats.available) / (1024**3)), 2)
+ logger.info(f'CPU Virtual Memory: used = {used_GB} GB, percent = {vm_stats.percent}%')
+
+ # get the peak memory to report correct data, so reset the counter for the next call
+ get_accelerator().reset_peak_memory_stats()
+
+
+def call_to_str(base, *args, **kwargs):
+ """Construct a string representation of a call.
+
+ Args:
+ base (str): name of the call
+ args (tuple, optional): args to ``base``
+ kwargs (dict, optional): kwargs supplied to ``base``
+
+ Returns:
+ str: A string representation of base(*args, **kwargs)
+ """
+ name = f'{base}('
+ if args:
+ name += ', '.join(repr(arg) for arg in args)
+ if kwargs:
+ name += ', '
+ if kwargs:
+ name += ', '.join(f'{key}={repr(arg)}' for key, arg in kwargs.items())
+ name += ')'
+ return name
+
+
+def get_only_unique_item(items):
+ item_set = set(items)
+ if len(item_set) != 1:
+ raise RuntimeError(f"expected there to be only one unique element in {items}")
+ unique_item, = item_set
+
+ return unique_item
+
+
+def clip_gradients(parameters, max_norm=1.0, global_grad_norm=None, mpu=None, eps=1e-6):
+ """Clip the gradient of a list of parameters.
+ Args:
+ parameters: List of parameters whose .grad will be clipped.
+ global_grad_norm (float, optional): Precomputed gradient norm. Defaults to None.
+ mpu (optional): model parallelism unit. Defaults to None.
+ eps (float, optional): epsilon value added to grad norm. Defaults to 1e-6
+ Returns:
+ float: the global gradient norm
+ """
+ if global_grad_norm is None:
+ global_grad_norm = get_grad_norm(parameters, mpu=mpu)
+ clip_coef = max_norm / (global_grad_norm + eps)
+ if clip_coef < 1:
+ for p in parameters:
+ p.grad.detach().mul_(clip_coef)
+ return global_grad_norm
+
+
+def get_global_norm_of_tensors(input_tensors, norm_type=2, mpu=None, use_graph=False):
+ """Get norm of an iterable of tensors.
+
+ This is adapted from torch.nn.utils.clip_grad.clip_grad_norm_ and
+ added functionality to handle model parallel parameters. Taken from Nvidia Megatron.
+
+ Arguments:
+ input_tensors (Iterable[Tensor]): an iterable of Tensors will have norm computed
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+
+ Returns:
+ Total norm of the tensors (viewed as a single vector).
+ """
+ assert isinstance(input_tensors, Iterable), f'expected Iterable type not {type(input_tensors)}'
+ assert all([torch.is_tensor(t) for t in input_tensors]), f'expected list of only tensors'
+
+ norm_type = float(norm_type)
+ if norm_type == inf:
+ total_norm = max(t.data.abs().max() for t in input_tensors)
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)])
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.MAX, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()
+ else:
+ if use_graph:
+ if 'norm_tensors_compute_buffer' not in graph_cache:
+ graph_cache['norm_tensors_compute_buffer'] = [t.data.float().norm(norm_type) for t in input_tensors]
+ compute_buffer = graph_cache['norm_tensors_compute_buffer']
+
+ def _norm_tensors(tensor_list, _compute_buffer, _norm_type):
+ for i, t in enumerate(tensor_list):
+ _compute_buffer[i].data.copy_(t.data.float().norm(_norm_type)**_norm_type)
+ if i != 0:
+ _compute_buffer[0].data.add_(_compute_buffer[i].data)
+
+ graph_process(False, _norm_tensors, input_tensors, compute_buffer, norm_type)
+
+ total_norm = compute_buffer[0]
+ else:
+ total_norm = sum([t.data.float().norm(norm_type).item()**norm_type for t in input_tensors])
+
+ total_norm_cuda = get_accelerator().FloatTensor([float(total_norm)]).detach()
+ if mpu is not None:
+ dist.all_reduce(total_norm_cuda, op=dist.ReduceOp.SUM, group=mpu.get_model_parallel_group())
+ total_norm = total_norm_cuda[0].item()**(1. / norm_type)
+
+ if total_norm == float('inf') or total_norm == -float('inf') or total_norm != total_norm:
+ total_norm = -1
+
+ return total_norm
+
+
+def clip_tensors_by_global_norm(input_tensors, max_norm=1.0, global_norm=None, mpu=None, eps=1e-6, use_graph=False):
+ """Clip list of tensors by global norm.
+ Args:
+ input_tensors: List of tensors to be clipped
+ global_norm (float, optional): Precomputed norm. Defaults to None.
+ mpu (optional): model parallelism unit. Defaults to None.
+ eps (float, optional): epsilon value added to grad norm. Defaults to 1e-6
+ Returns:
+ float: the global norm
+ """
+ if global_norm is None:
+ global_norm = get_global_norm_of_tensors(input_tensors, mpu=mpu, use_graph=use_graph)
+ clip_coef = max_norm / (global_norm + eps)
+ if clip_coef < 1:
+ if use_graph:
+
+ def clip_tensors(_tensor_list, _clip_coef_tensor):
+ for t in _tensor_list:
+ t.detach().mul_(_clip_coef_tensor)
+
+ if 'clip_coef_tensor' not in graph_cache:
+ # Alloc memory
+ graph_cache['clip_coef_tensor'] = torch.tensor(clip_coef,
+ dtype=torch.float32).to(get_accelerator().device_name())
+ clip_coef_tensor = graph_cache['clip_coef_tensor']
+ clip_coef_tensor.copy_(torch.tensor(clip_coef, dtype=torch.float32))
+ graph_process(False, clip_tensors, input_tensors, clip_coef_tensor)
+
+ else:
+ for t in input_tensors:
+ t.detach().mul_(clip_coef)
+ return global_norm
+
+
+def align_dense_tensors(tensor_list, alignment):
+ num_elements = sum(t.numel() for t in tensor_list)
+ remaining = num_elements % alignment
+
+ if remaining:
+ elements_to_add = alignment - remaining
+ pad_tensor = torch.zeros(elements_to_add, device=tensor_list[0].device, dtype=tensor_list[0].dtype)
+ padded_tensor_list = tensor_list + [pad_tensor]
+ else:
+ padded_tensor_list = tensor_list
+
+ return padded_tensor_list
+
+
+def all_gather_into_tensor_dp_groups(groups_flat, partitioned_param_groups, zp_process_group, dp_process_group=None):
+
+ for group_id, (group_flat, partitioned_params) in enumerate(zip(groups_flat, partitioned_param_groups)):
+ partition_id = dist.get_rank(group=zp_process_group[group_id])
+ dp_world_size = dist.get_world_size(group=dp_process_group)
+ if dp_world_size == 1:
+ # no groups share optimizer states
+ # pipeline parallel with bf16 will default call this even if dp size = 1.
+ continue
+ # print("call contiguous for all_gather_into_tensor_dp_groups")
+ dist.all_gather_into_tensor(group_flat, partitioned_params[partition_id].contiguous(), dp_process_group)
+
+
+def all_gather_dp_groups(groups_flat, partitioned_param_groups, zp_process_group, start_alignment_factor,
+ allgather_bucket_size, dp_process_group=None):
+ # if dist.has_all_gather_into_tensor():
+ return all_gather_into_tensor_dp_groups(groups_flat, partitioned_param_groups, zp_process_group, dp_process_group)
+
+ # for group_id, partitioned_params in enumerate(partitioned_param_groups):
+ # # Sequential AllGather Best of both worlds
+ # partition_id = dist.get_rank(group=dp_process_group[group_id])
+ # dp_world_size = dist.get_world_size(group=dp_process_group[group_id])
+ #
+ # if dp_world_size == 1:
+ # # no groups share optimizer states
+ # # pipeline parallel with bf16 will default call this even if dp size = 1.
+ # continue
+ # num_shards = max(1, partitioned_params[partition_id].numel() * dp_world_size // allgather_bucket_size)
+ #
+ # shard_size = partitioned_params[partition_id].numel() // num_shards
+ #
+ # # Enforce nccl/rccl alignment of start location of each shard
+ # shard_size = shard_size - (shard_size % start_alignment_factor)
+ #
+ # num_elements = shard_size
+ #
+ # assert shard_size * num_shards <= partitioned_params[partition_id].numel()
+ #
+ # for shard_id in range(num_shards):
+ #
+ # if shard_id == (num_shards - 1):
+ # num_elements = partitioned_params[partition_id].numel() - shard_id * shard_size
+ #
+ # shard_list = []
+ # for dp_id in range(dp_world_size):
+ # curr_shard = partitioned_params[dp_id].narrow(0, shard_id * shard_size, num_elements).detach()
+ # shard_list.append(curr_shard)
+ # dist.all_gather(shard_list, shard_list[partition_id].contiguous(), dp_process_group[group_id])
+
+
+class TLinear(torch.nn.Linear):
+
+ def __init__(self, orig_layer, name=""):
+ self.name = name
+ super().__init__(orig_layer.weight.shape[1], orig_layer.weight.shape[0], bias=(orig_layer.bias is not None))
+ self.weight.data = transpose(orig_layer.weight.data)
+ self.bias = orig_layer.bias
+ self._fwd_func = self._fwd_bias_add if self.bias is not None else self._fwd
+
+ def _fwd(self, input):
+ return F.linear(input, self.weight)
+
+ def _fwd_bias_add(self, input):
+ return F.linear(input, self.weight, bias=self.bias)
+
+ def forward(self, input):
+ return self._fwd_func(input)
+
+
+def get_inactive_params(param_list):
+ from deepspeed.runtime.zero.partition_parameters import ZeroParamStatus
+ return [param for param in param_list if (hasattr(param, 'ds_id') and \
+ param.ds_status == ZeroParamStatus.NOT_AVAILABLE)]
+
+
+def required_torch_version(min_version=None, max_version=None):
+ assert min_version or max_version, "Must provide a min_version or max_version argument"
+
+ torch_version = pkg_version.parse(torch.__version__)
+
+ if min_version and pkg_version.parse(str(min_version)) > torch_version:
+ return False
+
+ if max_version and pkg_version.parse(str(max_version)) < torch_version:
+ return False
+
+ return True
diff --git a/One-to-All-Animation/video-generation/opensora/adaptor/zp_manager.py b/One-to-All-Animation/video-generation/opensora/adaptor/zp_manager.py
new file mode 100644
index 0000000000000000000000000000000000000000..e05bfdbcd5a6b2c24be2de987c769117b31199f6
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/adaptor/zp_manager.py
@@ -0,0 +1,31 @@
+import torch
+import os
+import torch.distributed as dist
+
+
+class ZPManager(object):
+ def __init__(self, zp_size=8):
+ self.rank = int(os.getenv('RANK', '0'))
+ self.world_size = int(os.getenv("WORLD_SIZE", '1'))
+ self.zp_size = zp_size
+ self.zp_group = None
+ self.zp_rank = None
+ self.is_initialized = False
+
+ def init_group(self):
+ if self.is_initialized:
+ return
+
+ self.is_initialized = True
+
+ """Initialize the sequence parallel group."""
+ num_zp_groups: int = self.world_size // self.zp_size
+ for i in range(num_zp_groups):
+ ranks = range(i * self.zp_size, (i + 1) * self.zp_size)
+ group = dist.new_group(ranks)
+ if self.rank in ranks:
+ self.zp_group = group
+ self.zp_rank = self.rank % self.zp_size
+
+
+zp_manager = ZPManager()
diff --git a/One-to-All-Animation/video-generation/opensora/controlnet_modules/__init__.py b/One-to-All-Animation/video-generation/opensora/controlnet_modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/controlnet_modules/controlnet.py b/One-to-All-Animation/video-generation/opensora/controlnet_modules/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..3d1040303aa08bd4bdbdb50e760ce53888bd2542
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/controlnet_modules/controlnet.py
@@ -0,0 +1,641 @@
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+from torch import nn
+from torch.nn import functional as F
+from einops import rearrange
+
+from dataclasses import dataclass
+from typing import Optional, Tuple
+
+import numpy as np
+import torch
+import torch.nn as nn
+
+from diffusers.utils import BaseOutput, is_torch_version
+from diffusers.utils.torch_utils import randn_tensor
+from diffusers.models.attention_processor import SpatialNorm
+
+from opensora.vae_variants.hunyuan_vae_src.unet_causal_3d_blocks import (
+ CausalConv3d,
+ get_down_block3d,
+)
+
+class ControlNetCausalConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = CausalConv3d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+class MiniHunyuanEncoder(nn.Module):
+ '''
+ a direct copy of hunyuan encoder
+ '''
+ def __init__(
+ self,
+ in_channels = 3,
+ out_channels = 3,
+ down_block_types = ['DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D'],
+ block_out_channels = [128, 256, 512, 512],
+ layers_per_block = 2,
+ norm_num_groups = 32,
+ act_fn: str = "silu",
+ time_compression_ratio: int = 4,
+ spatial_compression_ratio: int = 8,
+ ):
+ super().__init__()
+ self.layers_per_block = layers_per_block
+ self.conv_in = CausalConv3d(
+ in_channels, block_out_channels[0], kernel_size=3, stride=1)
+ self.mid_block = None
+ self.down_blocks = nn.ModuleList([])
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+ num_spatial_downsample_layers = int(
+ np.log2(spatial_compression_ratio))
+ num_time_downsample_layers = int(np.log2(time_compression_ratio))
+
+ if time_compression_ratio == 4:
+ add_spatial_downsample = bool(
+ i < num_spatial_downsample_layers)
+ add_time_downsample = bool(i >= (
+ len(block_out_channels) - 1 - num_time_downsample_layers) and not is_final_block)
+ elif time_compression_ratio == 8:
+ add_spatial_downsample = bool(
+ i < num_spatial_downsample_layers)
+ add_time_downsample = bool(i < num_time_downsample_layers)
+ else:
+ raise ValueError(
+ f"Unsupported time_compression_ratio: {time_compression_ratio}")
+
+ downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1)
+ downsample_stride_T = (2, ) if add_time_downsample else (1, )
+ downsample_stride = tuple(
+ downsample_stride_T + downsample_stride_HW)
+ down_block = get_down_block3d(
+ down_block_type,
+ num_layers=self.layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ add_downsample=bool(
+ add_spatial_downsample or add_time_downsample),
+ downsample_stride=downsample_stride,
+ resnet_eps=1e-6,
+ downsample_padding=0,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ attention_head_dim=output_channel,
+ temb_channels=None,
+ )
+ self.down_blocks.append(down_block)
+
+ self.conv_out = zero_module(
+ CausalConv3d(block_out_channels[-1], out_channels, kernel_size=3)
+ )
+
+ def forward(self, sample):
+ assert len(sample.shape) == 5, "The input tensor should have 5 dimensions"
+ sample = self.conv_in(sample)
+ # down
+ for down_block in self.down_blocks:
+ sample = down_block(sample)
+ sample = self.conv_out(sample)
+ return sample
+
+
+class ControlNetConditioningEmbedding(nn.Module):
+ """
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
+ model) to encode image-space conditions ... into feature maps ..."
+ """
+
+ def __init__(
+ self,
+ conditioning_embedding_channels: int,
+ conditioning_channels: int = 3,
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
+ ):
+ super().__init__()
+
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
+
+ self.blocks = nn.ModuleList([])
+
+ for i in range(len(block_out_channels) - 1):
+ channel_in = block_out_channels[i]
+ channel_out = block_out_channels[i + 1]
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
+
+ self.conv_out = zero_module(
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
+ )
+
+ def forward(self, conditioning):
+ embedding = self.conv_in(conditioning)
+ embedding = F.silu(embedding)
+
+ for block in self.blocks:
+ embedding = block(embedding)
+ embedding = F.silu(embedding)
+
+ embedding = self.conv_out(embedding)
+
+ return embedding
+
+def zero_module(module):
+ for p in module.parameters():
+ nn.init.zeros_(p)
+ return module
+
+
+class InflatedGroupNorm(nn.GroupNorm):
+ def forward(self, x):
+ video_length = x.shape[2]
+
+ x = rearrange(x, "b c f h w -> (b f) c h w")
+ x = super().forward(x)
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
+
+ return x
+
+class InflatedConv3d(nn.Conv2d):
+ def forward(self, x):
+ video_length = x.shape[2]
+
+ x = rearrange(x, "b c f h w -> (b f) c h w")
+ x = super().forward(x)
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
+
+ return x
+
+
+class ResnetBlockInflated(nn.Module):
+ def __init__(
+ self,
+ *,
+ in_channels,
+ out_channels=None,
+ conv_shortcut=False,
+ dropout=0.0,
+ temb_channels=512,
+ groups=32,
+ groups_out=None,
+ pre_norm=True,
+ eps=1e-6,
+ non_linearity="swish",
+ time_embedding_norm="default",
+ output_scale_factor=1.0,
+ use_in_shortcut=None,
+ use_inflated_groupnorm=None,
+ ):
+ super().__init__()
+ self.pre_norm = pre_norm
+ self.pre_norm = True
+ self.in_channels = in_channels
+ out_channels = in_channels if out_channels is None else out_channels
+ self.out_channels = out_channels
+ self.use_conv_shortcut = conv_shortcut
+ self.time_embedding_norm = time_embedding_norm
+ self.output_scale_factor = output_scale_factor
+
+ if groups_out is None:
+ groups_out = groups
+
+ assert use_inflated_groupnorm != None
+ if use_inflated_groupnorm:
+ self.norm1 = InflatedGroupNorm(
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
+ )
+ else:
+ self.norm1 = torch.nn.GroupNorm(
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
+ )
+
+ self.conv1 = InflatedConv3d(
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+
+ if temb_channels is not None:
+ if self.time_embedding_norm == "default":
+ time_emb_proj_out_channels = out_channels
+ elif self.time_embedding_norm == "scale_shift":
+ time_emb_proj_out_channels = out_channels * 2
+ else:
+ raise ValueError(
+ f"unknown time_embedding_norm : {self.time_embedding_norm} "
+ )
+
+ self.time_emb_proj = torch.nn.Linear(
+ temb_channels, time_emb_proj_out_channels
+ )
+ else:
+ self.time_emb_proj = None
+
+ if use_inflated_groupnorm:
+ self.norm2 = InflatedGroupNorm(
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
+ )
+ else:
+ self.norm2 = torch.nn.GroupNorm(
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
+ )
+ self.dropout = torch.nn.Dropout(dropout)
+ self.conv2 = InflatedConv3d(
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+
+ if non_linearity == "swish":
+ self.nonlinearity = lambda x: F.silu(x)
+ elif non_linearity == "mish":
+ self.nonlinearity = Mish()
+ elif non_linearity == "silu":
+ self.nonlinearity = nn.SiLU()
+
+ self.use_in_shortcut = (
+ self.in_channels != self.out_channels
+ if use_in_shortcut is None
+ else use_in_shortcut
+ )
+
+ self.conv_shortcut = None
+ if self.use_in_shortcut:
+ self.conv_shortcut = InflatedConv3d(
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
+ )
+
+ def forward(self, input_tensor, temb):
+ hidden_states = input_tensor
+
+ hidden_states = self.norm1(hidden_states)
+ hidden_states = self.nonlinearity(hidden_states)
+
+ hidden_states = self.conv1(hidden_states)
+
+ if temb is not None:
+ temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
+
+ if temb is not None and self.time_embedding_norm == "default":
+ hidden_states = hidden_states + temb
+
+ hidden_states = self.norm2(hidden_states)
+
+ if temb is not None and self.time_embedding_norm == "scale_shift":
+ scale, shift = torch.chunk(temb, 2, dim=1)
+ hidden_states = hidden_states * (1 + scale) + shift
+
+ hidden_states = self.nonlinearity(hidden_states)
+
+ hidden_states = self.dropout(hidden_states)
+ hidden_states = self.conv2(hidden_states)
+
+ if self.conv_shortcut is not None:
+ input_tensor = self.conv_shortcut(input_tensor)
+
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
+
+ return output_tensor
+
+class DownEncoderBlockInflated(nn.Module):
+ def __init__(
+ self,
+ *,
+ num_layers: int,
+ in_channels: int,
+ out_channels: int,
+ add_downsample: bool,
+ downsample_stride: tuple = (1, 2, 2),
+ resnet_eps: float = 1e-6,
+ resnet_act_fn: str = "silu",
+ resnet_groups: int = 32,
+ temb_channels: int = None,
+ ):
+ super().__init__()
+
+ self.resnets = nn.ModuleList(
+ [
+ ResnetBlockInflated(
+ in_channels=in_channels if i == 0 else out_channels,
+ out_channels=out_channels,
+ temb_channels=temb_channels,
+ eps=resnet_eps,
+ non_linearity=resnet_act_fn,
+ groups=resnet_groups,
+ use_inflated_groupnorm=True,
+ )
+ for i in range(num_layers)
+ ]
+ )
+
+ self.downsamplers = nn.ModuleList()
+ if add_downsample:
+ self.downsamplers.append(
+ InflatedConv3d(
+ out_channels,
+ out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=1,
+ )
+ )
+ self.down_stride = downsample_stride
+ else:
+ self.down_stride = (1, 1, 1)
+
+ def forward(self, x, temb=None):
+ for resnet in self.resnets:
+ x = resnet(x, temb)
+
+ for down in self.downsamplers:
+ x = down(x)
+ return x
+
+
+
+class SFT(nn.Module): # 2D SFT
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ intermediate_channels=128,
+ groups=32,
+ eps=1e-6,
+ ):
+ super().__init__()
+ self.out_channels = out_channels
+ self.norm = InflatedGroupNorm(groups, out_channels, eps, affine=True)
+
+ self.mlp_shared = nn.Sequential(
+ InflatedConv3d(
+ in_channels, intermediate_channels, kernel_size=3, stride=1, padding=1
+ ),
+ nn.SiLU(),
+ )
+ self.mlp_gamma = InflatedConv3d(
+ intermediate_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+ self.mlp_beta = InflatedConv3d(
+ intermediate_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+
+ @staticmethod
+ def _match_time(cond, target_t):
+ b, c, tc, h, w = cond.shape
+ if tc == target_t:
+ return cond
+ if tc == 1:
+ return cond.repeat(1, 1, target_t, 1, 1)
+
+ def forward(self, hidden_state, condition):
+ """
+ hidden_state : (B, Cout, T, H, W)
+ condition : (B, Cin, 1, H, W)
+ """
+ b, _, t, h, w = hidden_state.shape
+ hidden_state = self.norm(hidden_state) #2D SFT 2D Norm
+
+ condition = self._match_time(condition, t)
+
+ actv = self.mlp_shared(condition)
+ gamma = self.mlp_gamma(actv)
+ beta = self.mlp_beta(actv)
+
+ return hidden_state * (1 + gamma) + beta
+
+
+class MiniEncoder2D(nn.Module):
+
+ def __init__(
+ self,
+ in_channels: int = 3,
+ out_channels: int = 3,
+ down_block_types: list = (
+ "DownEncoderBlockInflated",
+ "DownEncoderBlockInflated",
+ "DownEncoderBlockInflated",
+ "DownEncoderBlockInflated",
+ ),
+ block_out_channels: list = (128, 256, 512, 512),
+ layers_per_block: int = 2,
+ norm_num_groups: int = 32,
+ act_fn: str = "silu",
+ spatial_compression_ratio: int = 8,
+ ):
+ super().__init__()
+
+ # -------------------------------------------------------------------
+ # 输入卷积
+ # -------------------------------------------------------------------
+ self.conv_in = InflatedConv3d(
+ in_channels, block_out_channels[0], kernel_size=3, stride=1, padding=1
+ )
+
+ self.down_blocks = nn.ModuleList()
+ output_channel = block_out_channels[0]
+ num_spatial_down_layers = int(np.log2(spatial_compression_ratio))
+
+ for i, block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ # is_final_block = i == len(block_out_channels) - 1
+
+ add_spatial_downsample = bool(i < num_spatial_down_layers)
+
+ downsample_stride = (1, 2, 2) if add_spatial_downsample else (1, 1, 1)
+
+ down_block = DownEncoderBlockInflated(
+ num_layers=layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ add_downsample=add_spatial_downsample,
+ downsample_stride=downsample_stride,
+ resnet_eps=1e-6,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ temb_channels=None,
+ )
+ self.down_blocks.append(down_block)
+
+ self.conv_out = zero_module(
+ InflatedConv3d(output_channel, out_channels, kernel_size=3, stride=1, padding=1)
+ )
+
+ def forward(self, x):
+
+ if x.ndim == 4:
+ x = x.unsqueeze(2) # (B,C,1,H,W)
+
+ assert x.ndim == 5 and x.shape[2] == 1, "时间维度必须为 1"
+ feats = []
+
+ x = self.conv_in(x)
+
+ for block in self.down_blocks:
+ x = block(x)
+ feats.append(x)
+
+ x = self.conv_out(x)
+ return x, feats
+
+
+class Driven_Ref_PoseEncoder(nn.Module):
+ def __init__(
+ self,
+ in_channels = 3,
+ out_channels = 3,
+ down_block_types = ['DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D', 'DownEncoderBlockCausal3D'],
+ block_out_channels = [128, 256, 512, 512],
+ layers_per_block = 2,
+ norm_num_groups = 32,
+ act_fn: str = "silu",
+ time_compression_ratio: int = 4,
+ spatial_compression_ratio: int = 8,
+ ):
+ super().__init__()
+ self.layers_per_block = layers_per_block
+ self.conv_in = CausalConv3d(
+ in_channels, block_out_channels[0], kernel_size=3, stride=1)
+ self.mid_block = None
+ self.down_blocks = nn.ModuleList([])
+
+ # down
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+ num_spatial_downsample_layers = int(
+ np.log2(spatial_compression_ratio))
+ num_time_downsample_layers = int(np.log2(time_compression_ratio))
+
+ if time_compression_ratio == 4:
+ add_spatial_downsample = bool(
+ i < num_spatial_downsample_layers)
+ add_time_downsample = bool(i >= (
+ len(block_out_channels) - 1 - num_time_downsample_layers) and not is_final_block)
+ elif time_compression_ratio == 8:
+ add_spatial_downsample = bool(
+ i < num_spatial_downsample_layers)
+ add_time_downsample = bool(i < num_time_downsample_layers)
+ else:
+ raise ValueError(
+ f"Unsupported time_compression_ratio: {time_compression_ratio}")
+
+ downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1)
+ downsample_stride_T = (2, ) if add_time_downsample else (1, )
+ downsample_stride = tuple(
+ downsample_stride_T + downsample_stride_HW)
+ down_block = get_down_block3d(
+ down_block_type,
+ num_layers=self.layers_per_block,
+ in_channels=input_channel,
+ out_channels=output_channel,
+ add_downsample=bool(
+ add_spatial_downsample or add_time_downsample),
+ downsample_stride=downsample_stride,
+ resnet_eps=1e-6,
+ downsample_padding=0,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ attention_head_dim=output_channel,
+ temb_channels=None,
+ )
+ self.down_blocks.append(down_block)
+
+ self.conv_out = zero_module(
+ CausalConv3d(block_out_channels[-1], out_channels, kernel_size=3)
+ )
+
+ self.ref_pose_encoder = MiniEncoder2D(
+ in_channels = in_channels,
+ out_channels = out_channels,
+ block_out_channels = block_out_channels,
+ norm_num_groups = norm_num_groups,
+ layers_per_block = layers_per_block,
+ spatial_compression_ratio = spatial_compression_ratio,
+ )
+ self.sft_layers = nn.ModuleList()
+ for i, ch in enumerate(block_out_channels):
+ if i == 0: # 0 层 (H/2,W/2) 不做 SFT
+ self.sft_layers.append(None)
+ else: # H/4、H/8、H/16 做 SFT
+ self.sft_layers.append(
+ SFT(
+ in_channels=ch,
+ out_channels=ch,
+ intermediate_channels=max(8, ch // 2),
+ groups=norm_num_groups,
+ )
+ )
+
+ def forward(self, driven_pose, ref_pose):
+ # driven_pose b c t h w
+ # ref_pose b c 1 h w
+ ref_pose_cond, ref_feats = self.ref_pose_encoder(ref_pose)
+
+ x = self.conv_in(driven_pose)
+ for i, down_block in enumerate(self.down_blocks):
+ x = down_block(x)
+
+ if self.sft_layers[i] is not None:
+ cond_feat = ref_feats[i]
+ x = self.sft_layers[i](x, cond_feat)
+
+ driven_pose_cond = self.conv_out(x)
+ return driven_pose_cond, ref_pose_cond
+
+
+
+
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/__init__.py b/One-to-All-Animation/video-generation/opensora/dataset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc0d92c715c77092edffa6d9d4f42d4723dcc438
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/__init__.py
@@ -0,0 +1,101 @@
+from torchvision.transforms import Compose
+from transformers import AutoTokenizer, AutoImageProcessor
+
+from torchvision import transforms
+from torchvision.transforms import Lambda
+
+from opensora.dataset.t2v_multires_datasets import T2VMultiRes_dataset
+from opensora.dataset.bodydance_dataset_3 import BodyDance_dataset_3
+from opensora.dataset.bodydance_dataset_refmask import BodyDance_dataset as BodyDance_dataset_RefMask
+from opensora.dataset.transform import ToTensorVideo, TemporalRandomCrop, RandomHorizontalFlipVideo, CenterCropResizeVideo, LongSideResizeVideo, SpatialStrideCropVideo
+# from opensora.models.causalvideovae import ae_norm, ae_denorm
+
+ae_norm = Lambda(lambda x: 2. * x - 1.)
+ae_denorm = lambda x: (x + 1.) / 2.
+
+def getdataset(args):
+ temporal_sample = TemporalRandomCrop() # 16 x 简单地时序上的随机采样
+ norm_fun = ae_norm
+ if args.dataset == 't2v':
+ pass
+
+ elif args.dataset == 't2v_multi_res':
+ #TODO: 优化下
+ return T2VMultiRes_dataset(args, transform=None, temporal_sample=temporal_sample, tokenizer=None,
+ transform_topcrop=None, valid=args.valid,
+ ignore_timestamps=args.ignore_timestamps, one_more_second=args.one_more_second, temporal_downscale=args.temporal_downscale,
+ load_cached_latents=args.load_cached_latents,
+ null_embedding_path=args.null_embedding_path
+ )
+ elif args.dataset == 'bodydance_3':
+ return BodyDance_dataset_3(
+ args, transform=None, temporal_sample=temporal_sample, tokenizer=None,
+ transform_topcrop=None, valid=args.valid,
+ ignore_timestamps=args.ignore_timestamps, one_more_second=args.one_more_second, temporal_downscale=args.temporal_downscale,
+ load_cached_latents=args.load_cached_latents,
+ null_embedding_path=args.null_embedding_path
+ )
+ elif args.dataset == 'bodydance_refmask':
+ return BodyDance_dataset_RefMask(
+ args, transform=None, temporal_sample=temporal_sample, tokenizer=None,
+ transform_topcrop=None, valid=args.valid,
+ ignore_timestamps=args.ignore_timestamps, one_more_second=args.one_more_second, temporal_downscale=args.temporal_downscale,
+ load_cached_latents=args.load_cached_latents,
+ null_embedding_path=args.null_embedding_path
+ )
+
+ raise NotImplementedError(args.dataset)
+
+
+if __name__ == "__main__":
+ from accelerate import Accelerator
+ from opensora.dataset.t2v_datasets import dataset_prog
+ import random
+ from tqdm import tqdm
+ args = type('args', (),
+ {
+ 'ae': 'CausalVAEModel_4x8x8',
+ 'dataset': 't2v',
+ 'attention_mode': 'xformers',
+ 'use_rope': True,
+ 'model_max_length': 300,
+ 'max_height': 320,
+ 'max_width': 240,
+ 'num_frames': 1,
+ 'use_image_num': 0,
+ 'compress_kv_factor': 1,
+ 'interpolation_scale_t': 1,
+ 'interpolation_scale_h': 1,
+ 'interpolation_scale_w': 1,
+ 'cache_dir': '../cache_dir',
+ 'image_data': '/storage/ongoing/new/Open-Sora-Plan-bak/7.14bak/scripts/train_data/image_data.txt',
+ 'video_data': '1',
+ 'train_fps': 24,
+ 'drop_short_ratio': 1.0,
+ 'use_img_from_vid': False,
+ 'speed_factor': 1.0,
+ 'cfg': 0.1,
+ 'text_encoder_name': 'google/mt5-xxl',
+ 'dataloader_num_workers': 10,
+
+ }
+ )
+ accelerator = Accelerator()
+ dataset = getdataset(args)
+ num = len(dataset_prog.img_cap_list)
+ zero = 0
+ for idx in tqdm(range(num)):
+ image_data = dataset_prog.img_cap_list[idx]
+ caps = [i['cap'] if isinstance(i['cap'], list) else [i['cap']] for i in image_data]
+ try:
+ caps = [[random.choice(i)] for i in caps]
+ except Exception as e:
+ print(e)
+ # import ipdb;ipdb.set_trace()
+ print(image_data)
+ zero += 1
+ continue
+ assert caps[0] is not None and len(caps[0]) > 0
+ print(num, zero)
+ import ipdb;ipdb.set_trace()
+ print('end')
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_3.py b/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_3.py
new file mode 100644
index 0000000000000000000000000000000000000000..654c6e00b2353371fbdc5e17ac0576202ddad709
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_3.py
@@ -0,0 +1,638 @@
+import time
+import traceback
+import pandas as pd
+
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+import glob
+import json
+import os, io, csv, math, random
+import cv2 as cv
+import numpy as np
+import torchvision
+from einops import rearrange
+from decord import VideoReader
+from os.path import join as opj
+from collections import Counter
+from diffusers.models.embeddings import get_1d_sincos_pos_embed_from_grid
+
+import torch
+import torchvision.transforms as transforms
+from torch.utils.data.dataset import Dataset
+from torch.utils.data import DataLoader, Dataset, get_worker_info
+from tqdm import tqdm
+from PIL import Image
+from accelerate.logging import get_logger
+
+from opensora.utils.dataset_utils import DecordInit
+from opensora.utils.utils import text_preprocessing
+from opensora.models.causalvideovae import ae_norm
+from .transform import get_video_transform, get_mask_transform
+from torchvision.transforms import Lambda
+import tarfile
+import multiprocessing
+import sys
+from .utils import *
+from dwpose_utils.dwpose_detector import build_pose_dict
+# fix numpy bug
+sys.modules.setdefault('numpy._core', np.core)
+if 'numpy._core.multiarray' not in sys.modules:
+ sys.modules['numpy._core.multiarray'] = np.core.multiarray
+if 'numpy._core._multiarray_umath' not in sys.modules:
+ sys.modules['numpy._core._multiarray_umath'] = np.core.multiarray
+
+
+logger = get_logger(__name__)
+# multiprocessing.set_start_method('spawn')
+def is_video_file(path):
+ video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.mpeg', '.mpg']
+ ext = os.path.splitext(path)[1]
+ return ext.lower() in video_extensions
+
+def filter_json_by_existed_files(directory, data, postfixes=[".mp4", ".jpg"]):
+ matching_files = []
+ for postfix in postfixes:
+ pattern = os.path.join(directory, '**', f'*{postfix}')
+ matching_files.extend(glob.glob(pattern, recursive=True))
+ mp4_files_set = set(os.path.abspath(path) for path in matching_files)
+ filtered_items = [item for item in data if item['path'] in mp4_files_set]
+
+ return filtered_items
+
+def random_video_noise(t, c, h, w):
+ vid = torch.rand(t, c, h, w) * 255.0
+ vid = vid.to(torch.uint8)
+ return vid
+
+def to_list(x):
+ if isinstance(x, (list, tuple, np.ndarray)):
+ return list(x)
+ if isinstance(x, str) and x.strip():
+ try:
+ return list(ast.literal_eval(x))
+ except Exception:
+ pass
+ return []
+
+def prompt_cleaning(cap):
+ assert isinstance(cap, str)
+ return cap.replace('\n', ' ').replace('\t', ' ')
+
+def crop_frame(frame, target_w, target_h):
+ w, h = frame.size
+ crop_x = w // 2 - target_w // 2
+ crop_y = h // 2 - target_h // 2
+ cropped_frame = frame.crop((crop_x, crop_y, crop_x + target_w, crop_y+target_h))
+ resized_frame = cropped_frame.resize((w, h), Image.BICUBIC)
+ return resized_frame
+
+def zoomed_in(frame, zoom_factor=0.2, num_frames=49):
+ width, height = frame.size
+ smallest_w, smallest_h = int(width * (1-zoom_factor)), int(height * (1-zoom_factor))
+ width_per_frame = np.linspace(width, smallest_w, num_frames)
+ height_per_frame = np.linspace(height, smallest_h, num_frames)
+ result_frames = [np.array(frame)]
+ for i in range(1, num_frames):
+ frame_i = crop_frame(frame, width_per_frame[i], height_per_frame[i])
+ result_frames.append(np.array(frame_i))
+ result_frames = np.stack(result_frames)
+ return result_frames
+
+def get_embd_condition(pred, visiable, d, sample_type, height, width, points_num = None):
+ '''
+ trajectory: B F N 2
+ contidion: B F N
+ sample_type: random, grid, sparse
+ '''
+ batch, frames, L, _ = pred.shape
+ if sample_type == "random":
+ points_num = 0.9 * L # train stage 1 dense sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))))
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ elif sample_type == "grid":
+ pass
+ return None
+ elif sample_type == "sparse":
+ points_num = 0.1 * L # train stage 2 sparse sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))), output_type="pt")
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ return None
+
+class BodyDance_dataset_3(Dataset):
+ def __init__(self, args, transform, temporal_sample, tokenizer, transform_topcrop, temporal_downscale, device='cuda', one_more_second=False, ignore_timestamps=False, valid=False, load_cached_latents=False, null_embedding_path=None):
+ self.data = args.data
+
+ self.train_fps = args.train_fps
+ self.transform = transform
+ self.transform_topcrop = transform_topcrop
+ self.temporal_sample = temporal_sample
+ self.tokenizer = tokenizer
+ self.cfg = args.cfg
+ self.one_more_second=one_more_second
+ self.without_face = 0.2
+ self.pose_cfg = args.pose_cfg
+ self.refimg_cfg = args.refimg_cfg
+ self.hand_mask = args.hand_mask
+ self.refimg_crop = args.refimg_crop
+ self.video_crop = args.zoomin
+ self.only_ref = args.only_ref
+ if args.change_pose > 0:
+ self.pose_poolA = pd.read_csv(args.pose_poolA)
+ self.pose_poolB = pd.read_csv(args.pose_poolB)
+ else:
+ self.pose_poolA = None
+ self.pose_poolB = None
+
+ self.change_pose = args.change_pose
+ self.pose_aug = args.pose_aug
+ self.ref_keep = args.ref_keep
+ print("\n=== 参数配置 ===")
+ print(f"self.pose_cfg: {self.pose_cfg:.2f}")
+ print(f"self.refimg_cfg: {self.refimg_cfg:.2f}")
+ print(f"self.hand_mask: {self.hand_mask}")
+ print(f"self.refimg_crop: {self.refimg_crop:.2f}")
+ print(f"self.video_crop: {self.video_crop:.2f}")
+ print(f"self.only_ref: {args.only_ref}")
+ print(f"self.change_pose: {args.change_pose}")
+
+
+
+ self.drop_score_ratio = 0.2
+ self.load_cached_latents = load_cached_latents
+ self.args = args
+ # self.model = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(self.device).eval()
+ # self.model.requires_grad_(False)
+ if self.load_cached_latents:
+ self.null_text_embedding = torch.load(null_embedding_path, map_location='cpu', weights_only=True)
+ self.temporal_downscale = temporal_downscale
+ self.valid = valid
+ self.simulate = True
+
+ if valid:
+ self.drop_score_ratio = 0
+ self.cfg = 0
+ self.v_decoder = DecordInit()
+ self.support_Chinese = False
+ if not ('mt5' in args.text_encoder_name):
+ self.support_Chinese = False
+ if isinstance(self.data, list) and len(self.data) == 1:
+ self.data = self.data[0]
+ if isinstance(self.data, str) and self.data.endswith('txt'):
+ self.data = [line.strip() for line in open(self.data).readlines()]
+ if isinstance(self.data, list):
+ df = pd.DataFrame()
+ for csv_file in self.data:
+ df_ = pd.read_csv(csv_file)
+ df = pd.concat([df, df_], ignore_index=True)
+ self.data = df
+ else:
+ self.data = pd.read_csv(self.data)
+
+ if one_more_second and 'end_frame' in self.data:
+ self.data['end_frame'] = self.data['end_frame'] + self.data['fps'] * 2 #会遇到多重的取整损失,
+ self.data['end_frame'] = self.data[['end_frame', 'num_frames']].min(axis=1)
+
+ if ignore_timestamps and 'end_frame' in self.data:
+ # self.data = self.data.drop(['start_frame', 'end_frame'], axis=1)
+ self.data['end_frame'] = self.data['num_frames'] #cancel out end_frame的限制
+
+ self.data['id'] = np.arange(len(self.data))
+ self.norm_fun = Lambda(lambda x: 2. * x - 1.)
+
+ self.verbose = False
+
+ def set_bucket_info(self, bucket_info):
+ self.bucket_info = bucket_info
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, idx):
+ try:
+ if not self.verbose:
+ print(idx)
+ self.verbose = True
+ data = self.get_data(idx)
+ return data
+ except Exception as e:
+ print(e)
+ print('get data error at idx:', idx)
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ print('get data error at path:', path)
+
+ new_idx = f"{index+1}-{num_frames}-{height}-{width}"
+ new_data = self.get_data(new_idx)
+ return new_data
+
+ raise Exception(e)
+
+ def get_data(self, idx):
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ # return self.get_video(idx)
+ if is_video_file(path):
+ return self.get_video(idx)
+ else:
+ return self.get_image(idx)
+
+ def get_video(self, idx):
+ # import pdb; pdb.set_trace()
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ real_t, real_h, real_w = num_frames, height, width
+
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, ref_face_mask, reference_pose_tensor = self.read_frames(idx, real_t)
+
+ vid_face_bbox = get_bbox_from_mask(face_mask)
+ ref_face_bbox = get_bbox_from_mask(ref_face_mask)
+
+
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask = apply_random_cropping_strategy_v2(
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor,
+ vid_face_bbox, ref_face_bbox,
+ real_h, real_w,
+ pose_cfg=self.pose_cfg,
+ refimg_cfg = self.refimg_cfg,
+ refimg_crop=self.refimg_crop,
+ random_zoomin = self.video_crop,
+ ref_keep = self.ref_keep,
+ )
+
+ face_mask = torch.maximum(face_mask, hand_mask)
+
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ # 只做resize, 不需要归一化
+ mask_transform = get_mask_transform(real_h, real_w)
+
+ video = transform(video) # T C H W -> T C H W
+ pose = transform(pose)
+ reference_frame = transform(reference_frame)
+ reference_pose_tensor = transform(reference_pose_tensor)
+
+ face_mask = mask_transform(face_mask)
+ ocr_mask = mask_transform(ocr_mask)
+ inpaint_mask = mask_transform(inpaint_mask)
+
+
+
+
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ pose = pose.transpose(0, 1)
+
+ reference_frame = reference_frame.transpose(0, 1)
+ reference_pose_tensor = reference_pose_tensor.transpose(0, 1)
+ face_mask = face_mask.transpose(0, 1)
+ ocr_mask = ocr_mask.transpose(0, 1)
+ inpaint_mask = inpaint_mask.transpose(0, 1)
+
+ reference_frame = torch.cat([reference_frame,inpaint_mask],dim=0)
+
+
+ text = self.data.iloc[idx]['qwen_caption']
+ text = str(text) if pd.notna(text) else ''
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 6
+ text = ""
+ cfg_embed_scale = 6
+
+ condition = pose
+
+ return dict(pixel_values=video, caption=text, cfg_embed_scale = cfg_embed_scale,
+ condition = condition, reference_frame = reference_frame, face_mask = face_mask, ocr_mask = ocr_mask, reference_pose=reference_pose_tensor)
+
+ def get_image(self, idx):
+ # TODO: 对于图像数据,暂时没有vae缓存的逻辑
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ real_t, real_h, real_w = num_frames, height, width
+
+ row = self.data.iloc[idx]
+ ori_height = row['height']
+ ori_width = row['width']
+ img_pairs = row['img_pairs']
+ if isinstance(img_pairs, str):
+ img_pairs = eval(img_pairs)
+
+ pair = random.choice(img_pairs)
+ src_path = pair['src_path']
+ tgt_path = pair['tgt_path']
+ tgt_pose_path = pair['tgt_pose_path']
+ text = pair['qwen_caption']
+
+ src_pose_path = os.path.splitext(src_path)[0] + "_pose.npy"
+
+ if self.only_ref:
+ tgt_path = src_path
+ tgt_pose_path = src_pose_path
+
+ is_same_image = (src_path == tgt_path)
+
+
+ # 图像 → Tensor (1, 3, H, W)
+ def _read_rgb(path):
+ img = Image.open(path).convert("RGB")
+ img = torch.from_numpy(np.array(img, dtype=np.uint8)).permute(2, 0, 1) # (3,H,W)
+ return img.unsqueeze(0) # (1,3,H,W)
+
+ reference_frame = _read_rgb(src_path)
+ image = _read_rgb(tgt_path)
+
+ pose_data = np.load(tgt_pose_path, allow_pickle=True)
+ ref_pose_data = np.load(src_pose_path, allow_pickle=True)
+
+ def has_cartoon_keyword(text):
+ if isinstance(text, list):
+ text = " ".join(text)
+ text = str(text)
+ kws = ("cartoon", "animate", "anime")
+ return any(kw in text.lower() for kw in kws)
+
+ without_face = has_cartoon_keyword(text) or random.random() < self.without_face
+
+ if random.random() < self.change_pose:
+ aspect_ratio = ori_height / ori_width
+ pool = self.pose_poolA if aspect_ratio >= 1 else self.pose_poolB
+ row = pool.sample(1).iloc[0]
+ rand_pose_path = row['pose_path']
+ rand_h, rand_w = int(row['height']), int(row['width'])
+ rand_arr = np.load(rand_pose_path.replace(".npy", "_raw.npy"), allow_pickle=True)
+ # change pose
+ random_pose = build_pose_dict(rand_arr[0],rand_h, rand_w, aspect_ratio)
+ new_pose_data = pose_data
+ random_pose_aligned = align_pose_by_scale_and_translation(new_pose_data[0], random_pose)
+ # new_pose_data = align_poses_by_limb_scaling_only(random_pose_aligned, new_pose_data)
+ new_pose_data, did_limb_change, did_face_change = align_poses_by_limb_scaling_only(
+ random_pose_aligned, new_pose_data,
+ limb_change_prob=0.4,
+ face_change_prob=0.7,
+ )
+ pose = draw_pose_aligned(new_pose_data[0], ori_height, ori_width, without_face=without_face,head_change=did_limb_change,face_change=did_face_change)
+ else:
+ pose = draw_pose_aligned(pose_data[0], ori_height, ori_width, without_face=without_face)
+
+ ref_pose = draw_pose_aligned(ref_pose_data[0], ori_height, ori_width, without_face=without_face)
+
+
+ pose_tensor = torch.from_numpy(np.array([pose])).permute(0, 3, 1, 2)
+ ref_pose_tensor = torch.from_numpy(np.array([ref_pose])).permute(0, 3, 1, 2)
+
+ face_mask = draw_face_mask_frompose(pose_data, [0], 1, ori_height, ori_width, for_vae = True).unsqueeze(1)
+ ocr_mask = torch.ones((1, 1, real_h, real_w), dtype=torch.float32)
+
+ image, pose_tensor, reference_frame, ref_pose_tensor, face_mask, inpaint_mask = apply_image_augmentation_strategy_v2(
+ image, pose_tensor, reference_frame, ref_pose_tensor, face_mask,
+ is_same_image,
+ real_h, real_w,
+ pose_cfg=self.pose_cfg,
+ refimg_cfg = self.refimg_cfg,
+ refimg_crop = self.refimg_crop,
+ random_zoomin = self.video_crop,
+ ref_keep = self.ref_keep,
+ )
+
+
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ mask_transform = get_mask_transform(real_h, real_w)
+
+ image = transform(image)
+ pose_tensor = transform(pose_tensor)
+
+ reference_frame = transform(reference_frame)
+ ref_pose_tensor = transform(ref_pose_tensor)
+
+ image = image.transpose(0, 1)
+ pose_tensor = pose_tensor.transpose(0, 1)
+ reference_frame = reference_frame.transpose(0, 1)
+ ref_pose_tensor = ref_pose_tensor.transpose(0, 1)
+ face_mask = mask_transform(face_mask).transpose(0, 1)
+ ocr_mask = mask_transform(ocr_mask).transpose(0, 1)
+ inpaint_mask = mask_transform(inpaint_mask).transpose(0, 1)
+
+ reference_frame = torch.cat([reference_frame,inpaint_mask],dim=0)
+
+
+
+ text = str(text) if pd.notna(text) else ''
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 6
+ text = ""
+ cfg_embed_scale = 6
+
+ condition = pose_tensor
+ return dict(pixel_values=image, caption=text, cfg_embed_scale = cfg_embed_scale,
+ condition = condition, reference_frame = reference_frame, face_mask = face_mask, ocr_mask = ocr_mask, reference_pose=ref_pose_tensor)
+
+ def read_frames(self, idx, real_t):
+ row = self.data.iloc[idx]
+ decord_vr = self.v_decoder(row['path'])
+ pose_data = np.load(row['pose_path'],allow_pickle=True)
+
+ ori_height = row['height']
+ ori_width = row['width']
+
+ start_frame_idx = row['start_frame']
+ end_frame_idx = row['end_frame']
+ all_ocr_bbox = row['all_ocr_bbox']
+
+ vid_fps = np.round(row['fps'])
+
+ train_fps = self.train_fps
+ if vid_fps >= 50:
+ train_fps = self.train_fps if random.random() < 0.5 else 2 * self.train_fps
+
+ frame_interval = max(int(vid_fps / self.train_fps),1)
+
+ # -------- ① 处理 train_start_index --------
+ start_list = to_list(row.get('train_start_index', None))
+ if len(start_list) > 3:
+ start_list = start_list[1:-1]
+ if start_list:
+ start_idx = random.choice(start_list)
+ train_indices = np.arange(start_idx, start_idx + real_t * frame_interval, frame_interval).astype(int)
+ else:
+ frame_indices = np.arange(start_frame_idx+1, end_frame_idx-1, frame_interval).astype(int)
+ frame_indices = frame_indices[frame_indices < end_frame_idx]
+ valid_frame_count = ((len(frame_indices) - 1) // 4) * 4 + 1
+ train_indices = frame_indices[:valid_frame_count]
+ if len(train_indices) > real_t:
+ rs = random.randint(0, len(train_indices) - real_t)
+ train_indices = train_indices[rs:rs + real_t]
+ real_t = len(train_indices)
+
+
+ ref_list = to_list(row.get('refimg_index', None))
+ if not ref_list:
+ ref_list = np.arange(1, len(decord_vr) - 1)
+ ref_index = select_refimg_index(ref_list,train_indices)
+
+
+ video = decord_vr.get_batch(train_indices).asnumpy()
+
+ indices_to_build = set(train_indices)
+ indices_to_build.add(ref_index)
+
+
+ if random.random() < self.change_pose:
+ # without_face = True
+ without_face = random.random() < self.without_face
+ aspect_ratio = ori_height / ori_width
+ pool = self.pose_poolA if aspect_ratio >= 1 else self.pose_poolB
+ row = pool.sample(1).iloc[0]
+ rand_pose_path = row['pose_path']
+ rand_h, rand_w = int(row['height']), int(row['width'])
+ rand_arr = np.load(rand_pose_path.replace(".npy", "_raw.npy"), allow_pickle=True)
+ # change pose
+ random_pose = build_pose_dict(rand_arr[0],rand_h, rand_w, aspect_ratio)
+ new_pose_data = [pose_data[i] for i in train_indices]
+ random_pose_aligned = align_pose_by_scale_and_translation(new_pose_data[0], random_pose)
+
+ # new_pose_data = align_poses_by_limb_scaling_only(random_pose_aligned, new_pose_data)
+ new_pose_data, did_limb_change, did_face_change = align_poses_by_limb_scaling_only(
+ random_pose_aligned, new_pose_data,
+ limb_change_prob=0.4,
+ face_change_prob=0.7
+ )
+ pose = get_batch_pose(new_pose_data, range(len(new_pose_data)), ori_height, ori_width,without_face, pose_aug_flag = self.pose_aug, head_change=did_limb_change,face_change=did_face_change)
+
+ # debug
+ if random.random() < 0.00:
+ ori_img = video[0].copy() # (H,W,3) uint8
+ ori_pose_vis = draw_pose_aligned(
+ pose_data[train_indices[0]], ori_height, ori_width,
+ without_face=True,
+ ) # (H,W,3) uint8
+ ref_pose_vis = draw_pose_aligned(
+ random_pose_aligned, ori_height, ori_width,
+ without_face=True,
+ )
+ aligned_pose_vis_0 = draw_pose_aligned(
+ new_pose_data[0], ori_height, ori_width,
+ without_face=True,
+ )
+ aligned_pose_vis_3 = draw_pose_aligned(
+ new_pose_data[3], ori_height, ori_width,
+ without_face=True,
+ )
+ aligned_pose_vis_5 = draw_pose_aligned(
+ new_pose_data[5], ori_height, ori_width,
+ without_face=True,
+ )
+ canvas = np.concatenate(
+ [ori_img, ori_pose_vis, ref_pose_vis, aligned_pose_vis_0, aligned_pose_vis_3, aligned_pose_vis_5], axis=1
+ )
+ # ---------- 保存 ----------
+ os.makedirs('debug_vis', exist_ok=True)
+ save_name = f'debug_vis/temp_{random.randint(0, 99):02d}.png'
+ cv2.imwrite(save_name, cv2.cvtColor(canvas, cv2.COLOR_RGB2BGR))
+ # print(f'[debug] save pose alignment vis -> {save_name}')
+
+
+ else:
+ without_face = random.random() < self.without_face
+ pose = get_batch_pose(pose_data, train_indices, ori_height, ori_width,without_face,pose_aug_flag = self.pose_aug)
+
+
+ reference_frame = decord_vr[ref_index].asnumpy()
+
+ reference_pose = draw_pose_aligned(
+ pose_data[ref_index],
+ ori_height,
+ ori_width,
+ without_face=without_face,
+ )
+
+ reference_pose_tensor = torch.from_numpy(np.array([reference_pose])).permute(0, 3, 1, 2)
+
+ image_tensor = torch.from_numpy(video).permute(0, 3, 1, 2)
+ pose_tensor = torch.from_numpy(pose).permute(0, 3, 1, 2)
+ reference_frame = torch.from_numpy(reference_frame).unsqueeze(0).permute(0, 3, 1, 2)
+
+ try:
+ all_ocr_bbox = eval(str(all_ocr_bbox)) if all_ocr_bbox and not pd.isna(all_ocr_bbox) else []
+ except:
+ all_ocr_bbox = []
+ ocr_mask = draw_ocr_mask(all_ocr_bbox, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+
+ face_mask = draw_face_mask_frompose(pose_data, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+ ref_face_mask = draw_face_mask_frompose(pose_data, [ref_index], 1, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+ hand_mask = torch.zeros_like(face_mask)
+ if self.hand_mask:
+ hand_mask = draw_hand_mask(pose_data, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+ return image_tensor, pose_tensor, reference_frame, face_mask, ocr_mask, hand_mask, ref_face_mask, reference_pose_tensor
+
+
+ def decord_read(self, path, predefine_num_frames, start_frame_idx = 0, total_frames = None):
+ decord_vr = self.v_decoder(path)
+ if total_frames is None:
+ total_frames = len(decord_vr)
+ fps = decord_vr.get_avg_fps() if decord_vr.get_avg_fps() > 0 else 30.0
+ frame_interval = int(np.round(fps / self.train_fps))
+ if frame_interval == 0:
+ frame_interval = 1
+ frame_indices = np.arange(start_frame_idx, total_frames, frame_interval).astype(int) #total_frames不是整数的时候会取整
+ frame_indices = frame_indices[frame_indices < total_frames]
+ frames_count = len(frame_indices)
+ valid_frame_count = ((frames_count - 1) // 8) * 8 + 1
+ frame_indices = frame_indices[:valid_frame_count]
+ if len(frame_indices) > predefine_num_frames:
+ # if not self.valid:
+ # begin_index, end_index = self.temporal_sample(len(frame_indices), predefine_num_frames)
+ # frame_indices = frame_indices[begin_index: end_index]
+ # else:
+ frame_indices = frame_indices[:predefine_num_frames] #不要这个随机性了
+ video_data = decord_vr.get_batch(frame_indices).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_refmask.py b/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_refmask.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c96322d930b389b1d870d5a9c92cfefe49df480
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/bodydance_dataset_refmask.py
@@ -0,0 +1,534 @@
+import time
+import traceback
+import pandas as pd
+
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+import glob
+import json
+import os, io, csv, math, random
+import cv2 as cv
+import numpy as np
+import torchvision
+from einops import rearrange
+from decord import VideoReader
+from os.path import join as opj
+from collections import Counter
+from diffusers.models.embeddings import get_1d_sincos_pos_embed_from_grid
+
+import torch
+import torchvision.transforms as transforms
+from torch.utils.data.dataset import Dataset
+from torch.utils.data import DataLoader, Dataset, get_worker_info
+from tqdm import tqdm
+from PIL import Image
+from accelerate.logging import get_logger
+
+from opensora.utils.dataset_utils import DecordInit
+from opensora.utils.utils import text_preprocessing
+from opensora.models.causalvideovae import ae_norm
+from .transform import get_video_transform, get_mask_transform
+from torchvision.transforms import Lambda
+import tarfile
+import multiprocessing
+import sys
+from .utils import *
+# fix numpy bug
+sys.modules.setdefault('numpy._core', np.core)
+if 'numpy._core.multiarray' not in sys.modules:
+ sys.modules['numpy._core.multiarray'] = np.core.multiarray
+if 'numpy._core._multiarray_umath' not in sys.modules:
+ sys.modules['numpy._core._multiarray_umath'] = np.core.multiarray
+
+
+logger = get_logger(__name__)
+# multiprocessing.set_start_method('spawn')
+def is_video_file(path):
+ video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.mpeg', '.mpg']
+ ext = os.path.splitext(path)[1]
+ return ext.lower() in video_extensions
+
+def filter_json_by_existed_files(directory, data, postfixes=[".mp4", ".jpg"]):
+ # 构建搜索模式,以匹配指定后缀的文件
+ matching_files = []
+ for postfix in postfixes:
+ pattern = os.path.join(directory, '**', f'*{postfix}')
+ matching_files.extend(glob.glob(pattern, recursive=True))
+
+ # 使用文件的绝对路径构建集合
+ mp4_files_set = set(os.path.abspath(path) for path in matching_files)
+
+ # 过滤数据条目,只保留路径在mp4文件集合中的条目
+ filtered_items = [item for item in data if item['path'] in mp4_files_set]
+
+ return filtered_items
+
+def to_list(x):
+ if isinstance(x, (list, tuple, np.ndarray)):
+ return list(x)
+ if isinstance(x, str) and x.strip():
+ try:
+ return list(ast.literal_eval(x))
+ except Exception:
+ pass
+ return []
+
+def random_video_noise(t, c, h, w):
+ vid = torch.rand(t, c, h, w) * 255.0
+ vid = vid.to(torch.uint8)
+ return vid
+
+def prompt_cleaning(cap):
+ assert isinstance(cap, str)
+ return cap.replace('\n', ' ').replace('\t', ' ')
+
+def crop_frame(frame, target_w, target_h):
+ w, h = frame.size
+ crop_x = w // 2 - target_w // 2
+ crop_y = h // 2 - target_h // 2
+ cropped_frame = frame.crop((crop_x, crop_y, crop_x + target_w, crop_y+target_h))
+ resized_frame = cropped_frame.resize((w, h), Image.BICUBIC)
+ return resized_frame
+
+def zoomed_in(frame, zoom_factor=0.2, num_frames=49):
+ width, height = frame.size
+ smallest_w, smallest_h = int(width * (1-zoom_factor)), int(height * (1-zoom_factor))
+ width_per_frame = np.linspace(width, smallest_w, num_frames)
+ height_per_frame = np.linspace(height, smallest_h, num_frames)
+ result_frames = [np.array(frame)]
+ for i in range(1, num_frames):
+ frame_i = crop_frame(frame, width_per_frame[i], height_per_frame[i])
+ result_frames.append(np.array(frame_i))
+ result_frames = np.stack(result_frames)
+ return result_frames
+
+def get_embd_condition(pred, visiable, d, sample_type, height, width, points_num = None):
+ '''
+ trajectory: B F N 2
+ contidion: B F N
+ sample_type: random, grid, sparse
+ '''
+ batch, frames, L, _ = pred.shape
+ if sample_type == "random":
+ points_num = 0.9 * L # train stage 1 dense sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))))
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ elif sample_type == "grid":
+ pass
+ return None
+ elif sample_type == "sparse":
+ points_num = 0.1 * L # train stage 2 sparse sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))), output_type="pt")
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ return None
+
+class BodyDance_dataset(Dataset):
+ def __init__(self, args, transform, temporal_sample, tokenizer, transform_topcrop, temporal_downscale, device='cuda', one_more_second=False, ignore_timestamps=False, valid=False, load_cached_latents=False, null_embedding_path=None):
+ self.data = args.data
+
+ self.train_fps = args.train_fps
+ self.transform = transform
+ self.transform_topcrop = transform_topcrop
+ self.temporal_sample = temporal_sample
+ self.tokenizer = tokenizer
+ self.cfg = args.cfg
+ self.one_more_second=one_more_second
+ self.without_face = 0.2
+ self.pose_cfg = args.pose_cfg
+ self.refimg_cfg = args.refimg_cfg
+ self.hand_mask = args.hand_mask
+ self.refimg_crop = args.refimg_crop
+ self.video_crop = args.zoomin
+ self.only_ref = args.only_ref
+ self.i2v = args.i2v
+ print("\n=== 参数配置 ===")
+ print(f"self.pose_cfg: {self.pose_cfg:.2f}")
+ print(f"self.refimg_cfg: {self.refimg_cfg:.2f}")
+ print(f"self.hand_mask: {self.hand_mask}")
+ print(f"self.refimg_crop: {self.refimg_crop:.2f}")
+ print(f"self.video_crop: {self.video_crop:.2f}")
+ print(f"self.only_ref: {args.only_ref}")
+ print(f"self.i2v: {args.i2v}")
+
+ self.drop_score_ratio = 0.2
+ self.load_cached_latents = load_cached_latents
+ self.args = args
+ # self.model = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(self.device).eval()
+ # self.model.requires_grad_(False)
+ if self.load_cached_latents:
+ self.null_text_embedding = torch.load(null_embedding_path, map_location='cpu', weights_only=True)
+ self.temporal_downscale = temporal_downscale
+ self.valid = valid
+ self.simulate = True
+
+ if valid:
+ self.drop_score_ratio = 0
+ self.cfg = 0
+ self.v_decoder = DecordInit()
+ self.support_Chinese = False
+ if not ('mt5' in args.text_encoder_name):
+ self.support_Chinese = False
+ if isinstance(self.data, list) and len(self.data) == 1:
+ self.data = self.data[0]
+ if isinstance(self.data, str) and self.data.endswith('txt'):
+ self.data = [line.strip() for line in open(self.data).readlines()]
+ if isinstance(self.data, list):
+ df = pd.DataFrame()
+ for csv_file in self.data:
+ df_ = pd.read_csv(csv_file)
+ df = pd.concat([df, df_], ignore_index=True)
+ self.data = df
+ else:
+ self.data = pd.read_csv(self.data)
+
+ if one_more_second and 'end_frame' in self.data:
+ self.data['end_frame'] = self.data['end_frame'] + self.data['fps'] * 2 #会遇到多重的取整损失,
+ self.data['end_frame'] = self.data[['end_frame', 'num_frames']].min(axis=1)
+
+ if ignore_timestamps and 'end_frame' in self.data:
+ # self.data = self.data.drop(['start_frame', 'end_frame'], axis=1)
+ self.data['end_frame'] = self.data['num_frames'] #cancel out end_frame的限制
+
+ self.data['id'] = np.arange(len(self.data))
+ self.norm_fun = Lambda(lambda x: 2. * x - 1.)
+
+ self.verbose = False
+
+ def set_bucket_info(self, bucket_info):
+ self.bucket_info = bucket_info
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, idx):
+ try:
+ if not self.verbose:
+ print(idx)
+ self.verbose = True
+ data = self.get_data(idx)
+ return data
+ except Exception as e:
+ print(e)
+ print('get data error at idx:', idx)
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ print('get data error at path:', path)
+
+ new_idx = f"{index+1}-{num_frames}-{height}-{width}"
+ new_data = self.get_data(new_idx)
+ return new_data
+
+ raise Exception(e)
+
+ def get_data(self, idx):
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ # return self.get_video(idx)
+ if is_video_file(path):
+ return self.get_video(idx)
+ else:
+ return self.get_image(idx)
+
+ def get_video(self, idx):
+ # import pdb; pdb.set_trace()
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ real_t, real_h, real_w = num_frames, height, width
+
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, ref_face_mask, reference_pose_tensor = self.read_frames(idx, real_t)
+
+ vid_face_bbox = get_bbox_from_mask(face_mask)
+ ref_face_bbox = get_bbox_from_mask(ref_face_mask)
+
+
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask = apply_random_cropping_strategy_v2(
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor,
+ vid_face_bbox, ref_face_bbox,
+ real_h, real_w,
+ pose_cfg=self.pose_cfg,
+ refimg_cfg = self.refimg_cfg,
+ refimg_crop=self.refimg_crop,
+ )
+
+ face_mask = torch.maximum(face_mask, hand_mask)
+
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ # 只做resize, 不需要归一化
+ mask_transform = get_mask_transform(real_h, real_w)
+
+ video = transform(video) # T C H W -> T C H W
+ pose = transform(pose)
+ reference_frame = transform(reference_frame)
+ reference_pose_tensor = transform(reference_pose_tensor)
+
+ face_mask = mask_transform(face_mask)
+ ocr_mask = mask_transform(ocr_mask)
+ inpaint_mask = mask_transform(inpaint_mask)
+
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ pose = pose.transpose(0, 1)
+
+ reference_frame = reference_frame.transpose(0, 1)
+ reference_pose_tensor = reference_pose_tensor.transpose(0, 1)
+ face_mask = face_mask.transpose(0, 1)
+ ocr_mask = ocr_mask.transpose(0, 1)
+ inpaint_mask = inpaint_mask.transpose(0, 1)
+
+ reference_frame = torch.cat([reference_frame,inpaint_mask],dim=0)
+
+
+ # text = row['qwen_caption']
+ text = self.data.iloc[idx]['qwen_caption']
+ text = str(text) if pd.notna(text) else ''
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 6
+ text = ""
+ cfg_embed_scale = 6
+
+ condition = pose
+
+ return dict(pixel_values=video, caption=text, cfg_embed_scale = cfg_embed_scale,
+ condition = condition, reference_frame = reference_frame, face_mask = face_mask, ocr_mask = ocr_mask)
+
+ def get_image(self, idx):
+ # TODO: 对于图像数据,暂时没有vae缓存的逻辑
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ real_t, real_h, real_w = num_frames, height, width
+
+ row = self.data.iloc[idx]
+ ori_height = row['height']
+ ori_width = row['width']
+ img_pairs = row['img_pairs']
+ if isinstance(img_pairs, str):
+ img_pairs = eval(img_pairs)
+
+ pair = random.choice(img_pairs)
+ src_path = pair['src_path']
+ tgt_path = pair['tgt_path']
+ tgt_pose_path = pair['tgt_pose_path']
+ text = pair['qwen_caption']
+
+ src_pose_path = os.path.splitext(src_path)[0] + "_pose.npy"
+
+ if self.only_ref:
+ tgt_path = src_path
+ tgt_pose_path = src_pose_path
+
+ is_same_image = (src_path == tgt_path)
+
+
+ # 1) 图像 → Tensor (1, 3, H, W)
+ def _read_rgb(path):
+ img = Image.open(path).convert("RGB")
+ img = torch.from_numpy(np.array(img, dtype=np.uint8)).permute(2, 0, 1) # (3,H,W)
+ return img.unsqueeze(0) # (1,3,H,W)
+
+ reference_frame = _read_rgb(src_path)
+ image = _read_rgb(tgt_path)
+
+ pose_data = np.load(tgt_pose_path, allow_pickle=True)
+ ref_pose_data = np.load(src_pose_path, allow_pickle=True)
+
+ def has_cartoon_keyword(text):
+ if isinstance(text, list):
+ text = " ".join(text)
+ text = str(text)
+ kws = ("cartoon", "animate", "anime")
+ return any(kw in text.lower() for kw in kws)
+
+ without_face = has_cartoon_keyword(text) or random.random() < self.without_face
+ pose = draw_pose_aligned(pose_data[0], ori_height, ori_width, without_face=without_face)
+ ref_pose = draw_pose_aligned(ref_pose_data[0], ori_height, ori_width, without_face=True)
+
+
+ pose_tensor = torch.from_numpy(np.array([pose])).permute(0, 3, 1, 2)
+ ref_pose_tensor = torch.from_numpy(np.array([ref_pose])).permute(0, 3, 1, 2)
+
+ face_mask = draw_face_mask_frompose(pose_data, [0], 1, ori_height, ori_width, for_vae = True).unsqueeze(1)
+ ocr_mask = torch.ones((1, 1, real_h, real_w), dtype=torch.float32)
+
+ image, pose_tensor, reference_frame, ref_pose_tensor, face_mask, inpaint_mask = apply_image_augmentation_strategy_v2(
+ image, pose_tensor, reference_frame, ref_pose_tensor, face_mask,
+ is_same_image,
+ real_h, real_w,
+ pose_cfg=self.pose_cfg,
+ refimg_cfg = self.refimg_cfg,
+ refimg_crop = self.refimg_crop,
+ )
+
+
+
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ mask_transform = get_mask_transform(real_h, real_w)
+
+ image = transform(image)
+ pose_tensor = transform(pose_tensor)
+
+ reference_frame = transform(reference_frame)
+ ref_pose_tensor = transform(ref_pose_tensor)
+
+ image = image.transpose(0, 1)
+ pose_tensor = pose_tensor.transpose(0, 1)
+ reference_frame = reference_frame.transpose(0, 1)
+ ref_pose_tensor = ref_pose_tensor.transpose(0, 1)
+ face_mask = mask_transform(face_mask).transpose(0, 1)
+ ocr_mask = mask_transform(ocr_mask).transpose(0, 1)
+ inpaint_mask = mask_transform(inpaint_mask).transpose(0, 1)
+
+ # CTHW
+ reference_frame = torch.cat([reference_frame,inpaint_mask],dim=0)
+
+ text = str(text) if pd.notna(text) else ''
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 6
+ text = ""
+ cfg_embed_scale = 6
+
+ condition = pose_tensor
+ return dict(pixel_values=image, caption=text, cfg_embed_scale = cfg_embed_scale,
+ condition = condition, reference_frame = reference_frame, face_mask = face_mask, ocr_mask = ocr_mask)
+
+ def read_frames(self, idx, real_t):
+ row = self.data.iloc[idx]
+ decord_vr = self.v_decoder(row['path'])
+ pose_data = np.load(row['pose_path'],allow_pickle=True)
+ ori_height = row['height']
+ ori_width = row['width']
+
+ start_frame_idx = row['start_frame']
+ end_frame_idx = row['end_frame']
+ all_ocr_bbox = row['all_ocr_bbox']
+
+ vid_fps = np.round(row['fps'])
+
+ train_fps = self.train_fps
+ if vid_fps >= 50:
+ train_fps = self.train_fps if random.random() < 0.5 else 2 * self.train_fps
+
+ frame_interval = max(int(vid_fps / self.train_fps),1)
+ # -------- ① 处理 train_start_index --------
+ start_list = to_list(row.get('train_start_index', None))
+ if len(start_list) > 3: # 去掉首尾
+ start_list = start_list[1:-1]
+ if start_list: # 按预定义起点
+ start_idx = random.choice(start_list)
+ train_indices = np.arange(start_idx, start_idx + real_t * frame_interval, frame_interval).astype(int)
+ else: # 原逻辑
+ frame_indices = np.arange(start_frame_idx+1, end_frame_idx-1, frame_interval).astype(int)
+ frame_indices = frame_indices[frame_indices < end_frame_idx]
+ valid_frame_count = ((len(frame_indices) - 1) // 4) * 4 + 1
+ train_indices = frame_indices[:valid_frame_count]
+ if len(train_indices) > real_t:
+ rs = random.randint(0, len(train_indices) - real_t)
+ train_indices = train_indices[rs:rs + real_t]
+ real_t = len(train_indices)
+
+ # -------- ref_index:优先用 refimg_index,排除首尾 --------
+ ref_list = to_list(row.get('refimg_index', None))
+ if not ref_list:
+ ref_list = np.arange(1, len(decord_vr) - 1)
+ ref_index = select_refimg_index(ref_list,train_indices)
+ if random.random() < self.i2v:
+ ref_index = train_indices[0]
+
+ video = decord_vr.get_batch(train_indices).asnumpy()
+
+ without_face = random.random() < self.without_face
+ pose = get_batch_pose(pose_data, train_indices, ori_height, ori_width,without_face)
+ reference_frame = decord_vr[ref_index].asnumpy()
+ reference_pose = draw_pose_aligned(pose_data[ref_index], ori_height, ori_width, without_face=True)
+ reference_pose_tensor = torch.from_numpy(np.array([reference_pose])).permute(0, 3, 1, 2)
+
+ image_tensor = torch.from_numpy(video).permute(0, 3, 1, 2)
+ pose_tensor = torch.from_numpy(pose).permute(0, 3, 1, 2)
+ reference_frame = torch.from_numpy(reference_frame).unsqueeze(0).permute(0, 3, 1, 2)
+
+ try:
+ all_ocr_bbox = eval(str(all_ocr_bbox)) if all_ocr_bbox and not pd.isna(all_ocr_bbox) else []
+ except:
+ all_ocr_bbox = []
+ ocr_mask = draw_ocr_mask(all_ocr_bbox, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+
+ face_mask = draw_face_mask_frompose(pose_data, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+ ref_face_mask = draw_face_mask_frompose(pose_data, [ref_index], 1, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+ hand_mask = torch.zeros_like(face_mask)
+ if self.hand_mask:
+ hand_mask = draw_hand_mask(pose_data, train_indices, real_t, ori_height, ori_width, for_vae = True).unsqueeze(1)
+
+ return image_tensor, pose_tensor, reference_frame, face_mask, ocr_mask, hand_mask, ref_face_mask, reference_pose_tensor
+
+
+ def decord_read(self, path, predefine_num_frames, start_frame_idx = 0, total_frames = None):
+ decord_vr = self.v_decoder(path)
+ if total_frames is None:
+ total_frames = len(decord_vr)
+ fps = decord_vr.get_avg_fps() if decord_vr.get_avg_fps() > 0 else 30.0
+ frame_interval = int(np.round(fps / self.train_fps))
+ if frame_interval == 0:
+ frame_interval = 1
+ frame_indices = np.arange(start_frame_idx, total_frames, frame_interval).astype(int) #total_frames不是整数的时候会取整
+ frame_indices = frame_indices[frame_indices < total_frames]
+ frames_count = len(frame_indices)
+ valid_frame_count = ((frames_count - 1) // 8) * 8 + 1
+ frame_indices = frame_indices[:valid_frame_count]
+ if len(frame_indices) > predefine_num_frames:
+ # if not self.valid:
+ # begin_index, end_index = self.temporal_sample(len(frame_indices), predefine_num_frames)
+ # frame_indices = frame_indices[begin_index: end_index]
+ # else:
+ frame_indices = frame_indices[:predefine_num_frames] #不要这个随机性了
+ video_data = decord_vr.get_batch(frame_indices).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/motion_trajectory_datasets.py b/One-to-All-Animation/video-generation/opensora/dataset/motion_trajectory_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..46cb445f89f98ff7c0700bd01c0712d7a1e32c38
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/motion_trajectory_datasets.py
@@ -0,0 +1,341 @@
+import time
+import traceback
+import pandas as pd
+
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+import glob
+import json
+import os, io, csv, math, random
+import cv2 as cv
+import numpy as np
+import torchvision
+from einops import rearrange
+from decord import VideoReader
+from os.path import join as opj
+from collections import Counter
+from diffusers.models.embeddings import get_1d_sincos_pos_embed_from_grid
+
+import torch
+import torchvision.transforms as transforms
+from torch.utils.data.dataset import Dataset
+from torch.utils.data import DataLoader, Dataset, get_worker_info
+from tqdm import tqdm
+from PIL import Image
+from accelerate.logging import get_logger
+
+from opensora.utils.dataset_utils import DecordInit
+from opensora.utils.utils import text_preprocessing
+from opensora.models.causalvideovae import ae_norm
+from .transform import get_video_transform
+from torchvision.transforms import Lambda
+import tarfile
+logger = get_logger(__name__)
+
+def is_video_file(path):
+ video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.mpeg', '.mpg']
+ ext = os.path.splitext(path)[1]
+ return ext.lower() in video_extensions
+
+def filter_json_by_existed_files(directory, data, postfixes=[".mp4", ".jpg"]):
+ # 构建搜索模式,以匹配指定后缀的文件
+ matching_files = []
+ for postfix in postfixes:
+ pattern = os.path.join(directory, '**', f'*{postfix}')
+ matching_files.extend(glob.glob(pattern, recursive=True))
+
+ # 使用文件的绝对路径构建集合
+ mp4_files_set = set(os.path.abspath(path) for path in matching_files)
+
+ # 过滤数据条目,只保留路径在mp4文件集合中的条目
+ filtered_items = [item for item in data if item['path'] in mp4_files_set]
+
+ return filtered_items
+
+def random_video_noise(t, c, h, w):
+ vid = torch.rand(t, c, h, w) * 255.0
+ vid = vid.to(torch.uint8)
+ return vid
+
+def prompt_cleaning(cap):
+ assert isinstance(cap, str)
+ return cap.replace('\n', ' ').replace('\t', ' ')
+
+def crop_frame(frame, target_w, target_h):
+ w, h = frame.size
+ crop_x = w // 2 - target_w // 2
+ crop_y = h // 2 - target_h // 2
+ cropped_frame = frame.crop((crop_x, crop_y, crop_x + target_w, crop_y+target_h))
+ resized_frame = cropped_frame.resize((w, h), Image.BICUBIC)
+ return resized_frame
+
+def zoomed_in(frame, zoom_factor=0.2, num_frames=49):
+ width, height = frame.size
+ smallest_w, smallest_h = int(width * (1-zoom_factor)), int(height * (1-zoom_factor))
+ width_per_frame = np.linspace(width, smallest_w, num_frames)
+ height_per_frame = np.linspace(height, smallest_h, num_frames)
+ result_frames = [np.array(frame)]
+ for i in range(1, num_frames):
+ frame_i = crop_frame(frame, width_per_frame[i], height_per_frame[i])
+ result_frames.append(np.array(frame_i))
+ result_frames = np.stack(result_frames)
+ return result_frames
+
+def get_embd_condition(pred, visiable, d, sample_type, height, width, points_num = None):
+ '''
+ trajectory: B F N 2
+ contidion: B F N
+ sample_type: random, grid, sparse
+ '''
+ batch, frames, L, _ = pred.shape
+ if sample_type == "random":
+ points_num = 0.9 * L # train stage 1 dense sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))), output_type="pt")
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ elif sample_type == "grid":
+ pass
+ return None
+ elif sample_type == "sparse":
+ points_num = 0.1 * L # train stage 2 sparse sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))), output_type="pt")
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ return None
+
+class T2VMultiRes_dataset(Dataset):
+ def __init__(self, args, transform, temporal_sample, tokenizer, transform_topcrop, temporal_downscale, one_more_second=False, ignore_timestamps=False, valid=False, load_cached_latents=False, null_embedding_path=None):
+ self.data = args.data
+ self.num_frames = args.num_frames
+ self.train_fps = args.train_fps
+ self.use_image_num = args.use_image_num
+ self.use_img_from_vid = args.use_img_from_vid
+ self.transform = transform
+ self.transform_topcrop = transform_topcrop
+ self.temporal_sample = temporal_sample
+ self.tokenizer = tokenizer
+ self.model_max_length = args.model_max_length
+ self.cfg = args.cfg
+ self.one_more_second=one_more_second
+ self.drop_score_ratio = 0.2
+ self.load_cached_latents = load_cached_latents
+ self.args = args
+ if self.load_cached_latents:
+ self.null_text_embedding = torch.load(null_embedding_path, map_location='cpu', weights_only=True)
+ self.temporal_downscale = temporal_downscale
+ self.valid = valid
+ self.simulate = True
+ if valid:
+ self.drop_score_ratio = 0
+ self.cfg = 0
+ self.v_decoder = DecordInit()
+ self.support_Chinese = False
+ if not ('mt5' in args.text_encoder_name):
+ self.support_Chinese = False
+ if isinstance(self.data, list) and len(self.data) == 1:
+ self.data = self.data[0]
+ if isinstance(self.data, str) and self.data.endswith('txt'):
+ self.data = [line.strip() for line in open(self.data).readlines()]
+ if isinstance(self.data, list):
+ df = pd.DataFrame()
+ for csv_file in self.data:
+ df_ = pd.read_csv(csv_file)
+ df = pd.concat([df, df_], ignore_index=True)
+ self.data = df
+ else:
+ self.data = pd.read_csv(self.data)
+
+ if one_more_second and 'end_frame' in self.data:
+ self.data['end_frame'] = self.data['end_frame'] + self.data['fps'] * 2 #会遇到多重的取整损失,
+ self.data['end_frame'] = self.data[['end_frame', 'num_frames']].min(axis=1)
+
+ if ignore_timestamps and 'end_frame' in self.data:
+ # self.data = self.data.drop(['start_frame', 'end_frame'], axis=1)
+ self.data['end_frame'] = self.data['num_frames'] #cancel out end_frame的限制
+
+ self.data['id'] = np.arange(len(self.data))
+ self.norm_fun = Lambda(lambda x: 2. * x - 1.)
+
+ self.verbose = False
+
+ def set_bucket_info(self, bucket_info):
+ self.bucket_info = bucket_info
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, idx):
+ try:
+ if not self.verbose:
+ print(idx)
+ self.verbose = True
+ data = self.get_data(idx)
+ return data
+ except Exception as e:
+ print(e)
+ print('get data error at idx:', idx)
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ print('get data error at path:', path)
+ raise Exception(e)
+
+ def get_data(self, idx):
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ if is_video_file(path):
+ return self.get_video(idx)
+ else:
+ return self.get_image(idx)
+
+ def get_video(self, idx):
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ video_path = self.data.iloc[idx]['path']
+ if 'start_frame' in self.data.iloc[idx] and 'end_frame' in self.data.iloc[idx] and not pd.isna(self.data.iloc[idx]['start_frame']) and not pd.isna(self.data.iloc[idx]['end_frame']):
+ start_frame_idx = self.data.iloc[idx]['start_frame']
+ end_frame_idx = self.data.iloc[idx]['end_frame']
+ else:
+ start_frame_idx = 0
+ end_frame_idx = None
+ real_t, real_h, real_w = num_frames, height, width
+ # condition,trajectory
+ condition = None
+ if self.args.load_condition:
+ trajectory = os.path.splitext(video_path)[0]+f'_{start_frame_idx}_{end_frame_idx}_pred_{real_h}_{real_w}.pt'
+ condition = os.path.splitext(video_path)[0]+f'_{start_frame_idx}_{end_frame_idx}_visi_{real_h}_{real_w}.pt'
+ # assert os.path.exists(trajectory), f"file {trajectory} do not exist!"
+ if os.path.exists(trajectory) and os.path.exists(condition):
+ trajectory = torch.load(trajectory, weights_only=True)
+ condition = torch.load(condition, weights_only=True)
+ condition = get_embd_condition(trajectory, condition, dim = self.args.condition_dim, sample_type = self.args.sample_type, height = real_h, width = real_w)
+ else:
+ trajectory = None
+ condition = None
+ # assert os.path.exists(video_path), f"file {video_path} do not exist!"
+ vae_embedding_path = os.path.splitext(video_path)[0]+'%06d_vae_hunyuan_512.pt'%(start_frame_idx)
+ text_embedding_path = os.path.splitext(video_path)[0]+'%06d_text_hunyuan_512.pt'%(start_frame_idx)
+ cfg_embed_scale = 6
+ if self.load_cached_latents:
+ num_latents = (real_t - 1) // self.temporal_downscale + 1
+ video = torch.load(vae_embedding_path, map_location='cpu', weights_only=True).squeeze(0)[:, :num_latents]
+ text = torch.load(text_embedding_path, map_location='cpu', weights_only=True) #注意是一个字典
+ if random.random() < self.cfg:
+ text = self.null_text_embedding
+ cfg_embed_scale = 1
+ else:
+ video = self.decord_read(video_path, predefine_num_frames=real_t, start_frame_idx = start_frame_idx, total_frames = end_frame_idx)
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ video = transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ text = self.data.iloc[idx]['text']
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 1
+ text = ""
+ return dict(pixel_values=video, caption=text, cfg_embed_scale = cfg_embed_scale, condition = condition)
+
+ def get_image(self, idx):
+ # TODO: 对于图像数据,暂时没有vae缓存的逻辑
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ image_path = self.data.iloc[idx]['path']
+ real_t, real_h, real_w = num_frames, height, width
+ if os.path.isfile(image_path):
+ try:
+ image = Image.open(image_path).convert('RGB') # [h, w, c]
+ except:
+ image = cv.imread(image)
+ image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
+ image = Image.fromarray(image)
+ else:
+ tarname = os.path.dirname(image_path)
+ basename = os.path.basename(image_path)
+ assert tarname.endswith('.tar')
+ with tarfile.open(tarname, 'r') as tar:
+ with tar.extractfile(basename) as image_data:
+ image = np.frombuffer(image_data.read(), np.uint8)
+ image = cv.imdecode(image, cv.IMREAD_UNCHANGED).astype(np.uint8)
+ image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
+ image = Image.fromarray(image)
+ #NOTE: only for i2v testing
+ if self.simulate:
+ image = torch.from_numpy(zoomed_in(image))
+ image = rearrange(image, 't h w c ->t c h w')
+ else:
+ image = torch.from_numpy(np.array(image)) # [h, w, c]
+ image = rearrange(image, 'h w c -> c h w').unsqueeze(0) # [1 c h w]
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ image = transform(image)
+ image = image.transpose(0, 1)
+
+ #TODO: 考虑实现multiple caption
+ text = self.data.iloc[idx]['text']
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ if self.simulate:
+ text += ' The camera slowly zoom in.'
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ text = text if random.random() > self.cfg else ""
+ return dict(pixel_values=image, caption=text)
+
+ def decord_read(self, path, predefine_num_frames, start_frame_idx = 0, total_frames = None):
+ decord_vr = self.v_decoder(path)
+ if total_frames is None:
+ total_frames = len(decord_vr)
+ fps = decord_vr.get_avg_fps() if decord_vr.get_avg_fps() > 0 else 30.0
+ frame_interval = int(np.round(fps / self.train_fps))
+ if frame_interval == 0:
+ frame_interval = 1
+ frame_indices = np.arange(start_frame_idx, total_frames, frame_interval).astype(int) #total_frames不是整数的时候会取整
+ frame_indices = frame_indices[frame_indices < total_frames]
+ frames_count = len(frame_indices)
+ valid_frame_count = ((frames_count - 1) // 8) * 8 + 1
+ frame_indices = frame_indices[:valid_frame_count]
+ if len(frame_indices) > predefine_num_frames:
+ # if not self.valid:
+ # begin_index, end_index = self.temporal_sample(len(frame_indices), predefine_num_frames)
+ # frame_indices = frame_indices[begin_index: end_index]
+ # else:
+ frame_indices = frame_indices[:predefine_num_frames] #不要这个随机性了
+ video_data = decord_vr.get_batch(frame_indices).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/t2v_multires_datasets.py b/One-to-All-Animation/video-generation/opensora/dataset/t2v_multires_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..04721b376109fc0ecc12f724d8da5b3998584002
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/t2v_multires_datasets.py
@@ -0,0 +1,341 @@
+import time
+import traceback
+import pandas as pd
+
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+import glob
+import json
+import os, io, csv, math, random
+import cv2 as cv
+import numpy as np
+import torchvision
+from einops import rearrange
+from decord import VideoReader
+from os.path import join as opj
+from collections import Counter
+from diffusers.models.embeddings import get_1d_sincos_pos_embed_from_grid
+
+import torch
+import torchvision.transforms as transforms
+from torch.utils.data.dataset import Dataset
+from torch.utils.data import DataLoader, Dataset, get_worker_info
+from tqdm import tqdm
+from PIL import Image
+from accelerate.logging import get_logger
+
+from opensora.utils.dataset_utils import DecordInit
+from opensora.utils.utils import text_preprocessing
+from opensora.models.causalvideovae import ae_norm
+from .transform import get_video_transform
+from torchvision.transforms import Lambda
+import tarfile
+import multiprocessing
+
+logger = get_logger(__name__)
+# multiprocessing.set_start_method('spawn')
+def is_video_file(path):
+ video_extensions = ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.mpeg', '.mpg']
+ ext = os.path.splitext(path)[1]
+ return ext.lower() in video_extensions
+
+def filter_json_by_existed_files(directory, data, postfixes=[".mp4", ".jpg"]):
+ # 构建搜索模式,以匹配指定后缀的文件
+ matching_files = []
+ for postfix in postfixes:
+ pattern = os.path.join(directory, '**', f'*{postfix}')
+ matching_files.extend(glob.glob(pattern, recursive=True))
+
+ # 使用文件的绝对路径构建集合
+ mp4_files_set = set(os.path.abspath(path) for path in matching_files)
+
+ # 过滤数据条目,只保留路径在mp4文件集合中的条目
+ filtered_items = [item for item in data if item['path'] in mp4_files_set]
+
+ return filtered_items
+
+def random_video_noise(t, c, h, w):
+ vid = torch.rand(t, c, h, w) * 255.0
+ vid = vid.to(torch.uint8)
+ return vid
+
+def prompt_cleaning(cap):
+ assert isinstance(cap, str)
+ return cap.replace('\n', ' ').replace('\t', ' ')
+
+def crop_frame(frame, target_w, target_h):
+ w, h = frame.size
+ crop_x = w // 2 - target_w // 2
+ crop_y = h // 2 - target_h // 2
+ cropped_frame = frame.crop((crop_x, crop_y, crop_x + target_w, crop_y+target_h))
+ resized_frame = cropped_frame.resize((w, h), Image.BICUBIC)
+ return resized_frame
+
+def zoomed_in(frame, zoom_factor=0.2, num_frames=49):
+ width, height = frame.size
+ smallest_w, smallest_h = int(width * (1-zoom_factor)), int(height * (1-zoom_factor))
+ width_per_frame = np.linspace(width, smallest_w, num_frames)
+ height_per_frame = np.linspace(height, smallest_h, num_frames)
+ result_frames = [np.array(frame)]
+ for i in range(1, num_frames):
+ frame_i = crop_frame(frame, width_per_frame[i], height_per_frame[i])
+ result_frames.append(np.array(frame_i))
+ result_frames = np.stack(result_frames)
+ return result_frames
+
+def get_embd_condition(pred, visiable, d, sample_type, height, width, points_num = None):
+ '''
+ trajectory: B F N 2
+ contidion: B F N
+ sample_type: random, grid, sparse
+ '''
+ batch, frames, L, _ = pred.shape
+ if sample_type == "random":
+ points_num = 0.9 * L # train stage 1 dense sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))))
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ elif sample_type == "grid":
+ pass
+ return None
+ elif sample_type == "sparse":
+ points_num = 0.1 * L # train stage 2 sparse sample
+ points_index = random.sample(list(range(L)), points_num)
+ pred = pred[:, :, points_index, :]
+ visiable = visiable[:, :, points_index, :]
+ pos_embedding = get_1d_sincos_pos_embed_from_grid(d, torch.tensor(list(range(points_num))), output_type="pt")
+ indices = torch.randperm(points_num)
+ pos_embedding = pos_embedding[indices]
+ condition = np.zeros((batch, d, frames, height, width))
+ for t in range(frames):
+ for b in range(batch):
+ for n in range(len(pos_embedding)):
+ x_n = int(pred[b, t, n, 0]) # w
+ y_n = int(pred[b, t, n, 1]) # h
+ if x_n >= width or x_n < 0:
+ continue
+ if y_n >= height or y_n < 0:
+ continue
+ condition[b, :, t, y_n, x_n] = visiable[b, t, n].item() * pos_embedding[n,:]
+ return condition
+ return None
+
+class T2VMultiRes_dataset(Dataset):
+ def __init__(self, args, transform, temporal_sample, tokenizer, transform_topcrop, temporal_downscale, device='cuda', one_more_second=False, ignore_timestamps=False, valid=False, load_cached_latents=False, null_embedding_path=None):
+ self.data = args.data
+
+ self.train_fps = args.train_fps
+ self.transform = transform
+ self.transform_topcrop = transform_topcrop
+ self.temporal_sample = temporal_sample
+ self.tokenizer = tokenizer
+ self.cfg = args.cfg
+ self.one_more_second=one_more_second
+
+ self.drop_score_ratio = 0.2
+ self.load_cached_latents = load_cached_latents
+ self.args = args
+ # self.model = torch.hub.load("facebookresearch/co-tracker", "cotracker3_offline").to(self.device).eval()
+ # self.model.requires_grad_(False)
+ if self.load_cached_latents:
+ self.null_text_embedding = torch.load(null_embedding_path, map_location='cpu', weights_only=True)
+ self.temporal_downscale = temporal_downscale
+ self.valid = valid
+ self.simulate = True
+ if valid:
+ self.drop_score_ratio = 0
+ self.cfg = 0
+ self.v_decoder = DecordInit()
+ self.support_Chinese = False
+ if not ('mt5' in args.text_encoder_name):
+ self.support_Chinese = False
+ if isinstance(self.data, list) and len(self.data) == 1:
+ self.data = self.data[0]
+ if isinstance(self.data, str) and self.data.endswith('txt'):
+ self.data = [line.strip() for line in open(self.data).readlines()]
+ if isinstance(self.data, list):
+ df = pd.DataFrame()
+ for csv_file in self.data:
+ df_ = pd.read_csv(csv_file)
+ df = pd.concat([df, df_], ignore_index=True)
+ self.data = df
+ else:
+ self.data = pd.read_csv(self.data)
+
+ if one_more_second and 'end_frame' in self.data:
+ self.data['end_frame'] = self.data['end_frame'] + self.data['fps'] * 2 #会遇到多重的取整损失,
+ self.data['end_frame'] = self.data[['end_frame', 'num_frames']].min(axis=1)
+
+ if ignore_timestamps and 'end_frame' in self.data:
+ # self.data = self.data.drop(['start_frame', 'end_frame'], axis=1)
+ self.data['end_frame'] = self.data['num_frames'] #cancel out end_frame的限制
+
+ self.data['id'] = np.arange(len(self.data))
+ self.norm_fun = Lambda(lambda x: 2. * x - 1.)
+
+ self.verbose = False
+
+ def set_bucket_info(self, bucket_info):
+ self.bucket_info = bucket_info
+
+ def __len__(self):
+ return len(self.data)
+
+ def __getitem__(self, idx):
+ try:
+ if not self.verbose:
+ print(idx)
+ self.verbose = True
+ data = self.get_data(idx)
+ return data
+ except Exception as e:
+ print(e)
+ print('get data error at idx:', idx)
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ print('get data error at path:', path)
+ raise Exception(e)
+
+ def get_data(self, idx):
+ index, num_frames, height, width = [int(val) for val in idx.split("-")]
+ path = self.data.iloc[index]['path']
+ if is_video_file(path):
+ return self.get_video(idx)
+ else:
+ return self.get_image(idx)
+
+ def get_video(self, idx):
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ video_path = self.data.iloc[idx]['path']
+ if 'start_frame' in self.data.iloc[idx] and 'end_frame' in self.data.iloc[idx] and not pd.isna(self.data.iloc[idx]['start_frame']) and not pd.isna(self.data.iloc[idx]['end_frame']):
+ start_frame_idx = self.data.iloc[idx]['start_frame']
+ end_frame_idx = self.data.iloc[idx]['end_frame']
+ else:
+ start_frame_idx = 0
+ end_frame_idx = None
+ real_t, real_h, real_w = num_frames, height, width
+ # assert os.path.exists(video_path), f"file {video_path} do not exist!"
+ vae_embedding_path = os.path.splitext(video_path)[0]+'%06d_vae_hunyuan_512.pt'%(start_frame_idx)
+ text_embedding_path = os.path.splitext(video_path)[0]+'%06d_text_hunyuan_512.pt'%(start_frame_idx)
+ cfg_embed_scale = 6
+ if self.load_cached_latents:
+ num_latents = (real_t - 1) // self.temporal_downscale + 1
+ video = torch.load(vae_embedding_path, map_location='cpu', weights_only=True).squeeze(0)[:, :num_latents]
+ text = torch.load(text_embedding_path, map_location='cpu', weights_only=True) #注意是一个字典
+ if random.random() < self.cfg:
+ text = self.null_text_embedding
+ cfg_embed_scale = 6
+ else:
+ video = self.decord_read(video_path, predefine_num_frames=real_t, start_frame_idx = start_frame_idx, total_frames = end_frame_idx)
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ video = transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ text = self.data.iloc[idx]['text']
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ text = text
+ if random.random() > self.cfg:
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ else:
+ cfg_embed_scale = 6
+ text = ""
+
+ # 加载condition
+ condition = None
+ if self.args.load_condition: #TODO: 暂时用加载原始视频的方式,替换成任意controlnet condition即可
+ video = self.decord_read(video_path, predefine_num_frames=real_t, start_frame_idx = start_frame_idx, total_frames = end_frame_idx)
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ video = transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ condition=video
+ return dict(pixel_values=video, caption=text, cfg_embed_scale = cfg_embed_scale, condition = condition)
+
+ def get_image(self, idx):
+ # TODO: 对于图像数据,暂时没有vae缓存的逻辑
+ idx, num_frames, height, width = [int(val) for val in idx.split("-")]
+ image_path = self.data.iloc[idx]['path']
+ real_t, real_h, real_w = num_frames, height, width
+ if os.path.isfile(image_path):
+ try:
+ image = Image.open(image_path).convert('RGB') # [h, w, c]
+ except:
+ image = cv.imread(image)
+ image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
+ image = Image.fromarray(image)
+ else:
+ tarname = os.path.dirname(image_path)
+ basename = os.path.basename(image_path)
+ assert tarname.endswith('.tar')
+ with tarfile.open(tarname, 'r') as tar:
+ with tar.extractfile(basename) as image_data:
+ image = np.frombuffer(image_data.read(), np.uint8)
+ image = cv.imdecode(image, cv.IMREAD_UNCHANGED).astype(np.uint8)
+ image = cv.cvtColor(image, cv.COLOR_BGR2RGB)
+ image = Image.fromarray(image)
+ #NOTE: only for i2v testing
+ if self.simulate:
+ image = torch.from_numpy(zoomed_in(image))
+ image = rearrange(image, 't h w c ->t c h w')
+ else:
+ image = torch.from_numpy(np.array(image)) # [h, w, c]
+ image = rearrange(image, 'h w c -> c h w').unsqueeze(0) # [1 c h w]
+ transform = get_video_transform(real_h, real_w, self.norm_fun)
+ image = transform(image)
+ image = image.transpose(0, 1)
+
+ #TODO: 考虑实现multiple caption
+ text = self.data.iloc[idx]['text']
+ if not isinstance(text, list):
+ text = [text]
+ text = prompt_cleaning(random.choice(text))
+ if self.simulate:
+ text += ' The camera slowly zoom in.'
+ text = text_preprocessing(text, support_Chinese=self.support_Chinese)
+ text = text if random.random() > self.cfg else ""
+ return dict(pixel_values=image, caption=text)
+
+ def decord_read(self, path, predefine_num_frames, start_frame_idx = 0, total_frames = None):
+ decord_vr = self.v_decoder(path)
+ if total_frames is None:
+ total_frames = len(decord_vr)
+ fps = decord_vr.get_avg_fps() if decord_vr.get_avg_fps() > 0 else 30.0
+ frame_interval = int(np.round(fps / self.train_fps))
+ if frame_interval == 0:
+ frame_interval = 1
+ frame_indices = np.arange(start_frame_idx, total_frames, frame_interval).astype(int) #total_frames不是整数的时候会取整
+ frame_indices = frame_indices[frame_indices < total_frames]
+ frames_count = len(frame_indices)
+ valid_frame_count = ((frames_count - 1) // 8) * 8 + 1
+ frame_indices = frame_indices[:valid_frame_count]
+ if len(frame_indices) > predefine_num_frames:
+ # if not self.valid:
+ # begin_index, end_index = self.temporal_sample(len(frame_indices), predefine_num_frames)
+ # frame_indices = frame_indices[begin_index: end_index]
+ # else:
+ frame_indices = frame_indices[:predefine_num_frames] #不要这个随机性了
+ video_data = decord_vr.get_batch(frame_indices).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/transform.py b/One-to-All-Animation/video-generation/opensora/dataset/transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1eff89adcf2f968439260f887676c7eac5d8417
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/transform.py
@@ -0,0 +1,628 @@
+import torch
+import random
+import numbers
+import numpy as np
+from torchvision.transforms import RandomCrop, RandomResizedCrop
+from torchvision import transforms
+
+#预处理方法: 先按照aspect_ratio进行centercrop,然后resize到target resolution
+def get_video_transform(resize_height, resize_width, norm_fun):
+
+ # update 0110: 16的整数倍
+ resize_height = round(resize_height / 16) * 16
+ resize_width = round(resize_width / 16) * 16
+
+ resize = [CenterCropResizeVideo((resize_height, resize_width), interpolation_mode='nearest'), ]
+ transform = transforms.Compose([
+ ToTensorVideo(),
+ *resize,
+ transforms.Lambda(lambda x: x.clamp(0, 1)),
+ norm_fun
+ ])
+ return transform
+
+# mask should only have 0 and 1
+def get_mask_transform(resize_height, resize_width):
+
+ # update 0110: 16的整数倍
+ resize_height = round(resize_height / 16) * 16
+ resize_width = round(resize_width / 16) * 16
+
+ resize = [CenterCropResizeVideo((resize_height, resize_width), interpolation_mode='nearest'), ]
+ transform = transforms.Compose([
+ *resize,
+ ])
+ return transform
+
+
+def _is_tensor_video_clip(clip):
+ if not torch.is_tensor(clip):
+ raise TypeError("clip should be Tensor. Got %s" % type(clip))
+
+ if not clip.ndimension() == 4:
+ raise ValueError("clip should be 4D. Got %dD" % clip.dim())
+
+ return True
+
+
+def center_crop_arr(pil_image, image_size):
+ """
+ Center cropping implementation from ADM.
+ https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
+ """
+ while min(*pil_image.size) >= 2 * image_size:
+ pil_image = pil_image.resize(
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
+ )
+
+ scale = image_size / min(*pil_image.size)
+ pil_image = pil_image.resize(
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
+ )
+
+ arr = np.array(pil_image)
+ crop_y = (arr.shape[0] - image_size) // 2
+ crop_x = (arr.shape[1] - image_size) // 2
+ return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
+
+
+def crop(clip, i, j, h, w):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ """
+ if len(clip.size()) != 4:
+ raise ValueError("clip should be a 4D tensor")
+ return clip[..., i: i + h, j: j + w]
+
+
+def resize(clip, target_size, interpolation_mode):
+ if len(target_size) != 2:
+ raise ValueError(f"target size should be tuple (height, width), instead got {target_size}")
+ if interpolation_mode == 'nearest':
+ return torch.nn.functional.interpolate(clip, size=target_size)
+ else:
+ return torch.nn.functional.interpolate(clip, size=target_size, mode=interpolation_mode, align_corners=True, antialias=True)
+
+
+
+def resize_scale(clip, target_size, interpolation_mode):
+ if len(target_size) != 2:
+ raise ValueError(f"target size should be tuple (height, width), instead got {target_size}")
+ H, W = clip.size(-2), clip.size(-1)
+ scale_ = target_size[0] / min(H, W)
+ return torch.nn.functional.interpolate(clip, scale_factor=scale_, mode=interpolation_mode, align_corners=True, antialias=True)
+
+
+def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"):
+ """
+ Do spatial cropping and resizing to the video clip
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ i (int): i in (i,j) i.e coordinates of the upper left corner.
+ j (int): j in (i,j) i.e coordinates of the upper left corner.
+ h (int): Height of the cropped region.
+ w (int): Width of the cropped region.
+ size (tuple(int, int)): height and width of resized clip
+ Returns:
+ clip (torch.tensor): Resized and cropped clip. Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ clip = crop(clip, i, j, h, w)
+ clip = resize(clip, size, interpolation_mode)
+ return clip
+
+
+def center_crop(clip, crop_size):
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+ th, tw = crop_size
+ if h < th or w < tw:
+ raise ValueError("height and width must be no smaller than crop_size")
+
+ i = int(round((h - th) / 2.0))
+ j = int(round((w - tw) / 2.0))
+ return crop(clip, i, j, th, tw)
+
+
+def center_crop_using_short_edge(clip):
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+ if h < w:
+ th, tw = h, h
+ i = 0
+ j = int(round((w - tw) / 2.0))
+ else:
+ th, tw = w, w
+ i = int(round((h - th) / 2.0))
+ j = 0
+ return crop(clip, i, j, th, tw)
+
+
+
+def center_crop_th_tw(clip, th, tw, top_crop):
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+
+ # import ipdb;ipdb.set_trace()
+ h, w = clip.size(-2), clip.size(-1)
+ tr = th / tw
+ if h / w > tr:
+ new_h = int(w * tr)
+ new_w = w
+ else:
+ new_h = h
+ new_w = int(h / tr)
+
+ i = 0 if top_crop else int(round((h - new_h) / 2.0))
+ j = int(round((w - new_w) / 2.0))
+ return crop(clip, i, j, new_h, new_w)
+
+def random_shift_crop(clip):
+ '''
+ Slide along the long edge, with the short edge as crop size
+ '''
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+
+ if h <= w:
+ long_edge = w
+ short_edge = h
+ else:
+ long_edge = h
+ short_edge = w
+
+ th, tw = short_edge, short_edge
+
+ i = torch.randint(0, h - th + 1, size=(1,)).item()
+ j = torch.randint(0, w - tw + 1, size=(1,)).item()
+ return crop(clip, i, j, th, tw)
+
+
+def to_tensor(clip):
+ """
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
+ permute the dimensions of clip tensor
+ Args:
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W)
+ """
+ _is_tensor_video_clip(clip)
+ if not clip.dtype == torch.uint8:
+ raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype))
+ # return clip.float().permute(3, 0, 1, 2) / 255.0
+ return clip.float() / 255.0
+
+
+def normalize(clip, mean, std, inplace=False):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be normalized. Size is (T, C, H, W)
+ mean (tuple): pixel RGB mean. Size is (3)
+ std (tuple): pixel standard deviation. Size is (3)
+ Returns:
+ normalized clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ if not inplace:
+ clip = clip.clone()
+ mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device)
+ # print(mean)
+ std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device)
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
+ return clip
+
+
+def hflip(clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be normalized. Size is (T, C, H, W)
+ Returns:
+ flipped clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ return clip.flip(-1)
+
+
+class RandomCropVideo:
+ def __init__(self, size):
+ if isinstance(size, numbers.Number):
+ self.size = (int(size), int(size))
+ else:
+ self.size = size
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: randomly cropped video clip.
+ size is (T, C, OH, OW)
+ """
+ i, j, h, w = self.get_params(clip)
+ return crop(clip, i, j, h, w)
+
+ def get_params(self, clip):
+ h, w = clip.shape[-2:]
+ th, tw = self.size
+
+ if h < th or w < tw:
+ raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}")
+
+ if w == tw and h == th:
+ return 0, 0, h, w
+
+ i = torch.randint(0, h - th + 1, size=(1,)).item()
+ j = torch.randint(0, w - tw + 1, size=(1,)).item()
+
+ return i, j, th, tw
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size})"
+
+
+class SpatialStrideCropVideo:
+ def __init__(self, stride):
+ self.stride = stride
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: cropped video clip by stride.
+ size is (T, C, OH, OW)
+ """
+ i, j, h, w = self.get_params(clip)
+ return crop(clip, i, j, h, w)
+
+ def get_params(self, clip):
+ h, w = clip.shape[-2:]
+
+ th, tw = h // self.stride * self.stride, w // self.stride * self.stride
+
+ return 0, 0, th, tw # from top-left
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size})"
+
+class LongSideResizeVideo:
+ '''
+ First use the long side,
+ then resize to the specified size
+ '''
+
+ def __init__(
+ self,
+ size,
+ skip_low_resolution=False,
+ interpolation_mode="bilinear",
+ ):
+ self.size = size
+ self.skip_low_resolution = skip_low_resolution
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized video clip.
+ size is (T, C, 512, *) or (T, C, *, 512)
+ """
+ _, _, h, w = clip.shape
+ if self.skip_low_resolution and max(h, w) <= self.size:
+ return clip
+ if h > w:
+ w = int(w * self.size / h)
+ h = self.size
+ else:
+ h = int(h * self.size / w)
+ w = self.size
+ resize_clip = resize(clip, target_size=(h, w),
+ interpolation_mode=self.interpolation_mode)
+ return resize_clip
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+class CenterCropResizeVideo:
+ '''
+ First use the short side for cropping length,
+ center crop video, then resize to the specified size
+ '''
+
+ def __init__(
+ self,
+ size,
+ top_crop=False,
+ interpolation_mode="bilinear",
+ ):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ self.top_crop = top_crop
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized / center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ # clip_center_crop = center_crop_using_short_edge(clip)
+ clip_center_crop = center_crop_th_tw(clip, self.size[0], self.size[1], top_crop=self.top_crop)
+ # import ipdb;ipdb.set_trace()
+ clip_center_crop_resize = resize(clip_center_crop, target_size=self.size,
+ interpolation_mode=self.interpolation_mode)
+ return clip_center_crop_resize
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class UCFCenterCropVideo:
+ '''
+ First scale to the specified size in equal proportion to the short edge,
+ then center cropping
+ '''
+
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized / center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ clip_resize = resize_scale(clip=clip, target_size=self.size, interpolation_mode=self.interpolation_mode)
+ clip_center_crop = center_crop(clip_resize, self.size)
+ return clip_center_crop
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class KineticsRandomCropResizeVideo:
+ '''
+ Slide along the long edge, with the short edge as crop size. And resie to the desired size.
+ '''
+
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ clip_random_crop = random_shift_crop(clip)
+ clip_resize = resize(clip_random_crop, self.size, self.interpolation_mode)
+ return clip_resize
+
+
+class CenterCropVideo:
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ clip_center_crop = center_crop(clip, self.size)
+ return clip_center_crop
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class NormalizeVideo:
+ """
+ Normalize the video clip by mean subtraction and division by standard deviation
+ Args:
+ mean (3-tuple): pixel RGB mean
+ std (3-tuple): pixel RGB standard deviation
+ inplace (boolean): whether do in-place normalization
+ """
+
+ def __init__(self, mean, std, inplace=False):
+ self.mean = mean
+ self.std = std
+ self.inplace = inplace
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): video clip must be normalized. Size is (C, T, H, W)
+ """
+ return normalize(clip, self.mean, self.std, self.inplace)
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})"
+
+
+class ToTensorVideo:
+ """
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
+ permute the dimensions of clip tensor
+ """
+
+ def __init__(self):
+ pass
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W)
+ """
+ return to_tensor(clip)
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__
+
+
+class RandomHorizontalFlipVideo:
+ """
+ Flip the video clip along the horizontal direction with a given probability
+ Args:
+ p (float): probability of the clip being flipped. Default value is 0.5
+ """
+
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if random.random() < self.p:
+ clip = hflip(clip)
+ return clip
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(p={self.p})"
+
+
+# ------------------------------------------------------------
+# --------------------- Sampling ---------------------------
+# ------------------------------------------------------------
+class TemporalRandomCrop(object):
+ """Temporally crop the given frame indices at a random location.
+
+ Args:
+ size (int): Desired length of frames will be seen in the model.
+ """
+
+ def __init__(self):
+ pass
+
+ def __call__(self, total_frames, target_frames):
+ size = target_frames
+ rand_end = max(0, total_frames - size - 1)
+ begin_index = random.randint(0, rand_end)
+ end_index = min(begin_index + size, total_frames)
+ return begin_index, end_index
+
+class DynamicSampleDuration(object):
+ """Temporally crop the given frame indices at a random location.
+
+ Args:
+ size (int): Desired length of frames will be seen in the model.
+ """
+
+ def __init__(self, t_stride, extra_1):
+ self.t_stride = t_stride
+ self.extra_1 = extra_1
+
+ def __call__(self, t, h, w):
+ if self.extra_1:
+ t = t - 1
+ truncate_t_list = list(range(t+1))[t//2:][::self.t_stride] # need half at least
+ truncate_t = random.choice(truncate_t_list)
+ if self.extra_1:
+ truncate_t = truncate_t + 1
+ return 0, truncate_t
+
+if __name__ == '__main__':
+ from torchvision import transforms
+ import torchvision.io as io
+ import numpy as np
+ from torchvision.utils import save_image
+ import os
+
+ vframes, aframes, info = io.read_video(
+ filename='./v_Archery_g01_c03.avi',
+ pts_unit='sec',
+ output_format='TCHW'
+ )
+
+ trans = transforms.Compose([
+ ToTensorVideo(),
+ RandomHorizontalFlipVideo(),
+ UCFCenterCropVideo(512),
+ # NormalizeVideo(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
+ ])
+
+ target_video_len = 32
+ frame_interval = 1
+ total_frames = len(vframes)
+ print(total_frames)
+
+ temporal_sample = TemporalRandomCrop(target_video_len * frame_interval)
+
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = temporal_sample(total_frames)
+ # print(start_frame_ind)
+ # print(end_frame_ind)
+ assert end_frame_ind - start_frame_ind >= target_video_len
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, target_video_len, dtype=int)
+ print(frame_indice)
+
+ select_vframes = vframes[frame_indice]
+ print(select_vframes.shape)
+ print(select_vframes.dtype)
+
+ select_vframes_trans = trans(select_vframes)
+ print(select_vframes_trans.shape)
+ print(select_vframes_trans.dtype)
+
+ select_vframes_trans_int = ((select_vframes_trans * 0.5 + 0.5) * 255).to(dtype=torch.uint8)
+ print(select_vframes_trans_int.dtype)
+ print(select_vframes_trans_int.permute(0, 2, 3, 1).shape)
+
+ io.write_video('./test.avi', select_vframes_trans_int.permute(0, 2, 3, 1), fps=8)
+
+ for i in range(target_video_len):
+ save_image(select_vframes_trans[i], os.path.join('./test000', '%04d.png' % i), normalize=True,
+ value_range=(-1, 1))
diff --git a/One-to-All-Animation/video-generation/opensora/dataset/utils.py b/One-to-All-Animation/video-generation/opensora/dataset/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..6dcb233616b726b8cbd352fec7c00e58a9a73882
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/dataset/utils.py
@@ -0,0 +1,1222 @@
+import cv2
+import numpy as np
+import matplotlib
+import math
+import torch
+import random
+import copy
+from dwpose_utils.dwpose_detector import build_pose_dict
+from torch.nn import functional as F
+eps = 0.01
+
+DROP_FACE_POINTS = {0, 14, 15, 16, 17}
+DROP_UPPER_POINTS = {0, 14, 15, 16, 17, 2, 1, 5, 3, 6}
+DROP_LOWER_POINTS = {8, 9, 10, 11, 12, 13}
+
+def generate_pose_plan(pose_aug_probs):
+ p1, p2, p3, p4 = pose_aug_probs
+ r = random.random()
+ if r < p1:
+ return {"mode": "drop_point", "point_idx": random.randint(0, 17)}
+ elif r < p1 + p2:
+ return {"mode": "stretch_limb", "limb_idx": random.randint(0, 18),
+ "stretch_scale": random.uniform(0.5, 2.0)}
+ elif r < p1 + p2 + p3:
+ region_mode = random.choice(["face", "upper", "lower"])
+ if region_mode == "face":
+ pts = DROP_FACE_POINTS
+ elif region_mode == "upper":
+ pts = DROP_UPPER_POINTS
+ else:
+ pts = DROP_LOWER_POINTS
+ return {"mode": "drop_region", "region": region_mode, "points": pts}
+ else:
+ return {"mode": "none"}
+
+def get_stickwidth(W, H, stickwidth=4):
+ if max(W, H) < 512:
+ ratio = 1.0
+ elif max(W, H) < 1080:
+ ratio = 1.5
+ elif max(W, H) < 2160:
+ ratio = 2.0
+ elif max(W, H) < 3240:
+ ratio = 2.5
+ elif max(W, H) < 4320:
+ ratio = 3.5
+ elif max(W, H) < 5400:
+ ratio = 4.5
+ else:
+ ratio = 4.0
+ return int(stickwidth * ratio)
+
+
+def alpha_blend_color(color, alpha):
+ """blend color according to point conf
+ """
+ return [int(c * alpha) for c in color]
+
+
+def draw_bodypose_aligned(canvas, candidate, subset, score,
+ plan=None, # 新增,用于全视频固定增强
+ random_drop=False):
+ H, W, C = canvas.shape
+ candidate = np.array(candidate)
+ subset = np.array(subset)
+ stickwidth = get_stickwidth(W, H, stickwidth=3)
+
+ limbSeq = [
+ [2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8],
+ [2, 9], [9, 10], [10, 11], [2, 12], [12, 13], [13, 14],
+ [2, 1], [1, 15], [15, 17], [1, 16], [16, 18], [3, 17], [6, 18]]
+ colors = [
+ [255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0],
+ [85, 255, 0], [0, 255, 0], [0, 255, 85], [0, 255, 170], [0, 255, 255],
+ [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255],
+ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
+
+ HIDE_JOINTS = set()
+ stretch_limb_idx = None
+ stretch_scale = None
+ if plan:
+ if plan["mode"] == "drop_point":
+ HIDE_JOINTS.add(plan["point_idx"])
+ elif plan["mode"] == "drop_region":
+ HIDE_JOINTS |= set(plan["points"])
+ elif plan["mode"] == "stretch_limb":
+ stretch_limb_idx = plan["limb_idx"]
+ stretch_scale = plan["stretch_scale"]
+
+ hide_joint = np.zeros_like(subset, dtype=bool)
+
+ for i in range(17):
+ for n in range(len(subset)):
+ idx_pair = limbSeq[i]
+
+ if any(j in HIDE_JOINTS for j in idx_pair):
+ continue
+
+ index = subset[n][np.array(idx_pair) - 1]
+ conf = score[n][np.array(idx_pair) - 1]
+ if -1 in index:
+ continue
+ # color lighten
+ alpha = max(conf[0] * conf[1], 0) if conf[0]>0 and conf[1]>0 else 0.35
+
+ Y = candidate[index.astype(int), 0] * float(W)
+ X = candidate[index.astype(int), 1] * float(H)
+
+ if stretch_limb_idx == i:
+ vec_x = X[1] - X[0]
+ vec_y = Y[1] - Y[0]
+ X[1] = X[0] + vec_x * stretch_scale
+ Y[1] = Y[0] + vec_y * stretch_scale
+ hide_joint[n, idx_pair[1]-1] = True
+
+ mX = np.mean(X)
+ mY = np.mean(Y)
+ length = ((X[0]-X[1])**2 + (Y[0]-Y[1])**2) ** 0.5
+ angle = math.degrees(math.atan2(X[0]-X[1], Y[0]-Y[1]))
+ polygon = cv2.ellipse2Poly((int(mY), int(mX)),
+ (int(length/2), stickwidth), int(angle), 0, 360, 1)
+ cv2.fillConvexPoly(canvas, polygon, alpha_blend_color(colors[i], alpha))
+
+ canvas = (canvas * 0.6).astype(np.uint8)
+
+ for i in range(18):
+ if i in HIDE_JOINTS:
+ continue
+ for n in range(len(subset)):
+ if hide_joint[n, i]:
+ continue
+ index = int(subset[n][i])
+ if index == -1:
+ continue
+ x, y = candidate[index][0:2]
+ conf = score[n][i]
+ # head_change=True
+ alpha = 0 if conf==-2 else max(conf, 0)
+ x = int(x * W)
+ y = int(y * H)
+ cv2.circle(canvas, (x, y), stickwidth,
+ alpha_blend_color(colors[i], alpha), thickness=-1)
+
+ return canvas
+
+
+def draw_handpose_aligned(canvas, all_hand_peaks, all_hand_scores, draw_th=0.3,):
+ H, W, C = canvas.shape
+ stickwidth = get_stickwidth(W, H, stickwidth=2)
+ line_thickness = get_stickwidth(W, H, stickwidth=2)
+
+ edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \
+ [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
+
+ for peaks, scores in zip(all_hand_peaks, all_hand_scores):
+ for ie, e in enumerate(edges):
+ if scores[e[0]] < draw_th or scores[e[1]] < draw_th:
+ continue
+ x1, y1 = peaks[e[0]]
+ x2, y2 = peaks[e[1]]
+ x1 = int(x1 * W)
+ y1 = int(y1 * H)
+ x2 = int(x2 * W)
+ y2 = int(y2 * H)
+
+ score = int(scores[e[0]] * scores[e[1]] * 255)
+ if x1 > eps and y1 > eps and x2 > eps and y2 > eps:
+ # 原来是2
+ cv2.line(canvas, (x1, y1), (x2, y2),
+ matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * score, thickness=line_thickness)
+
+ for i, keyponit in enumerate(peaks):
+ if scores[i] < draw_th:
+ continue
+
+ x, y = keyponit
+ x = int(x * W)
+ y = int(y * H)
+ score = int(scores[i] * 255)
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), stickwidth, (0, 0, score), thickness=-1)
+ return canvas
+
+
+def draw_facepose_aligned(canvas, all_lmks, all_scores, draw_th=0.3,face_change=False):
+ H, W, C = canvas.shape
+ stickwidth = get_stickwidth(W, H, stickwidth=2)
+ SKIP_IDX = set(range(0, 17))
+ SKIP_IDX |= set(range(27, 36))
+
+ for lmks, scores in zip(all_lmks, all_scores):
+ for idx, (lmk, score) in enumerate(zip(lmks, scores)):
+ # 跳过下巴点
+ if idx in SKIP_IDX:
+ continue
+ if score < draw_th:
+ continue
+ x, y = lmk
+ x = int(x * W)
+ y = int(y * H)
+ conf = int(score * 255)
+ # color lighten
+ if face_change:
+ conf = int(conf * 0.35)
+
+ if x > eps and y > eps:
+ cv2.circle(canvas, (x, y), stickwidth, (conf, conf, conf), thickness=-1)
+ return canvas
+
+
+def draw_pose_aligned(pose, H, W, ref_w=2160,
+ without_face=False,
+ pose_plan=None,
+ head_change=False,
+ face_change=False):
+ bodies = pose['bodies']
+ faces = pose['faces']
+ hands = pose['hands']
+ candidate = bodies['candidate']
+ subset = bodies['subset']
+ body_score = bodies['score'].copy()
+ # control color
+ if head_change:
+ target_joints = [0, 14, 15, 16, 17]
+ body_score[:, target_joints] = -2
+
+
+ sz = min(H, W)
+ sr = (ref_w / sz) if sz != ref_w else 1
+ canvas = np.zeros(shape=(int(H*sr), int(W*sr), 3), dtype=np.uint8)
+
+ canvas = draw_bodypose_aligned(canvas, candidate, subset,
+ score=body_score,
+ plan=pose_plan,)
+
+ # drop上半身 → 手不要画
+ if pose_plan and pose_plan["mode"] == "drop_region" and pose_plan.get("region") == "upper":
+ pass
+ else:
+ canvas = draw_handpose_aligned(canvas, hands, pose['hands_score'])
+
+ # drop脸 → 不画脸
+ if pose_plan and pose_plan["mode"] == "drop_region" and pose_plan.get("region") in {"upper","face"}:
+ pass
+ elif not without_face:
+ canvas = draw_facepose_aligned(canvas, faces, pose['faces_score'],face_change=face_change)
+ # print(W,H)
+ return cv2.resize(canvas, (W, H))
+
+# 训练中并没有用到
+def generate_pose_plan(pose_aug_probs):
+ p1, p2, p3, p4 = pose_aug_probs
+ r = random.random()
+ if r < p1:
+ return {"mode": "drop_point", "point_idx": random.randint(0, 17)}
+ elif r < p1 + p2:
+ return {"mode": "stretch_limb", "limb_idx": random.randint(0, 18),
+ "stretch_scale": random.uniform(0.5, 2.0)}
+ elif r < p1 + p2 + p3:
+ region_mode = random.choice(["face", "upper", "lower"])
+ if region_mode == "face":
+ pts = DROP_FACE_POINTS
+ elif region_mode == "upper":
+ pts = DROP_UPPER_POINTS
+ else:
+ pts = DROP_LOWER_POINTS
+ return {"mode": "drop_region", "region": region_mode, "points": pts}
+ else:
+ return {"mode": "none"}
+
+def get_batch_pose(pose_data, train_indices, H, W,
+ without_face=False,
+ pose_aug_flag=False,
+ head_change=False,
+ face_change=False):
+
+ if pose_aug_flag:
+ pose_plan = generate_pose_plan((0.1, 0.1, 0.3, 0.5))
+ else:
+ pose_plan = None
+
+ pose_batch = []
+ for i in train_indices:
+ frame_pose_img = draw_pose_aligned(pose_data[i], H, W, without_face=without_face,pose_plan=pose_plan,head_change=head_change,face_change=face_change)
+ pose_batch.append(frame_pose_img)
+ return np.array(pose_batch)
+
+
+
+def select_refimg_index(refimg_indices, train_indices):
+ valid_indices = [idx for idx in refimg_indices if idx < train_indices[0] or idx > train_indices[-1]]
+ if not valid_indices:
+ valid_indices = refimg_indices
+
+ return np.random.choice(valid_indices)
+
+
+def draw_face_mask(all_face_bbox, train_indices, real_t, ori_height, ori_width, for_vae = True):
+ vae_t = 1 + (real_t-1) // 4
+ if len(all_face_bbox) == 0:
+ if for_vae:
+ return torch.ones((vae_t, ori_height, ori_width), dtype=torch.float32)
+ else:
+ return torch.ones((real_t, ori_height, ori_width), dtype=torch.float32)
+ # 如果存在facebbox
+ if for_vae:
+ mask = torch.zeros((vae_t, ori_height, ori_width), dtype=torch.float32)
+ else:
+ mask = torch.zeros((real_t, ori_height, ori_width), dtype=torch.float32)
+
+ for i, idx in enumerate(train_indices):
+ bbox = all_face_bbox[idx] # 获取对应的 bbox
+ if len(bbox) == 0:
+ continue
+ x1, y1, x2, y2 = map(int,bbox)
+
+ if for_vae:
+ compressed_idx = (i + 3) // 4 # 每 4 帧压缩成一帧
+ # 并集
+ mask[compressed_idx, y1:y2, x1:x2] = 1
+ else:
+ mask[i, y1:y2, x1:x2] = 1
+ return mask
+
+
+def draw_face_mask_frompose(pose_data, train_indices, real_t,
+ ori_height, ori_width,
+ for_vae=True, # 是否 4→1 压缩
+ score_thresh=0.8, # 关键点平均置信度阈值
+ expand_ratio=0.1): # 人脸 box 适当放大一点
+
+ vae_t = 1 + (real_t - 1) // 4
+ if for_vae:
+ mask = torch.zeros((vae_t, ori_height, ori_width), dtype=torch.float32)
+ valid_flags = [True] * vae_t
+ else:
+ mask = torch.zeros((real_t, ori_height, ori_width), dtype=torch.float32)
+
+ for i, idx in enumerate(train_indices):
+ pose = pose_data[idx]
+ faces = pose.get('faces', pose.get('face', []))
+ scores = pose.get('faces_score', pose.get('face_score', []))
+
+ if len(scores) == 0 or len(faces) == 0:
+ if for_vae:
+ valid_flags[(i + 3) // 4] = False
+ continue
+
+ frame_valid = True
+ frame_mask = torch.zeros((ori_height, ori_width), dtype=torch.float32)
+
+ for peaks, sc in zip(faces, scores):
+ if np.mean(sc) < score_thresh:
+ frame_valid = False
+ break
+ xys = np.array(peaks)
+ if xys.size == 0:
+ continue
+ x1, y1 = int(np.min(xys[:, 0] * ori_width)), int(np.min(xys[:, 1] * ori_height))
+ x2, y2 = int(np.max(xys[:, 0] * ori_width)), int(np.max(xys[:, 1] * ori_height))
+
+ # 额外抬高顶部
+ extra_top = int((y2 - y1) * 0.4)
+ y1 = max(0, y1 - extra_top)
+
+ x1, y1, x2, y2 = expand_bbox(
+ x1, y1, x2, y2,
+ big=expand_ratio, small=expand_ratio,
+ frame_width=ori_width, frame_height=ori_height
+ )
+
+ frame_mask[y1:y2, x1:x2] = 1
+
+ if not frame_valid:
+ if for_vae:
+ valid_flags[(i + 3) // 4] = False
+ continue
+
+ if for_vae:
+ compressed_idx = (i + 3) // 4
+ mask[compressed_idx] = torch.maximum(mask[compressed_idx], frame_mask)
+ else:
+ mask[i] = frame_mask
+
+ if for_vae:
+ for t, valid in enumerate(valid_flags):
+ if not valid:
+ mask[t] = 0
+
+ return mask
+
+
+def draw_hand_mask(pose_data, train_indices, real_t, ori_height, ori_width, for_vae=True, score_thresh=0.8, expand_ratio=0.2):
+ vae_t = 1 + (real_t - 1) // 4
+ if for_vae:
+ mask = torch.zeros((vae_t, ori_height, ori_width), dtype=torch.float32)
+ valid_flags = [True] * vae_t
+ else:
+ mask = torch.zeros((real_t, ori_height, ori_width), dtype=torch.float32)
+
+ for i, idx in enumerate(train_indices):
+ pose = pose_data[idx]
+ hands = pose.get('hands', [])
+ hand_scores = pose.get('hands_score', [])
+ if len(hand_scores) == 0 or len(hands) == 0:
+ if for_vae:
+ valid_flags[(i + 3) // 4] = False
+ continue
+
+ frame_valid = True
+ # 用一个临时mask存每只手的mask,最后叠加
+ frame_mask = torch.zeros((ori_height, ori_width), dtype=torch.float32)
+ for peaks, scores in zip(hands, hand_scores):
+ if np.mean(scores) < score_thresh:
+ frame_valid = False
+ break
+ xys = np.array(peaks)
+ if xys.size == 0:
+ continue
+ x1, y1 = int(np.min(xys[:, 0] * ori_width)), int(np.min(xys[:, 1] * ori_height))
+ x2, y2 = int(np.max(xys[:, 0] * ori_width)), int(np.max(xys[:, 1] * ori_height))
+
+ x1, y1, x2, y2 = expand_bbox(
+ x1, y1, x2, y2,
+ big=expand_ratio, small=expand_ratio,
+ frame_width=ori_width,
+ frame_height=ori_height
+ )
+
+ frame_mask[y1:y2, x1:x2] = 1 # 给每只手单独mask
+ if not frame_valid:
+ if for_vae:
+ valid_flags[(i + 3) // 4] = False
+ continue
+ # 合并frame_mask到大mask
+ if for_vae:
+ compressed_idx = (i + 3) // 4
+ mask[compressed_idx] = torch.maximum(mask[compressed_idx], frame_mask)
+ else:
+ mask[i] = frame_mask
+
+ if for_vae:
+ for t, valid in enumerate(valid_flags):
+ if not valid:
+ mask[t] = 0 # 四帧内只要有一帧不合格,就清空对应压缩帧mask
+ return mask
+
+def expand_bbox(x1, y1, x2, y2, big=0.1, small=0.4,max_expand_pixels=None, frame_width=None, frame_height=None):
+ width = x2 - x1
+ height = y2 - y1
+ if width > height:
+ width_expand_ratio = big
+ height_expand_ratio = small
+ else:
+ width_expand_ratio = small
+ height_expand_ratio = big
+
+ expand_width = width * width_expand_ratio
+ expand_height = height * height_expand_ratio
+
+ if max_expand_pixels is not None:
+ expand_width = min(expand_width, max_expand_pixels)
+ expand_height = min(expand_height, max_expand_pixels)
+
+ x1_new = max(0, x1 - expand_width)
+ y1_new = max(0, y1 - expand_height)
+ x2_new = x2 + expand_width
+ y2_new = y2 + expand_height
+
+ # 如果提供了图像宽度和高度,限制扩展后的坐标
+ if frame_width is not None:
+ x2_new = min(x2_new, frame_width)
+ if frame_height is not None:
+ y2_new = min(y2_new, frame_height)
+
+ return int(x1_new), int(y1_new), int(x2_new), int(y2_new)
+
+
+#ocr_bbox可能有多个, ocr_bbox需要expand,目标:ocr部分为0
+def draw_ocr_mask(all_ocr_bbox, train_indices, real_t, ori_height, ori_width, for_vae = True):
+ vae_t = 1 + (real_t-1) // 4
+ if len(all_ocr_bbox) == 0:
+ if for_vae:
+ return torch.ones((vae_t, ori_height, ori_width), dtype=torch.float32)
+ else:
+ return torch.ones((real_t, ori_height, ori_width), dtype=torch.float32)
+ # 如果存在ocrbbox
+ if for_vae:
+ mask = torch.ones((vae_t, ori_height, ori_width), dtype=torch.float32)
+ else:
+ mask = torch.ones((real_t, ori_height, ori_width), dtype=torch.float32)
+
+ for i, idx in enumerate(train_indices):
+ bbox_list = all_ocr_bbox[idx]
+ if len(bbox_list) == 0:
+ continue
+ for bbox in bbox_list: # 遍历所有的 bbox
+ x1, y1, x2, y2 = map(int, bbox)
+ x1, y1, x2, y2 = expand_bbox(
+ x1, y1, x2, y2,
+ max_expand_pixels=20,
+ frame_width=ori_width,
+ frame_height=ori_height
+ )
+ if for_vae:
+ compressed_idx = (i + 3) // 4 # 每 4 帧压缩成一帧
+ # 并集
+ mask[compressed_idx, y1:y2, x1:x2] = 0
+ else:
+ mask[i, y1:y2, x1:x2] = 0
+ return mask
+
+def crop_tensors(tensors, bbox):
+ if not bbox:
+ return tensors
+ x1, y1, x2, y2 = bbox
+ return [t[..., y1:y2, x1:x2] for t in tensors]
+
+def get_bbox_from_mask(mask: torch.Tensor):
+ if not mask.any():
+ return None
+ combined_mask = mask.any(dim=0).squeeze(0)
+ coords = combined_mask.nonzero(as_tuple=False)
+ if coords.numel() == 0:
+ return None
+ y_min, x_min = coords.min(dim=0).values
+ y_max, x_max = coords.max(dim=0).values
+ return int(x_min), int(y_min), int(x_max), int(y_max)
+
+
+
+
+def apply_random_cropping_strategy(
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask,
+ reference_pose_tensor,
+ vid_face_bbox, ref_face_bbox,
+ real_h, real_w,
+ pose_cfg=0.2, refimg_cfg=0.0,refimg_crop=0.2, video_crop=0.2
+):
+ p = random.random()
+
+ if p < pose_cfg:
+ # 场景A: CFG - 置零 pose 和 reference_frame
+ pose = torch.zeros_like(pose)
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose_tensor = torch.zeros_like(reference_pose_tensor)
+
+ elif p < pose_cfg+refimg_cfg:
+ # 场景B: CFG - 置零 reference_frame
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose_tensor = torch.zeros_like(reference_pose_tensor)
+
+ elif p < pose_cfg + refimg_cfg + video_crop and vid_face_bbox is not None:
+ f_x1, f_y1, f_x2, f_y2 = vid_face_bbox
+ H, W = video.shape[-2:]
+
+ y1_crop = max(0, f_y1 - int((f_y2 - f_y1) * 0.1))
+ y2_crop = random.randint(int(H * 0.7), H)
+
+ if y2_crop > y1_crop + 10: # 保证有效高度
+ crop_h = y2_crop - y1_crop
+ crop_w = int(crop_h * (real_w / real_h))
+
+ x_start_range = max(0, f_x2 - crop_w)
+ x_end_range = min(W - crop_w, f_x1)
+
+ if x_start_range < x_end_range:
+ x1_crop = random.randint(x_start_range, x_end_range)
+ x2_crop = x1_crop + crop_w
+ final_bbox = (x1_crop, y1_crop, x2_crop, y2_crop)
+ video, pose, face_mask, ocr_mask, hand_mask = crop_tensors(
+ [video, pose, face_mask, ocr_mask, hand_mask], final_bbox
+ )
+
+ elif p < pose_cfg + refimg_cfg + video_crop + refimg_crop and ref_face_bbox is not None:
+ f_x1, f_y1, f_x2, f_y2 = ref_face_bbox
+ H, W = reference_frame.shape[-2:]
+
+ y1_crop = max(0, f_y1 - int((f_y2 - f_y1) * 0.1))
+ y2_crop_min = f_y2 + int((f_y2 - f_y1) * 0.3)
+ y2_crop = random.randint(min(y2_crop_min, H - 1), H - 1)
+
+ if y2_crop > y1_crop + 10:
+ crop_h = y2_crop - y1_crop
+ crop_w = int(crop_h * (real_w / real_h))
+ x_start_range = max(0, f_x2 - crop_w)
+ x_end_range = min(W - crop_w, f_x1)
+ if x_start_range < x_end_range:
+ x1_crop = random.randint(x_start_range, x_end_range)
+ x2_crop = x1_crop + crop_w
+ final_bbox = (x1_crop, y1_crop, x2_crop, y2_crop)
+ reference_frame, reference_pose_tensor = crop_tensors([reference_frame, reference_pose_tensor], final_bbox)
+
+ return video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor
+
+
+def generate_random_rectangle_mask(H, W, max_rects=1, max_size_ratio=0.2):
+ mask = torch.zeros((1, 1, H, W), dtype=torch.uint8)
+ for _ in range(random.randint(1, max_rects)):
+ rect_h = random.randint(int(H * 0.05), int(H * max_size_ratio))
+ rect_w = random.randint(int(W * 0.05), int(W * max_size_ratio))
+
+ start_y = random.randint(0, H - rect_h)
+ start_x = random.randint(0, W - rect_w)
+
+ mask[:, :, start_y : start_y + rect_h, start_x : start_x + rect_w] = 1
+
+ return mask
+
+# use mask
+def apply_random_cropping_strategy_v2(
+ video, pose, reference_frame, face_mask, ocr_mask, hand_mask,
+ reference_pose_tensor,
+ vid_face_bbox, ref_face_bbox,
+ real_h, real_w,
+ pose_cfg=0.0, refimg_cfg=0.0, refimg_crop=0.0, random_zoomin=0.0,ref_keep=0.0,
+):
+ reference_frame_ori = reference_frame.clone()
+ _, _, H, W = reference_frame.shape
+ inpaint_mask = torch.zeros((1, 1, H, W),dtype=torch.uint8)
+
+ p = random.random()
+
+ if p < pose_cfg:
+ pose = torch.zeros_like(pose)
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose_tensor = torch.zeros_like(reference_pose_tensor)
+ return video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask
+
+ elif p < pose_cfg + refimg_cfg:
+ reference_frame = torch.zeros_like(reference_frame)
+ # reference_pose_tensor = torch.zeros_like(reference_pose_tensor)
+ return video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask
+
+ elif p < pose_cfg + refimg_cfg + refimg_crop and ref_face_bbox is not None:
+ ratio_bottom = 0.9
+ f_x1, f_y1, f_x2, f_y2 = ref_face_bbox
+ H, W = reference_frame.shape[-2:]
+
+ y1_crop = max(0, f_y1 - int((f_y2 - f_y1) * 0.1))
+ y2_crop_min = f_y2 + int((f_y2 - f_y1) * 0.1)
+ y2_crop_max = int(H * ratio_bottom)
+ if y2_crop_max < y2_crop_min: # 极端情况下保证有合法区间
+ y2_crop_max = y2_crop_min
+
+ y2_crop = random.randint(y2_crop_min, y2_crop_max)
+ # y2_crop = random.randint(min(y2_crop_min, H - 1), H - 1)
+
+ if y2_crop > y1_crop + 10:
+ crop_h = y2_crop - y1_crop
+ crop_w = int(crop_h * (real_w / real_h))
+ x_start_range = max(0, f_x2 - crop_w)
+ x_end_range = min(W - crop_w, f_x1)
+ if x_start_range < x_end_range:
+ x1_crop = random.randint(x_start_range, x_end_range)
+ x2_crop = x1_crop + crop_w
+ final_bbox = (x1_crop, y1_crop, x2_crop, y2_crop)
+ # x1, y1, x2, y2 = final_bbox
+ mask_keep = torch.zeros((1, 1, H, W),dtype=torch.uint8)
+ mask_keep[..., y1_crop:y2_crop, x1_crop:x2_crop] = 1
+
+ # 更新 inpaint_mask (bbox外为1,内为0)
+ inpaint_mask = 1 - mask_keep
+ # mask ref and ref pose
+ reference_frame = reference_frame * mask_keep
+ reference_pose_tensor = reference_pose_tensor * mask_keep
+ else:
+ if random.random() < 0.2:
+ random_mask_to_add = generate_random_rectangle_mask(H, W).to(inpaint_mask.device)
+ inpaint_mask = random_mask_to_add
+ mask_keep = (1 - inpaint_mask).to(reference_frame.dtype)
+ reference_frame = reference_frame * mask_keep
+ reference_pose_tensor = reference_pose_tensor * mask_keep
+
+ if random.random() < ref_keep:
+ pose = torch.zeros_like(pose)
+ reference_pose_tensor = torch.zeros_like(reference_pose_tensor)
+ if video.shape[0] == 1: # T=1
+ video = reference_frame_ori
+
+ return video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask
+
+ if random_zoomin > 0.0:
+ q = random.random()
+ zoom_scale = 1.0 + random.uniform(0.0, 0.2)
+
+ def zoom_in_center_crop(x, scale):
+ Hx, Wx = x.shape[-2], x.shape[-1]
+ newH = max(1, int(round(Hx * scale)))
+ newW = max(1, int(round(Wx * scale)))
+ if newH == Hx and newW == Wx:
+ return x
+ x_up = F.interpolate(x, size=(newH, newW), mode='nearest')
+ top = max(0, (newH - Hx) // 2)
+ left = max(0, (newW - Wx) // 2)
+ return x_up[..., top:top + Hx, left:left + Wx]
+
+ if q < random_zoomin * 0.5:
+ reference_frame = zoom_in_center_crop(reference_frame, zoom_scale)
+ reference_pose_tensor = zoom_in_center_crop(reference_pose_tensor, zoom_scale)
+ inpaint_mask = zoom_in_center_crop(inpaint_mask.float(), zoom_scale).to(inpaint_mask.dtype)
+
+ elif q < random_zoomin:
+ video = zoom_in_center_crop(video, zoom_scale)
+ pose = zoom_in_center_crop(pose, zoom_scale)
+ face_mask = zoom_in_center_crop(face_mask.float(), zoom_scale).to(face_mask.dtype)
+ ocr_mask = zoom_in_center_crop(ocr_mask.float(), zoom_scale).to(ocr_mask.dtype)
+ hand_mask = zoom_in_center_crop(hand_mask.float(), zoom_scale).to(hand_mask.dtype)
+
+ return video, pose, reference_frame, face_mask, ocr_mask, hand_mask, reference_pose_tensor, inpaint_mask
+
+
+
+
+
+def _calculate_center_crop_bbox(H, W, zoom_factor=0.7):
+ crop_h = int(H * zoom_factor)
+ crop_w = int(W * zoom_factor)
+ y1 = (H - crop_h) // 2
+ x1 = (W - crop_w) // 2
+ return (x1, y1, x1 + crop_w, y1 + crop_h)
+
+def _calculate_smart_crop_bbox(bbox, H, W, real_h, real_w):
+ ratio_bottom = 0.75
+ f_x1, f_y1, f_x2, f_y2 = bbox
+ # 使用你之前为 refimg 设计的随机裁剪逻辑
+ y1_crop = max(0, f_y1 - int((f_y2 - f_y1) * 0.1))
+ y2_crop_min = f_y2 + int((f_y2 - f_y1) * 0.1)
+ y2_crop_max = int(H * ratio_bottom)
+ if y2_crop_max < y2_crop_min: # 极端情况下保证有合法区间
+ y2_crop_max = y2_crop_min
+ y2_crop = random.randint(y2_crop_min, y2_crop_max)
+ # y2_crop = random.randint(min(y2_crop_min, H - 1), H - 1)
+
+ if y2_crop <= y1_crop + 10:
+ return None
+
+ crop_h = y2_crop - y1_crop
+ crop_w = int(crop_h * (real_w / real_h))
+ x_start_range = max(0, f_x2 - crop_w)
+ x_end_range = min(W - crop_w, f_x1)
+
+ if x_start_range >= x_end_range:
+ return None
+
+ x1_crop = random.randint(x_start_range, x_end_range)
+ x2_crop = x1_crop + crop_w
+ return (x1_crop, y1_crop, x2_crop, y2_crop)
+
+# mask
+def apply_image_augmentation_strategy_v2(
+ image, pose, reference_frame, reference_pose,
+ tgt_face_mask,
+ is_same_image,
+ real_h, real_w,
+ pose_cfg=0.0,
+ refimg_cfg = 0.0,
+ refimg_crop = 0.0,
+ random_zoomin=0.0,
+ ref_keep=0.0,
+):
+
+ reference_frame_ori = reference_frame.clone()
+ _, _, H, W = reference_frame.shape
+ inpaint_mask = torch.zeros((1, 1, H, W),dtype=torch.uint8)
+
+ if random.random() < pose_cfg:
+ pose = torch.zeros_like(pose)
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose = torch.zeros_like(reference_pose)
+
+ elif random.random() < pose_cfg + refimg_cfg:
+ reference_frame = torch.zeros_like(reference_frame)
+ # reference_pose = torch.zeros_like(reference_pose)
+
+ # diff image
+ elif refimg_crop == 0.0 or not is_same_image:
+ return image, pose, reference_frame, reference_pose, tgt_face_mask, inpaint_mask
+
+ else:
+ bbox = get_bbox_from_mask(tgt_face_mask)
+ final_bbox = None
+ if bbox:
+ final_bbox = _calculate_smart_crop_bbox(bbox, reference_frame.shape[-2], reference_frame.shape[-1], real_h, real_w)
+ if final_bbox:
+ x1_crop, y1_crop, x2_crop, y2_crop = final_bbox
+ mask_keep = torch.zeros((1, 1, H, W),dtype=torch.uint8)
+ mask_keep[..., y1_crop:y2_crop, x1_crop:x2_crop] = 1
+ inpaint_mask = 1 - mask_keep
+ reference_frame = reference_frame * mask_keep
+ reference_pose = reference_pose * mask_keep
+
+
+ else:
+ H, W = reference_frame.shape[-2:]
+ center_crop_bbox = _calculate_center_crop_bbox(H, W)
+ x1_crop, y1_crop, x2_crop, y2_crop = center_crop_bbox
+ mask_keep = torch.zeros((1, 1, H, W),dtype=torch.uint8)
+ mask_keep[..., y1_crop:y2_crop, x1_crop:x2_crop] = 1
+ inpaint_mask = 1 - mask_keep
+ reference_frame = reference_frame * mask_keep
+ reference_pose = reference_pose * mask_keep
+
+ if random.random() < ref_keep:
+ pose = torch.zeros_like(pose)
+ reference_pose = torch.zeros_like(reference_pose)
+ image = reference_frame_ori
+ return image, pose, reference_frame, reference_pose, tgt_face_mask, inpaint_mask
+ if random_zoomin > 0.0:
+ q = random.random()
+ zoom_scale = 1.0 + random.uniform(0.0, 0.3)
+
+ def zoom_in_center_crop(x, scale):
+ Hx, Wx = x.shape[-2], x.shape[-1]
+ newH = max(1, int(round(Hx * scale)))
+ newW = max(1, int(round(Wx * scale)))
+ if newH == Hx and newW == Wx:
+ return x
+ x_up = F.interpolate(x, size=(newH, newW), mode='nearest')
+ top = max(0, (newH - Hx) // 2)
+ left = max(0, (newW - Wx) // 2)
+ return x_up[..., top:top + Hx, left:left + Wx]
+
+ if q < random_zoomin * 0.5:
+ reference_frame = zoom_in_center_crop(reference_frame, zoom_scale)
+ reference_frame = zoom_in_center_crop(reference_frame, zoom_scale)
+ inpaint_mask = zoom_in_center_crop(inpaint_mask.float(), zoom_scale).to(inpaint_mask.dtype)
+
+ elif q < random_zoomin:
+ image = zoom_in_center_crop(image, zoom_scale)
+ pose = zoom_in_center_crop(pose, zoom_scale)
+ tgt_face_mask = zoom_in_center_crop(tgt_face_mask.float(), zoom_scale).to(tgt_face_mask.dtype)
+ return image, pose, reference_frame, reference_pose, tgt_face_mask, inpaint_mask
+
+
+def apply_image_augmentation_strategy(
+ image, pose, reference_frame, reference_pose,
+ tgt_face_mask,
+ is_same_image,
+ real_h, real_w,
+ pose_cfg=0.2,
+ refimg_cfg = 0.0,
+ refimg_crop = 0.0
+):
+ if random.random() < pose_cfg:
+ pose = torch.zeros_like(pose)
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose = torch.zeros_like(reference_pose)
+ return image, pose, reference_frame, reference_pose, tgt_face_mask
+
+ if random.random() < pose_cfg + refimg_cfg:
+ reference_frame = torch.zeros_like(reference_frame)
+ reference_pose = torch.zeros_like(reference_pose)
+ return image, pose, reference_frame, reference_pose, tgt_face_mask
+
+ if refimg_crop == 0.0 or not is_same_image:
+ return image, pose, reference_frame, reference_pose, tgt_face_mask
+
+ bbox = get_bbox_from_mask(tgt_face_mask)
+ final_bbox = None
+ if bbox:
+ final_bbox = _calculate_smart_crop_bbox(bbox, reference_frame.shape[-2], reference_frame.shape[-1], real_h, real_w)
+ if final_bbox:
+ if random.random() < 0.5:
+ reference_frame, reference_pose = crop_tensors([reference_frame, reference_pose], final_bbox)
+ else:
+ image, pose, tgt_face_mask = crop_tensors([image, pose, tgt_face_mask], final_bbox)
+ else:
+ H, W = reference_frame.shape[-2:]
+ center_crop_bbox = _calculate_center_crop_bbox(H, W)
+ reference_frame, reference_pose = crop_tensors([reference_frame, reference_pose], center_crop_bbox)
+
+ return image, pose, reference_frame, reference_pose, tgt_face_mask
+
+
+def crop_around_face(image, bbox, base_scale=0.3, jitter=2.0, aggressive_prob=0.6):
+
+ H, W, _ = image.shape
+ if len(bbox) == 0:
+ return image
+
+ x1, y1, x2, y2 = bbox
+ face_cx = (x1 + x2) / 2
+ face_cy = (y1 + y2) / 2
+ face_top = min(y1, y2)
+ face_bottom = max(y1, y2)
+ face_h = face_bottom - face_top
+
+ if random.random() > aggressive_prob:
+ aspect_ratio = W / H
+ crop_h = int(H * base_scale * random.uniform(1.0, jitter))
+ crop_w = int(crop_h * aspect_ratio)
+
+ crop_h = min(crop_h, H)
+ crop_w = min(crop_w, W)
+
+ top = int(max(0, min(face_cy - crop_h * random.uniform(0.3, 0.5), H - crop_h)))
+ left = int(max(0, min(face_cx - crop_w / 2, W - crop_w)))
+ else:
+ tight_scale = random.uniform(1.5, 2.5)
+ crop_h = int(face_h * tight_scale)
+ crop_w = int(crop_h * (W / H))
+
+ crop_h = min(crop_h, H)
+ crop_w = min(crop_w, W)
+
+ top = int(max(0, face_top - 0.15 * crop_h))
+ top = min(top, H - crop_h)
+ left = int(max(0, face_cx - crop_w / 2))
+ left = min(left, W - crop_w)
+
+ cropped = image[top:top + crop_h, left:left + crop_w, :]
+
+ if cropped.shape[0] == 0 or cropped.shape[1] == 0:
+ return image
+
+ if cropped.shape[0] != crop_h or cropped.shape[1] != crop_w:
+ return image
+
+ return cropped
+
+# ========================== face region enhancement ========================
+L_EYE_IDXS = list(range(36, 42))
+R_EYE_IDXS = list(range(42, 48))
+NOSE_TIP = 30
+MOUTH_L = 48
+MOUTH_R = 54
+JAW_LINE = list(range(0, 17))
+
+def _to_68x2(arr):
+ arr = arr[:1]
+ if arr.shape == (1, 68, 2):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x[np.newaxis, :, :]
+ return arr[0].astype(np.float64), to_orig
+ if arr.shape == (68, 2):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x
+ return arr.astype(np.float64), to_orig
+ if arr.shape == (2, 68):
+ def to_orig(x):
+ x = np.asarray(x, dtype=np.float64)
+ if x.shape != (68, 2):
+ raise ValueError("to_orig expects (68,2)")
+ return x.T
+ return arr.T.astype(np.float64), to_orig
+ raise ValueError(f"faces shape {arr.shape} not supported; expected (1,68,2) or (68,2) or (2,68)")
+
+def _eye_center(face68, idxs):
+ return face68[idxs].mean(axis=0)
+
+def _anchors(face68):
+ le = _eye_center(face68, L_EYE_IDXS)
+ re = _eye_center(face68, R_EYE_IDXS)
+ nose = face68[NOSE_TIP]
+ lm = face68[MOUTH_L]
+ rm = face68[MOUTH_R]
+ if re[0] < le[0]:
+ le, re = re, le
+ return np.stack([le, re, nose, lm, rm], axis=0)
+
+def _face_scale_only(src68, ref68, target_nose_pos, alpha=1.0, anchor_pairs=[[36, 45], [33, 8]],near_min=0.9, near_max=1.1,
+ near_keep_prob=0.1, push_factor=1.2):
+
+ src = np.asarray(src68, dtype=np.float64)
+ ref = np.asarray(ref68, dtype=np.float64)
+
+
+ center = _anchors(src).mean(axis=0)
+ src_centered = src - center
+
+ src_w = np.linalg.norm(src[anchor_pairs[0][0]] - src[anchor_pairs[0][1]])
+ ref_w = np.linalg.norm(ref[anchor_pairs[0][0]] - ref[anchor_pairs[0][1]])
+
+ src_h = np.linalg.norm(src[anchor_pairs[1][0]] - src[anchor_pairs[1][1]])
+ ref_h = np.linalg.norm(ref[anchor_pairs[1][0]] - ref[anchor_pairs[1][1]])
+
+ scale_x = ref_w / src_w if src_w > 1e-6 else 1.0
+ scale_y = ref_h / src_h if src_h > 1e-6 else 1.0
+
+ def push_if_near(val):
+ if near_min < val < near_max:
+ if np.random.rand() > near_keep_prob:
+ if val >= 1.0:
+ return max(near_max, val * push_factor)
+ else:
+ return min(near_min, val / push_factor)
+ return val
+
+ scale_x = push_if_near(scale_x)
+ scale_y = push_if_near(scale_y)
+
+ scaled_local = src_centered.copy()
+ scaled_local[:, 0] *= (1 - alpha) + scale_x * alpha
+ scaled_local[:, 1] *= (1 - alpha) + scale_y * alpha
+
+ scaled_global = scaled_local + center
+
+ nose_idx = NOSE_TIP
+ current_nose = scaled_global[nose_idx]
+ offset = target_nose_pos - current_nose
+ scaled_global += offset
+
+ return scaled_global
+
+
+def _face_roundify(src68, ref68, strength=1.0):
+
+ src68 = np.asarray(src68, dtype=np.float64).copy()
+ ref68 = np.asarray(ref68, dtype=np.float64)
+
+ src_anchor = _anchors(src68)
+ ref_anchor = _anchors(ref68)
+ A = []
+ B = []
+ for sa, ra in zip(ref_anchor, src_anchor): # 注意顺序:ref -> src
+ A.append([sa[0], sa[1], 1, 0, 0, 0])
+ A.append([0, 0, 0, sa[0], sa[1], 1])
+ B.append(ra[0])
+ B.append(ra[1])
+ A = np.array(A)
+ B = np.array(B)
+ x, *_ = np.linalg.lstsq(A, B, rcond=None)
+ M_ref2src = np.array([
+ [x[0], x[1], x[2]],
+ [x[3], x[4], x[5]]
+ ])
+
+ ones = np.ones((ref68.shape[0], 1))
+ ref68_in_src = np.hstack([ref68, ones]) @ M_ref2src.T
+
+ for idx in JAW_LINE:
+ src68[idx] = (1-strength) * src68[idx] + strength * ref68_in_src[idx]
+
+ return src68
+
+def align_poses_by_limb_scaling_only(
+ ref_pose, detected_poses,
+ limb_change_prob=0.2, # 骨骼变动的概率(20%)
+ face_change_prob=0.8, # 脸部变动的概率(80%)
+ limb_alpha_range=(0.0, 0.8), # 骨骼缩放强度范围
+ face_alpha_range=(0.5, 1.0), # 脸部缩放强度范围
+ min_scale=0.5, max_scale=2.0,
+ face_roundify_strength=1.0,
+ seed=None):
+
+ if not detected_poses:
+ return [], False
+
+ aligned_poses = copy.deepcopy(detected_poses)
+ th = 1e-6
+
+ rng = np.random.RandomState(seed) if seed is not None else np.random
+
+ ref_candidate = ref_pose['bodies']['candidate']
+ source_candidate_for_ratio = detected_poses[0]['bodies']['candidate']
+
+ def get_limb_length(points, p1_idx, p2_idx):
+ return np.linalg.norm(points[p1_idx] - points[p2_idx])
+
+ def make_ratio(p1_idx, p2_idx, coef=1.0, alpha=0.0,
+ near_min=0.9, near_max=1.1,
+ near_keep_prob=0.1, push_factor=1.2):
+ len_ref = get_limb_length(ref_candidate, p1_idx, p2_idx)
+ len_src = get_limb_length(source_candidate_for_ratio, p1_idx, p2_idx)
+ if len_src <= th or len_ref <= th:
+ return 1.0
+
+ target = len_ref / len_src
+ target = float(np.clip(target, min_scale, max_scale))
+
+ if near_min < target < near_max:
+ if np.random.rand() > near_keep_prob:
+ if target >= 1.0:
+ target = max(near_max, target * push_factor)
+ else:
+ target = min(near_min, target / push_factor)
+
+ return (1.0 * (1.0 - alpha) + target * alpha) * coef
+
+ do_limb_change = (random.random() < limb_change_prob)
+ do_face_change = (random.random() < face_change_prob)
+ if do_limb_change:
+ alpha_limb = rng.uniform(*limb_alpha_range)
+ neck_ratio = make_ratio(0, 1, alpha=alpha_limb)
+ r_eye_ratio = make_ratio(0,14, alpha=alpha_limb)
+ l_eye_ratio = make_ratio(0,15, alpha=alpha_limb)
+ r_ear_ratio = make_ratio(14,16, alpha=alpha_limb)
+ l_ear_ratio = make_ratio(15,17, alpha=alpha_limb)
+ else:
+ neck_ratio = r_eye_ratio = l_eye_ratio = r_ear_ratio = l_ear_ratio = 1.0
+
+ has_ref_face = 'faces' in ref_pose and ref_pose['faces'] is not None
+ if has_ref_face:
+ ref68, _ = _to_68x2(ref_pose['faces'])
+
+ for i, pose in enumerate(aligned_poses):
+ candidate = pose['bodies']['candidate']
+
+ if do_limb_change:
+ offset = (candidate[1] - candidate[0]) * (1.0 - neck_ratio)
+ for idx in [0,14,15,16,17]: candidate[idx] += offset
+
+ offset = (candidate[0] - candidate[14]) * (1.0 - r_eye_ratio)
+ for idx in [14,16]: candidate[idx] += offset
+
+ offset = (candidate[0] - candidate[15]) * (1.0 - l_eye_ratio)
+ for idx in [15,17]: candidate[idx] += offset
+
+ offset = (candidate[14] - candidate[16]) * (1.0 - r_ear_ratio)
+ candidate[16] += offset
+
+ offset = (candidate[15] - candidate[17]) * (1.0 - l_ear_ratio)
+ candidate[17] += offset
+
+ if has_ref_face and 'faces' in detected_poses[i] and detected_poses[i]['faces'] is not None:
+
+ if do_face_change or do_limb_change:
+ try:
+ src68, to_orig = _to_68x2(detected_poses[i]['faces'])
+ face_alpha = rng.uniform(*face_alpha_range)
+ scaled68 = _face_scale_only(src68, ref68, candidate[0], alpha=face_alpha)
+ scaled68 = _face_roundify(scaled68, ref68, strength=face_roundify_strength)
+ pose['faces'] = to_orig(scaled68)
+ except Exception as e:
+ print('Face scaling error:', e)
+
+ return aligned_poses, do_limb_change, do_face_change or do_limb_change
+
+
+def _euclid(p1, p2):
+ return np.linalg.norm(p1 - p2)
+
+def align_pose_by_scale_and_translation(ref_pose: dict,
+ tgt_pose: dict,
+ conf_th: float = 0.5):
+ aligned_pose = copy.deepcopy(tgt_pose)
+ th = 1e-6
+
+ if 'bodies' not in ref_pose or 'bodies' not in tgt_pose:
+ print("Warning: 'bodies' key not found in one of the poses. Returning original target pose.")
+ return aligned_pose
+
+ ref_kpt = ref_pose['bodies']['candidate'].astype(np.float32)
+ tgt_kpt = aligned_pose['bodies']['candidate'].astype(np.float32)
+
+ ref_sc = ref_pose['bodies'].get('score', np.ones(ref_kpt.shape[0])).astype(np.float32).reshape(-1)
+ tgt_sc = tgt_pose['bodies'].get('score', np.ones(tgt_kpt.shape[0])).astype(np.float32).reshape(-1)
+
+
+ ref_shoulder_valid = (ref_sc[2] >= conf_th) and (ref_sc[5] >= conf_th)
+ tgt_shoulder_valid = (tgt_sc[2] >= conf_th) and (tgt_sc[5] >= conf_th)
+ shoulder_ok = ref_shoulder_valid and tgt_shoulder_valid
+
+ ref_hip_valid = (ref_sc[8] >= conf_th) and (ref_sc[11] >= conf_th)
+ tgt_hip_valid = (tgt_sc[8] >= conf_th) and (tgt_sc[11] >= conf_th)
+ hip_ok = ref_hip_valid and tgt_hip_valid
+
+ ref_ear_valid = (ref_sc[16] >= conf_th) and (ref_sc[17] >= conf_th)
+ tgt_ear_valid = (tgt_sc[16] >= conf_th) and (tgt_sc[17] >= conf_th)
+ ear_ok = ref_ear_valid and tgt_ear_valid
+
+ x_ratio, y_ratio = 1.0, 1.0
+
+ if shoulder_ok and hip_ok:
+ # print("Scaling strategy: Using separate X (shoulder) and Y (torso) ratios.")
+
+ ref_shoulder_w = abs(ref_kpt[5, 0] - ref_kpt[2, 0])
+ tgt_shoulder_w = abs(tgt_kpt[5, 0] - tgt_kpt[2, 0])
+ x_ratio = ref_shoulder_w / tgt_shoulder_w if tgt_shoulder_w > th else 1.0
+
+ ref_torso_h = abs(np.mean(ref_kpt[[8, 11], 1]) - np.mean(ref_kpt[[2, 5], 1]))
+ tgt_torso_h = abs(np.mean(tgt_kpt[[8, 11], 1]) - np.mean(tgt_kpt[[2, 5], 1]))
+ y_ratio = ref_torso_h / tgt_torso_h if tgt_torso_h > th else 1.0
+
+ elif shoulder_ok:
+ # print("Scaling strategy: Fallback to unified ratio using shoulder distance.")
+ ref_sh_dist = _euclid(ref_kpt[2], ref_kpt[5])
+ tgt_sh_dist = _euclid(tgt_kpt[2], tgt_kpt[5])
+ scale_ratio = ref_sh_dist / tgt_sh_dist if tgt_sh_dist > th else 1.0
+ x_ratio = y_ratio = scale_ratio
+
+ else:
+ # print("Scaling strategy: Fallback to unified ratio using ear distance.")
+ ref_ear_dist = _euclid(ref_kpt[16], ref_kpt[17])
+ tgt_ear_dist = _euclid(tgt_kpt[16], tgt_kpt[17])
+ scale_ratio = ref_ear_dist / tgt_ear_dist if tgt_ear_dist > th else 1.0
+ x_ratio = y_ratio = scale_ratio
+
+ # else:
+ # print("Warning: No reliable keypoints for scaling. Using scale=1.0.")
+
+ anchor_idx = 1
+
+ anchor_pt_before_scale = tgt_kpt[anchor_idx].copy()
+
+ def scale(arr):
+ if arr is not None and arr.size > 0:
+ arr[..., 0] = anchor_pt_before_scale[0] + (arr[..., 0] - anchor_pt_before_scale[0]) * x_ratio
+ arr[..., 1] = anchor_pt_before_scale[1] + (arr[..., 1] - anchor_pt_before_scale[1]) * y_ratio
+
+ scale(tgt_kpt)
+ scale(aligned_pose.get('faces'))
+ scale(aligned_pose.get('hands'))
+
+ offset = ref_kpt[anchor_idx] - tgt_kpt[anchor_idx]
+
+ def translate(arr):
+ if arr is not None and arr.size > 0:
+ arr += offset
+
+ translate(tgt_kpt)
+ translate(aligned_pose.get('faces'))
+ translate(aligned_pose.get('hands'))
+ aligned_pose['bodies']['candidate'] = tgt_kpt
+ return aligned_pose
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/__init__.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..11bb9475fd9b14e8e92ad0d2ea3b4685f4ac87ca
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/__init__.py
@@ -0,0 +1,25 @@
+from .t5 import T5EncoderWrapper
+from opensora.flux_modules import FluxTextEncoderWithMask
+from .hunyuan import HunyuanEncoderWrapper,HunyuanImageEncoderWrapper
+from .hunyuan_i2v import HunyuanEncoderWrapperI2V
+from .wanx_t2v import WanxEncoderWrapperT2V
+from .wanx_i2v import WanxEncoderWrapperI2V
+def get_text_enc(enc_name, model_path, weight_dtype, i2v_type=None):
+ if enc_name == 'flux':
+ return FluxTextEncoderWithMask(model_path, torch_dtype=weight_dtype).eval()
+ elif enc_name == 't5':
+ return T5EncoderWrapper(model_path, weight_dtype)
+ elif enc_name == 'hunyuan':
+ return HunyuanEncoderWrapper(model_path, weight_dtype)
+ elif enc_name == 'hunyuan_image':
+ return HunyuanImageEncoderWrapper(model_path, weight_dtype)
+
+ elif enc_name == 'hunyuan-i2v':
+ return HunyuanEncoderWrapperI2V(model_path, weight_dtype, task = 'i2v', i2v_type = i2v_type)
+ elif enc_name == 'wanx-i2v':
+ return WanxEncoderWrapperI2V(model_path, weight_dtype)
+ elif enc_name == 'wanx-t2v':
+ return WanxEncoderWrapperT2V(model_path, weight_dtype)
+ else:
+ raise NotImplementedError(f'{enc_name} is not implemented.')
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan.py
new file mode 100644
index 0000000000000000000000000000000000000000..8fe590e1aa23f702e38f1eab2ec9dd818ddb0d20
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan.py
@@ -0,0 +1,667 @@
+from dataclasses import dataclass
+from typing import Optional, Tuple
+from copy import deepcopy
+
+import torch
+import torch.nn as nn
+from transformers import CLIPTextModel, CLIPTokenizer, AutoTokenizer, AutoModel
+from transformers.utils import ModelOutput
+from diffusers.pipelines.stable_video_diffusion.pipeline_stable_video_diffusion \
+ import _resize_with_antialiasing, _append_dims
+from transformers import CLIPVisionModelWithProjection, CLIPImageProcessor
+
+# from ..constants import TEXT_ENCODER_PATH, TOKENIZER_PATH
+# from ..constants import PRECISION_TO_TYPE
+
+
+# TEXT_ENCODER_PATH = {
+# "clipL": f"{MODEL_BASE}/text_encoder_2",
+# "llm": f"{MODEL_BASE}/text_encoder",
+# }
+
+# # Tokenizer
+# TOKENIZER_PATH = {
+# "clipL": f"{MODEL_BASE}/text_encoder_2",
+# "llm": f"{MODEL_BASE}/text_encoder",
+# }
+
+def use_default(value, default):
+ return value if value is not None else default
+
+
+def load_text_encoder(
+ text_encoder_type,
+ weight_dtype,
+ text_encoder_path=None,
+ logger=None,
+ device=None,
+):
+ # if text_encoder_path is None:
+ # text_encoder_path = TEXT_ENCODER_PATH[text_encoder_type]
+ if text_encoder_type == 'clipL':
+ text_encoder_path = f"{text_encoder_path}/text_encoder_2"
+ elif text_encoder_type == 'llm':
+ text_encoder_path = f"{text_encoder_path}/text_encoder"
+ if logger is not None:
+ logger.info(
+ f"Loading text encoder model ({text_encoder_type}) from: {text_encoder_path}"
+ )
+
+ if text_encoder_type == "clipL":
+ text_encoder = CLIPTextModel.from_pretrained(text_encoder_path)
+ text_encoder.final_layer_norm = text_encoder.text_model.final_layer_norm
+ elif text_encoder_type == "llm":
+ text_encoder = AutoModel.from_pretrained(
+ text_encoder_path, low_cpu_mem_usage=True
+ # text_encoder_path,
+ )
+ text_encoder.final_layer_norm = text_encoder.norm
+ else:
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
+ # from_pretrained will ensure that the model is in eval mode.
+
+ text_encoder = text_encoder.to(dtype=weight_dtype)
+
+ text_encoder.requires_grad_(False)
+
+ if logger is not None:
+ logger.info(f"Text encoder to dtype: {text_encoder.dtype}")
+
+ if device is not None:
+ text_encoder = text_encoder.to(device)
+
+ return text_encoder, text_encoder_path
+
+
+def load_tokenizer(
+ tokenizer_type, tokenizer_path=None, padding_side="right", logger=None
+):
+ # if tokenizer_type == 'clipL':
+ # tokenizer_path = f"{tokenizer_path}/text_encoder_2"
+ # elif tokenizer_type == 'llm':
+ # tokenizer_path = f"{tokenizer_path}/text_encoder"
+
+ if logger is not None:
+ logger.info(f"Loading tokenizer ({tokenizer_type}) from: {tokenizer_path}")
+
+ if tokenizer_type == "clipL":
+ tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path, max_length=77)
+ elif tokenizer_type == "llm":
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_path, padding_side=padding_side
+ )
+ else:
+ raise ValueError(f"Unsupported tokenizer type: {tokenizer_type}")
+
+ return tokenizer, tokenizer_path
+
+
+@dataclass
+class TextEncoderModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that also contains a pooling of the last hidden states.
+
+ Args:
+ hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
+ hidden_states_list (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
+ text_outputs (`list`, *optional*, returned when `return_texts=True` is passed):
+ List of decoded texts.
+ """
+
+ hidden_state: torch.FloatTensor = None
+ attention_mask: Optional[torch.LongTensor] = None
+ hidden_states_list: Optional[Tuple[torch.FloatTensor, ...]] = None
+ text_outputs: Optional[list] = None
+
+
+class TextEncoder(nn.Module):
+ def __init__(
+ self,
+ text_encoder_type: str,
+ max_length: int,
+ weight_dtype,
+ text_encoder_path: Optional[str] = None,
+ tokenizer_type: Optional[str] = None,
+ tokenizer_path: Optional[str] = None,
+ output_key: Optional[str] = None,
+ use_attention_mask: bool = True,
+ input_max_length: Optional[int] = None,
+ prompt_template: Optional[dict] = None,
+ prompt_template_video: Optional[dict] = None,
+ hidden_state_skip_layer: Optional[int] = None,
+ apply_final_norm: bool = False,
+ reproduce: bool = False,
+ logger=None,
+ device=None,
+ ):
+ super().__init__()
+ self.text_encoder_type = text_encoder_type
+ self.max_length = max_length
+ self.weight_dtype = weight_dtype
+ self.model_path = text_encoder_path
+ self.tokenizer_type = (
+ tokenizer_type if tokenizer_type is not None else text_encoder_type
+ )
+ self.tokenizer_path = (
+ tokenizer_path if tokenizer_path is not None else text_encoder_path
+ )
+ self.use_attention_mask = use_attention_mask
+ if prompt_template_video is not None:
+ assert (
+ use_attention_mask is True
+ ), "Attention mask is True required when training videos."
+ self.input_max_length = (
+ input_max_length if input_max_length is not None else max_length
+ )
+ self.prompt_template = prompt_template
+ self.prompt_template_video = prompt_template_video
+ self.hidden_state_skip_layer = hidden_state_skip_layer
+ self.apply_final_norm = apply_final_norm
+ self.reproduce = reproduce
+ self.logger = logger
+
+ self.use_template = self.prompt_template is not None
+ if self.use_template:
+ assert (
+ isinstance(self.prompt_template, dict)
+ and "template" in self.prompt_template
+ ), f"`prompt_template` must be a dictionary with a key 'template', got {self.prompt_template}"
+ assert "{}" in str(self.prompt_template["template"]), (
+ "`prompt_template['template']` must contain a placeholder `{}` for the input text, "
+ f"got {self.prompt_template['template']}"
+ )
+
+ self.use_video_template = self.prompt_template_video is not None
+ if self.use_video_template:
+ if self.prompt_template_video is not None:
+ assert (
+ isinstance(self.prompt_template_video, dict)
+ and "template" in self.prompt_template_video
+ ), f"`prompt_template_video` must be a dictionary with a key 'template', got {self.prompt_template_video}"
+ assert "{}" in str(self.prompt_template_video["template"]), (
+ "`prompt_template_video['template']` must contain a placeholder `{}` for the input text, "
+ f"got {self.prompt_template_video['template']}"
+ )
+
+ if "t5" in text_encoder_type:
+ self.output_key = output_key or "last_hidden_state"
+ elif "clip" in text_encoder_type:
+ self.output_key = output_key or "pooler_output"
+ elif "llm" in text_encoder_type or "glm" in text_encoder_type:
+ self.output_key = output_key or "last_hidden_state"
+ else:
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
+
+ self.model, self.model_path = load_text_encoder(
+ text_encoder_type=self.text_encoder_type,
+ weight_dtype = self.weight_dtype,
+ text_encoder_path=self.model_path,
+ logger=self.logger,
+ device=device,
+ )
+ self.dtype = self.model.dtype
+ self.device = self.model.device
+
+ self.tokenizer, self.tokenizer_path = load_tokenizer(
+ tokenizer_type=self.tokenizer_type,
+ tokenizer_path=self.model_path,
+ padding_side="right",
+ logger=self.logger,
+ )
+
+ def __repr__(self):
+ return f"{self.text_encoder_type} ({self.weight_dtype} - {self.model_path})"
+
+ @staticmethod
+ def apply_text_to_template(text, template, prevent_empty_text=True):
+ """
+ Apply text to template.
+
+ Args:
+ text (str): Input text.
+ template (str or list): Template string or list of chat conversation.
+ prevent_empty_text (bool): If Ture, we will prevent the user text from being empty
+ by adding a space. Defaults to True.
+ """
+ if isinstance(template, str):
+ # Will send string to tokenizer. Used for llm
+ return template.format(text)
+ else:
+ raise TypeError(f"Unsupported template type: {type(template)}")
+
+ def text2tokens(self, text, data_type="image"):
+ """
+ Tokenize the input text.
+
+ Args:
+ text (str or list): Input text.
+ """
+ tokenize_input_type = "str"
+ if self.use_template:
+ if data_type == "image":
+ prompt_template = self.prompt_template["template"]
+ elif data_type == "video":
+ prompt_template = self.prompt_template_video["template"]
+ else:
+ raise ValueError(f"Unsupported data type: {data_type}")
+ if isinstance(text, (list, tuple)):
+ text = [
+ self.apply_text_to_template(one_text, prompt_template)
+ for one_text in text
+ ]
+ if isinstance(text[0], list):
+ tokenize_input_type = "list"
+ elif isinstance(text, str):
+ text = self.apply_text_to_template(text, prompt_template)
+ if isinstance(text, list):
+ tokenize_input_type = "list"
+ else:
+ raise TypeError(f"Unsupported text type: {type(text)}")
+
+ kwargs = dict(
+ truncation=True,
+ max_length=self.max_length,
+ padding="max_length",
+ return_tensors="pt",
+ )
+ if tokenize_input_type == "str":
+ return self.tokenizer(
+ text,
+ return_length=False,
+ return_overflowing_tokens=False,
+ return_attention_mask=True,
+ **kwargs,
+ )
+ elif tokenize_input_type == "list":
+ return self.tokenizer.apply_chat_template(
+ text,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ **kwargs,
+ )
+ else:
+ raise ValueError(f"Unsupported tokenize_input_type: {tokenize_input_type}")
+
+ def encode(
+ self,
+ batch_encoding,
+ use_attention_mask=None,
+ output_hidden_states=False,
+ do_sample=None,
+ hidden_state_skip_layer=None,
+ return_texts=False,
+ data_type="image",
+ device=None,
+ ):
+ """
+ Args:
+ batch_encoding (dict): Batch encoding from tokenizer.
+ use_attention_mask (bool): Whether to use attention mask. If None, use self.use_attention_mask.
+ Defaults to None.
+ output_hidden_states (bool): Whether to output hidden states. If False, return the value of
+ self.output_key. If True, return the entire output. If set self.hidden_state_skip_layer,
+ output_hidden_states will be set True. Defaults to False.
+ do_sample (bool): Whether to sample from the model. Used for Decoder-Only LLMs. Defaults to None.
+ When self.produce is False, do_sample is set to True by default.
+ hidden_state_skip_layer (int): Number of hidden states to hidden_state_skip_layer. 0 means the last layer.
+ If None, self.output_key will be used. Defaults to None.
+ return_texts (bool): Whether to return the decoded texts. Defaults to False.
+ """
+ device = self.model.device if device is None else device
+ use_attention_mask = use_default(use_attention_mask, self.use_attention_mask)
+ hidden_state_skip_layer = use_default(
+ hidden_state_skip_layer, self.hidden_state_skip_layer
+ )
+ do_sample = use_default(do_sample, not self.reproduce)
+ attention_mask = (
+ batch_encoding["attention_mask"].to(device) if use_attention_mask else None
+ )
+ outputs = self.model(
+ input_ids=batch_encoding["input_ids"].to(device),
+ attention_mask=attention_mask,
+ output_hidden_states=output_hidden_states
+ or hidden_state_skip_layer is not None,
+ )
+ if hidden_state_skip_layer is not None:
+ last_hidden_state = outputs.hidden_states[-(hidden_state_skip_layer + 1)]
+ # Real last hidden state already has layer norm applied. So here we only apply it
+ # for intermediate layers.
+ if hidden_state_skip_layer > 0 and self.apply_final_norm:
+ last_hidden_state = self.model.final_layer_norm(last_hidden_state)
+ else:
+ last_hidden_state = outputs[self.output_key]
+
+ # Remove hidden states of instruction tokens, only keep prompt tokens.
+ if self.use_template:
+ if data_type == "image":
+ crop_start = self.prompt_template.get("crop_start", -1)
+ elif data_type == "video":
+ crop_start = self.prompt_template_video.get("crop_start", -1)
+ else:
+ raise ValueError(f"Unsupported data type: {data_type}")
+ if crop_start > 0:
+ last_hidden_state = last_hidden_state[:, crop_start:]
+ attention_mask = (
+ attention_mask[:, crop_start:] if use_attention_mask else None
+ )
+
+ if output_hidden_states:
+ return TextEncoderModelOutput(
+ last_hidden_state, attention_mask, outputs.hidden_states
+ )
+ return TextEncoderModelOutput(last_hidden_state, attention_mask)
+
+ def forward(
+ self,
+ text,
+ use_attention_mask=None,
+ output_hidden_states=False,
+ do_sample=False,
+ hidden_state_skip_layer=None,
+ return_texts=False,
+ ):
+ batch_encoding = self.text2tokens(text)
+ return self.encode(
+ batch_encoding,
+ use_attention_mask=use_attention_mask,
+ output_hidden_states=output_hidden_states,
+ do_sample=do_sample,
+ hidden_state_skip_layer=hidden_state_skip_layer,
+ return_texts=return_texts,
+ )
+from diffusers.models import ModelMixin
+
+class HunyuanEncoderWrapper(ModelMixin):
+ def __init__(self, model_path, weight_dtype):
+ super().__init__()
+ text_encoder_type_1 = "llm"
+ max_length_1 = 351
+ # weight_dtype = torch.float16 # overwrite,这里是默认如此,先跑通再说
+ tokenizer_type_1 = "llm"
+ prompt_template = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 36}
+ prompt_template_video = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: 1. The main content and theme of the video.2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.4. background environment, light, style and atmosphere.5. camera angles, movements, and transitions used in the video:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95}
+ hidden_state_skip_layer = 2
+ apply_final_norm = False
+ reproduce = False
+ logger = None
+ device = None
+
+ text_encoder_1 = TextEncoder(
+ text_encoder_type=text_encoder_type_1,
+ max_length=max_length_1,
+ weight_dtype=weight_dtype,
+ tokenizer_type=tokenizer_type_1,
+ prompt_template=prompt_template,
+ prompt_template_video=prompt_template_video,
+ hidden_state_skip_layer=hidden_state_skip_layer,
+ apply_final_norm=apply_final_norm,
+ reproduce=reproduce,
+ logger=logger,
+ device=device,
+ text_encoder_path = model_path
+ )
+
+ text_encoder_type_2 = "clipL"
+ text_len_2 = 77
+ tokenizer_2 = 'clipL'
+
+ text_encoder_2 = TextEncoder(
+ text_encoder_type=text_encoder_type_2,
+ max_length=text_len_2,
+ weight_dtype = weight_dtype,
+ tokenizer_type=tokenizer_2,
+ reproduce=reproduce,
+ logger=logger,
+ device=device,
+ text_encoder_path = model_path
+ )
+
+ self.text_encoder_1 = text_encoder_1
+ self.text_encoder_2 = text_encoder_2
+
+ def encode_prompt(
+ self,
+ prompt,
+ device,
+ num_videos_per_prompt = 1,
+ clip_skip: Optional[int] = None,
+ text_encoder: Optional[TextEncoder] = None,
+ data_type: Optional[str] = "image",
+ ):
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type)
+
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(
+ text_inputs, data_type=data_type, device=device
+ )
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(
+ text_inputs,
+ output_hidden_states=True,
+ data_type=data_type,
+ device=device,
+ )
+ # Access the `hidden_states` first, that contains a tuple of
+ # all the hidden states from the encoder layers. Then index into
+ # the tuple to access the hidden states from the desired layer.
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ # We also need to apply the final LayerNorm here to not mess with the
+ # representations. The `last_hidden_states` that we typically use for
+ # obtaining the final prompt representations passes through the LayerNorm
+ # layer.
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(
+ prompt_embeds
+ )
+
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(device)
+ bs_embed, seq_len = attention_mask.shape
+ attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
+ attention_mask = attention_mask.view(
+ bs_embed * num_videos_per_prompt, seq_len
+ )
+
+
+ prompt_embeds_dtype = text_encoder.dtype
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
+
+ if prompt_embeds.ndim == 2:
+ bs_embed, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)
+ else:
+ bs_embed, seq_len, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(
+ bs_embed * num_videos_per_prompt, seq_len, -1
+ )
+ return prompt_embeds, attention_mask
+
+ def forward(self, caption, device=None, max_length=226):
+ prompt_embeds_1, attention_mask_1 = self.encode_prompt(
+ caption,
+ device,
+ data_type = 'video', #TODO: 注意图像和视频需要使用不同的,因为llm里使用不同的template
+ text_encoder = self.text_encoder_1
+ )
+ prompt_embeds_2, attention_mask_2 = self.encode_prompt(
+ caption,
+ device,
+ data_type = 'video', #TODO: 注意图像和视频需要使用不同的,因为llm里使用不同的template
+ text_encoder = self.text_encoder_2
+ )
+ pooled_projections = None
+ return (prompt_embeds_1, prompt_embeds_2), (attention_mask_1, attention_mask_2), pooled_projections
+
+
+
+
+
+class HunyuanImageEncoderWrapper(ModelMixin):
+ def __init__(self, model_path, weight_dtype):
+ super().__init__()
+ text_encoder_type_1 = "llm"
+ max_length_1 = 351
+ # weight_dtype = torch.float16 # overwrite,这里是默认如此,先跑通再说
+ tokenizer_type_1 = "llm"
+ prompt_template = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, quantity, text, spatial relationships of the objects and background:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 36}
+ prompt_template_video = {'template': '<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: 1. The main content and theme of the video.2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects.3. Actions, events, behaviors temporal relationships, physical movement changes of the objects.4. background environment, light, style and atmosphere.5. camera angles, movements, and transitions used in the video:<|eot_id|><|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>', 'crop_start': 95}
+ hidden_state_skip_layer = 2
+ apply_final_norm = False
+ reproduce = False
+ logger = None
+ device = None
+
+ text_encoder_1 = TextEncoder(
+ text_encoder_type=text_encoder_type_1,
+ max_length=max_length_1,
+ weight_dtype=weight_dtype,
+ tokenizer_type=tokenizer_type_1,
+ prompt_template=prompt_template,
+ prompt_template_video=prompt_template_video,
+ hidden_state_skip_layer=hidden_state_skip_layer,
+ apply_final_norm=apply_final_norm,
+ reproduce=reproduce,
+ logger=logger,
+ device=device,
+ text_encoder_path = model_path
+ )
+
+ text_encoder_type_2 = "clipL"
+
+ image_encoder = CLIPVisionModelWithProjection.from_pretrained(
+ model_path, subfolder="text_encoder_2"
+ )
+ feature_extractor = CLIPImageProcessor.from_pretrained(
+ model_path, subfolder="text_encoder_2"
+ )
+
+ self.text_encoder_1 = text_encoder_1
+ self.image_encoder = image_encoder
+ self.feature_extractor = feature_extractor
+
+ def encode_image(self, image, device):
+ # make sure image input is [-1, 1] and [B,C,H,W]
+ image = _resize_with_antialiasing(image, (224, 224))
+ image = (image + 1.0) / 2.0
+
+ # Normalize the image with for CLIP input
+ image = self.feature_extractor(
+ images=image,
+ do_normalize=True,
+ do_center_crop=False,
+ do_resize=False,
+ do_rescale=False,
+ return_tensors="pt",
+ ).pixel_values
+
+ image = image.to(device=device,dtype=self.image_encoder.dtype)
+ image_embeddings = self.image_encoder(image).image_embeds
+ return image_embeddings, None
+
+
+
+ def encode_prompt(
+ self,
+ prompt,
+ device,
+ num_videos_per_prompt = 1,
+ clip_skip: Optional[int] = None,
+ text_encoder: Optional[TextEncoder] = None,
+ data_type: Optional[str] = "image",
+ ):
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type)
+
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(
+ text_inputs, data_type=data_type, device=device
+ )
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(
+ text_inputs,
+ output_hidden_states=True,
+ data_type=data_type,
+ device=device,
+ )
+ # Access the `hidden_states` first, that contains a tuple of
+ # all the hidden states from the encoder layers. Then index into
+ # the tuple to access the hidden states from the desired layer.
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ # We also need to apply the final LayerNorm here to not mess with the
+ # representations. The `last_hidden_states` that we typically use for
+ # obtaining the final prompt representations passes through the LayerNorm
+ # layer.
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(
+ prompt_embeds
+ )
+
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(device)
+ bs_embed, seq_len = attention_mask.shape
+ attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
+ attention_mask = attention_mask.view(
+ bs_embed * num_videos_per_prompt, seq_len
+ )
+
+
+ prompt_embeds_dtype = text_encoder.dtype
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
+
+ if prompt_embeds.ndim == 2:
+ bs_embed, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)
+ else:
+ bs_embed, seq_len, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(
+ bs_embed * num_videos_per_prompt, seq_len, -1
+ )
+ return prompt_embeds, attention_mask
+
+ def forward(self, caption, image, device=None,max_length=226):
+ prompt_embeds_1, attention_mask_1 = self.encode_prompt(
+ caption,
+ device,
+ data_type = 'video', #TODO: 注意图像和视频需要使用不同的,因为llm里使用不同的template
+ text_encoder = self.text_encoder_1
+ )
+ prompt_embeds_2, attention_mask_2 = self.encode_image(
+ image,
+ device,
+ )
+ pooled_projections = None
+ return (prompt_embeds_1, prompt_embeds_2), (attention_mask_1, attention_mask_2), pooled_projections
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan_i2v.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan_i2v.py
new file mode 100644
index 0000000000000000000000000000000000000000..9241a688f64c96244bf6e26ae4e115428f85d168
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/hunyuan_i2v.py
@@ -0,0 +1,746 @@
+from dataclasses import dataclass
+from typing import Optional, Tuple
+from copy import deepcopy
+
+import torch
+import torch.nn as nn
+from transformers import CLIPTextModel, CLIPTokenizer, AutoTokenizer, AutoModel, LlavaForConditionalGeneration, CLIPImageProcessor
+from transformers.utils import ModelOutput
+
+# from ..constants import TEXT_ENCODER_PATH, TOKENIZER_PATH
+# from ..constants import PRECISION_TO_TYPE
+
+
+# TEXT_ENCODER_PATH = {
+# "clipL": f"{MODEL_BASE}/text_encoder_2",
+# "llm": f"{MODEL_BASE}/text_encoder",
+# }
+
+# # Tokenizer
+# TOKENIZER_PATH = {
+# "clipL": f"{MODEL_BASE}/text_encoder_2",
+# "llm": f"{MODEL_BASE}/text_encoder",
+# }
+
+def use_default(value, default):
+ return value if value is not None else default
+
+
+def load_text_encoder(
+ text_encoder_type,
+ text_encoder_precision=None,
+ text_encoder_path=None,
+ logger=None,
+ device=None,
+):
+ # if text_encoder_path is None:
+ # text_encoder_path = TEXT_ENCODER_PATH[text_encoder_type]
+ if text_encoder_type == 'clipL':
+ text_encoder_path = f"{text_encoder_path}/text_encoder_2"
+ elif text_encoder_type == 'llm':
+ text_encoder_path = f"{text_encoder_path}/text_encoder"
+ elif text_encoder_type == 'llm-i2v':
+ text_encoder_path = f"{text_encoder_path}/text_encoder_i2v"
+ if logger is not None:
+ logger.info(
+ f"Loading text encoder model ({text_encoder_type}) from: {text_encoder_path}"
+ )
+
+ if text_encoder_type == "clipL":
+ text_encoder = CLIPTextModel.from_pretrained(text_encoder_path, low_cpu_mem_usage=True)
+ text_encoder.final_layer_norm = text_encoder.text_model.final_layer_norm
+ elif text_encoder_type == "llm":
+ text_encoder = AutoModel.from_pretrained(
+ text_encoder_path, low_cpu_mem_usage=True
+ )
+ text_encoder.final_layer_norm = text_encoder.norm
+ elif text_encoder_type == "llm-i2v":
+ text_encoder = LlavaForConditionalGeneration.from_pretrained(
+ text_encoder_path, low_cpu_mem_usage=True
+ )
+ else:
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
+ # from_pretrained will ensure that the model is in eval mode.
+
+ text_encoder = text_encoder.to(dtype=text_encoder_precision)
+ try:
+ if torch.distributed.get_rank() == 0:
+ text_encoder_dict = text_encoder.state_dict()
+ params = [text_encoder_dict]
+ else:
+ text_encoder_dict = None
+ params = [None]
+ torch.distributed.barrier()
+ torch.distributed.broadcast_object_list(params, 0)
+ if torch.distributed.get_rank() != 0:
+ text_encoder.load_state_dict(params[0])
+ except:
+ pass
+
+ text_encoder.requires_grad_(False)
+ text_encoder.eval()
+ if logger is not None:
+ logger.info(f"Text encoder to dtype: {text_encoder.dtype}")
+
+ if device is not None:
+ text_encoder = text_encoder.to(device)
+
+ return text_encoder, text_encoder_path
+
+
+def load_tokenizer(
+ tokenizer_type, tokenizer_path=None, padding_side="right", logger=None
+):
+ if tokenizer_type == 'clipL':
+ tokenizer_path = f"{tokenizer_path}/text_encoder_2"
+ elif tokenizer_type == 'llm-i2v':
+ tokenizer_path = f"{tokenizer_path}/text_encoder_i2v"
+
+ if logger is not None:
+ logger.info(f"Loading tokenizer ({tokenizer_type}) from: {tokenizer_path}")
+
+ processor = None
+ if tokenizer_type == "clipL":
+ tokenizer = CLIPTokenizer.from_pretrained(tokenizer_path, max_length=77)
+ elif tokenizer_type == "llm":
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_path, padding_side=padding_side
+ )
+ elif tokenizer_type == "llm-i2v":
+ tokenizer = AutoTokenizer.from_pretrained(
+ tokenizer_path, padding_side=padding_side
+ )
+ processor = CLIPImageProcessor.from_pretrained(tokenizer_path)
+ else:
+ raise ValueError(f"Unsupported tokenizer type: {tokenizer_type}")
+
+ return tokenizer, tokenizer_path, processor
+
+
+@dataclass
+class TextEncoderModelOutput(ModelOutput):
+ """
+ Base class for model's outputs that also contains a pooling of the last hidden states.
+
+ Args:
+ hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
+ Sequence of hidden-states at the output of the last layer of the model.
+ attention_mask (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
+ Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
+ hidden_states_list (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed):
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
+ text_outputs (`list`, *optional*, returned when `return_texts=True` is passed):
+ List of decoded texts.
+ """
+
+ hidden_state: torch.FloatTensor = None
+ attention_mask: Optional[torch.LongTensor] = None
+ hidden_states_list: Optional[Tuple[torch.FloatTensor, ...]] = None
+ text_outputs: Optional[list] = None
+
+
+class TextEncoder(nn.Module):
+ def __init__(
+ self,
+ text_encoder_type: str,
+ max_length: int,
+ text_encoder_precision: Optional[str] = None,
+ text_encoder_path: Optional[str] = None,
+ tokenizer_type: Optional[str] = None,
+ tokenizer_path: Optional[str] = None,
+ output_key: Optional[str] = None,
+ use_attention_mask: bool = True,
+ i2v_mode: bool = False,
+ input_max_length: Optional[int] = None,
+ prompt_template: Optional[dict] = None,
+ prompt_template_video: Optional[dict] = None,
+ hidden_state_skip_layer: Optional[int] = None,
+ apply_final_norm: bool = False,
+ reproduce: bool = False,
+ logger=None,
+ device=None,
+ image_embed_interleave=None,
+ ):
+ super().__init__()
+ self.text_encoder_type = text_encoder_type
+ self.max_length = max_length
+ self.precision = text_encoder_precision
+ self.model_path = text_encoder_path
+ self.tokenizer_type = (
+ tokenizer_type if tokenizer_type is not None else text_encoder_type
+ )
+ self.tokenizer_path = (
+ tokenizer_path if tokenizer_path is not None else text_encoder_path
+ )
+ self.use_attention_mask = use_attention_mask
+ if prompt_template_video is not None:
+ assert (
+ use_attention_mask is True
+ ), "Attention mask is True required when training videos."
+ self.input_max_length = (
+ input_max_length if input_max_length is not None else max_length
+ )
+ self.prompt_template = prompt_template
+ self.prompt_template_video = prompt_template_video
+ self.hidden_state_skip_layer = hidden_state_skip_layer
+ self.apply_final_norm = apply_final_norm
+ self.i2v_mode = i2v_mode
+ self.reproduce = reproduce
+ self.logger = logger
+ self.image_embed_interleave = image_embed_interleave
+
+ self.use_template = self.prompt_template is not None
+ if self.use_template:
+ assert (
+ isinstance(self.prompt_template, dict)
+ and "template" in self.prompt_template
+ ), f"`prompt_template` must be a dictionary with a key 'template', got {self.prompt_template}"
+ assert "{}" in str(self.prompt_template["template"]), (
+ "`prompt_template['template']` must contain a placeholder `{}` for the input text, "
+ f"got {self.prompt_template['template']}"
+ )
+
+ self.use_video_template = self.prompt_template_video is not None
+ if self.use_video_template:
+ if self.prompt_template_video is not None:
+ assert (
+ isinstance(self.prompt_template_video, dict)
+ and "template" in self.prompt_template_video
+ ), f"`prompt_template_video` must be a dictionary with a key 'template', got {self.prompt_template_video}"
+ assert "{}" in str(self.prompt_template_video["template"]), (
+ "`prompt_template_video['template']` must contain a placeholder `{}` for the input text, "
+ f"got {self.prompt_template_video['template']}"
+ )
+
+ if "t5" in text_encoder_type:
+ self.output_key = output_key or "last_hidden_state"
+ elif "clip" in text_encoder_type:
+ self.output_key = output_key or "pooler_output"
+ elif "llm" in text_encoder_type or "glm" in text_encoder_type:
+ self.output_key = output_key or "last_hidden_state"
+ else:
+ raise ValueError(f"Unsupported text encoder type: {text_encoder_type}")
+
+ self.model, self.model_path = load_text_encoder(
+ text_encoder_type=self.text_encoder_type,
+ text_encoder_precision=self.precision,
+ text_encoder_path=self.model_path,
+ logger=self.logger,
+ device=device,
+ )
+ self.dtype = self.model.dtype
+ self.device = self.model.device
+
+ self.tokenizer, self.tokenizer_path, self.processor = load_tokenizer(
+ tokenizer_type=self.tokenizer_type,
+ tokenizer_path=self.tokenizer_path,
+ padding_side="right",
+ logger=self.logger,
+ )
+
+ def __repr__(self):
+ return f"{self.text_encoder_type} ({self.precision} - {self.model_path})"
+
+ @staticmethod
+ def apply_text_to_template(text, template, prevent_empty_text=True):
+ """
+ Apply text to template.
+
+ Args:
+ text (str): Input text.
+ template (str or list): Template string or list of chat conversation.
+ prevent_empty_text (bool): If Ture, we will prevent the user text from being empty
+ by adding a space. Defaults to True.
+ """
+ if isinstance(template, str):
+ # Will send string to tokenizer. Used for llm
+ return template.format(text)
+ else:
+ raise TypeError(f"Unsupported template type: {type(template)}")
+
+ def text2tokens(self, text, data_type="image"):
+ """
+ Tokenize the input text.
+
+ Args:
+ text (str or list): Input text.
+ """
+ tokenize_input_type = "str"
+ if self.use_template:
+ if data_type == "image":
+ prompt_template = self.prompt_template["template"]
+ elif data_type == "video":
+ prompt_template = self.prompt_template_video["template"]
+ else:
+ raise ValueError(f"Unsupported data type: {data_type}")
+ if isinstance(text, (list, tuple)):
+ text = [
+ self.apply_text_to_template(one_text, prompt_template)
+ for one_text in text
+ ]
+ if isinstance(text[0], list):
+ tokenize_input_type = "list"
+ elif isinstance(text, str):
+ text = self.apply_text_to_template(text, prompt_template)
+ if isinstance(text, list):
+ tokenize_input_type = "list"
+ else:
+ raise TypeError(f"Unsupported text type: {type(text)}")
+
+ kwargs = dict(
+ truncation=True,
+ max_length=self.max_length,
+ padding="max_length",
+ return_tensors="pt",
+ )
+ if tokenize_input_type == "str":
+ return self.tokenizer(
+ text,
+ return_length=False,
+ return_overflowing_tokens=False,
+ return_attention_mask=True,
+ **kwargs,
+ )
+ elif tokenize_input_type == "list":
+ return self.tokenizer.apply_chat_template(
+ text,
+ add_generation_prompt=True,
+ tokenize=True,
+ return_dict=True,
+ **kwargs,
+ )
+ else:
+ raise ValueError(f"Unsupported tokenize_input_type: {tokenize_input_type}")
+
+ def encode(
+ self,
+ batch_encoding,
+ use_attention_mask=None,
+ output_hidden_states=False,
+ do_sample=None,
+ hidden_state_skip_layer=None,
+ return_texts=False,
+ data_type="image",
+ semantic_images=None,
+ device=None,
+ ):
+ """
+ Args:
+ batch_encoding (dict): Batch encoding from tokenizer.
+ use_attention_mask (bool): Whether to use attention mask. If None, use self.use_attention_mask.
+ Defaults to None.
+ output_hidden_states (bool): Whether to output hidden states. If False, return the value of
+ self.output_key. If True, return the entire output. If set self.hidden_state_skip_layer,
+ output_hidden_states will be set True. Defaults to False.
+ do_sample (bool): Whether to sample from the model. Used for Decoder-Only LLMs. Defaults to None.
+ When self.produce is False, do_sample is set to True by default.
+ hidden_state_skip_layer (int): Number of hidden states to hidden_state_skip_layer. 0 means the last layer.
+ If None, self.output_key will be used. Defaults to None.
+ hidden_state_skip_layer (PIL.Image): The reference images for i2v models.
+ return_texts (bool): Whether to return the decoded texts. Defaults to False.
+ """
+ device = self.model.device if device is None else device
+ use_attention_mask = use_default(use_attention_mask, self.use_attention_mask)
+ hidden_state_skip_layer = use_default(
+ hidden_state_skip_layer, self.hidden_state_skip_layer
+ )
+ do_sample = use_default(do_sample, not self.reproduce)
+ if not self.i2v_mode:
+ attention_mask = (
+ batch_encoding["attention_mask"].to(device)
+ if use_attention_mask
+ else None
+ )
+ outputs = self.model(
+ input_ids=batch_encoding["input_ids"].to(device),
+ attention_mask=attention_mask,
+ output_hidden_states=output_hidden_states
+ or hidden_state_skip_layer is not None,
+ )
+ if hidden_state_skip_layer is not None:
+ last_hidden_state = outputs.hidden_states[
+ -(hidden_state_skip_layer + 1)
+ ]
+ # Real last hidden state already has layer norm applied. So here we only apply it
+ # for intermediate layers.
+ if hidden_state_skip_layer > 0 and self.apply_final_norm:
+ last_hidden_state = self.model.final_layer_norm(last_hidden_state)
+ else:
+ last_hidden_state = outputs[self.output_key]
+
+ # Remove hidden states of instruction tokens, only keep prompt tokens.
+ if self.use_template:
+ if data_type == "image":
+ crop_start = self.prompt_template.get("crop_start", -1)
+ elif data_type == "video":
+ crop_start = self.prompt_template_video.get("crop_start", -1)
+ else:
+ raise ValueError(f"Unsupported data type: {data_type}")
+ if crop_start > 0:
+ last_hidden_state = last_hidden_state[:, crop_start:]
+ attention_mask = (
+ attention_mask[:, crop_start:] if use_attention_mask else None
+ )
+
+ if output_hidden_states:
+ return TextEncoderModelOutput(
+ last_hidden_state, attention_mask, outputs.hidden_states
+ )
+ return TextEncoderModelOutput(last_hidden_state, attention_mask)
+ else:
+ image_outputs = self.processor(semantic_images, return_tensors="pt")[
+ "pixel_values"
+ ].to(device=device, dtype=self.precision)
+ attention_mask = (
+ batch_encoding["attention_mask"].to(device)
+ if use_attention_mask
+ else None
+ )
+ outputs = self.model(
+ input_ids=batch_encoding["input_ids"].to(device),
+ attention_mask=attention_mask,
+ output_hidden_states=output_hidden_states
+ or hidden_state_skip_layer is not None,
+ pixel_values=image_outputs,
+ )
+ if hidden_state_skip_layer is not None:
+ last_hidden_state = outputs.hidden_states[
+ -(hidden_state_skip_layer + 1)
+ ]
+ # Real last hidden state already has layer norm applied. So here we only apply it
+ # for intermediate layers.
+ if hidden_state_skip_layer > 0 and self.apply_final_norm:
+ last_hidden_state = self.model.final_layer_norm(last_hidden_state)
+ else:
+ last_hidden_state = outputs[self.output_key]
+ if self.use_template:
+ if data_type == "video":
+ crop_start = self.prompt_template_video.get("crop_start", -1)
+ text_crop_start = (
+ crop_start
+ - 1
+ + self.prompt_template_video.get("image_emb_len", 576)
+ )
+ image_crop_start = self.prompt_template_video.get(
+ "image_emb_start", 5
+ )
+ image_crop_end = self.prompt_template_video.get(
+ "image_emb_end", 581
+ )
+ batch_indices, last_double_return_token_indices = torch.where(
+ batch_encoding["input_ids"]
+ == self.prompt_template_video.get("double_return_token_id", 271)
+ )
+ if last_double_return_token_indices.shape[0] == 3:
+ # in case the prompt is too long
+ last_double_return_token_indices = torch.cat(
+ (
+ last_double_return_token_indices,
+ torch.tensor([batch_encoding["input_ids"].shape[-1]]).to(
+ device=last_double_return_token_indices.device),
+ )
+ )
+ last_double_return_token_indices = (
+ last_double_return_token_indices.reshape(
+ batch_encoding["input_ids"].shape[0], -1
+ )[:, -1]
+ )
+ assistant_crop_start = (
+ last_double_return_token_indices
+ - 1
+ + self.prompt_template_video.get("image_emb_len", 576)
+ - 4
+ )
+ assistant_crop_end = (
+ last_double_return_token_indices
+ - 1
+ + self.prompt_template_video.get("image_emb_len", 576)
+ )
+ attention_mask_assistant_crop_start = (
+ last_double_return_token_indices - 4
+ )
+ attention_mask_assistant_crop_end = last_double_return_token_indices
+ else:
+ raise ValueError(f"Unsupported data type: {data_type}")
+
+ text_last_hidden_state = []
+ text_attention_mask = []
+ image_last_hidden_state = []
+ image_attention_mask = []
+ for i in range(batch_encoding["input_ids"].shape[0]):
+ text_last_hidden_state.append(
+ torch.cat(
+ [
+ last_hidden_state[
+ i, text_crop_start : assistant_crop_start[i].item()
+ ],
+ last_hidden_state[i, assistant_crop_end[i].item() :],
+ ]
+ )
+ )
+ text_attention_mask.append(
+ torch.cat(
+ [
+ attention_mask[
+ i,
+ crop_start : attention_mask_assistant_crop_start[
+ i
+ ].item(),
+ ],
+ attention_mask[
+ i, attention_mask_assistant_crop_end[i].item() :
+ ],
+ ]
+ )
+ if use_attention_mask
+ else None
+ )
+ image_last_hidden_state.append(
+ last_hidden_state[i, image_crop_start:image_crop_end]
+ )
+ image_attention_mask.append(
+ torch.ones(image_last_hidden_state[-1].shape[0])
+ .to(last_hidden_state.device)
+ .to(attention_mask.dtype)
+ if use_attention_mask
+ else None
+ )
+
+ text_last_hidden_state = torch.stack(text_last_hidden_state)
+ text_attention_mask = torch.stack(text_attention_mask)
+ image_last_hidden_state = torch.stack(image_last_hidden_state)
+ image_attention_mask = torch.stack(image_attention_mask)
+
+ if semantic_images is not None and 0 < self.image_embed_interleave < 6:
+ image_last_hidden_state = image_last_hidden_state[
+ :, ::self.image_embed_interleave, :
+ ]
+ image_attention_mask = image_attention_mask[
+ :, ::self.image_embed_interleave
+ ]
+
+ assert (
+ text_last_hidden_state.shape[0] == text_attention_mask.shape[0]
+ and image_last_hidden_state.shape[0]
+ == image_attention_mask.shape[0]
+ )
+
+ last_hidden_state = torch.cat(
+ [image_last_hidden_state, text_last_hidden_state], dim=1
+ )
+ attention_mask = torch.cat(
+ [image_attention_mask, text_attention_mask], dim=1
+ )
+ if output_hidden_states:
+ return TextEncoderModelOutput(
+ last_hidden_state,
+ attention_mask,
+ hidden_states_list=outputs.hidden_states,
+ )
+ return TextEncoderModelOutput(last_hidden_state, attention_mask)
+
+ def forward(
+ self,
+ text,
+ use_attention_mask=None,
+ output_hidden_states=False,
+ do_sample=False,
+ hidden_state_skip_layer=None,
+ return_texts=False,
+ ):
+ batch_encoding = self.text2tokens(text)
+ return self.encode(
+ batch_encoding,
+ use_attention_mask=use_attention_mask,
+ output_hidden_states=output_hidden_states,
+ do_sample=do_sample,
+ hidden_state_skip_layer=hidden_state_skip_layer,
+ return_texts=return_texts,
+ )
+from diffusers.models import ModelMixin
+PROMPT_TEMPLATE_ENCODE = (
+ "<|start_header_id|>system<|end_header_id|>\n\nDescribe the image by detailing the color, shape, size, texture, "
+ "quantity, text, spatial relationships of the objects and background:<|eot_id|>"
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
+)
+PROMPT_TEMPLATE_ENCODE_VIDEO = (
+ "<|start_header_id|>system<|end_header_id|>\n\nDescribe the video by detailing the following aspects: "
+ "1. The main content and theme of the video."
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
+ "4. background environment, light, style and atmosphere."
+ "5. camera angles, movements, and transitions used in the video:<|eot_id|>"
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
+)
+
+PROMPT_TEMPLATE_ENCODE_I2V = (
+ "<|start_header_id|>system<|end_header_id|>\n\n\nDescribe the image by detailing the color, shape, size, texture, "
+ "quantity, text, spatial relationships of the objects and background:<|eot_id|>"
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
+ "<|start_header_id|>assistant<|end_header_id|>\n\n"
+)
+
+PROMPT_TEMPLATE_ENCODE_VIDEO_I2V = (
+ "<|start_header_id|>system<|end_header_id|>\n\n\nDescribe the video by detailing the following aspects according to the reference image: "
+ "1. The main content and theme of the video."
+ "2. The color, shape, size, texture, quantity, text, and spatial relationships of the objects."
+ "3. Actions, events, behaviors temporal relationships, physical movement changes of the objects."
+ "4. background environment, light, style and atmosphere."
+ "5. camera angles, movements, and transitions used in the video:<|eot_id|>\n\n"
+ "<|start_header_id|>user<|end_header_id|>\n\n{}<|eot_id|>"
+ "<|start_header_id|>assistant<|end_header_id|>\n\n"
+)
+class HunyuanEncoderWrapperI2V(ModelMixin):
+ def __init__(self, model_path, weight_dtype, task='i2v', i2v_type = 'concat'):
+ super().__init__()
+ text_encoder_type_1 = "llm-i2v"
+ # weight_dtype = torch.float16 # overwrite,这里是默认如此,先跑通再说
+ tokenizer_type_1 = "llm-i2v"
+ prompt_template = {'template': PROMPT_TEMPLATE_ENCODE_I2V, 'crop_start': 36, "image_emb_start": 5,"image_emb_end": 581,"image_emb_len": 576,
+ "double_return_token_id": 271}
+ prompt_template_video = {"template": PROMPT_TEMPLATE_ENCODE_VIDEO_I2V, "crop_start": 103,"image_emb_start": 5,"image_emb_end": 581,"image_emb_len": 576,
+ "double_return_token_id": 271}
+ max_length_1 = 256 + (
+ prompt_template_video.get("crop_start", 0)
+ if prompt_template_video is not None
+ else prompt_template.get("crop_start", 0)
+ if prompt_template is not None
+ else 0
+ )
+ # print("text len1:", max_length_1)
+ hidden_state_skip_layer = 2
+ text_encoder_precision = "fp16"
+ apply_final_norm = False
+ reproduce = False
+ logger = None
+ device = None
+
+ text_encoder_1 = TextEncoder(
+ text_encoder_type=text_encoder_type_1,
+ max_length=max_length_1,
+ text_encoder_precision=weight_dtype,
+ tokenizer_type=tokenizer_type_1,
+ i2v_mode = True,
+ prompt_template=prompt_template,
+ prompt_template_video=prompt_template_video,
+ hidden_state_skip_layer=hidden_state_skip_layer,
+ apply_final_norm=apply_final_norm,
+ reproduce=reproduce,
+ logger=logger,
+ device=device,
+ text_encoder_path = model_path,
+ image_embed_interleave = 2 if i2v_type == 'concat' else 4
+ )
+
+ text_encoder_type_2 = "clipL"
+ text_len_2 = 77
+ tokenizer_2 = 'clipL'
+
+ text_encoder_2 = TextEncoder(
+ text_encoder_type=text_encoder_type_2,
+ max_length=text_len_2,
+ tokenizer_type=tokenizer_2,
+ text_encoder_precision=weight_dtype,
+ reproduce=reproduce,
+ logger=logger,
+ device=device,
+ text_encoder_path = model_path,
+ image_embed_interleave = 2 if i2v_type == 'concat' else 4
+ )
+
+ self.text_encoder_1 = text_encoder_1
+ self.text_encoder_2 = text_encoder_2
+
+ def encode_prompt(
+ self,
+ prompt,
+ device,
+ num_videos_per_prompt = 1,
+ clip_skip: Optional[int] = None,
+ text_encoder: Optional[TextEncoder] = None,
+ data_type: Optional[str] = "image",
+ semantic_images=None
+ ):
+ if prompt is not None and isinstance(prompt, str):
+ batch_size = 1
+ elif prompt is not None and isinstance(prompt, list):
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+
+ text_inputs = text_encoder.text2tokens(prompt, data_type=data_type)
+
+ if clip_skip is None:
+ prompt_outputs = text_encoder.encode(
+ text_inputs, data_type=data_type, device=device, semantic_images=semantic_images,
+ )
+ prompt_embeds = prompt_outputs.hidden_state
+ else:
+ prompt_outputs = text_encoder.encode(
+ text_inputs,
+ output_hidden_states=True,
+ data_type=data_type,
+ device=device,
+ semantic_images=semantic_images
+ )
+ # Access the `hidden_states` first, that contains a tuple of
+ # all the hidden states from the encoder layers. Then index into
+ # the tuple to access the hidden states from the desired layer.
+ prompt_embeds = prompt_outputs.hidden_states_list[-(clip_skip + 1)]
+ # We also need to apply the final LayerNorm here to not mess with the
+ # representations. The `last_hidden_states` that we typically use for
+ # obtaining the final prompt representations passes through the LayerNorm
+ # layer.
+ prompt_embeds = text_encoder.model.text_model.final_layer_norm(
+ prompt_embeds
+ )
+
+ attention_mask = prompt_outputs.attention_mask
+ if attention_mask is not None:
+ attention_mask = attention_mask.to(device)
+ bs_embed, seq_len = attention_mask.shape
+ attention_mask = attention_mask.repeat(1, num_videos_per_prompt)
+ attention_mask = attention_mask.view(
+ bs_embed * num_videos_per_prompt, seq_len
+ )
+
+
+ prompt_embeds_dtype = text_encoder.dtype
+ prompt_embeds = prompt_embeds.to(dtype=prompt_embeds_dtype, device=device)
+
+ if prompt_embeds.ndim == 2:
+ bs_embed, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt)
+ prompt_embeds = prompt_embeds.view(bs_embed * num_videos_per_prompt, -1)
+ else:
+ bs_embed, seq_len, _ = prompt_embeds.shape
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(
+ bs_embed * num_videos_per_prompt, seq_len, -1
+ )
+ return prompt_embeds, attention_mask
+
+ def forward(self, caption, semantic_images, device=None, max_length=226):
+ prompt_embeds_1, attention_mask_1 = self.encode_prompt(
+ caption,
+ device,
+ data_type = 'video', #TODO: 注意图像和视频需要使用不同的,因为llm里使用不同的template
+ text_encoder = self.text_encoder_1,
+ semantic_images = semantic_images
+ )
+ prompt_embeds_2, attention_mask_2 = self.encode_prompt(
+ caption,
+ device,
+ data_type = 'video', #TODO: 注意图像和视频需要使用不同的,因为llm里使用不同的template
+ text_encoder = self.text_encoder_2,
+ semantic_images = None
+ )
+ pooled_projections = None
+ return (prompt_embeds_1, prompt_embeds_2), (attention_mask_1, attention_mask_2), pooled_projections
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/t5.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/t5.py
new file mode 100644
index 0000000000000000000000000000000000000000..d68b6abe717991d016e518de13783aaef74264a1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/t5.py
@@ -0,0 +1,28 @@
+import torch
+import torch.nn as nn
+from transformers import T5EncoderModel, T5Tokenizer
+
+class T5EncoderWrapper(nn.Module):
+ def __init__(self, model_path, weight_dtype):
+ super().__init__()
+ self.text_encoder = T5EncoderModel.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder='text_encoder').eval()
+ self.tokenizer = T5Tokenizer.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder = 'tokenizer')
+ self.text_encoder.requires_grad_(False)
+
+ def forward(self, caption, device=None, max_length=226):
+ caption = [caption] if isinstance(caption, str) else caption
+ text_inputs = self.tokenizer(
+ caption, #convert to list if not
+ padding="max_length",
+ max_length=max_length,
+ truncation=True,
+ add_special_tokens=True,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ prompt_attention_mask = text_inputs.attention_mask
+ prompt_attention_mask = prompt_attention_mask.bool().to(device)
+ cond = self.text_encoder(text_input_ids.to(device))[0]
+ cond_mask = prompt_attention_mask
+ pooled_projections = None
+ return cond, cond_mask, pooled_projections
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_i2v.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_i2v.py
new file mode 100644
index 0000000000000000000000000000000000000000..b8e6e0749cea7600db18dcfe2c7b11fe05d1d18e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_i2v.py
@@ -0,0 +1,108 @@
+import torch
+import torch.nn as nn
+from transformers import AutoTokenizer, CLIPImageProcessor, CLIPVisionModel, UMT5EncoderModel
+from torchvision.transforms.functional import to_pil_image
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+from opensora.utils.utils import center_square_crop
+class WanxEncoderWrapperI2V(nn.Module):
+ def __init__(self, model_path, weight_dtype):
+ super().__init__()
+ self.text_encoder = UMT5EncoderModel.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder='text_encoder').eval()
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder = 'tokenizer')
+ self.text_encoder.requires_grad_(False)
+ self.image_encoder = CLIPVisionModel.from_pretrained(
+ model_path, subfolder="image_encoder", torch_dtype=weight_dtype
+ ).eval()
+ self.image_encoder.requires_grad_(False)
+ self.image_processor = CLIPImageProcessor.from_pretrained(
+ model_path, subfolder="image_processor"
+ )
+
+ def _get_t5_prompt_embeds(
+ self,
+ prompt: Union[str, List[str]] = None,
+ num_videos_per_prompt: int = 1,
+ max_sequence_length: int = 512,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ):
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ batch_size = len(prompt)
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=max_sequence_length,
+ truncation=True,
+ add_special_tokens=True,
+ return_attention_mask=True,
+ return_tensors="pt",
+ )
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
+ seq_lens = mask.gt(0).sum(dim=1).long()
+
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
+ prompt_embeds = torch.stack(
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
+ )
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ _, seq_len, _ = prompt_embeds.shape
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
+ return prompt_embeds
+
+
+ def encode_image(
+ self,
+ image,
+ device: Optional[torch.device] = None,
+ ):
+ device = device
+
+ # import pdb; pdb.set_trace()
+ image = self.image_processor(images=image, return_tensors="pt").to(device)
+ image_embeds = self.image_encoder(**image, output_hidden_states=True)
+ return image_embeds.hidden_states[-2]
+
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
+ def encode_prompt(
+ self,
+ prompt: Union[str, List[str]],
+ num_videos_per_prompt: int = 1,
+ prompt_embeds: Optional[torch.Tensor] = None,
+ max_sequence_length: int = 226,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ):
+
+
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ if prompt is not None:
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ if prompt_embeds is None:
+ prompt_embeds = self._get_t5_prompt_embeds(
+ prompt=prompt,
+ num_videos_per_prompt=num_videos_per_prompt,
+ max_sequence_length=max_sequence_length,
+ device=device,
+ dtype=dtype,
+ )
+ return prompt_embeds
+
+
+
+ def forward(self, caption, image, device=None, max_length=226):
+ # make sure image in Tensor [-1,1]
+ caption = [caption] if isinstance(caption, str) else caption
+ cond = self.encode_prompt(caption, device= device, max_sequence_length=max_length)
+ image = to_pil_image(((image + 1) / 2.).clamp(0, 1))
+ # image_crop =
+ croped_image = center_square_crop(image)
+ image_cond = self.encode_image(croped_image, device=device)
+ return cond, image_cond, croped_image
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_t2v.py b/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_t2v.py
new file mode 100644
index 0000000000000000000000000000000000000000..9d084af7856a5cca2bf80eb151e3ce74365f48ef
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/encoder_variants/wanx_t2v.py
@@ -0,0 +1,117 @@
+import torch
+import torch.nn as nn
+from transformers import AutoTokenizer, UMT5EncoderModel
+from typing import Any, Callable, Dict, List, Optional, Tuple, Union
+import os
+class WanxEncoderWrapperT2V(nn.Module):
+ def __init__(self, model_path, weight_dtype):
+ super().__init__()
+ self.text_encoder = UMT5EncoderModel.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder='text_encoder').eval()
+ self.tokenizer = AutoTokenizer.from_pretrained(model_path, torch_dtype=weight_dtype, subfolder = 'tokenizer')
+ self.text_encoder.requires_grad_(False)
+ # Load null text embeddings if available
+ self.null_text_embedding = None
+ null_embed_path = os.path.join(model_path, 'null_text_embedding.pt')
+ if os.path.exists(null_embed_path):
+ self.null_text_embedding = torch.load(null_embed_path).to(dtype=weight_dtype)
+
+ def _get_t5_prompt_embeds(
+ self,
+ prompt: Union[str, List[str]] = None,
+ num_videos_per_prompt: int = 1,
+ max_sequence_length: int = 512,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ):
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ batch_size = len(prompt)
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=max_sequence_length,
+ truncation=True,
+ add_special_tokens=True,
+ return_attention_mask=True,
+ return_tensors="pt",
+ )
+ text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
+ seq_lens = mask.gt(0).sum(dim=1).long()
+
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), mask.to(device)).last_hidden_state
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
+ prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
+ prompt_embeds = torch.stack(
+ [torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))]) for u in prompt_embeds], dim=0
+ )
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ _, seq_len, _ = prompt_embeds.shape
+ prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(batch_size * num_videos_per_prompt, seq_len, -1)
+ return prompt_embeds
+
+ # Copied from diffusers.pipelines.wan.pipeline_wan.WanPipeline.encode_prompt
+ def encode_prompt(
+ self,
+ prompt: Union[str, List[str]],
+ num_videos_per_prompt: int = 1,
+ prompt_embeds: Optional[torch.Tensor] = None,
+ max_sequence_length: int = 226,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ):
+
+
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ if prompt is not None:
+ batch_size = len(prompt)
+ else:
+ batch_size = prompt_embeds.shape[0]
+
+ if prompt_embeds is None:
+ prompt_embeds = self._get_t5_prompt_embeds(
+ prompt=prompt,
+ num_videos_per_prompt=num_videos_per_prompt,
+ max_sequence_length=max_sequence_length,
+ device=device,
+ dtype=dtype,
+ )
+ return prompt_embeds
+
+
+
+ def forward(self, caption, device=None, max_length=226):
+ if caption == "" or [""] and self.null_text_embedding is not None:
+ return self.null_text_embedding.to(device=device)
+ caption = [caption] if isinstance(caption, str) else caption
+ cond = self.encode_prompt(caption, device= device, max_sequence_length=max_length)
+ return cond
+
+def save_null_text_embedding(model_path, max_length=226):
+ """Save null text embeddings for empty strings"""
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
+ dtype = torch.float16 if torch.cuda.is_available() else torch.float32
+
+ # Initialize model
+ model = WanxEncoderWrapperT2V(model_path, weight_dtype=dtype)
+ model.to(device)
+
+ # Get embeddings for empty string
+ null_embedding = model.encode_prompt(
+ prompt="",
+ max_sequence_length=max_length,
+ device=device,
+ dtype=dtype
+ )
+ print("null_embedding.shape",null_embedding.shape)
+ # import pdb;pdb.set_trace()
+ # Save the embeddings
+ null_embedding = null_embedding.cpu()
+ save_path = os.path.join(model_path, 'null_text_embedding.pt')
+ torch.save(null_embedding, save_path)
+ print(f"Saved null text embeddings to {save_path}")
+
+if __name__ == "__main__":
+ model_path = "../pretrained_models/Wan2.1-T2V-1.3B-Diffusers/"
+ save_null_text_embedding(model_path)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/cal_flolpips.py b/One-to-All-Animation/video-generation/opensora/eval/cal_flolpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..eaf7ca9e17f059aad99157881de6304cc0a14d44
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/cal_flolpips.py
@@ -0,0 +1,83 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+from einops import rearrange
+import sys
+sys.path.append(".")
+from opensora.eval.flolpips.pwcnet import Network as PWCNet
+from opensora.eval.flolpips.flolpips import FloLPIPS
+
+loss_fn = FloLPIPS(net='alex', version='0.1').eval().requires_grad_(False)
+flownet = PWCNet().eval().requires_grad_(False)
+
+def trans(x):
+ return x
+
+
+def calculate_flolpips(videos1, videos2, device):
+ global loss_fn, flownet
+
+ print("calculate_flowlpips...")
+ loss_fn = loss_fn.to(device)
+ flownet = flownet.to(device)
+
+ if videos1.shape != videos2.shape:
+ print("Warning: the shape of videos are not equal.")
+ min_frames = min(videos1.shape[1], videos2.shape[1])
+ videos1 = videos1[:, :min_frames]
+ videos2 = videos2[:, :min_frames]
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ flolpips_results = []
+ for video_num in tqdm(range(videos1.shape[0])):
+ video1 = videos1[video_num].to(device)
+ video2 = videos2[video_num].to(device)
+ frames_rec = video1[:-1]
+ frames_rec_next = video1[1:]
+ frames_gt = video2[:-1]
+ frames_gt_next = video2[1:]
+ t, c, h, w = frames_gt.shape
+ flow_gt = flownet(frames_gt, frames_gt_next)
+ flow_dis = flownet(frames_rec, frames_rec_next)
+ flow_diff = flow_gt - flow_dis
+ flolpips = loss_fn.forward(frames_gt, frames_rec, flow_diff, normalize=True)
+ flolpips_results.append(flolpips.cpu().numpy().tolist())
+
+ flolpips_results = np.array(flolpips_results) # [batch_size, num_frames]
+ flolpips = {}
+ flolpips_std = {}
+
+ for clip_timestamp in range(flolpips_results.shape[1]):
+ flolpips[clip_timestamp] = np.mean(flolpips_results[:,clip_timestamp], axis=-1)
+ flolpips_std[clip_timestamp] = np.std(flolpips_results[:,clip_timestamp], axis=-1)
+
+ result = {
+ "value": flolpips,
+ "value_std": flolpips_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ "result": flolpips_results,
+ "details": flolpips_results.tolist()
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+
+ import json
+ result = calculate_flolpips(videos1, videos2, "cuda:0")
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/cal_fvd.py b/One-to-All-Animation/video-generation/opensora/eval/cal_fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f1a9806eb55d067a48b222ec718460222205898
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/cal_fvd.py
@@ -0,0 +1,85 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+
+def trans(x):
+ # if greyscale images add channel
+ if x.shape[-3] == 1:
+ x = x.repeat(1, 1, 3, 1, 1)
+
+ # permute BTCHW -> BCTHW
+ x = x.permute(0, 2, 1, 3, 4)
+
+ return x
+
+def calculate_fvd(videos1, videos2, device, method='styleganv'):
+
+ if method == 'styleganv':
+ from fvd.styleganv.fvd import get_fvd_feats, frechet_distance, load_i3d_pretrained
+ elif method == 'videogpt':
+ from fvd.videogpt.fvd import load_i3d_pretrained
+ from fvd.videogpt.fvd import get_fvd_logits as get_fvd_feats
+ from fvd.videogpt.fvd import frechet_distance
+
+ print("calculate_fvd...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ i3d = load_i3d_pretrained(device=device)
+ fvd_results = []
+
+ # support grayscale input, if grayscale -> channel*3
+ # BTCHW -> BCTHW
+ # videos -> [batch_size, channel, timestamps, h, w]
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ fvd_results = {}
+
+ # for calculate FVD, each clip_timestamp must >= 10
+ for clip_timestamp in tqdm(range(10, videos1.shape[-3]+1)):
+
+ # get a video clip
+ # videos_clip [batch_size, channel, timestamps[:clip], h, w]
+ videos_clip1 = videos1[:, :, : clip_timestamp]
+ videos_clip2 = videos2[:, :, : clip_timestamp]
+
+ # get FVD features
+ feats1 = get_fvd_feats(videos_clip1, i3d=i3d, device=device)
+ feats2 = get_fvd_feats(videos_clip2, i3d=i3d, device=device)
+
+ # calculate FVD when timestamps[:clip]
+ fvd_results[clip_timestamp] = frechet_distance(feats1, feats2)
+
+ result = {
+ "value": fvd_results,
+ "video_setting": videos1.shape,
+ "video_setting_name": "batch_size, channel, time, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+ # device = torch.device("cpu")
+
+ import json
+ result = calculate_fvd(videos1, videos2, device, method='videogpt')
+ print(json.dumps(result, indent=4))
+
+ result = calculate_fvd(videos1, videos2, device, method='styleganv')
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/eval/cal_lpips.py b/One-to-All-Animation/video-generation/opensora/eval/cal_lpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..10edc610b1977b859245d2307f1bebfb0f277216
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/cal_lpips.py
@@ -0,0 +1,97 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+
+import torch
+import lpips
+
+spatial = True # Return a spatial map of perceptual distance.
+
+# Linearly calibrated models (LPIPS)
+loss_fn = lpips.LPIPS(net='alex', spatial=spatial) # Can also set net = 'squeeze' or 'vgg'
+# loss_fn = lpips.LPIPS(net='alex', spatial=spatial, lpips=False) # Can also set net = 'squeeze' or 'vgg'
+
+def trans(x):
+ # if greyscale images add channel
+ if x.shape[-3] == 1:
+ x = x.repeat(1, 1, 3, 1, 1)
+
+ # value range [0, 1] -> [-1, 1]
+ x = x * 2 - 1
+
+ return x
+
+def calculate_lpips(videos1, videos2, device):
+ # image should be RGB, IMPORTANT: normalized to [-1,1]
+ print("calculate_lpips...")
+
+ assert videos1.shape == videos2.shape
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ # support grayscale input, if grayscale -> channel*3
+ # value range [0, 1] -> [-1, 1]
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ lpips_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ lpips_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] tensor
+
+ img1 = video1[clip_timestamp].unsqueeze(0).to(device)
+ img2 = video2[clip_timestamp].unsqueeze(0).to(device)
+
+ loss_fn.to(device)
+
+ # calculate lpips of a video
+ lpips_results_of_a_video.append(loss_fn.forward(img1, img2).mean().detach().cpu().tolist())
+ lpips_results.append(lpips_results_of_a_video)
+
+ lpips_results = np.array(lpips_results)
+
+ lpips = {}
+ lpips_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ lpips[clip_timestamp] = np.mean(lpips_results[:,clip_timestamp])
+ lpips_std[clip_timestamp] = np.std(lpips_results[:,clip_timestamp])
+
+
+ result = {
+ "value": lpips,
+ "value_std": lpips_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+ # device = torch.device("cpu")
+
+ import json
+ result = calculate_lpips(videos1, videos2, device)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/cal_psnr.py b/One-to-All-Animation/video-generation/opensora/eval/cal_psnr.py
new file mode 100644
index 0000000000000000000000000000000000000000..b325106c6cc70b1194f0ba64ae5e8a11ad3a3740
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/cal_psnr.py
@@ -0,0 +1,84 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+
+def img_psnr(img1, img2):
+ # [0,1]
+ # compute mse
+ # mse = np.mean((img1-img2)**2)
+ mse = np.mean((img1 / 1.0 - img2 / 1.0) ** 2)
+ # compute psnr
+ if mse < 1e-10:
+ return 100
+ psnr = 20 * math.log10(1 / math.sqrt(mse))
+ return psnr
+
+def trans(x):
+ return x
+
+def calculate_psnr(videos1, videos2):
+ print("calculate_psnr...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ psnr_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ psnr_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] numpy
+
+ img1 = video1[clip_timestamp].numpy()
+ img2 = video2[clip_timestamp].numpy()
+
+ # calculate psnr of a video
+ psnr_results_of_a_video.append(img_psnr(img1, img2))
+
+ psnr_results.append(psnr_results_of_a_video)
+
+ psnr_results = np.array(psnr_results) # [batch_size, num_frames]
+ psnr = {}
+ psnr_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ psnr[clip_timestamp] = np.mean(psnr_results[:,clip_timestamp])
+ psnr_std[clip_timestamp] = np.std(psnr_results[:,clip_timestamp])
+
+ result = {
+ "value": psnr,
+ "value_std": psnr_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+
+ import json
+ result = calculate_psnr(videos1, videos2)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/cal_ssim.py b/One-to-All-Animation/video-generation/opensora/eval/cal_ssim.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2de811b6c508667177e0c58a1b8a654063fff6b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/cal_ssim.py
@@ -0,0 +1,113 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import cv2
+
+def ssim(img1, img2):
+ C1 = 0.01 ** 2
+ C2 = 0.03 ** 2
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+ kernel = cv2.getGaussianKernel(11, 1.5)
+ window = np.outer(kernel, kernel.transpose())
+ mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid
+ mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
+ mu1_sq = mu1 ** 2
+ mu2_sq = mu2 ** 2
+ mu1_mu2 = mu1 * mu2
+ sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
+ sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
+ sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
+ ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *
+ (sigma1_sq + sigma2_sq + C2))
+ return ssim_map.mean()
+
+
+def calculate_ssim_function(img1, img2):
+ # [0,1]
+ # ssim is the only metric extremely sensitive to gray being compared to b/w
+ if not img1.shape == img2.shape:
+ raise ValueError('Input images must have the same dimensions.')
+ if img1.ndim == 2:
+ return ssim(img1, img2)
+ elif img1.ndim == 3:
+ if img1.shape[0] == 3:
+ ssims = []
+ for i in range(3):
+ ssims.append(ssim(img1[i], img2[i]))
+ return np.array(ssims).mean()
+ elif img1.shape[0] == 1:
+ return ssim(np.squeeze(img1), np.squeeze(img2))
+ else:
+ raise ValueError('Wrong input image dimensions.')
+
+def trans(x):
+ return x
+
+def calculate_ssim(videos1, videos2):
+ print("calculate_ssim...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ ssim_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ ssim_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] numpy
+
+ img1 = video1[clip_timestamp].numpy()
+ img2 = video2[clip_timestamp].numpy()
+
+ # calculate ssim of a video
+ ssim_results_of_a_video.append(calculate_ssim_function(img1, img2))
+
+ ssim_results.append(ssim_results_of_a_video)
+
+ ssim_results = np.array(ssim_results)
+
+ ssim = {}
+ ssim_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ ssim[clip_timestamp] = np.mean(ssim_results[:,clip_timestamp])
+ ssim_std[clip_timestamp] = np.std(ssim_results[:,clip_timestamp])
+
+ result = {
+ "value": ssim,
+ "value_std": ssim_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+
+ import json
+ result = calculate_ssim(videos1, videos2)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/eval_clip_score.py b/One-to-All-Animation/video-generation/opensora/eval/eval_clip_score.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed2f5108233a5bc65d0e945f74edc9599d1d5557
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/eval_clip_score.py
@@ -0,0 +1,225 @@
+"""Calculates the CLIP Scores
+
+The CLIP model is a contrasitively learned language-image model. There is
+an image encoder and a text encoder. It is believed that the CLIP model could
+measure the similarity of cross modalities. Please find more information from
+https://github.com/openai/CLIP.
+
+The CLIP Score measures the Cosine Similarity between two embedded features.
+This repository utilizes the pretrained CLIP Model to calculate
+the mean average of cosine similarities.
+
+See --help to see further details.
+
+Code apapted from https://github.com/mseitzer/pytorch-fid and https://github.com/openai/CLIP.
+
+Copyright 2023 The Hong Kong Polytechnic University
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+import os
+import os.path as osp
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
+
+import clip
+import torch
+from PIL import Image
+from torch.utils.data import Dataset, DataLoader
+
+try:
+ from tqdm import tqdm
+except ImportError:
+ # If tqdm is not available, provide a mock version of it
+ def tqdm(x):
+ return x
+
+
+IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
+ 'tif', 'tiff', 'webp'}
+
+TEXT_EXTENSIONS = {'txt'}
+
+
+class DummyDataset(Dataset):
+
+ FLAGS = ['img', 'txt']
+ def __init__(self, real_path, generated_path,
+ real_flag: str = 'img',
+ generated_flag: str = 'img',
+ transform = None,
+ tokenizer = None) -> None:
+ super().__init__()
+ assert real_flag in self.FLAGS and generated_flag in self.FLAGS, \
+ 'CLIP Score only support modality of {}. However, get {} and {}'.format(
+ self.FLAGS, real_flag, generated_flag
+ )
+ self.real_folder = self._combine_without_prefix(real_path)
+ self.real_flag = real_flag
+ self.fake_foler = self._combine_without_prefix(generated_path)
+ self.generated_flag = generated_flag
+ self.transform = transform
+ self.tokenizer = tokenizer
+ # assert self._check()
+
+ def __len__(self):
+ return len(self.real_folder)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_path = self.real_folder[index]
+ generated_path = self.fake_foler[index]
+ real_data = self._load_modality(real_path, self.real_flag)
+ fake_data = self._load_modality(generated_path, self.generated_flag)
+
+ sample = dict(real=real_data, fake=fake_data)
+ return sample
+
+ def _load_modality(self, path, modality):
+ if modality == 'img':
+ data = self._load_img(path)
+ elif modality == 'txt':
+ data = self._load_txt(path)
+ else:
+ raise TypeError("Got unexpected modality: {}".format(modality))
+ return data
+
+ def _load_img(self, path):
+ img = Image.open(path)
+ if self.transform is not None:
+ img = self.transform(img)
+ return img
+
+ def _load_txt(self, path):
+ with open(path, 'r') as fp:
+ data = fp.read()
+ fp.close()
+ if self.tokenizer is not None:
+ data = self.tokenizer(data).squeeze()
+ return data
+
+ def _check(self):
+ for idx in range(len(self)):
+ real_name = self.real_folder[idx].split('.')
+ fake_name = self.fake_folder[idx].split('.')
+ if fake_name != real_name:
+ return False
+ return True
+
+ def _combine_without_prefix(self, folder_path, prefix='.'):
+ folder = []
+ for name in os.listdir(folder_path):
+ if name[0] == prefix:
+ continue
+ folder.append(osp.join(folder_path, name))
+ folder.sort()
+ return folder
+
+
+@torch.no_grad()
+def calculate_clip_score(dataloader, model, real_flag, generated_flag):
+ score_acc = 0.
+ sample_num = 0.
+ logit_scale = model.logit_scale.exp()
+ for batch_data in tqdm(dataloader):
+ real = batch_data['real']
+ real_features = forward_modality(model, real, real_flag)
+ fake = batch_data['fake']
+ fake_features = forward_modality(model, fake, generated_flag)
+
+ # normalize features
+ real_features = real_features / real_features.norm(dim=1, keepdim=True).to(torch.float32)
+ fake_features = fake_features / fake_features.norm(dim=1, keepdim=True).to(torch.float32)
+
+ # calculate scores
+ # score = logit_scale * real_features @ fake_features.t()
+ # score_acc += torch.diag(score).sum()
+ score = logit_scale * (fake_features * real_features).sum()
+ score_acc += score
+ sample_num += real.shape[0]
+
+ return score_acc / sample_num
+
+
+def forward_modality(model, data, flag):
+ device = next(model.parameters()).device
+ if flag == 'img':
+ features = model.encode_image(data.to(device))
+ elif flag == 'txt':
+ features = model.encode_text(data.to(device))
+ else:
+ raise TypeError
+ return features
+
+
+def main():
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
+ parser.add_argument('--batch-size', type=int, default=50,
+ help='Batch size to use')
+ parser.add_argument('--clip-model', type=str, default='ViT-B/32',
+ help='CLIP model to use')
+ parser.add_argument('--num-workers', type=int, default=8,
+ help=('Number of processes to use for data loading. '
+ 'Defaults to `min(8, num_cpus)`'))
+ parser.add_argument('--device', type=str, default=None,
+ help='Device to use. Like cuda, cuda:0 or cpu')
+ parser.add_argument('--real_flag', type=str, default='img',
+ help=('The modality of real path. '
+ 'Default to img'))
+ parser.add_argument('--generated_flag', type=str, default='txt',
+ help=('The modality of generated path. '
+ 'Default to txt'))
+ parser.add_argument('--real_path', type=str,
+ help=('Paths to the real images or '
+ 'to .npz statistic files'))
+ parser.add_argument('--generated_path', type=str,
+ help=('Paths to the generated images or '
+ 'to .npz statistic files'))
+ args = parser.parse_args()
+
+ if args.device is None:
+ device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
+ else:
+ device = torch.device(args.device)
+
+ if args.num_workers is None:
+ try:
+ num_cpus = len(os.sched_getaffinity(0))
+ except AttributeError:
+ # os.sched_getaffinity is not available under Windows, use
+ # os.cpu_count instead (which may not return the *available* number
+ # of CPUs).
+ num_cpus = os.cpu_count()
+
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
+ else:
+ num_workers = args.num_workers
+
+ print('Loading CLIP model: {}'.format(args.clip_model))
+ model, preprocess = clip.load(args.clip_model, device=device)
+
+ dataset = DummyDataset(args.real_path, args.generated_path,
+ args.real_flag, args.generated_flag,
+ transform=preprocess, tokenizer=clip.tokenize)
+ dataloader = DataLoader(dataset, args.batch_size,
+ num_workers=num_workers, pin_memory=True)
+
+ print('Calculating CLIP Score:')
+ clip_score = calculate_clip_score(dataloader, model,
+ args.real_flag, args.generated_flag)
+ clip_score = clip_score.cpu().item()
+ print('CLIP Score: ', clip_score)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/eval/eval_common_metric.py b/One-to-All-Animation/video-generation/opensora/eval/eval_common_metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..452c03209615026e0acdbf1765df92b017ea04fe
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/eval_common_metric.py
@@ -0,0 +1,224 @@
+"""Calculates the CLIP Scores
+
+The CLIP model is a contrasitively learned language-image model. There is
+an image encoder and a text encoder. It is believed that the CLIP model could
+measure the similarity of cross modalities. Please find more information from
+https://github.com/openai/CLIP.
+
+The CLIP Score measures the Cosine Similarity between two embedded features.
+This repository utilizes the pretrained CLIP Model to calculate
+the mean average of cosine similarities.
+
+See --help to see further details.
+
+Code apapted from https://github.com/mseitzer/pytorch-fid and https://github.com/openai/CLIP.
+
+Copyright 2023 The Hong Kong Polytechnic University
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import os
+import os.path as osp
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
+import numpy as np
+import torch
+from torch.utils.data import Dataset, DataLoader, Subset
+from decord import VideoReader, cpu
+import random
+from pytorchvideo.transforms import ShortSideScale
+from torchvision.io import read_video
+from torchvision.transforms import Lambda, Compose
+from torchvision.transforms._transforms_video import CenterCropVideo
+import sys
+sys.path.append(".")
+from opensora.eval.cal_lpips import calculate_lpips
+from opensora.eval.cal_fvd import calculate_fvd
+from opensora.eval.cal_psnr import calculate_psnr
+from opensora.eval.cal_flolpips import calculate_flolpips
+from opensora.eval.cal_ssim import calculate_ssim
+
+try:
+ from tqdm import tqdm
+except ImportError:
+ # If tqdm is not available, provide a mock version of it
+ def tqdm(x):
+ return x
+
+class VideoDataset(Dataset):
+ def __init__(self,
+ real_video_dir,
+ generated_video_dir,
+ num_frames,
+ sample_rate = 1,
+ crop_size=None,
+ resolution=128,
+ ) -> None:
+ super().__init__()
+ self.real_video_files = self._combine_without_prefix(real_video_dir)
+ self.generated_video_files = self._combine_without_prefix(generated_video_dir)
+ self.num_frames = num_frames
+ self.sample_rate = sample_rate
+ self.crop_size = crop_size
+ self.short_size = resolution
+
+
+ def __len__(self):
+ return len(self.real_video_files)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_video_file = self.real_video_files[index]
+ generated_video_file = self.generated_video_files[index]
+ print(real_video_file, generated_video_file)
+ real_video_tensor = self._load_video(real_video_file)
+ generated_video_tensor = self._load_video(generated_video_file)
+ return {'real': real_video_tensor, 'generated':generated_video_tensor }
+
+
+ def _load_video(self, video_path):
+ num_frames = self.num_frames
+ sample_rate = self.sample_rate
+ decord_vr = VideoReader(video_path, ctx=cpu(0))
+ total_frames = len(decord_vr)
+ sample_frames_len = sample_rate * num_frames
+
+ if total_frames >= sample_frames_len:
+ s = 0
+ e = s + sample_frames_len
+ num_frames = num_frames
+ else:
+ s = 0
+ e = total_frames
+ num_frames = int(total_frames / sample_frames_len * num_frames)
+ print(f'sample_frames_len {sample_frames_len}, only can sample {num_frames * sample_rate}', video_path,
+ total_frames)
+
+
+ frame_id_list = np.linspace(s, e - 1, num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (C, T, H, W)
+ return _preprocess(video_data, short_size=self.short_size, crop_size = self.crop_size)
+
+
+ def _combine_without_prefix(self, folder_path, prefix='.'):
+ folder = []
+ os.makedirs(folder_path, exist_ok=True)
+ for name in os.listdir(folder_path):
+ if name[0] == prefix:
+ continue
+ if osp.isfile(osp.join(folder_path, name)):
+ folder.append(osp.join(folder_path, name))
+ folder.sort()
+ return folder
+
+def _preprocess(video_data, short_size=128, crop_size=None):
+ transform = Compose(
+ [
+ Lambda(lambda x: x / 255.0),
+ ShortSideScale(size=short_size),
+ CenterCropVideo(crop_size=crop_size),
+ ]
+ )
+ video_outputs = transform(video_data)
+ # video_outputs = torch.unsqueeze(video_outputs, 0) # (bz,c,t,h,w)
+ return video_outputs
+
+
+def calculate_common_metric(args, dataloader, device):
+
+ score_list = []
+ for batch_data in tqdm(dataloader): # {'real': real_video_tensor, 'generated':generated_video_tensor }
+ real_videos = batch_data['real']
+ generated_videos = batch_data['generated']
+ assert real_videos.shape[2] == generated_videos.shape[2]
+ if args.metric == 'fvd':
+ tmp_list = list(calculate_fvd(real_videos, generated_videos, args.device, method=args.fvd_method)['value'].values())
+ elif args.metric == 'ssim':
+ tmp_list = list(calculate_ssim(real_videos, generated_videos)['value'].values())
+ elif args.metric == 'psnr':
+ tmp_list = list(calculate_psnr(real_videos, generated_videos)['value'].values())
+ elif args.metric == 'flolpips':
+ result = calculate_flolpips(real_videos, generated_videos, args.device)
+ tmp_list = list(result['value'].values())
+ else:
+ tmp_list = list(calculate_lpips(real_videos, generated_videos, args.device)['value'].values())
+ score_list += tmp_list
+ return np.mean(score_list)
+
+def main():
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
+ parser.add_argument('--batch_size', type=int, default=2,
+ help='Batch size to use')
+ parser.add_argument('--real_video_dir', type=str,
+ help=('the path of real videos`'))
+ parser.add_argument('--generated_video_dir', type=str,
+ help=('the path of generated videos`'))
+ parser.add_argument('--device', type=str, default=None,
+ help='Device to use. Like cuda, cuda:0 or cpu')
+ parser.add_argument('--num_workers', type=int, default=8,
+ help=('Number of processes to use for data loading. '
+ 'Defaults to `min(8, num_cpus)`'))
+ parser.add_argument('--sample_fps', type=int, default=30)
+ parser.add_argument('--resolution', type=int, default=336)
+ parser.add_argument('--crop_size', type=int, default=None)
+ parser.add_argument('--num_frames', type=int, default=100)
+ parser.add_argument('--sample_rate', type=int, default=1)
+ parser.add_argument('--subset_size', type=int, default=None)
+ parser.add_argument("--metric", type=str, default="fvd",choices=['fvd','psnr','ssim','lpips', 'flolpips'])
+ parser.add_argument("--fvd_method", type=str, default='styleganv',choices=['styleganv','videogpt'])
+
+
+ args = parser.parse_args()
+
+ if args.device is None:
+ device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
+ else:
+ device = torch.device(args.device)
+
+ if args.num_workers is None:
+ try:
+ num_cpus = len(os.sched_getaffinity(0))
+ except AttributeError:
+ # os.sched_getaffinity is not available under Windows, use
+ # os.cpu_count instead (which may not return the *available* number
+ # of CPUs).
+ num_cpus = os.cpu_count()
+
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
+ else:
+ num_workers = args.num_workers
+
+
+ dataset = VideoDataset(args.real_video_dir,
+ args.generated_video_dir,
+ num_frames = args.num_frames,
+ sample_rate = args.sample_rate,
+ crop_size=args.crop_size,
+ resolution=args.resolution)
+
+ if args.subset_size:
+ indices = range(args.subset_size)
+ dataset = Subset(dataset, indices=indices)
+
+ dataloader = DataLoader(dataset, args.batch_size,
+ num_workers=num_workers, pin_memory=True)
+
+
+ metric_score = calculate_common_metric(args, dataloader,device)
+ print('metric: ', args.metric, " ",metric_score)
+
+if __name__ == '__main__':
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/eval/flolpips/correlation/correlation.py b/One-to-All-Animation/video-generation/opensora/eval/flolpips/correlation/correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c91055bacd3e142840563cde55d8ed4033a0fc7
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/flolpips/correlation/correlation.py
@@ -0,0 +1,397 @@
+#!/usr/bin/env python
+
+import torch
+
+import cupy
+import re
+
+kernel_Correlation_rearrange = '''
+ extern "C" __global__ void kernel_Correlation_rearrange(
+ const int n,
+ const float* input,
+ float* output
+ ) {
+ int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x;
+
+ if (intIndex >= n) {
+ return;
+ }
+
+ int intSample = blockIdx.z;
+ int intChannel = blockIdx.y;
+
+ float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex];
+
+ __syncthreads();
+
+ int intPaddedY = (intIndex / SIZE_3(input)) + 4;
+ int intPaddedX = (intIndex % SIZE_3(input)) + 4;
+ int intRearrange = ((SIZE_3(input) + 8) * intPaddedY) + intPaddedX;
+
+ output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue;
+ }
+'''
+
+kernel_Correlation_updateOutput = '''
+ extern "C" __global__ void kernel_Correlation_updateOutput(
+ const int n,
+ const float* rbot0,
+ const float* rbot1,
+ float* top
+ ) {
+ extern __shared__ char patch_data_char[];
+
+ float *patch_data = (float *)patch_data_char;
+
+ // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1
+ int x1 = blockIdx.x + 4;
+ int y1 = blockIdx.y + 4;
+ int item = blockIdx.z;
+ int ch_off = threadIdx.x;
+
+ // Load 3D patch into shared shared memory
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch;
+ int idxPatchData = ji_off + ch;
+ patch_data[idxPatchData] = rbot0[idx1];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ __shared__ float sum[32];
+
+ // Compute correlation
+ for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) {
+ sum[ch_off] = 0;
+
+ int s2o = top_channel % 9 - 4;
+ int s2p = top_channel / 9 - 4;
+
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int x2 = x1 + s2o;
+ int y2 = y1 + s2p;
+
+ int idxPatchData = ji_off + ch;
+ int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch;
+
+ sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ if (ch_off == 0) {
+ float total_sum = 0;
+ for (int idx = 0; idx < 32; idx++) {
+ total_sum += sum[idx];
+ }
+ const int sumelems = SIZE_3(rbot0);
+ const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x;
+ top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems;
+ }
+ }
+ }
+'''
+
+kernel_Correlation_updateGradFirst = '''
+ #define ROUND_OFF 50000
+
+ extern "C" __global__ void kernel_Correlation_updateGradFirst(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradFirst,
+ float* gradSecond
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradFirst); // channels
+ int l = (intIndex / SIZE_1(gradFirst)) % SIZE_3(gradFirst) + 4; // w-pos
+ int m = (intIndex / SIZE_1(gradFirst) / SIZE_3(gradFirst)) % SIZE_2(gradFirst) + 4; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = round_off;
+
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
+ int ymin = (m - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
+
+ // Same here:
+ int xmax = (l - 4 + round_off_s1) - round_off; // floor (l - 4)
+ int ymax = (m - 4 + round_off_s1) - round_off; // floor (m - 4)
+
+ float sum = 0;
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ for (int p = -4; p <= 4; p++) {
+ for (int o = -4; o <= 4; o++) {
+ // Get rbot1 data:
+ int s2o = o;
+ int s2p = p;
+ int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n;
+ float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+4) * 9 + (o+4); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot1tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradFirst);
+ const int bot0index = ((n * SIZE_2(gradFirst)) + (m-4)) * SIZE_3(gradFirst) + (l-4);
+ gradFirst[bot0index + intSample*SIZE_1(gradFirst)*SIZE_2(gradFirst)*SIZE_3(gradFirst)] = sum / (float)sumelems;
+ } }
+'''
+
+kernel_Correlation_updateGradSecond = '''
+ #define ROUND_OFF 50000
+
+ extern "C" __global__ void kernel_Correlation_updateGradSecond(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradFirst,
+ float* gradSecond
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradSecond); // channels
+ int l = (intIndex / SIZE_1(gradSecond)) % SIZE_3(gradSecond) + 4; // w-pos
+ int m = (intIndex / SIZE_1(gradSecond) / SIZE_3(gradSecond)) % SIZE_2(gradSecond) + 4; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = round_off;
+
+ float sum = 0;
+ for (int p = -4; p <= 4; p++) {
+ for (int o = -4; o <= 4; o++) {
+ int s2o = o;
+ int s2p = p;
+
+ //Get X,Y ranges and clamp
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 4 - s2o + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
+ int ymin = (m - 4 - s2p + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
+
+ // Same here:
+ int xmax = (l - 4 - s2o + round_off_s1) - round_off; // floor (l - 4 - s2o)
+ int ymax = (m - 4 - s2p + round_off_s1) - round_off; // floor (m - 4 - s2p)
+
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ // Get rbot0 data:
+ int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n;
+ float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+4) * 9 + (o+4); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot0tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradSecond);
+ const int bot1index = ((n * SIZE_2(gradSecond)) + (m-4)) * SIZE_3(gradSecond) + (l-4);
+ gradSecond[bot1index + intSample*SIZE_1(gradSecond)*SIZE_2(gradSecond)*SIZE_3(gradSecond)] = sum / (float)sumelems;
+ } }
+'''
+
+def cupy_kernel(strFunction, objVariables):
+ strKernel = globals()[strFunction]
+
+ while True:
+ objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArg = int(objMatch.group(2))
+
+ strTensor = objMatch.group(4)
+ intSizes = objVariables[strTensor].size()
+
+ strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))
+ # end
+
+ while True:
+ objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArgs = int(objMatch.group(2))
+ strArgs = objMatch.group(4).split(',')
+
+ strTensor = strArgs[0]
+ intStrides = objVariables[strTensor].stride()
+ strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
+
+ strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
+ # end
+
+ return strKernel
+# end
+
+@cupy.memoize(for_each_device=True)
+def cupy_launch(strFunction, strKernel):
+ return cupy.RawKernel(strKernel, strFunction)
+# end
+
+class _FunctionCorrelation(torch.autograd.Function):
+ @staticmethod
+ def forward(self, first, second):
+ rbot0 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
+ rbot1 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
+
+ self.save_for_backward(first, second, rbot0, rbot1)
+
+ first = first.contiguous(); assert(first.is_cuda == True)
+ second = second.contiguous(); assert(second.is_cuda == True)
+
+ output = first.new_zeros([ first.shape[0], 81, first.shape[2], first.shape[3] ])
+
+ if first.is_cuda == True:
+ n = first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'input': first,
+ 'output': rbot0
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), first.shape[1], first.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ n, first.data_ptr(), rbot0.data_ptr() ]
+ )
+
+ n = second.shape[2] * second.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'input': second,
+ 'output': rbot1
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), second.shape[1], second.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ n, second.data_ptr(), rbot1.data_ptr() ]
+ )
+
+ n = output.shape[1] * output.shape[2] * output.shape[3]
+ cupy_launch('kernel_Correlation_updateOutput', cupy_kernel('kernel_Correlation_updateOutput', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'top': output
+ }))(
+ grid=tuple([ output.shape[3], output.shape[2], output.shape[0] ]),
+ block=tuple([ 32, 1, 1 ]),
+ shared_mem=first.shape[1] * 4,
+ args=[ n, rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr() ]
+ )
+
+ elif first.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ return output
+ # end
+
+ @staticmethod
+ def backward(self, gradOutput):
+ first, second, rbot0, rbot1 = self.saved_tensors
+
+ gradOutput = gradOutput.contiguous(); assert(gradOutput.is_cuda == True)
+
+ gradFirst = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[0] == True else None
+ gradSecond = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[1] == True else None
+
+ if first.is_cuda == True:
+ if gradFirst is not None:
+ for intSample in range(first.shape[0]):
+ n = first.shape[1] * first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_updateGradFirst', cupy_kernel('kernel_Correlation_updateGradFirst', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradFirst': gradFirst,
+ 'gradSecond': None
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), gradFirst.data_ptr(), None ]
+ )
+ # end
+ # end
+
+ if gradSecond is not None:
+ for intSample in range(first.shape[0]):
+ n = first.shape[1] * first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_updateGradSecond', cupy_kernel('kernel_Correlation_updateGradSecond', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradFirst': None,
+ 'gradSecond': gradSecond
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), None, gradSecond.data_ptr() ]
+ )
+ # end
+ # end
+
+ elif first.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ return gradFirst, gradSecond
+ # end
+# end
+
+def FunctionCorrelation(tenFirst, tenSecond):
+ return _FunctionCorrelation.apply(tenFirst, tenSecond)
+# end
+
+class ModuleCorrelation(torch.nn.Module):
+ def __init__(self):
+ super(ModuleCorrelation, self).__init__()
+ # end
+
+ def forward(self, tenFirst, tenSecond):
+ return _FunctionCorrelation.apply(tenFirst, tenSecond)
+ # end
+# end
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/flolpips/flolpips.py b/One-to-All-Animation/video-generation/opensora/eval/flolpips/flolpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..66f4731496482d4fe1ccda76680d316cc3d773cd
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/flolpips/flolpips.py
@@ -0,0 +1,308 @@
+
+from __future__ import absolute_import
+import os
+import numpy as np
+import torch
+import torch.nn as nn
+from torch.autograd import Variable
+from .pretrained_networks import vgg16, alexnet, squeezenet
+import torch.nn
+import torch.nn.functional as F
+import torchvision.transforms.functional as TF
+import cv2
+
+from .pwcnet import Network as PWCNet
+from .utils import *
+
+def spatial_average(in_tens, keepdim=True):
+ return in_tens.mean([2,3],keepdim=keepdim)
+
+def mw_spatial_average(in_tens, flow, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = torch.sqrt(flow[:,0:1]**2 + flow[:,1:2]**2)
+ flow_mag = flow_mag / torch.sum(flow_mag, dim=[1,2,3], keepdim=True)
+ return torch.sum(in_tens*flow_mag, dim=[2,3],keepdim=keepdim)
+
+
+def mtw_spatial_average(in_tens, flow, texture, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ texture = F.interpolate(texture, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = torch.sqrt(flow[:,0:1]**2 + flow[:,1:2]**2)
+ flow_mag = (flow_mag - flow_mag.min()) / (flow_mag.max() - flow_mag.min()) + 1e-6
+ texture = (texture - texture.min()) / (texture.max() - texture.min()) + 1e-6
+ weight = flow_mag / texture
+ weight /= torch.sum(weight)
+ return torch.sum(in_tens*weight, dim=[2,3],keepdim=keepdim)
+
+
+
+def m2w_spatial_average(in_tens, flow, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = flow[:,0:1]**2 + flow[:,1:2]**2 # B,1,H,W
+ flow_mag = flow_mag / torch.sum(flow_mag)
+ return torch.sum(in_tens*flow_mag, dim=[2,3],keepdim=keepdim)
+
+def upsample(in_tens, out_HW=(64,64)): # assumes scale factor is same for H and W
+ in_H, in_W = in_tens.shape[2], in_tens.shape[3]
+ return nn.Upsample(size=out_HW, mode='bilinear', align_corners=False)(in_tens)
+
+# Learned perceptual metric
+class LPIPS(nn.Module):
+ def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False,
+ pnet_rand=False, pnet_tune=False, use_dropout=True, model_path=None, eval_mode=True, verbose=False):
+ # lpips - [True] means with linear calibration on top of base network
+ # pretrained - [True] means load linear weights
+
+ super(LPIPS, self).__init__()
+ if(verbose):
+ print('Setting up [%s] perceptual loss: trunk [%s], v[%s], spatial [%s]'%
+ ('LPIPS' if lpips else 'baseline', net, version, 'on' if spatial else 'off'))
+
+ self.pnet_type = net
+ self.pnet_tune = pnet_tune
+ self.pnet_rand = pnet_rand
+ self.spatial = spatial
+ self.lpips = lpips # false means baseline of just averaging all layers
+ self.version = version
+ self.scaling_layer = ScalingLayer()
+
+ if(self.pnet_type in ['vgg','vgg16']):
+ net_type = vgg16
+ self.chns = [64,128,256,512,512]
+ elif(self.pnet_type=='alex'):
+ net_type = alexnet
+ self.chns = [64,192,384,256,256]
+ elif(self.pnet_type=='squeeze'):
+ net_type = squeezenet
+ self.chns = [64,128,256,384,384,512,512]
+ self.L = len(self.chns)
+
+ self.net = net_type(pretrained=not self.pnet_rand, requires_grad=self.pnet_tune)
+
+ if(lpips):
+ self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
+ self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
+ self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
+ self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
+ self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
+ self.lins = [self.lin0,self.lin1,self.lin2,self.lin3,self.lin4]
+ if(self.pnet_type=='squeeze'): # 7 layers for squeezenet
+ self.lin5 = NetLinLayer(self.chns[5], use_dropout=use_dropout)
+ self.lin6 = NetLinLayer(self.chns[6], use_dropout=use_dropout)
+ self.lins+=[self.lin5,self.lin6]
+ self.lins = nn.ModuleList(self.lins)
+
+ if(pretrained):
+ if(model_path is None):
+ import inspect
+ import os
+ model_path = os.path.abspath(os.path.join(inspect.getfile(self.__init__), '..', 'weights/v%s/%s.pth'%(version,net)))
+
+ if(verbose):
+ print('Loading model from: %s'%model_path)
+ self.load_state_dict(torch.load(model_path, map_location='cpu'), strict=False)
+
+ if(eval_mode):
+ self.eval()
+
+ def forward(self, in0, in1, retPerLayer=False, normalize=False):
+ if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
+ in0 = 2 * in0 - 1
+ in1 = 2 * in1 - 1
+
+ # v0.0 - original release had a bug, where input was not scaled
+ in0_input, in1_input = (self.scaling_layer(in0), self.scaling_layer(in1)) if self.version=='0.1' else (in0, in1)
+ outs0, outs1 = self.net.forward(in0_input), self.net.forward(in1_input)
+ feats0, feats1, diffs = {}, {}, {}
+
+ for kk in range(self.L):
+ feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
+ diffs[kk] = (feats0[kk]-feats1[kk])**2
+
+ if(self.lpips):
+ if(self.spatial):
+ res = [upsample(self.lins[kk](diffs[kk]), out_HW=in0.shape[2:]) for kk in range(self.L)]
+ else:
+ res = [spatial_average(self.lins[kk](diffs[kk]), keepdim=True) for kk in range(self.L)]
+ else:
+ if(self.spatial):
+ res = [upsample(diffs[kk].sum(dim=1,keepdim=True), out_HW=in0.shape[2:]) for kk in range(self.L)]
+ else:
+ res = [spatial_average(diffs[kk].sum(dim=1,keepdim=True), keepdim=True) for kk in range(self.L)]
+
+ # val = res[0]
+ # for l in range(1,self.L):
+ # val += res[l]
+ # print(val)
+
+ # a = spatial_average(self.lins[kk](diffs[kk]), keepdim=True)
+ # b = torch.max(self.lins[kk](feats0[kk]**2))
+ # for kk in range(self.L):
+ # a += spatial_average(self.lins[kk](diffs[kk]), keepdim=True)
+ # b = torch.max(b,torch.max(self.lins[kk](feats0[kk]**2)))
+ # a = a/self.L
+ # from IPython import embed
+ # embed()
+ # return 10*torch.log10(b/a)
+
+ # if(retPerLayer):
+ # return (val, res)
+ # else:
+ return torch.sum(torch.cat(res, 1), dim=(1,2,3), keepdims=False)
+
+
+class ScalingLayer(nn.Module):
+ def __init__(self):
+ super(ScalingLayer, self).__init__()
+ self.register_buffer('shift', torch.Tensor([-.030,-.088,-.188])[None,:,None,None])
+ self.register_buffer('scale', torch.Tensor([.458,.448,.450])[None,:,None,None])
+
+ def forward(self, inp):
+ return (inp - self.shift) / self.scale
+
+
+class NetLinLayer(nn.Module):
+ ''' A single linear layer which does a 1x1 conv '''
+ def __init__(self, chn_in, chn_out=1, use_dropout=False):
+ super(NetLinLayer, self).__init__()
+
+ layers = [nn.Dropout(),] if(use_dropout) else []
+ layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),]
+ self.model = nn.Sequential(*layers)
+
+ def forward(self, x):
+ return self.model(x)
+
+class Dist2LogitLayer(nn.Module):
+ ''' takes 2 distances, puts through fc layers, spits out value between [0,1] (if use_sigmoid is True) '''
+ def __init__(self, chn_mid=32, use_sigmoid=True):
+ super(Dist2LogitLayer, self).__init__()
+
+ layers = [nn.Conv2d(5, chn_mid, 1, stride=1, padding=0, bias=True),]
+ layers += [nn.LeakyReLU(0.2,True),]
+ layers += [nn.Conv2d(chn_mid, chn_mid, 1, stride=1, padding=0, bias=True),]
+ layers += [nn.LeakyReLU(0.2,True),]
+ layers += [nn.Conv2d(chn_mid, 1, 1, stride=1, padding=0, bias=True),]
+ if(use_sigmoid):
+ layers += [nn.Sigmoid(),]
+ self.model = nn.Sequential(*layers)
+
+ def forward(self,d0,d1,eps=0.1):
+ return self.model.forward(torch.cat((d0,d1,d0-d1,d0/(d1+eps),d1/(d0+eps)),dim=1))
+
+class BCERankingLoss(nn.Module):
+ def __init__(self, chn_mid=32):
+ super(BCERankingLoss, self).__init__()
+ self.net = Dist2LogitLayer(chn_mid=chn_mid)
+ # self.parameters = list(self.net.parameters())
+ self.loss = torch.nn.BCELoss()
+
+ def forward(self, d0, d1, judge):
+ per = (judge+1.)/2.
+ self.logit = self.net.forward(d0,d1)
+ return self.loss(self.logit, per)
+
+# L2, DSSIM metrics
+class FakeNet(nn.Module):
+ def __init__(self, use_gpu=True, colorspace='Lab'):
+ super(FakeNet, self).__init__()
+ self.use_gpu = use_gpu
+ self.colorspace = colorspace
+
+class L2(FakeNet):
+ def forward(self, in0, in1, retPerLayer=None):
+ assert(in0.size()[0]==1) # currently only supports batchSize 1
+
+ if(self.colorspace=='RGB'):
+ (N,C,X,Y) = in0.size()
+ value = torch.mean(torch.mean(torch.mean((in0-in1)**2,dim=1).view(N,1,X,Y),dim=2).view(N,1,1,Y),dim=3).view(N)
+ return value
+ elif(self.colorspace=='Lab'):
+ value = l2(tensor2np(tensor2tensorlab(in0.data,to_norm=False)),
+ tensor2np(tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
+ ret_var = Variable( torch.Tensor((value,) ) )
+ if(self.use_gpu):
+ ret_var = ret_var.cuda()
+ return ret_var
+
+class DSSIM(FakeNet):
+
+ def forward(self, in0, in1, retPerLayer=None):
+ assert(in0.size()[0]==1) # currently only supports batchSize 1
+
+ if(self.colorspace=='RGB'):
+ value = dssim(1.*tensor2im(in0.data), 1.*tensor2im(in1.data), range=255.).astype('float')
+ elif(self.colorspace=='Lab'):
+ value = dssim(tensor2np(tensor2tensorlab(in0.data,to_norm=False)),
+ tensor2np(tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
+ ret_var = Variable( torch.Tensor((value,) ) )
+ if(self.use_gpu):
+ ret_var = ret_var.cuda()
+ return ret_var
+
+def print_network(net):
+ num_params = 0
+ for param in net.parameters():
+ num_params += param.numel()
+ print('Network',net)
+ print('Total number of parameters: %d' % num_params)
+
+
+class FloLPIPS(LPIPS):
+ def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False, pnet_rand=False, pnet_tune=False, use_dropout=True, model_path=None, eval_mode=True, verbose=False):
+ super(FloLPIPS, self).__init__(pretrained, net, version, lpips, spatial, pnet_rand, pnet_tune, use_dropout, model_path, eval_mode, verbose)
+
+ def forward(self, in0, in1, flow, retPerLayer=False, normalize=False):
+ if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
+ in0 = 2 * in0 - 1
+ in1 = 2 * in1 - 1
+
+ in0_input, in1_input = (self.scaling_layer(in0), self.scaling_layer(in1)) if self.version=='0.1' else (in0, in1)
+ outs0, outs1 = self.net.forward(in0_input), self.net.forward(in1_input)
+ feats0, feats1, diffs = {}, {}, {}
+
+ for kk in range(self.L):
+ feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
+ diffs[kk] = (feats0[kk]-feats1[kk])**2
+
+ res = [mw_spatial_average(self.lins[kk](diffs[kk]), flow, keepdim=True) for kk in range(self.L)]
+
+ return torch.sum(torch.cat(res, 1), dim=(1,2,3), keepdims=False)
+
+
+
+
+
+class Flolpips(nn.Module):
+ def __init__(self):
+ super(Flolpips, self).__init__()
+ self.loss_fn = FloLPIPS(net='alex',version='0.1')
+ self.flownet = PWCNet()
+
+ @torch.no_grad()
+ def forward(self, I0, I1, frame_dis, frame_ref):
+ """
+ args:
+ I0: first frame of the triplet, shape: [B, C, H, W]
+ I1: third frame of the triplet, shape: [B, C, H, W]
+ frame_dis: prediction of the intermediate frame, shape: [B, C, H, W]
+ frame_ref: ground-truth of the intermediate frame, shape: [B, C, H, W]
+ """
+ assert I0.size() == I1.size() == frame_dis.size() == frame_ref.size(), \
+ "the 4 input tensors should have same size"
+
+ flow_ref = self.flownet(frame_ref, I0)
+ flow_dis = self.flownet(frame_dis, I0)
+ flow_diff = flow_ref - flow_dis
+ flolpips_wrt_I0 = self.loss_fn.forward(frame_ref, frame_dis, flow_diff, normalize=True)
+
+ flow_ref = self.flownet(frame_ref, I1)
+ flow_dis = self.flownet(frame_dis, I1)
+ flow_diff = flow_ref - flow_dis
+ flolpips_wrt_I1 = self.loss_fn.forward(frame_ref, frame_dis, flow_diff, normalize=True)
+
+ flolpips = (flolpips_wrt_I0 + flolpips_wrt_I1) / 2
+ return flolpips
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/flolpips/pretrained_networks.py b/One-to-All-Animation/video-generation/opensora/eval/flolpips/pretrained_networks.py
new file mode 100644
index 0000000000000000000000000000000000000000..82f14e206e7b395ac9d989cb2536e17b17e65184
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/flolpips/pretrained_networks.py
@@ -0,0 +1,180 @@
+from collections import namedtuple
+import torch
+from torchvision import models as tv
+
+class squeezenet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(squeezenet, self).__init__()
+ pretrained_features = tv.squeezenet1_1(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.slice6 = torch.nn.Sequential()
+ self.slice7 = torch.nn.Sequential()
+ self.N_slices = 7
+ for x in range(2):
+ self.slice1.add_module(str(x), pretrained_features[x])
+ for x in range(2,5):
+ self.slice2.add_module(str(x), pretrained_features[x])
+ for x in range(5, 8):
+ self.slice3.add_module(str(x), pretrained_features[x])
+ for x in range(8, 10):
+ self.slice4.add_module(str(x), pretrained_features[x])
+ for x in range(10, 11):
+ self.slice5.add_module(str(x), pretrained_features[x])
+ for x in range(11, 12):
+ self.slice6.add_module(str(x), pretrained_features[x])
+ for x in range(12, 13):
+ self.slice7.add_module(str(x), pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1 = h
+ h = self.slice2(h)
+ h_relu2 = h
+ h = self.slice3(h)
+ h_relu3 = h
+ h = self.slice4(h)
+ h_relu4 = h
+ h = self.slice5(h)
+ h_relu5 = h
+ h = self.slice6(h)
+ h_relu6 = h
+ h = self.slice7(h)
+ h_relu7 = h
+ vgg_outputs = namedtuple("SqueezeOutputs", ['relu1','relu2','relu3','relu4','relu5','relu6','relu7'])
+ out = vgg_outputs(h_relu1,h_relu2,h_relu3,h_relu4,h_relu5,h_relu6,h_relu7)
+
+ return out
+
+
+class alexnet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(alexnet, self).__init__()
+ alexnet_pretrained_features = tv.alexnet(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.N_slices = 5
+ for x in range(2):
+ self.slice1.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(2, 5):
+ self.slice2.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(5, 8):
+ self.slice3.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(8, 10):
+ self.slice4.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(10, 12):
+ self.slice5.add_module(str(x), alexnet_pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1 = h
+ h = self.slice2(h)
+ h_relu2 = h
+ h = self.slice3(h)
+ h_relu3 = h
+ h = self.slice4(h)
+ h_relu4 = h
+ h = self.slice5(h)
+ h_relu5 = h
+ alexnet_outputs = namedtuple("AlexnetOutputs", ['relu1', 'relu2', 'relu3', 'relu4', 'relu5'])
+ out = alexnet_outputs(h_relu1, h_relu2, h_relu3, h_relu4, h_relu5)
+
+ return out
+
+class vgg16(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(vgg16, self).__init__()
+ vgg_pretrained_features = tv.vgg16(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.N_slices = 5
+ for x in range(4):
+ self.slice1.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(4, 9):
+ self.slice2.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(9, 16):
+ self.slice3.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(16, 23):
+ self.slice4.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(23, 30):
+ self.slice5.add_module(str(x), vgg_pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1_2 = h
+ h = self.slice2(h)
+ h_relu2_2 = h
+ h = self.slice3(h)
+ h_relu3_3 = h
+ h = self.slice4(h)
+ h_relu4_3 = h
+ h = self.slice5(h)
+ h_relu5_3 = h
+ vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
+ out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
+
+ return out
+
+
+
+class resnet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True, num=18):
+ super(resnet, self).__init__()
+ if(num==18):
+ self.net = tv.resnet18(pretrained=pretrained)
+ elif(num==34):
+ self.net = tv.resnet34(pretrained=pretrained)
+ elif(num==50):
+ self.net = tv.resnet50(pretrained=pretrained)
+ elif(num==101):
+ self.net = tv.resnet101(pretrained=pretrained)
+ elif(num==152):
+ self.net = tv.resnet152(pretrained=pretrained)
+ self.N_slices = 5
+
+ self.conv1 = self.net.conv1
+ self.bn1 = self.net.bn1
+ self.relu = self.net.relu
+ self.maxpool = self.net.maxpool
+ self.layer1 = self.net.layer1
+ self.layer2 = self.net.layer2
+ self.layer3 = self.net.layer3
+ self.layer4 = self.net.layer4
+
+ def forward(self, X):
+ h = self.conv1(X)
+ h = self.bn1(h)
+ h = self.relu(h)
+ h_relu1 = h
+ h = self.maxpool(h)
+ h = self.layer1(h)
+ h_conv2 = h
+ h = self.layer2(h)
+ h_conv3 = h
+ h = self.layer3(h)
+ h_conv4 = h
+ h = self.layer4(h)
+ h_conv5 = h
+
+ outputs = namedtuple("Outputs", ['relu1','conv2','conv3','conv4','conv5'])
+ out = outputs(h_relu1, h_conv2, h_conv3, h_conv4, h_conv5)
+
+ return out
diff --git a/One-to-All-Animation/video-generation/opensora/eval/flolpips/pwcnet.py b/One-to-All-Animation/video-generation/opensora/eval/flolpips/pwcnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..374f18e20ce27d1fe596559c5a2f17f333e2d50f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/flolpips/pwcnet.py
@@ -0,0 +1,344 @@
+#!/usr/bin/env python
+
+import torch
+
+import getopt
+import math
+import numpy
+import os
+import PIL
+import PIL.Image
+import sys
+
+# try:
+from .correlation import correlation # the custom cost volume layer
+# except:
+# sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python
+# end
+
+##########################################################
+
+# assert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0
+
+# torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
+
+# torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
+
+# ##########################################################
+
+# arguments_strModel = 'default' # 'default', or 'chairs-things'
+# arguments_strFirst = './images/first.png'
+# arguments_strSecond = './images/second.png'
+# arguments_strOut = './out.flo'
+
+# for strOption, strArgument in getopt.getopt(sys.argv[1:], '', [ strParameter[2:] + '=' for strParameter in sys.argv[1::2] ])[0]:
+# if strOption == '--model' and strArgument != '': arguments_strModel = strArgument # which model to use
+# if strOption == '--first' and strArgument != '': arguments_strFirst = strArgument # path to the first frame
+# if strOption == '--second' and strArgument != '': arguments_strSecond = strArgument # path to the second frame
+# if strOption == '--out' and strArgument != '': arguments_strOut = strArgument # path to where the output should be stored
+# end
+
+##########################################################
+
+
+
+def backwarp(tenInput, tenFlow):
+ backwarp_tenGrid = {}
+ backwarp_tenPartial = {}
+ if str(tenFlow.shape) not in backwarp_tenGrid:
+ tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]).view(1, 1, 1, -1).expand(-1, -1, tenFlow.shape[2], -1)
+ tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]).view(1, 1, -1, 1).expand(-1, -1, -1, tenFlow.shape[3])
+
+ backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([ tenHor, tenVer ], 1).cuda()
+ # end
+
+ if str(tenFlow.shape) not in backwarp_tenPartial:
+ backwarp_tenPartial[str(tenFlow.shape)] = tenFlow.new_ones([ tenFlow.shape[0], 1, tenFlow.shape[2], tenFlow.shape[3] ])
+ # end
+
+ tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)
+ tenInput = torch.cat([ tenInput, backwarp_tenPartial[str(tenFlow.shape)] ], 1)
+
+ tenOutput = torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=False)
+
+ tenMask = tenOutput[:, -1:, :, :]; tenMask[tenMask > 0.999] = 1.0; tenMask[tenMask < 1.0] = 0.0
+
+ return tenOutput[:, :-1, :, :] * tenMask
+# end
+
+##########################################################
+
+class Network(torch.nn.Module):
+ def __init__(self):
+ super(Network, self).__init__()
+
+ class Extractor(torch.nn.Module):
+ def __init__(self):
+ super(Extractor, self).__init__()
+
+ self.netOne = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netTwo = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netThr = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFou = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFiv = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netSix = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+ # end
+
+ def forward(self, tenInput):
+ tenOne = self.netOne(tenInput)
+ tenTwo = self.netTwo(tenOne)
+ tenThr = self.netThr(tenTwo)
+ tenFou = self.netFou(tenThr)
+ tenFiv = self.netFiv(tenFou)
+ tenSix = self.netSix(tenFiv)
+
+ return [ tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix ]
+ # end
+ # end
+
+ class Decoder(torch.nn.Module):
+ def __init__(self, intLevel):
+ super(Decoder, self).__init__()
+
+ intPrevious = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 1]
+ intCurrent = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 0]
+
+ if intLevel < 6: self.netUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)
+ if intLevel < 6: self.netUpfeat = torch.nn.ConvTranspose2d(in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1)
+ if intLevel < 6: self.fltBackwarp = [ None, None, None, 5.0, 2.5, 1.25, 0.625, None ][intLevel + 1]
+
+ self.netOne = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netTwo = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netThr = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFou = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFiv = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netSix = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1)
+ )
+ # end
+
+ def forward(self, tenFirst, tenSecond, objPrevious):
+ tenFlow = None
+ tenFeat = None
+
+ if objPrevious is None:
+ tenFlow = None
+ tenFeat = None
+
+ tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=tenSecond), negative_slope=0.1, inplace=False)
+
+ tenFeat = torch.cat([ tenVolume ], 1)
+
+ elif objPrevious is not None:
+ tenFlow = self.netUpflow(objPrevious['tenFlow'])
+ tenFeat = self.netUpfeat(objPrevious['tenFeat'])
+
+ tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=backwarp(tenInput=tenSecond, tenFlow=tenFlow * self.fltBackwarp)), negative_slope=0.1, inplace=False)
+
+ tenFeat = torch.cat([ tenVolume, tenFirst, tenFlow, tenFeat ], 1)
+
+ # end
+
+ tenFeat = torch.cat([ self.netOne(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netTwo(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netThr(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netFou(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netFiv(tenFeat), tenFeat ], 1)
+
+ tenFlow = self.netSix(tenFeat)
+
+ return {
+ 'tenFlow': tenFlow,
+ 'tenFeat': tenFeat
+ }
+ # end
+ # end
+
+ class Refiner(torch.nn.Module):
+ def __init__(self):
+ super(Refiner, self).__init__()
+
+ self.netMain = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=81 + 32 + 2 + 2 + 128 + 128 + 96 + 64 + 32, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1)
+ )
+ # end
+
+ def forward(self, tenInput):
+ return self.netMain(tenInput)
+ # end
+ # end
+
+ self.netExtractor = Extractor()
+
+ self.netTwo = Decoder(2)
+ self.netThr = Decoder(3)
+ self.netFou = Decoder(4)
+ self.netFiv = Decoder(5)
+ self.netSix = Decoder(6)
+
+ self.netRefiner = Refiner()
+
+ self.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.hub.load_state_dict_from_url(url='http://content.sniklaus.com/github/pytorch-pwc/network-' + 'default' + '.pytorch').items() })
+ # end
+
+ def forward(self, tenFirst, tenSecond):
+ intWidth = tenFirst.shape[3]
+ intHeight = tenFirst.shape[2]
+
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
+
+ tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+ tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+
+ tenFirst = self.netExtractor(tenPreprocessedFirst)
+ tenSecond = self.netExtractor(tenPreprocessedSecond)
+
+
+ objEstimate = self.netSix(tenFirst[-1], tenSecond[-1], None)
+ objEstimate = self.netFiv(tenFirst[-2], tenSecond[-2], objEstimate)
+ objEstimate = self.netFou(tenFirst[-3], tenSecond[-3], objEstimate)
+ objEstimate = self.netThr(tenFirst[-4], tenSecond[-4], objEstimate)
+ objEstimate = self.netTwo(tenFirst[-5], tenSecond[-5], objEstimate)
+
+ tenFlow = objEstimate['tenFlow'] + self.netRefiner(objEstimate['tenFeat'])
+ tenFlow = 20.0 * torch.nn.functional.interpolate(input=tenFlow, size=(intHeight, intWidth), mode='bilinear', align_corners=False)
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
+
+ return tenFlow
+ # end
+# end
+
+netNetwork = None
+
+##########################################################
+
+def estimate(tenFirst, tenSecond):
+ global netNetwork
+
+ if netNetwork is None:
+ netNetwork = Network().cuda().eval()
+ # end
+
+ assert(tenFirst.shape[1] == tenSecond.shape[1])
+ assert(tenFirst.shape[2] == tenSecond.shape[2])
+
+ intWidth = tenFirst.shape[2]
+ intHeight = tenFirst.shape[1]
+
+ assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+ assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+
+ tenPreprocessedFirst = tenFirst.cuda().view(1, 3, intHeight, intWidth)
+ tenPreprocessedSecond = tenSecond.cuda().view(1, 3, intHeight, intWidth)
+
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
+
+ tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+ tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+
+ tenFlow = 20.0 * torch.nn.functional.interpolate(input=netNetwork(tenPreprocessedFirst, tenPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False)
+
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
+
+ return tenFlow[0, :, :, :].cpu()
+# end
+
+##########################################################
+
+# if __name__ == '__main__':
+# tenFirst = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strFirst))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+# tenSecond = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strSecond))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+
+# tenOutput = estimate(tenFirst, tenSecond)
+
+# objOutput = open(arguments_strOut, 'wb')
+
+# numpy.array([ 80, 73, 69, 72 ], numpy.uint8).tofile(objOutput)
+# numpy.array([ tenOutput.shape[2], tenOutput.shape[1] ], numpy.int32).tofile(objOutput)
+# numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput)
+
+# objOutput.close()
+# end
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/flolpips/utils.py b/One-to-All-Animation/video-generation/opensora/eval/flolpips/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..98d4502d5de7b0c44cf11a15de58139325b68a19
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/flolpips/utils.py
@@ -0,0 +1,95 @@
+import numpy as np
+import cv2
+import torch
+
+
+def normalize_tensor(in_feat,eps=1e-10):
+ norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True))
+ return in_feat/(norm_factor+eps)
+
+def l2(p0, p1, range=255.):
+ return .5*np.mean((p0 / range - p1 / range)**2)
+
+def dssim(p0, p1, range=255.):
+ from skimage.measure import compare_ssim
+ return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2.
+
+def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.):
+ image_numpy = image_tensor[0].cpu().float().numpy()
+ image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor
+ return image_numpy.astype(imtype)
+
+def tensor2np(tensor_obj):
+ # change dimension of a tensor object into a numpy array
+ return tensor_obj[0].cpu().float().numpy().transpose((1,2,0))
+
+def np2tensor(np_obj):
+ # change dimenion of np array into tensor array
+ return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1)))
+
+def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False):
+ # image tensor to lab tensor
+ from skimage import color
+
+ img = tensor2im(image_tensor)
+ img_lab = color.rgb2lab(img)
+ if(mc_only):
+ img_lab[:,:,0] = img_lab[:,:,0]-50
+ if(to_norm and not mc_only):
+ img_lab[:,:,0] = img_lab[:,:,0]-50
+ img_lab = img_lab/100.
+
+ return np2tensor(img_lab)
+
+def read_frame_yuv2rgb(stream, width, height, iFrame, bit_depth, pix_fmt='420'):
+ if pix_fmt == '420':
+ multiplier = 1
+ uv_factor = 2
+ elif pix_fmt == '444':
+ multiplier = 2
+ uv_factor = 1
+ else:
+ print('Pixel format {} is not supported'.format(pix_fmt))
+ return
+
+ if bit_depth == 8:
+ datatype = np.uint8
+ stream.seek(iFrame*1.5*width*height*multiplier)
+ Y = np.fromfile(stream, dtype=datatype, count=width*height).reshape((height, width))
+
+ # read chroma samples and upsample since original is 4:2:0 sampling
+ U = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+ V = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+
+ else:
+ datatype = np.uint16
+ stream.seek(iFrame*3*width*height*multiplier)
+ Y = np.fromfile(stream, dtype=datatype, count=width*height).reshape((height, width))
+
+ U = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+ V = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+
+ if pix_fmt == '420':
+ yuv = np.empty((height*3//2, width), dtype=datatype)
+ yuv[0:height,:] = Y
+
+ yuv[height:height+height//4,:] = U.reshape(-1, width)
+ yuv[height+height//4:,:] = V.reshape(-1, width)
+
+ if bit_depth != 8:
+ yuv = (yuv/(2**bit_depth-1)*255).astype(np.uint8)
+
+ #convert to rgb
+ rgb = cv2.cvtColor(yuv, cv2.COLOR_YUV2RGB_I420)
+
+ else:
+ yvu = np.stack([Y,V,U],axis=2)
+ if bit_depth != 8:
+ yvu = (yvu/(2**bit_depth-1)*255).astype(np.uint8)
+ rgb = cv2.cvtColor(yvu, cv2.COLOR_YCrCb2RGB)
+
+ return rgb
diff --git a/One-to-All-Animation/video-generation/opensora/eval/fvd/styleganv/fvd.py b/One-to-All-Animation/video-generation/opensora/eval/fvd/styleganv/fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..3043a2a4a4c4fc48ca97aedba074c2c2379685e4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/fvd/styleganv/fvd.py
@@ -0,0 +1,90 @@
+import torch
+import os
+import math
+import torch.nn.functional as F
+
+# https://github.com/universome/fvd-comparison
+
+
+def load_i3d_pretrained(device=torch.device('cpu')):
+ i3D_WEIGHTS_URL = "https://www.dropbox.com/s/ge9e5ujwgetktms/i3d_torchscript.pt"
+ filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'i3d_torchscript.pt')
+ print(filepath)
+ if not os.path.exists(filepath):
+ print(f"preparing for download {i3D_WEIGHTS_URL}, you can download it by yourself.")
+ os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
+ i3d = torch.jit.load(filepath).eval().to(device)
+ i3d = torch.nn.DataParallel(i3d)
+ return i3d
+
+
+def get_feats(videos, detector, device, bs=10):
+ # videos : torch.tensor BCTHW [0, 1]
+ detector_kwargs = dict(rescale=False, resize=False, return_features=True) # Return raw features before the softmax layer.
+ feats = np.empty((0, 400))
+ with torch.no_grad():
+ for i in range((len(videos)-1)//bs + 1):
+ feats = np.vstack([feats, detector(torch.stack([preprocess_single(video) for video in videos[i*bs:(i+1)*bs]]).to(device), **detector_kwargs).detach().cpu().numpy()])
+ return feats
+
+
+def get_fvd_feats(videos, i3d, device, bs=10):
+ # videos in [0, 1] as torch tensor BCTHW
+ # videos = [preprocess_single(video) for video in videos]
+ embeddings = get_feats(videos, i3d, device, bs)
+ return embeddings
+
+
+def preprocess_single(video, resolution=224, sequence_length=None):
+ # video: CTHW, [0, 1]
+ c, t, h, w = video.shape
+
+ # temporal crop
+ if sequence_length is not None:
+ assert sequence_length <= t
+ video = video[:, :sequence_length]
+
+ # scale shorter side to resolution
+ scale = resolution / min(h, w)
+ if h < w:
+ target_size = (resolution, math.ceil(w * scale))
+ else:
+ target_size = (math.ceil(h * scale), resolution)
+ video = F.interpolate(video, size=target_size, mode='bilinear', align_corners=False)
+
+ # center crop
+ c, t, h, w = video.shape
+ w_start = (w - resolution) // 2
+ h_start = (h - resolution) // 2
+ video = video[:, :, h_start:h_start + resolution, w_start:w_start + resolution]
+
+ # [0, 1] -> [-1, 1]
+ video = (video - 0.5) * 2
+
+ return video.contiguous()
+
+
+"""
+Copy-pasted from https://github.com/cvpr2022-stylegan-v/stylegan-v/blob/main/src/metrics/frechet_video_distance.py
+"""
+from typing import Tuple
+from scipy.linalg import sqrtm
+import numpy as np
+
+
+def compute_stats(feats: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
+ mu = feats.mean(axis=0) # [d]
+ sigma = np.cov(feats, rowvar=False) # [d, d]
+ return mu, sigma
+
+
+def frechet_distance(feats_fake: np.ndarray, feats_real: np.ndarray) -> float:
+ mu_gen, sigma_gen = compute_stats(feats_fake)
+ mu_real, sigma_real = compute_stats(feats_real)
+ m = np.square(mu_gen - mu_real).sum()
+ if feats_fake.shape[0]>1:
+ s, _ = sqrtm(np.dot(sigma_gen, sigma_real), disp=False) # pylint: disable=no-member
+ fid = np.real(m + np.trace(sigma_gen + sigma_real - s * 2))
+ else:
+ fid = np.real(m)
+ return float(fid)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/fvd.py b/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81c8290456a5f54de6d31bf0f946f87a12eda9c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/fvd.py
@@ -0,0 +1,137 @@
+import torch
+import os
+import math
+import torch.nn.functional as F
+import numpy as np
+import einops
+
+def load_i3d_pretrained(device=torch.device('cpu')):
+ i3D_WEIGHTS_URL = "https://onedrive.live.com/download?cid=78EEF3EB6AE7DBCB&resid=78EEF3EB6AE7DBCB%21199&authkey=AApKdFHPXzWLNyI"
+ filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'i3d_pretrained_400.pt')
+ print(filepath)
+ if not os.path.exists(filepath):
+ print(f"preparing for download {i3D_WEIGHTS_URL}, you can download it by yourself.")
+ os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
+ from .pytorch_i3d import InceptionI3d
+ i3d = InceptionI3d(400, in_channels=3).eval().to(device)
+ i3d.load_state_dict(torch.load(filepath, map_location=device))
+ i3d = torch.nn.DataParallel(i3d)
+ return i3d
+
+def preprocess_single(video, resolution, sequence_length=None):
+ # video: THWC, {0, ..., 255}
+ video = video.permute(0, 3, 1, 2).float() / 255. # TCHW
+ t, c, h, w = video.shape
+
+ # temporal crop
+ if sequence_length is not None:
+ assert sequence_length <= t
+ video = video[:sequence_length]
+
+ # scale shorter side to resolution
+ scale = resolution / min(h, w)
+ if h < w:
+ target_size = (resolution, math.ceil(w * scale))
+ else:
+ target_size = (math.ceil(h * scale), resolution)
+ video = F.interpolate(video, size=target_size, mode='bilinear',
+ align_corners=False)
+
+ # center crop
+ t, c, h, w = video.shape
+ w_start = (w - resolution) // 2
+ h_start = (h - resolution) // 2
+ video = video[:, :, h_start:h_start + resolution, w_start:w_start + resolution]
+ video = video.permute(1, 0, 2, 3).contiguous() # CTHW
+
+ video -= 0.5
+
+ return video
+
+def preprocess(videos, target_resolution=224):
+ # we should tras videos in [0-1] [b c t h w] as th.float
+ # -> videos in {0, ..., 255} [b t h w c] as np.uint8 array
+ videos = einops.rearrange(videos, 'b c t h w -> b t h w c')
+ videos = (videos*255).numpy().astype(np.uint8)
+
+ b, t, h, w, c = videos.shape
+ videos = torch.from_numpy(videos)
+ videos = torch.stack([preprocess_single(video, target_resolution) for video in videos])
+ return videos * 2 # [-0.5, 0.5] -> [-1, 1]
+
+def get_fvd_logits(videos, i3d, device, bs=10):
+ videos = preprocess(videos)
+ embeddings = get_logits(i3d, videos, device, bs=10)
+ return embeddings
+
+# https://github.com/tensorflow/gan/blob/de4b8da3853058ea380a6152bd3bd454013bf619/tensorflow_gan/python/eval/classifier_metrics.py#L161
+def _symmetric_matrix_square_root(mat, eps=1e-10):
+ u, s, v = torch.svd(mat)
+ si = torch.where(s < eps, s, torch.sqrt(s))
+ return torch.matmul(torch.matmul(u, torch.diag(si)), v.t())
+
+# https://github.com/tensorflow/gan/blob/de4b8da3853058ea380a6152bd3bd454013bf619/tensorflow_gan/python/eval/classifier_metrics.py#L400
+def trace_sqrt_product(sigma, sigma_v):
+ sqrt_sigma = _symmetric_matrix_square_root(sigma)
+ sqrt_a_sigmav_a = torch.matmul(sqrt_sigma, torch.matmul(sigma_v, sqrt_sigma))
+ return torch.trace(_symmetric_matrix_square_root(sqrt_a_sigmav_a))
+
+# https://discuss.pytorch.org/t/covariance-and-gradient-support/16217/2
+def cov(m, rowvar=False):
+ '''Estimate a covariance matrix given data.
+
+ Covariance indicates the level to which two variables vary together.
+ If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,
+ then the covariance matrix element `C_{ij}` is the covariance of
+ `x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`.
+
+ Args:
+ m: A 1-D or 2-D array containing multiple variables and observations.
+ Each row of `m` represents a variable, and each column a single
+ observation of all those variables.
+ rowvar: If `rowvar` is True, then each row represents a
+ variable, with observations in the columns. Otherwise, the
+ relationship is transposed: each column represents a variable,
+ while the rows contain observations.
+
+ Returns:
+ The covariance matrix of the variables.
+ '''
+ if m.dim() > 2:
+ raise ValueError('m has more than 2 dimensions')
+ if m.dim() < 2:
+ m = m.view(1, -1)
+ if not rowvar and m.size(0) != 1:
+ m = m.t()
+
+ fact = 1.0 / (m.size(1) - 1) # unbiased estimate
+ m -= torch.mean(m, dim=1, keepdim=True)
+ mt = m.t() # if complex: mt = m.t().conj()
+ return fact * m.matmul(mt).squeeze()
+
+
+def frechet_distance(x1, x2):
+ x1 = x1.flatten(start_dim=1)
+ x2 = x2.flatten(start_dim=1)
+ m, m_w = x1.mean(dim=0), x2.mean(dim=0)
+ sigma, sigma_w = cov(x1, rowvar=False), cov(x2, rowvar=False)
+ mean = torch.sum((m - m_w) ** 2)
+ if x1.shape[0]>1:
+ sqrt_trace_component = trace_sqrt_product(sigma, sigma_w)
+ trace = torch.trace(sigma + sigma_w) - 2.0 * sqrt_trace_component
+ fd = trace + mean
+ else:
+ fd = np.real(mean)
+ return float(fd)
+
+
+def get_logits(i3d, videos, device, bs=10):
+ # assert videos.shape[0] % 16 == 0
+ with torch.no_grad():
+ logits = []
+ for i in range(0, videos.shape[0], bs):
+ batch = videos[i:i + bs].to(device)
+ # logits.append(i3d.module.extract_features(batch)) # wrong
+ logits.append(i3d(batch)) # right
+ logits = torch.cat(logits, dim=0)
+ return logits
diff --git a/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/pytorch_i3d.py b/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/pytorch_i3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..58a16cdd797e5a0e9d711bb0ba14281486d44d03
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/fvd/videogpt/pytorch_i3d.py
@@ -0,0 +1,322 @@
+# Original code from https://github.com/piergiaj/pytorch-i3d
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+class MaxPool3dSamePadding(nn.MaxPool3d):
+
+ def compute_pad(self, dim, s):
+ if s % self.stride[dim] == 0:
+ return max(self.kernel_size[dim] - self.stride[dim], 0)
+ else:
+ return max(self.kernel_size[dim] - (s % self.stride[dim]), 0)
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ out_t = np.ceil(float(t) / float(self.stride[0]))
+ out_h = np.ceil(float(h) / float(self.stride[1]))
+ out_w = np.ceil(float(w) / float(self.stride[2]))
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+ return super(MaxPool3dSamePadding, self).forward(x)
+
+
+class Unit3D(nn.Module):
+
+ def __init__(self, in_channels,
+ output_channels,
+ kernel_shape=(1, 1, 1),
+ stride=(1, 1, 1),
+ padding=0,
+ activation_fn=F.relu,
+ use_batch_norm=True,
+ use_bias=False,
+ name='unit_3d'):
+
+ """Initializes Unit3D module."""
+ super(Unit3D, self).__init__()
+
+ self._output_channels = output_channels
+ self._kernel_shape = kernel_shape
+ self._stride = stride
+ self._use_batch_norm = use_batch_norm
+ self._activation_fn = activation_fn
+ self._use_bias = use_bias
+ self.name = name
+ self.padding = padding
+
+ self.conv3d = nn.Conv3d(in_channels=in_channels,
+ out_channels=self._output_channels,
+ kernel_size=self._kernel_shape,
+ stride=self._stride,
+ padding=0, # we always want padding to be 0 here. We will dynamically pad based on input size in forward function
+ bias=self._use_bias)
+
+ if self._use_batch_norm:
+ self.bn = nn.BatchNorm3d(self._output_channels, eps=1e-5, momentum=0.001)
+
+ def compute_pad(self, dim, s):
+ if s % self._stride[dim] == 0:
+ return max(self._kernel_shape[dim] - self._stride[dim], 0)
+ else:
+ return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0)
+
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ out_t = np.ceil(float(t) / float(self._stride[0]))
+ out_h = np.ceil(float(h) / float(self._stride[1]))
+ out_w = np.ceil(float(w) / float(self._stride[2]))
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+
+ x = self.conv3d(x)
+ if self._use_batch_norm:
+ x = self.bn(x)
+ if self._activation_fn is not None:
+ x = self._activation_fn(x)
+ return x
+
+
+
+class InceptionModule(nn.Module):
+ def __init__(self, in_channels, out_channels, name):
+ super(InceptionModule, self).__init__()
+
+ self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_0/Conv3d_0a_1x1')
+ self.b1a = Unit3D(in_channels=in_channels, output_channels=out_channels[1], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_1/Conv3d_0a_1x1')
+ self.b1b = Unit3D(in_channels=out_channels[1], output_channels=out_channels[2], kernel_shape=[3, 3, 3],
+ name=name+'/Branch_1/Conv3d_0b_3x3')
+ self.b2a = Unit3D(in_channels=in_channels, output_channels=out_channels[3], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_2/Conv3d_0a_1x1')
+ self.b2b = Unit3D(in_channels=out_channels[3], output_channels=out_channels[4], kernel_shape=[3, 3, 3],
+ name=name+'/Branch_2/Conv3d_0b_3x3')
+ self.b3a = MaxPool3dSamePadding(kernel_size=[3, 3, 3],
+ stride=(1, 1, 1), padding=0)
+ self.b3b = Unit3D(in_channels=in_channels, output_channels=out_channels[5], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_3/Conv3d_0b_1x1')
+ self.name = name
+
+ def forward(self, x):
+ b0 = self.b0(x)
+ b1 = self.b1b(self.b1a(x))
+ b2 = self.b2b(self.b2a(x))
+ b3 = self.b3b(self.b3a(x))
+ return torch.cat([b0,b1,b2,b3], dim=1)
+
+
+class InceptionI3d(nn.Module):
+ """Inception-v1 I3D architecture.
+ The model is introduced in:
+ Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
+ Joao Carreira, Andrew Zisserman
+ https://arxiv.org/pdf/1705.07750v1.pdf.
+ See also the Inception architecture, introduced in:
+ Going deeper with convolutions
+ Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,
+ Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.
+ http://arxiv.org/pdf/1409.4842v1.pdf.
+ """
+
+ # Endpoints of the model in order. During construction, all the endpoints up
+ # to a designated `final_endpoint` are returned in a dictionary as the
+ # second return value.
+ VALID_ENDPOINTS = (
+ 'Conv3d_1a_7x7',
+ 'MaxPool3d_2a_3x3',
+ 'Conv3d_2b_1x1',
+ 'Conv3d_2c_3x3',
+ 'MaxPool3d_3a_3x3',
+ 'Mixed_3b',
+ 'Mixed_3c',
+ 'MaxPool3d_4a_3x3',
+ 'Mixed_4b',
+ 'Mixed_4c',
+ 'Mixed_4d',
+ 'Mixed_4e',
+ 'Mixed_4f',
+ 'MaxPool3d_5a_2x2',
+ 'Mixed_5b',
+ 'Mixed_5c',
+ 'Logits',
+ 'Predictions',
+ )
+
+ def __init__(self, num_classes=400, spatial_squeeze=True,
+ final_endpoint='Logits', name='inception_i3d', in_channels=3, dropout_keep_prob=0.5):
+ """Initializes I3D model instance.
+ Args:
+ num_classes: The number of outputs in the logit layer (default 400, which
+ matches the Kinetics dataset).
+ spatial_squeeze: Whether to squeeze the spatial dimensions for the logits
+ before returning (default True).
+ final_endpoint: The model contains many possible endpoints.
+ `final_endpoint` specifies the last endpoint for the model to be built
+ up to. In addition to the output at `final_endpoint`, all the outputs
+ at endpoints up to `final_endpoint` will also be returned, in a
+ dictionary. `final_endpoint` must be one of
+ InceptionI3d.VALID_ENDPOINTS (default 'Logits').
+ name: A string (optional). The name of this module.
+ Raises:
+ ValueError: if `final_endpoint` is not recognized.
+ """
+
+ if final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' % final_endpoint)
+
+ super(InceptionI3d, self).__init__()
+ self._num_classes = num_classes
+ self._spatial_squeeze = spatial_squeeze
+ self._final_endpoint = final_endpoint
+ self.logits = None
+
+ if self._final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' % self._final_endpoint)
+
+ self.end_points = {}
+ end_point = 'Conv3d_1a_7x7'
+ self.end_points[end_point] = Unit3D(in_channels=in_channels, output_channels=64, kernel_shape=[7, 7, 7],
+ stride=(2, 2, 2), padding=(3,3,3), name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_2a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Conv3d_2b_1x1'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=64, kernel_shape=[1, 1, 1], padding=0,
+ name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Conv3d_2c_3x3'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=192, kernel_shape=[3, 3, 3], padding=1,
+ name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_3a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_3b'
+ self.end_points[end_point] = InceptionModule(192, [64,96,128,16,32,32], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_3c'
+ self.end_points[end_point] = InceptionModule(256, [128,128,192,32,96,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_4a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[3, 3, 3], stride=(2, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4b'
+ self.end_points[end_point] = InceptionModule(128+192+96+64, [192,96,208,16,48,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4c'
+ self.end_points[end_point] = InceptionModule(192+208+48+64, [160,112,224,24,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4d'
+ self.end_points[end_point] = InceptionModule(160+224+64+64, [128,128,256,24,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4e'
+ self.end_points[end_point] = InceptionModule(128+256+64+64, [112,144,288,32,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4f'
+ self.end_points[end_point] = InceptionModule(112+288+64+64, [256,160,320,32,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_5a_2x2'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[2, 2, 2], stride=(2, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_5b'
+ self.end_points[end_point] = InceptionModule(256+320+128+128, [256,160,320,32,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_5c'
+ self.end_points[end_point] = InceptionModule(256+320+128+128, [384,192,384,48,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Logits'
+ self.avg_pool = nn.AvgPool3d(kernel_size=[2, 7, 7],
+ stride=(1, 1, 1))
+ self.dropout = nn.Dropout(dropout_keep_prob)
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+ self.build()
+
+
+ def replace_logits(self, num_classes):
+ self._num_classes = num_classes
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+
+ def build(self):
+ for k in self.end_points.keys():
+ self.add_module(k, self.end_points[k])
+
+ def forward(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ x = self._modules[end_point](x) # use _modules to work with dataparallel
+
+ x = self.logits(self.dropout(self.avg_pool(x)))
+ if self._spatial_squeeze:
+ logits = x.squeeze(3).squeeze(3)
+ logits = logits.mean(dim=2)
+ # logits is batch X time X classes, which is what we want to work with
+ return logits
+
+
+ def extract_features(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ x = self._modules[end_point](x)
+ return self.avg_pool(x)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/script/cal_clip_score.sh b/One-to-All-Animation/video-generation/opensora/eval/script/cal_clip_score.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8bc241c154a72805282b511dcfb2164a5f6a282e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/script/cal_clip_score.sh
@@ -0,0 +1,23 @@
+# clip_score cross modality
+python eval_clip_score.py \
+ --real_path path/to/image \
+ --generated_path path/to/text \
+ --batch-size 50 \
+ --device "cuda"
+
+# clip_score within the same modality
+python eval_clip_score.py \
+ --real_path path/to/textA \
+ --generated_path path/to/textB \
+ --real_flag txt \
+ --generated_flag txt \
+ --batch-size 50 \
+ --device "cuda"
+
+python eval_clip_score.py \
+ --real_path path/to/imageA \
+ --generated_path path/to/imageB \
+ --real_flag img \
+ --generated_flag img \
+ --batch-size 50 \
+ --device "cuda"
diff --git a/One-to-All-Animation/video-generation/opensora/eval/script/cal_fvd.sh b/One-to-All-Animation/video-generation/opensora/eval/script/cal_fvd.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e344242a0ec2bf4d62f390312d6a396591c049a8
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/script/cal_fvd.sh
@@ -0,0 +1,9 @@
+python eval_common_metric.py \
+ --real_video_dir path/to/imageA\
+ --generated_video_dir path/to/imageB \
+ --batch_size 10 \
+ --crop_size 64 \
+ --num_frames 20 \
+ --device 'cuda' \
+ --metric 'fvd' \
+ --fvd_method 'styleganv'
diff --git a/One-to-All-Animation/video-generation/opensora/eval/script/cal_lpips.sh b/One-to-All-Animation/video-generation/opensora/eval/script/cal_lpips.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9ebaf26e856166fed4573a8164f7c5b557bfd229
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/script/cal_lpips.sh
@@ -0,0 +1,8 @@
+python eval_common_metric.py \
+ --real_video_dir path/to/imageA\
+ --generated_video_dir path/to/imageB \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'lpips'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/script/cal_psnr.sh b/One-to-All-Animation/video-generation/opensora/eval/script/cal_psnr.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a60a5d1c167f2dcd4a251b31af0d8a534bfee195
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/script/cal_psnr.sh
@@ -0,0 +1,9 @@
+
+python eval_common_metric.py \
+ --real_video_dir /data/xiaogeng_liu/data/video1 \
+ --generated_video_dir /data/xiaogeng_liu/data/video2 \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'psnr'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/eval/script/cal_ssim.sh b/One-to-All-Animation/video-generation/opensora/eval/script/cal_ssim.sh
new file mode 100644
index 0000000000000000000000000000000000000000..404d8da9a12a28a3c173dc87652a380e7a754b25
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/eval/script/cal_ssim.sh
@@ -0,0 +1,8 @@
+python eval_common_metric.py \
+ --real_video_dir /data/xiaogeng_liu/data/video1 \
+ --generated_video_dir /data/xiaogeng_liu/data/video2 \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'ssim'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/__init__.py b/One-to-All-Animation/video-generation/opensora/flux_modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..9fedf56504bdee0d5a4b4972245e7dfcce0e134f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/__init__.py
@@ -0,0 +1,3 @@
+from .modeling_pyramid_flux import PyramidFluxTransformer
+from .modeling_text_encoder import FluxTextEncoderWithMask
+from .modeling_flux_block import FluxSingleTransformerBlock, FluxTransformerBlock
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/controlnet_flux.py b/One-to-All-Animation/video-generation/opensora/flux_modules/controlnet_flux.py
new file mode 100644
index 0000000000000000000000000000000000000000..d4c5c45490ab18304aae1c434ddf9a261dc3d90c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/controlnet_flux.py
@@ -0,0 +1,536 @@
+# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from ...configuration_utils import ConfigMixin, register_to_config
+from ...loaders import PeftAdapterMixin
+from ...models.attention_processor import AttentionProcessor
+from ...models.modeling_utils import ModelMixin
+from ...utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from ..controlnets.controlnet import ControlNetConditioningEmbedding, zero_module
+from ..embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
+from ..modeling_outputs import Transformer2DModelOutput
+from ..transformers.transformer_flux import FluxSingleTransformerBlock, FluxTransformerBlock
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@dataclass
+class FluxControlNetOutput(BaseOutput):
+ controlnet_block_samples: Tuple[torch.Tensor]
+ controlnet_single_block_samples: Tuple[torch.Tensor]
+
+
+class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: int = 1,
+ in_channels: int = 64,
+ num_layers: int = 19,
+ num_single_layers: int = 38,
+ attention_head_dim: int = 128,
+ num_attention_heads: int = 24,
+ joint_attention_dim: int = 4096,
+ pooled_projection_dim: int = 768,
+ guidance_embeds: bool = False,
+ axes_dims_rope: List[int] = [16, 56, 56],
+ num_mode: int = None,
+ conditioning_embedding_channels: int = None,
+ ):
+ super().__init__()
+ self.out_channels = in_channels
+ self.inner_dim = num_attention_heads * attention_head_dim
+
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
+ text_time_guidance_cls = (
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
+ )
+ self.time_text_embed = text_time_guidance_cls(
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
+ )
+
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
+ self.x_embedder = torch.nn.Linear(in_channels, self.inner_dim)
+
+ self.transformer_blocks = nn.ModuleList(
+ [
+ FluxTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ )
+ for i in range(num_layers)
+ ]
+ )
+
+ self.single_transformer_blocks = nn.ModuleList(
+ [
+ FluxSingleTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ )
+ for i in range(num_single_layers)
+ ]
+ )
+
+ # controlnet_blocks
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.transformer_blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
+
+ self.controlnet_single_blocks = nn.ModuleList([])
+ for _ in range(len(self.single_transformer_blocks)):
+ self.controlnet_single_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
+
+ self.union = num_mode is not None
+ if self.union:
+ self.controlnet_mode_embedder = nn.Embedding(num_mode, self.inner_dim)
+
+ if conditioning_embedding_channels is not None:
+ self.input_hint_block = ControlNetConditioningEmbedding(
+ conditioning_embedding_channels=conditioning_embedding_channels, block_out_channels=(16, 16, 16, 16)
+ )
+ self.controlnet_x_embedder = torch.nn.Linear(in_channels, self.inner_dim)
+ else:
+ self.input_hint_block = None
+ self.controlnet_x_embedder = zero_module(torch.nn.Linear(in_channels, self.inner_dim))
+
+ self.gradient_checkpointing = False
+
+ @property
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self):
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "get_processor"):
+ processors[f"{name}.processor"] = module.get_processor()
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor):
+ r"""
+ Sets the attention processor to use to compute attention.
+
+ Parameters:
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ for **all** `Attention` layers.
+
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
+ processor. This is strongly recommended when setting trainable attention processors.
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ @classmethod
+ def from_transformer(
+ cls,
+ transformer,
+ num_layers: int = 4,
+ num_single_layers: int = 10,
+ attention_head_dim: int = 128,
+ num_attention_heads: int = 24,
+ load_weights_from_transformer=True,
+ ):
+ config = dict(transformer.config)
+ config["num_layers"] = num_layers
+ config["num_single_layers"] = num_single_layers
+ config["attention_head_dim"] = attention_head_dim
+ config["num_attention_heads"] = num_attention_heads
+
+ controlnet = cls.from_config(config)
+
+ if load_weights_from_transformer:
+ controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
+ controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict())
+ controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict())
+ controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict())
+ controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict(), strict=False)
+ controlnet.single_transformer_blocks.load_state_dict(
+ transformer.single_transformer_blocks.state_dict(), strict=False
+ )
+
+ controlnet.controlnet_x_embedder = zero_module(controlnet.controlnet_x_embedder)
+
+ return controlnet
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ controlnet_mode: torch.Tensor = None,
+ conditioning_scale: float = 1.0,
+ encoder_hidden_states: torch.Tensor = None,
+ pooled_projections: torch.Tensor = None,
+ timestep: torch.LongTensor = None,
+ img_ids: torch.Tensor = None,
+ txt_ids: torch.Tensor = None,
+ guidance: torch.Tensor = None,
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
+ """
+ The [`FluxTransformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
+ Input `hidden_states`.
+ controlnet_cond (`torch.Tensor`):
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
+ controlnet_mode (`torch.Tensor`):
+ The mode tensor of shape `(batch_size, 1)`.
+ conditioning_scale (`float`, defaults to `1.0`):
+ The scale factor for ControlNet outputs.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
+ from the embeddings of input conditions.
+ timestep ( `torch.LongTensor`):
+ Used to indicate denoising step.
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
+ A list of tensors that if specified are added to the residuals of transformer blocks.
+ joint_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ if joint_attention_kwargs is not None:
+ joint_attention_kwargs = joint_attention_kwargs.copy()
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+ hidden_states = self.x_embedder(hidden_states)
+
+ if self.input_hint_block is not None:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ batch_size, channels, height_pw, width_pw = controlnet_cond.shape
+ height = height_pw // self.config.patch_size
+ width = width_pw // self.config.patch_size
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels, height, self.config.patch_size, width, self.config.patch_size
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 1, 3, 5)
+ controlnet_cond = controlnet_cond.reshape(batch_size, height * width, -1)
+ # add
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
+
+ timestep = timestep.to(hidden_states.dtype) * 1000
+ if guidance is not None:
+ guidance = guidance.to(hidden_states.dtype) * 1000
+ else:
+ guidance = None
+ temb = (
+ self.time_text_embed(timestep, pooled_projections)
+ if guidance is None
+ else self.time_text_embed(timestep, guidance, pooled_projections)
+ )
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
+
+ if self.union:
+ # union mode
+ if controlnet_mode is None:
+ raise ValueError("`controlnet_mode` cannot be `None` when applying ControlNet-Union")
+ # union mode emb
+ controlnet_mode_emb = self.controlnet_mode_embedder(controlnet_mode)
+ encoder_hidden_states = torch.cat([controlnet_mode_emb, encoder_hidden_states], dim=1)
+ txt_ids = torch.cat([txt_ids[:1], txt_ids], dim=0)
+
+ if txt_ids.ndim == 3:
+ logger.warning(
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ txt_ids = txt_ids[0]
+ if img_ids.ndim == 3:
+ logger.warning(
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ img_ids = img_ids[0]
+
+ ids = torch.cat((txt_ids, img_ids), dim=0)
+ image_rotary_emb = self.pos_embed(ids)
+
+ block_samples = ()
+ for index_block, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ encoder_hidden_states, hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ )
+ block_samples = block_samples + (hidden_states,)
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ single_block_samples = ()
+ for index_block, block in enumerate(self.single_transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ hidden_states = block(
+ hidden_states=hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ )
+ single_block_samples = single_block_samples + (hidden_states[:, encoder_hidden_states.shape[1] :],)
+
+ # controlnet block
+ controlnet_block_samples = ()
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (block_sample,)
+
+ controlnet_single_block_samples = ()
+ for single_block_sample, controlnet_block in zip(single_block_samples, self.controlnet_single_blocks):
+ single_block_sample = controlnet_block(single_block_sample)
+ controlnet_single_block_samples = controlnet_single_block_samples + (single_block_sample,)
+
+ # scaling
+ controlnet_block_samples = [sample * conditioning_scale for sample in controlnet_block_samples]
+ controlnet_single_block_samples = [sample * conditioning_scale for sample in controlnet_single_block_samples]
+
+ controlnet_block_samples = None if len(controlnet_block_samples) == 0 else controlnet_block_samples
+ controlnet_single_block_samples = (
+ None if len(controlnet_single_block_samples) == 0 else controlnet_single_block_samples
+ )
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (controlnet_block_samples, controlnet_single_block_samples)
+
+ return FluxControlNetOutput(
+ controlnet_block_samples=controlnet_block_samples,
+ controlnet_single_block_samples=controlnet_single_block_samples,
+ )
+
+
+class FluxMultiControlNetModel(ModelMixin):
+ r"""
+ `FluxMultiControlNetModel` wrapper class for Multi-FluxControlNetModel
+
+ This module is a wrapper for multiple instances of the `FluxControlNetModel`. The `forward()` API is designed to be
+ compatible with `FluxControlNetModel`.
+
+ Args:
+ controlnets (`List[FluxControlNetModel]`):
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
+ `FluxControlNetModel` as a list.
+ """
+
+ def __init__(self, controlnets):
+ super().__init__()
+ self.nets = nn.ModuleList(controlnets)
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ controlnet_cond: List[torch.tensor],
+ controlnet_mode: List[torch.tensor],
+ conditioning_scale: List[float],
+ encoder_hidden_states: torch.Tensor = None,
+ pooled_projections: torch.Tensor = None,
+ timestep: torch.LongTensor = None,
+ img_ids: torch.Tensor = None,
+ txt_ids: torch.Tensor = None,
+ guidance: torch.Tensor = None,
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
+ return_dict: bool = True,
+ ) -> Union[FluxControlNetOutput, Tuple]:
+ # ControlNet-Union with multiple conditions
+ # only load one ControlNet for saving memories
+ if len(self.nets) == 1 and self.nets[0].union:
+ controlnet = self.nets[0]
+
+ for i, (image, mode, scale) in enumerate(zip(controlnet_cond, controlnet_mode, conditioning_scale)):
+ block_samples, single_block_samples = controlnet(
+ hidden_states=hidden_states,
+ controlnet_cond=image,
+ controlnet_mode=mode[:, None],
+ conditioning_scale=scale,
+ timestep=timestep,
+ guidance=guidance,
+ pooled_projections=pooled_projections,
+ encoder_hidden_states=encoder_hidden_states,
+ txt_ids=txt_ids,
+ img_ids=img_ids,
+ joint_attention_kwargs=joint_attention_kwargs,
+ return_dict=return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ control_block_samples = block_samples
+ control_single_block_samples = single_block_samples
+ else:
+ control_block_samples = [
+ control_block_sample + block_sample
+ for control_block_sample, block_sample in zip(control_block_samples, block_samples)
+ ]
+
+ control_single_block_samples = [
+ control_single_block_sample + block_sample
+ for control_single_block_sample, block_sample in zip(
+ control_single_block_samples, single_block_samples
+ )
+ ]
+
+ # Regular Multi-ControlNets
+ # load all ControlNets into memories
+ else:
+ for i, (image, mode, scale, controlnet) in enumerate(
+ zip(controlnet_cond, controlnet_mode, conditioning_scale, self.nets)
+ ):
+ block_samples, single_block_samples = controlnet(
+ hidden_states=hidden_states,
+ controlnet_cond=image,
+ controlnet_mode=mode[:, None],
+ conditioning_scale=scale,
+ timestep=timestep,
+ guidance=guidance,
+ pooled_projections=pooled_projections,
+ encoder_hidden_states=encoder_hidden_states,
+ txt_ids=txt_ids,
+ img_ids=img_ids,
+ joint_attention_kwargs=joint_attention_kwargs,
+ return_dict=return_dict,
+ )
+
+ # merge samples
+ if i == 0:
+ control_block_samples = block_samples
+ control_single_block_samples = single_block_samples
+ else:
+ if block_samples is not None and control_block_samples is not None:
+ control_block_samples = [
+ control_block_sample + block_sample
+ for control_block_sample, block_sample in zip(control_block_samples, block_samples)
+ ]
+ if single_block_samples is not None and control_single_block_samples is not None:
+ control_single_block_samples = [
+ control_single_block_sample + block_sample
+ for control_single_block_sample, block_sample in zip(
+ control_single_block_samples, single_block_samples
+ )
+ ]
+
+ return control_block_samples, control_single_block_samples
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/flux.py b/One-to-All-Animation/video-generation/opensora/flux_modules/flux.py
new file mode 100644
index 0000000000000000000000000000000000000000..845c2c599a31df609ddda5d7101fdce72c070eae
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/flux.py
@@ -0,0 +1,593 @@
+# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from ...configuration_utils import ConfigMixin, register_to_config
+from ...loaders import FluxTransformer2DLoadersMixin, FromOriginalModelMixin, PeftAdapterMixin
+from ...models.attention import FeedForward
+from ...models.attention_processor import (
+ Attention,
+ AttentionProcessor,
+ FluxAttnProcessor2_0,
+ FluxAttnProcessor2_0_NPU,
+ FusedFluxAttnProcessor2_0,
+)
+from ...models.modeling_utils import ModelMixin
+from ...models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
+from ...utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from ...utils.import_utils import is_torch_npu_available
+from ...utils.torch_utils import maybe_allow_in_graph
+from ..embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
+from ..modeling_outputs import Transformer2DModelOutput
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@maybe_allow_in_graph
+class FluxSingleTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
+ super().__init__()
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
+
+ self.norm = AdaLayerNormZeroSingle(dim)
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
+ self.act_mlp = nn.GELU(approximate="tanh")
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
+
+ if is_torch_npu_available():
+ processor = FluxAttnProcessor2_0_NPU()
+ else:
+ processor = FluxAttnProcessor2_0()
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ bias=True,
+ processor=processor,
+ qk_norm="rms_norm",
+ eps=1e-6,
+ pre_only=True,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ image_rotary_emb=None,
+ joint_attention_kwargs=None,
+ ):
+ residual = hidden_states
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
+ joint_attention_kwargs = joint_attention_kwargs or {}
+ attn_output = self.attn(
+ hidden_states=norm_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ **joint_attention_kwargs,
+ )
+
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
+ gate = gate.unsqueeze(1)
+ hidden_states = gate * self.proj_out(hidden_states)
+ hidden_states = residual + hidden_states
+ if hidden_states.dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+@maybe_allow_in_graph
+class FluxTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6):
+ super().__init__()
+
+ self.norm1 = AdaLayerNormZero(dim)
+
+ self.norm1_context = AdaLayerNormZero(dim)
+
+ if hasattr(F, "scaled_dot_product_attention"):
+ processor = FluxAttnProcessor2_0()
+ else:
+ raise ValueError(
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
+ )
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ added_kv_proj_dim=dim,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ context_pre_only=False,
+ bias=True,
+ processor=processor,
+ qk_norm=qk_norm,
+ eps=eps,
+ )
+
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ image_rotary_emb=None,
+ joint_attention_kwargs=None,
+ ):
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
+
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
+ encoder_hidden_states, emb=temb
+ )
+ joint_attention_kwargs = joint_attention_kwargs or {}
+ # Attention.
+ attention_outputs = self.attn(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=norm_encoder_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ **joint_attention_kwargs,
+ )
+
+ if len(attention_outputs) == 2:
+ attn_output, context_attn_output = attention_outputs
+ elif len(attention_outputs) == 3:
+ attn_output, context_attn_output, ip_attn_output = attention_outputs
+
+ # Process attention outputs for the `hidden_states`.
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = hidden_states + attn_output
+
+ norm_hidden_states = self.norm2(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ ff_output = self.ff(norm_hidden_states)
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+
+ hidden_states = hidden_states + ff_output
+ if len(attention_outputs) == 3:
+ hidden_states = hidden_states + ip_attn_output
+
+ # Process attention outputs for the `encoder_hidden_states`.
+
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
+
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
+
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
+ if encoder_hidden_states.dtype == torch.float16:
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
+
+ return encoder_hidden_states, hidden_states
+
+
+class FluxTransformer2DModel(
+ ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, FluxTransformer2DLoadersMixin
+):
+ """
+ The Transformer model introduced in Flux.
+
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
+
+ Parameters:
+ patch_size (`int`): Patch size to turn the input data into small patches.
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
+ num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
+ num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
+ guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
+ """
+
+ _supports_gradient_checkpointing = True
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: int = 1,
+ in_channels: int = 64,
+ out_channels: Optional[int] = None,
+ num_layers: int = 19,
+ num_single_layers: int = 38,
+ attention_head_dim: int = 128,
+ num_attention_heads: int = 24,
+ joint_attention_dim: int = 4096,
+ pooled_projection_dim: int = 768,
+ guidance_embeds: bool = False,
+ axes_dims_rope: Tuple[int] = (16, 56, 56),
+ ):
+ super().__init__()
+ self.out_channels = out_channels or in_channels
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
+
+ text_time_guidance_cls = (
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
+ )
+ self.time_text_embed = text_time_guidance_cls(
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
+ )
+
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
+ self.x_embedder = nn.Linear(self.config.in_channels, self.inner_dim)
+
+ self.transformer_blocks = nn.ModuleList(
+ [
+ FluxTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ )
+ for i in range(self.config.num_layers)
+ ]
+ )
+
+ self.single_transformer_blocks = nn.ModuleList(
+ [
+ FluxSingleTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ )
+ for i in range(self.config.num_single_layers)
+ ]
+ )
+
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
+
+ self.gradient_checkpointing = False
+
+ @property
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "get_processor"):
+ processors[f"{name}.processor"] = module.get_processor()
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Sets the attention processor to use to compute attention.
+
+ Parameters:
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ for **all** `Attention` layers.
+
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
+ processor. This is strongly recommended when setting trainable attention processors.
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
+ def fuse_qkv_projections(self):
+ """
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
+ are fused. For cross-attention modules, key and value projection matrices are fused.
+
+
+
+ This API is 🧪 experimental.
+
+
+ """
+ self.original_attn_processors = None
+
+ for _, attn_processor in self.attn_processors.items():
+ if "Added" in str(attn_processor.__class__.__name__):
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
+
+ self.original_attn_processors = self.attn_processors
+
+ for module in self.modules():
+ if isinstance(module, Attention):
+ module.fuse_projections(fuse=True)
+
+ self.set_attn_processor(FusedFluxAttnProcessor2_0())
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
+ def unfuse_qkv_projections(self):
+ """Disables the fused QKV projection if enabled.
+
+
+
+ This API is 🧪 experimental.
+
+
+
+ """
+ if self.original_attn_processors is not None:
+ self.set_attn_processor(self.original_attn_processors)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor = None,
+ pooled_projections: torch.Tensor = None,
+ timestep: torch.LongTensor = None,
+ img_ids: torch.Tensor = None,
+ txt_ids: torch.Tensor = None,
+ guidance: torch.Tensor = None,
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ return_dict: bool = True,
+ controlnet_blocks_repeat: bool = False,
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
+ """
+ The [`FluxTransformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
+ Input `hidden_states`.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
+ from the embeddings of input conditions.
+ timestep ( `torch.LongTensor`):
+ Used to indicate denoising step.
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
+ A list of tensors that if specified are added to the residuals of transformer blocks.
+ joint_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ if joint_attention_kwargs is not None:
+ joint_attention_kwargs = joint_attention_kwargs.copy()
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ hidden_states = self.x_embedder(hidden_states)
+
+ timestep = timestep.to(hidden_states.dtype) * 1000
+ if guidance is not None:
+ guidance = guidance.to(hidden_states.dtype) * 1000
+ else:
+ guidance = None
+
+ temb = (
+ self.time_text_embed(timestep, pooled_projections)
+ if guidance is None
+ else self.time_text_embed(timestep, guidance, pooled_projections)
+ )
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
+
+ if txt_ids.ndim == 3:
+ logger.warning(
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ txt_ids = txt_ids[0]
+ if img_ids.ndim == 3:
+ logger.warning(
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ img_ids = img_ids[0]
+
+ ids = torch.cat((txt_ids, img_ids), dim=0)
+ image_rotary_emb = self.pos_embed(ids)
+
+ if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
+ ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
+ ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds)
+ joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states})
+
+ for index_block, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ encoder_hidden_states, hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ joint_attention_kwargs=joint_attention_kwargs,
+ )
+
+ # controlnet residual
+ if controlnet_block_samples is not None:
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # For Xlabs ControlNet.
+ if controlnet_blocks_repeat:
+ hidden_states = (
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ for index_block, block in enumerate(self.single_transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ hidden_states = block(
+ hidden_states=hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ joint_attention_kwargs=joint_attention_kwargs,
+ )
+
+ # controlnet residual
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
+
+ hidden_states = self.norm_out(hidden_states, temb)
+ output = self.proj_out(hidden_states)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_embedding.py b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_embedding.py
new file mode 100644
index 0000000000000000000000000000000000000000..11b5b034bc6312c042720511ba283c91f8d37cbf
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_embedding.py
@@ -0,0 +1,201 @@
+import math
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.models.activations import get_activation, FP32SiLU
+
+def get_timestep_embedding(
+ timesteps: torch.Tensor,
+ embedding_dim: int,
+ flip_sin_to_cos: bool = False,
+ downscale_freq_shift: float = 1,
+ scale: float = 1,
+ max_period: int = 10000,
+):
+ """
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
+
+ Args
+ timesteps (torch.Tensor):
+ a 1-D Tensor of N indices, one per batch element. These may be fractional.
+ embedding_dim (int):
+ the dimension of the output.
+ flip_sin_to_cos (bool):
+ Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False)
+ downscale_freq_shift (float):
+ Controls the delta between frequencies between dimensions
+ scale (float):
+ Scaling factor applied to the embeddings.
+ max_period (int):
+ Controls the maximum frequency of the embeddings
+ Returns
+ torch.Tensor: an [N x dim] Tensor of positional embeddings.
+ """
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
+
+ half_dim = embedding_dim // 2
+ exponent = -math.log(max_period) * torch.arange(
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
+ )
+ exponent = exponent / (half_dim - downscale_freq_shift)
+
+ emb = torch.exp(exponent)
+ emb = timesteps[:, None].float() * emb[None, :]
+
+ # scale embeddings
+ emb = scale * emb
+
+ # concat sine and cosine embeddings
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
+
+ # flip sine and cosine embeddings
+ if flip_sin_to_cos:
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
+
+ # zero pad
+ if embedding_dim % 2 == 1:
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
+ return emb
+
+
+class Timesteps(nn.Module):
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float, scale: int = 1):
+ super().__init__()
+ self.num_channels = num_channels
+ self.flip_sin_to_cos = flip_sin_to_cos
+ self.downscale_freq_shift = downscale_freq_shift
+ self.scale = scale
+
+ def forward(self, timesteps):
+ t_emb = get_timestep_embedding(
+ timesteps,
+ self.num_channels,
+ flip_sin_to_cos=self.flip_sin_to_cos,
+ downscale_freq_shift=self.downscale_freq_shift,
+ scale=self.scale,
+ )
+ return t_emb
+
+
+class TimestepEmbedding(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ act_fn: str = "silu",
+ out_dim: int = None,
+ post_act_fn: Optional[str] = None,
+ cond_proj_dim=None,
+ sample_proj_bias=True,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
+
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+
+ self.act = get_activation(act_fn)
+
+ if out_dim is not None:
+ time_embed_dim_out = out_dim
+ else:
+ time_embed_dim_out = time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out, sample_proj_bias)
+
+ if post_act_fn is None:
+ self.post_act = None
+ else:
+ self.post_act = get_activation(post_act_fn)
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+
+ if self.act is not None:
+ sample = self.act(sample)
+
+ sample = self.linear_2(sample)
+
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+
+class PixArtAlphaTextProjection(nn.Module):
+ """
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
+
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
+ """
+
+ def __init__(self, in_features, hidden_size, out_features=None, act_fn="gelu_tanh"):
+ super().__init__()
+ if out_features is None:
+ out_features = hidden_size
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
+ if act_fn == "gelu_tanh":
+ self.act_1 = nn.GELU(approximate="tanh")
+ elif act_fn == "silu":
+ self.act_1 = nn.SiLU()
+ elif act_fn == "silu_fp32":
+ self.act_1 = FP32SiLU()
+ else:
+ raise ValueError(f"Unknown activation function: {act_fn}")
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=out_features, bias=True)
+
+ def forward(self, caption):
+ hidden_states = self.linear_1(caption)
+ hidden_states = self.act_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+class CombinedTimestepGuidanceTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, guidance, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ guidance_proj = self.time_proj(guidance)
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ time_guidance_emb = timesteps_emb + guidance_emb
+
+ pooled_projections = self.text_embedder(pooled_projection)
+ conditioning = time_guidance_emb + pooled_projections
+
+ return conditioning
+
+
+class CombinedTimestepTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ pooled_projections = self.text_embedder(pooled_projection)
+
+ conditioning = timesteps_emb + pooled_projections
+
+ return conditioning
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_flux_block.py b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_flux_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..53e474620ec1d6a5ca55d709212207d1064389e1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_flux_block.py
@@ -0,0 +1,1051 @@
+from typing import Any, Dict, List, Optional, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import inspect
+from einops import rearrange
+
+from diffusers.utils import deprecate
+from diffusers.models.activations import GEGLU, GELU, ApproximateGELU # SwiGLU
+
+from .modeling_normalization import (
+ AdaLayerNormContinuous, AdaLayerNormZero,
+ AdaLayerNormZeroSingle, FP32LayerNorm, RMSNorm
+)
+
+# from trainer_misc import (
+# is_sequence_parallel_initialized,
+# get_sequence_parallel_group,
+# get_sequence_parallel_world_size,
+# all_to_all,
+# )
+
+from opensora.trainer_misc import (
+ is_sequence_parallel_initialized,
+ get_sequence_parallel_group,
+ get_sequence_parallel_world_size,
+ all_to_all,
+)
+
+try:
+ from flash_attn import flash_attn_qkvpacked_func, flash_attn_func
+ from flash_attn.bert_padding import pad_input, unpad_input, index_first_axis
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
+except:
+ flash_attn_func = None
+ flash_attn_qkvpacked_func = None
+ flash_attn_varlen_func = None
+
+
+def apply_rope(xq, xk, freqs_cis):
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
+
+
+class FeedForward(nn.Module):
+ r"""
+ A feed-forward layer.
+
+ Parameters:
+ dim (`int`): The number of channels in the input.
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ dim_out: Optional[int] = None,
+ mult: int = 4,
+ dropout: float = 0.0,
+ activation_fn: str = "geglu",
+ final_dropout: bool = False,
+ inner_dim=None,
+ bias: bool = True,
+ ):
+ super().__init__()
+ if inner_dim is None:
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim, bias=bias)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
+ elif activation_fn == "swiglu":
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
+
+ self.net = nn.ModuleList([])
+ # project in
+ self.net.append(act_fn)
+ # project dropout
+ self.net.append(nn.Dropout(dropout))
+ # project out
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
+
+
+class SequenceParallelVarlenFlashSelfAttentionWithT5Mask:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
+ ):
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
+
+ batch_size = query.shape[0]
+ qkv_list = []
+ num_stages = len(hidden_length)
+
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ # To sync the encoder query, key and values
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+
+ output_hidden = torch.zeros_like(qkv[:,:,0])
+ output_encoder_hidden = torch.zeros_like(encoder_qkv[:,:,0])
+ encoder_length = encoder_qkv.shape[1]
+
+ i_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ # get the query, key, value from padding sequence
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, pad_seq, 3, nhead, dim]
+
+ if image_rotary_emb is not None:
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ indices = encoder_attention_mask[i_p]['indices']
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
+ i_sum += length
+
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
+ qkv = torch.cat(qkv_list, dim=0)
+ query, key, value = qkv.unbind(1)
+
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
+ max_seqlen_q = cu_seqlens.max().item()
+ max_seqlen_k = max_seqlen_q
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
+ cu_seqlens_k = cu_seqlens_q.clone()
+
+ output = flash_attn_varlen_func(
+ query,
+ key,
+ value,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_k=cu_seqlens_k,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_k=max_seqlen_k,
+ dropout_p=0.0,
+ causal=False,
+ softmax_scale=scale,
+ )
+
+ # To merge the tokens
+ i_sum = 0;token_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ tot_token_num = token_lengths[i_p]
+ stage_output = output[token_sum : token_sum + tot_token_num]
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length * sp_group_size)
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
+ stage_hidden_output = stage_output[:, encoder_length:]
+ stage_hidden_output = all_to_all(stage_hidden_output, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
+ token_sum += tot_token_num
+ i_sum += length
+
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_hidden = output_hidden.flatten(2, 3)
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
+
+ return output_hidden, output_encoder_hidden
+
+
+class VarlenFlashSelfAttentionWithT5Mask:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
+ heads, scale, hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
+ ):
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
+
+ batch_size = query.shape[0]
+ output_hidden = torch.zeros_like(query)
+ output_encoder_hidden = torch.zeros_like(encoder_query)
+ encoder_length = encoder_query.shape[1]
+
+ qkv_list = []
+ num_stages = len(hidden_length)
+
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ i_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
+
+ if image_rotary_emb is not None:
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ indices = encoder_attention_mask[i_p]['indices']
+ qkv_list.append(index_first_axis(rearrange(concat_qkv_tokens, "b s ... -> (b s) ..."), indices))
+ i_sum += length
+
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
+ qkv = torch.cat(qkv_list, dim=0)
+ query, key, value = qkv.unbind(1)
+
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
+ max_seqlen_q = cu_seqlens.max().item()
+ max_seqlen_k = max_seqlen_q
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
+ cu_seqlens_k = cu_seqlens_q.clone()
+
+ output = flash_attn_varlen_func(
+ query,
+ key,
+ value,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_k=cu_seqlens_k,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_k=max_seqlen_k,
+ dropout_p=0.0,
+ causal=False,
+ softmax_scale=scale,
+ )
+
+ # To merge the tokens
+ i_sum = 0;token_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ tot_token_num = token_lengths[i_p]
+ stage_output = output[token_sum : token_sum + tot_token_num]
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, encoder_length + length)
+ stage_encoder_hidden_output = stage_output[:, :encoder_length]
+ stage_hidden_output = stage_output[:, encoder_length:]
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
+ output_encoder_hidden[i_p::num_stages] = stage_encoder_hidden_output
+ token_sum += tot_token_num
+ i_sum += length
+
+ output_hidden = output_hidden.flatten(2, 3)
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
+
+ return output_hidden, output_encoder_hidden
+
+
+class SequenceParallelVarlenSelfAttentionWithT5Mask:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None,
+ ):
+ assert attention_mask is not None, "The attention mask needed to be set"
+
+ num_stages = len(hidden_length)
+
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ # To sync the encoder query, key and values
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ encoder_qkv = all_to_all(encoder_qkv, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+ encoder_length = encoder_qkv.shape[1]
+
+ i_sum = 0
+ output_encoder_hidden_list = []
+ output_hidden_list = []
+
+ for i_p, length in enumerate(hidden_length):
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
+
+ if image_rotary_emb is not None:
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ stage_hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
+ )
+ stage_hidden_states = stage_hidden_states.transpose(1, 2) # [bs, tot_seq, nhead, dim]
+
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
+
+ output_hidden = stage_hidden_states[:, encoder_length:]
+ output_hidden = all_to_all(output_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_hidden_list.append(output_hidden)
+
+ i_sum += length
+
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s nhead d]
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s h d -> (b n) s h d')
+ output_encoder_hidden = all_to_all(output_encoder_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_encoder_hidden = output_encoder_hidden.flatten(2, 3)
+ output_hidden = torch.cat(output_hidden_list, dim=1).flatten(2, 3)
+
+ return output_hidden, output_encoder_hidden
+
+
+class VarlenSelfAttentionWithT5Mask:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, encoder_query, encoder_key, encoder_value,
+ heads, scale, hidden_length=None, image_rotary_emb=None, attention_mask=None,
+ ):
+ assert attention_mask is not None, "The attention mask needed to be set"
+
+ encoder_length = encoder_query.shape[1]
+ num_stages = len(hidden_length)
+
+ encoder_qkv = torch.stack([encoder_query, encoder_key, encoder_value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ i_sum = 0
+ output_encoder_hidden_list = []
+ output_hidden_list = []
+
+ for i_p, length in enumerate(hidden_length):
+ encoder_qkv_tokens = encoder_qkv[i_p::num_stages]
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ concat_qkv_tokens = torch.cat([encoder_qkv_tokens, qkv_tokens], dim=1) # [bs, tot_seq, 3, nhead, dim]
+
+ if image_rotary_emb is not None:
+ concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1] = apply_rope(concat_qkv_tokens[:,:,0], concat_qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ query, key, value = concat_qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
+ stage_hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
+ )
+ stage_hidden_states = stage_hidden_states.transpose(1, 2).flatten(2, 3) # [bs, tot_seq, dim]
+
+ output_encoder_hidden_list.append(stage_hidden_states[:, :encoder_length])
+ output_hidden_list.append(stage_hidden_states[:, encoder_length:])
+ i_sum += length
+
+ output_encoder_hidden = torch.stack(output_encoder_hidden_list, dim=1) # [b n s d]
+ output_encoder_hidden = rearrange(output_encoder_hidden, 'b n s d -> (b n) s d')
+ output_hidden = torch.cat(output_hidden_list, dim=1)
+
+ return output_hidden, output_encoder_hidden
+
+
+class SequenceParallelVarlenFlashAttnSingle:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, heads, scale,
+ hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
+ ):
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
+
+ batch_size = query.shape[0]
+ qkv_list = []
+ num_stages = len(hidden_length)
+
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+ output_hidden = torch.zeros_like(qkv[:,:,0])
+
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+
+ i_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ # get the query, key, value from padding sequence
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+
+ if image_rotary_emb is not None:
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ indices = encoder_attention_mask[i_p]['indices']
+ qkv_list.append(index_first_axis(rearrange(qkv_tokens, "b s ... -> (b s) ..."), indices))
+ i_sum += length
+
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
+ qkv = torch.cat(qkv_list, dim=0)
+ query, key, value = qkv.unbind(1)
+
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
+ max_seqlen_q = cu_seqlens.max().item()
+ max_seqlen_k = max_seqlen_q
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
+ cu_seqlens_k = cu_seqlens_q.clone()
+
+ output = flash_attn_varlen_func(
+ query,
+ key,
+ value,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_k=cu_seqlens_k,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_k=max_seqlen_k,
+ dropout_p=0.0,
+ causal=False,
+ softmax_scale=scale,
+ )
+
+ # To merge the tokens
+ i_sum = 0;token_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ tot_token_num = token_lengths[i_p]
+ stage_output = output[token_sum : token_sum + tot_token_num]
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, length * sp_group_size)
+ stage_hidden_output = all_to_all(stage_output, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_hidden[:, i_sum:i_sum+length] = stage_hidden_output
+ token_sum += tot_token_num
+ i_sum += length
+
+ output_hidden = output_hidden.flatten(2, 3)
+
+ return output_hidden
+
+
+class VarlenFlashSelfAttnSingle:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, heads, scale,
+ hidden_length=None, image_rotary_emb=None, encoder_attention_mask=None,
+ ):
+ assert encoder_attention_mask is not None, "The encoder-hidden mask needed to be set"
+
+ batch_size = query.shape[0]
+ output_hidden = torch.zeros_like(query)
+
+ qkv_list = []
+ num_stages = len(hidden_length)
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ i_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+
+ if image_rotary_emb is not None:
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ indices = encoder_attention_mask[i_p]['indices']
+ qkv_list.append(index_first_axis(rearrange(qkv_tokens, "b s ... -> (b s) ..."), indices))
+ i_sum += length
+
+ token_lengths = [x_.shape[0] for x_ in qkv_list]
+ qkv = torch.cat(qkv_list, dim=0)
+ query, key, value = qkv.unbind(1)
+
+ cu_seqlens = torch.cat([x_['seqlens_in_batch'] for x_ in encoder_attention_mask], dim=0)
+ max_seqlen_q = cu_seqlens.max().item()
+ max_seqlen_k = max_seqlen_q
+ cu_seqlens_q = F.pad(torch.cumsum(cu_seqlens, dim=0, dtype=torch.int32), (1, 0))
+ cu_seqlens_k = cu_seqlens_q.clone()
+
+ output = flash_attn_varlen_func(
+ query,
+ key,
+ value,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_k=cu_seqlens_k,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_k=max_seqlen_k,
+ dropout_p=0.0,
+ causal=False,
+ softmax_scale=scale,
+ )
+
+ # To merge the tokens
+ i_sum = 0;token_sum = 0
+ for i_p, length in enumerate(hidden_length):
+ tot_token_num = token_lengths[i_p]
+ stage_output = output[token_sum : token_sum + tot_token_num]
+ stage_output = pad_input(stage_output, encoder_attention_mask[i_p]['indices'], batch_size, length)
+ output_hidden[:, i_sum:i_sum+length] = stage_output
+ token_sum += tot_token_num
+ i_sum += length
+
+ output_hidden = output_hidden.flatten(2, 3)
+
+ return output_hidden
+
+
+class SequenceParallelVarlenAttnSingle:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, heads, scale,
+ hidden_length=None, image_rotary_emb=None, attention_mask=None,
+ ):
+ assert attention_mask is not None, "The attention mask needed to be set"
+
+ num_stages = len(hidden_length)
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ # To sync the encoder query, key and values
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+
+ i_sum = 0
+ output_hidden_list = []
+
+ for i_p, length in enumerate(hidden_length):
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+ qkv_tokens = all_to_all(qkv_tokens, sp_group, sp_group_size, scatter_dim=3, gather_dim=1) # [bs, seq, 3, sub_head, head_dim]
+
+ if image_rotary_emb is not None:
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ query, key, value = qkv_tokens.unbind(2) # [bs, tot_seq, nhead, dim]
+ query = query.transpose(1, 2).contiguous()
+ key = key.transpose(1, 2).contiguous()
+ value = value.transpose(1, 2).contiguous()
+
+ stage_hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
+ )
+ stage_hidden_states = stage_hidden_states.transpose(1, 2) # [bs, tot_seq, nhead, dim]
+
+ output_hidden = stage_hidden_states
+ output_hidden = all_to_all(output_hidden, sp_group, sp_group_size, scatter_dim=1, gather_dim=2)
+ output_hidden_list.append(output_hidden)
+
+ i_sum += length
+
+ output_hidden = torch.cat(output_hidden_list, dim=1).flatten(2, 3)
+
+ return output_hidden
+
+
+class VarlenSelfAttnSingle:
+
+ def __init__(self):
+ pass
+
+ def __call__(
+ self, query, key, value, heads, scale,
+ hidden_length=None, image_rotary_emb=None, attention_mask=None,
+ ):
+ assert attention_mask is not None, "The attention mask needed to be set"
+
+ num_stages = len(hidden_length)
+ qkv = torch.stack([query, key, value], dim=2) # [bs, sub_seq, 3, head, head_dim]
+
+ i_sum = 0
+ output_hidden_list = []
+
+ for i_p, length in enumerate(hidden_length):
+ qkv_tokens = qkv[:, i_sum:i_sum+length]
+
+ if image_rotary_emb is not None:
+ qkv_tokens[:,:,0], qkv_tokens[:,:,1] = apply_rope(qkv_tokens[:,:,0], qkv_tokens[:,:,1], image_rotary_emb[i_p])
+
+ query, key, value = qkv_tokens.unbind(2)
+ query = query.transpose(1, 2).contiguous()
+ key = key.transpose(1, 2).contiguous()
+ value = value.transpose(1, 2).contiguous()
+
+ stage_hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False, attn_mask=attention_mask[i_p],
+ )
+ stage_hidden_states = stage_hidden_states.transpose(1, 2).flatten(2, 3) # [bs, tot_seq, dim]
+
+ output_hidden_list.append(stage_hidden_states)
+ i_sum += length
+
+ output_hidden = torch.cat(output_hidden_list, dim=1)
+
+ return output_hidden
+
+
+class Attention(nn.Module):
+
+ def __init__(
+ self,
+ query_dim: int,
+ cross_attention_dim: Optional[int] = None,
+ heads: int = 8,
+ dim_head: int = 64,
+ dropout: float = 0.0,
+ bias: bool = False,
+ qk_norm: Optional[str] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ added_proj_bias: Optional[bool] = True,
+ out_bias: bool = True,
+ only_cross_attention: bool = False,
+ eps: float = 1e-5,
+ processor: Optional["AttnProcessor"] = None,
+ out_dim: int = None,
+ context_pre_only=None,
+ pre_only=False,
+ ):
+ super().__init__()
+
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
+ self.inner_kv_dim = self.inner_dim
+ self.query_dim = query_dim
+ self.use_bias = bias
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
+
+ self.dropout = dropout
+ self.out_dim = out_dim if out_dim is not None else query_dim
+ self.context_pre_only = context_pre_only
+ self.pre_only = pre_only
+
+ self.scale = dim_head**-0.5
+ self.heads = out_dim // dim_head if out_dim is not None else heads
+
+
+ self.added_kv_proj_dim = added_kv_proj_dim
+ self.only_cross_attention = only_cross_attention
+
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
+ raise ValueError(
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
+ )
+
+ if qk_norm is None:
+ self.norm_q = None
+ self.norm_k = None
+ elif qk_norm == "rms_norm":
+ self.norm_q = RMSNorm(dim_head, eps=eps)
+ self.norm_k = RMSNorm(dim_head, eps=eps)
+ else:
+ raise ValueError(f"unknown qk_norm: {qk_norm}. Should be None or 'layer_norm'")
+
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
+
+ if not self.only_cross_attention:
+ # only relevant for the `AddedKVProcessor` classes
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ else:
+ self.to_k = None
+ self.to_v = None
+
+ self.added_proj_bias = added_proj_bias
+ if self.added_kv_proj_dim is not None:
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ if self.context_pre_only is not None:
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+
+ if not self.pre_only:
+ self.to_out = nn.ModuleList([])
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
+ self.to_out.append(nn.Dropout(dropout))
+
+ if self.context_pre_only is not None and not self.context_pre_only:
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_dim, bias=out_bias)
+
+ if qk_norm is not None and added_kv_proj_dim is not None:
+ if qk_norm == "fp32_layer_norm":
+ self.norm_added_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ self.norm_added_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ elif qk_norm == "rms_norm":
+ self.norm_added_q = RMSNorm(dim_head, eps=eps)
+ self.norm_added_k = RMSNorm(dim_head, eps=eps)
+ else:
+ self.norm_added_q = None
+ self.norm_added_k = None
+
+ # set attention processor
+ self.set_processor(processor)
+
+ def set_processor(self, processor: "AttnProcessor") -> None:
+ self.processor = processor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ hidden_length: List = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+
+ return self.processor(
+ self,
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ attention_mask=attention_mask,
+ hidden_length=hidden_length,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+
+class FluxSingleAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ """
+ def __init__(self, use_flash_attn=False):
+ self.use_flash_attn = use_flash_attn
+
+ if self.use_flash_attn:
+ if is_sequence_parallel_initialized():
+ self.varlen_flash_attn = SequenceParallelVarlenFlashAttnSingle()
+ else:
+ self.varlen_flash_attn = VarlenFlashSelfAttnSingle()
+ else:
+ if is_sequence_parallel_initialized():
+ self.varlen_attn = SequenceParallelVarlenAttnSingle()
+ else:
+ self.varlen_attn = VarlenSelfAttnSingle()
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ hidden_length: List = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(query.shape[0], -1, attn.heads, head_dim)
+ key = key.view(key.shape[0], -1, attn.heads, head_dim)
+ value = value.view(value.shape[0], -1, attn.heads, head_dim)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ if self.use_flash_attn:
+ hidden_states = self.varlen_flash_attn(
+ query, key, value,
+ attn.heads, attn.scale, hidden_length,
+ image_rotary_emb, encoder_attention_mask,
+ )
+ else:
+ hidden_states = self.varlen_attn(
+ query, key, value,
+ attn.heads, attn.scale, hidden_length,
+ image_rotary_emb, attention_mask,
+ )
+
+ return hidden_states
+
+
+class FluxAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self, use_flash_attn=False):
+ self.use_flash_attn = use_flash_attn
+
+ if self.use_flash_attn:
+ if is_sequence_parallel_initialized():
+ self.varlen_flash_attn = SequenceParallelVarlenFlashSelfAttentionWithT5Mask()
+ else:
+ self.varlen_flash_attn = VarlenFlashSelfAttentionWithT5Mask()
+ else:
+ if is_sequence_parallel_initialized():
+ self.varlen_attn = SequenceParallelVarlenSelfAttentionWithT5Mask()
+ else:
+ self.varlen_attn = VarlenSelfAttentionWithT5Mask()
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ hidden_length: List = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(query.shape[0], -1, attn.heads, head_dim)
+ key = key.view(key.shape[0], -1, attn.heads, head_dim)
+ value = value.view(value.shape[0], -1, attn.heads, head_dim)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ encoder_hidden_states_query_proj.shape[0], -1, attn.heads, head_dim
+ )
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ encoder_hidden_states_key_proj.shape[0], -1, attn.heads, head_dim
+ )
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ encoder_hidden_states_value_proj.shape[0], -1, attn.heads, head_dim
+ )
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ if self.use_flash_attn:
+ hidden_states, encoder_hidden_states = self.varlen_flash_attn(
+ query, key, value,
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj, attn.heads, attn.scale, hidden_length,
+ image_rotary_emb, encoder_attention_mask,
+ )
+ else:
+ hidden_states, encoder_hidden_states = self.varlen_attn(
+ query, key, value,
+ encoder_hidden_states_query_proj, encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj, attn.heads, attn.scale, hidden_length,
+ image_rotary_emb, attention_mask,
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+
+
+class FluxSingleTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0, use_flash_attn=False):
+ super().__init__()
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
+
+ self.norm = AdaLayerNormZeroSingle(dim)
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
+ self.act_mlp = nn.GELU(approximate="tanh")
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
+
+ processor = FluxSingleAttnProcessor2_0(use_flash_attn)
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ bias=True,
+ processor=processor,
+ qk_norm="rms_norm",
+ eps=1e-6,
+ pre_only=True,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ encoder_attention_mask=None,
+ attention_mask=None,
+ hidden_length=None,
+ image_rotary_emb=None,
+ ):
+ residual = hidden_states
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb, hidden_length=hidden_length)
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
+
+ attn_output = self.attn(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=None,
+ encoder_attention_mask=encoder_attention_mask,
+ attention_mask=attention_mask,
+ hidden_length=hidden_length,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
+ hidden_states = gate * self.proj_out(hidden_states)
+ hidden_states = residual + hidden_states
+ if hidden_states.dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+class FluxTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6, use_flash_attn=False):
+ super().__init__()
+
+ self.norm1 = AdaLayerNormZero(dim)
+
+ self.norm1_context = AdaLayerNormZero(dim)
+
+ if hasattr(F, "scaled_dot_product_attention"):
+ processor = FluxAttnProcessor2_0(use_flash_attn)
+ else:
+ raise ValueError(
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
+ )
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ added_kv_proj_dim=dim,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ context_pre_only=False,
+ bias=True,
+ processor=processor,
+ qk_norm=qk_norm,
+ eps=eps,
+ )
+
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor,
+ encoder_attention_mask: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ attention_mask: torch.FloatTensor = None,
+ hidden_length: List = None,
+ image_rotary_emb=None,
+ ):
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb, hidden_length=hidden_length)
+
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
+ encoder_hidden_states, emb=temb
+ )
+
+ # Attention.
+ attn_output, context_attn_output = self.attn(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=norm_encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ attention_mask=attention_mask,
+ hidden_length=hidden_length,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ # Process attention outputs for the `hidden_states`.
+ attn_output = gate_msa * attn_output
+ hidden_states = hidden_states + attn_output
+
+ norm_hidden_states = self.norm2(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
+
+ ff_output = self.ff(norm_hidden_states)
+ ff_output = gate_mlp * ff_output
+
+ hidden_states = hidden_states + ff_output
+
+ # Process attention outputs for the `encoder_hidden_states`.
+
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
+
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
+
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
+
+ if encoder_hidden_states.dtype == torch.float16:
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
+
+ return encoder_hidden_states, hidden_states
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_normalization.py b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..76eb409aec61eebe95b9681d10495dc85c7ef36c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_normalization.py
@@ -0,0 +1,249 @@
+import numbers
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+from diffusers.utils import is_torch_version
+
+
+if is_torch_version(">=", "2.1.0"):
+ LayerNorm = nn.LayerNorm
+else:
+ # Has optional bias parameter compared to torch layer norm
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
+ class LayerNorm(nn.Module):
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
+ else:
+ self.weight = None
+ self.bias = None
+
+ def forward(self, input):
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
+
+
+class FP32LayerNorm(nn.LayerNorm):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ origin_dtype = inputs.dtype
+ return F.layer_norm(
+ inputs.float(),
+ self.normalized_shape,
+ self.weight.float() if self.weight is not None else None,
+ self.bias.float() if self.bias is not None else None,
+ self.eps,
+ ).to(origin_dtype)
+
+
+class RMSNorm(nn.Module):
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ else:
+ self.weight = None
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
+
+ if self.weight is not None:
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+ hidden_states = hidden_states * self.weight
+ else:
+ hidden_states = hidden_states.to(input_dtype)
+
+ return hidden_states
+
+
+class AdaLayerNormContinuous(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ conditioning_embedding_dim: int,
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
+ # However, this is how it was implemented in the original code, and it's rather likely you should
+ # set `elementwise_affine` to False.
+ elementwise_affine=True,
+ eps=1e-5,
+ bias=True,
+ norm_type="layer_norm",
+ ):
+ super().__init__()
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
+ elif norm_type == "rms_norm":
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
+ else:
+ raise ValueError(f"unknown norm_type {norm_type}")
+
+ def forward_with_pad(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
+ assert hidden_length is not None
+
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 2)
+
+ i_sum = 0
+ num_stages = len(hidden_length)
+ for i_p, length in enumerate(hidden_length):
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
+ i_sum += length
+
+ batch_scale, batch_shift = torch.chunk(batch_emb, 2, dim=2)
+ x = self.norm(x) * (1 + batch_scale) + batch_shift
+ return x
+
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor, hidden_length=None) -> torch.Tensor:
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
+ if hidden_length is not None:
+ return self.forward_with_pad(x, conditioning_embedding, hidden_length)
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
+ scale, shift = torch.chunk(emb, 2, dim=1)
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
+ return x
+
+
+class AdaLayerNormZero(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None):
+ super().__init__()
+ self.emb = None
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+
+ def forward_with_pad(
+ self,
+ x: torch.Tensor,
+ timestep: Optional[torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ hidden_dtype: Optional[torch.dtype] = None,
+ emb: Optional[torch.Tensor] = None,
+ hidden_length: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ # hidden_length: [[20, 30], [30, 40], [50, 60]]
+ # x: [bs, seq_len, dim]
+ if self.emb is not None:
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
+
+ emb = self.linear(self.silu(emb))
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 6)
+
+ i_sum = 0
+ num_stages = len(hidden_length)
+ for i_p, length in enumerate(hidden_length):
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
+ i_sum += length
+
+ batch_shift_msa, batch_scale_msa, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp = batch_emb.chunk(6, dim=2)
+ x = self.norm(x) * (1 + batch_scale_msa) + batch_shift_msa
+ return x, batch_gate_msa, batch_shift_mlp, batch_scale_mlp, batch_gate_mlp
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ timestep: Optional[torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ hidden_dtype: Optional[torch.dtype] = None,
+ emb: Optional[torch.Tensor] = None,
+ hidden_length: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ if hidden_length is not None:
+ return self.forward_with_pad(x, timestep, class_labels, hidden_dtype, emb, hidden_length)
+ if self.emb is not None:
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
+
+
+class AdaLayerNormZeroSingle(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ raise ValueError(
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
+ )
+
+ def forward_with_pad(
+ self,
+ x: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ hidden_length: Optional[torch.Tensor] = None,
+ ):
+ emb = self.linear(self.silu(emb))
+ batch_emb = torch.zeros_like(x).repeat(1, 1, 3)
+
+ i_sum = 0
+ num_stages = len(hidden_length)
+ for i_p, length in enumerate(hidden_length):
+ batch_emb[:, i_sum:i_sum+length] = emb[i_p::num_stages][:,None]
+ i_sum += length
+
+ batch_shift_msa, batch_scale_msa, batch_gate_msa = batch_emb.chunk(3, dim=2)
+
+ x = self.norm(x) * (1 + batch_scale_msa) + batch_shift_msa
+
+ return x, batch_gate_msa
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ hidden_length: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ if hidden_length is not None:
+ return self.forward_with_pad(x, emb, hidden_length)
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_pyramid_flux.py b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_pyramid_flux.py
new file mode 100644
index 0000000000000000000000000000000000000000..2fb4dacbe38ab715418073f7867b3e35b503ec25
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_pyramid_flux.py
@@ -0,0 +1,544 @@
+from typing import Any, Dict, List, Optional, Union
+
+import torch
+import os
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+from tqdm import tqdm
+
+from diffusers.utils.torch_utils import randn_tensor
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import is_torch_version
+
+from .modeling_normalization import AdaLayerNormContinuous
+from .modeling_embedding import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings
+from .modeling_flux_block import FluxTransformerBlock, FluxSingleTransformerBlock
+
+# from trainer_misc import (
+# is_sequence_parallel_initialized,
+# get_sequence_parallel_group,
+# get_sequence_parallel_world_size,
+# get_sequence_parallel_rank,
+# all_to_all,
+# )
+
+from opensora.trainer_misc import (
+ is_sequence_parallel_initialized,
+ get_sequence_parallel_group,
+ get_sequence_parallel_world_size,
+ all_to_all,
+)
+
+def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
+ assert dim % 2 == 0, "The dimension must be even."
+
+ scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim
+ omega = 1.0 / (theta**scale)
+
+ batch_size, seq_length = pos.shape
+ out = torch.einsum("...n,d->...nd", pos, omega)
+ cos_out = torch.cos(out)
+ sin_out = torch.sin(out)
+
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
+ return out.float()
+
+
+class EmbedND(nn.Module):
+ def __init__(self, dim: int, theta: int, axes_dim: List[int]):
+ super().__init__()
+ self.dim = dim
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
+ n_axes = ids.shape[-1]
+ emb = torch.cat(
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
+ dim=-3,
+ )
+ return emb.unsqueeze(2)
+
+
+class PyramidFluxTransformer(ModelMixin, ConfigMixin):
+ """
+ The Transformer model introduced in Flux.
+
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
+
+ Parameters:
+ patch_size (`int`): Patch size to turn the input data into small patches.
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
+ num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
+ num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: int = 1,
+ in_channels: int = 64,
+ num_layers: int = 19,
+ num_single_layers: int = 38,
+ attention_head_dim: int = 64,
+ num_attention_heads: int = 24,
+ joint_attention_dim: int = 4096,
+ pooled_projection_dim: int = 768,
+ axes_dims_rope: List[int] = [16, 24, 24],
+ use_flash_attn: bool = False,
+ use_temporal_causal: bool = True,
+ interp_condition_pos: bool = True,
+ use_gradient_checkpointing: bool = False,
+ gradient_checkpointing_ratio: float = 0.6,
+ ):
+ super().__init__()
+ self.out_channels = in_channels
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+
+ self.pos_embed = EmbedND(dim=self.inner_dim, theta=10000, axes_dim=axes_dims_rope)
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
+ )
+
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
+ self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
+
+ self.transformer_blocks = nn.ModuleList(
+ [
+ FluxTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ use_flash_attn=use_flash_attn,
+ )
+ for i in range(self.config.num_layers)
+ ]
+ )
+
+ self.single_transformer_blocks = nn.ModuleList(
+ [
+ FluxSingleTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ use_flash_attn=use_flash_attn,
+ )
+ for i in range(self.config.num_single_layers)
+ ]
+ )
+
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
+
+ self.gradient_checkpointing = use_gradient_checkpointing
+ self.gradient_checkpointing_ratio = gradient_checkpointing_ratio
+
+ self.use_temporal_causal = use_temporal_causal
+ if self.use_temporal_causal:
+ print("Using temporal causal attention")
+
+ self.use_flash_attn = use_flash_attn
+ if self.use_flash_attn:
+ print("Using Flash attention")
+
+ self.patch_size = 2 # hard-code for now
+
+ # init weights
+ self.initialize_weights()
+
+ def initialize_weights(self):
+ # Initialize transformer layers:
+ def _basic_init(module):
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.Conv3d)):
+ torch.nn.init.xavier_uniform_(module.weight)
+ if module.bias is not None:
+ nn.init.constant_(module.bias, 0)
+ self.apply(_basic_init)
+
+ # Initialize all the conditioning to normal init
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_1.weight, std=0.02)
+ nn.init.normal_(self.time_text_embed.timestep_embedder.linear_2.weight, std=0.02)
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_1.weight, std=0.02)
+ nn.init.normal_(self.time_text_embed.text_embedder.linear_2.weight, std=0.02)
+ nn.init.normal_(self.context_embedder.weight, std=0.02)
+
+ # Zero-out adaLN modulation layers in DiT blocks:
+ for block in self.transformer_blocks:
+ nn.init.constant_(block.norm1.linear.weight, 0)
+ nn.init.constant_(block.norm1.linear.bias, 0)
+ nn.init.constant_(block.norm1_context.linear.weight, 0)
+ nn.init.constant_(block.norm1_context.linear.bias, 0)
+
+ for block in self.single_transformer_blocks:
+ nn.init.constant_(block.norm.linear.weight, 0)
+ nn.init.constant_(block.norm.linear.bias, 0)
+
+ # Zero-out output layers:
+ nn.init.constant_(self.norm_out.linear.weight, 0)
+ nn.init.constant_(self.norm_out.linear.bias, 0)
+ nn.init.constant_(self.proj_out.weight, 0)
+ nn.init.constant_(self.proj_out.bias, 0)
+
+ @torch.no_grad()
+ def _prepare_image_ids(self, batch_size, temp, height, width, train_height, train_width, device, start_time_stamp=0):
+ latent_image_ids = torch.zeros(temp, height, width, 3)
+
+ # Temporal Rope
+ latent_image_ids[..., 0] = latent_image_ids[..., 0] + torch.arange(start_time_stamp, start_time_stamp + temp)[:, None, None]
+
+ # height Rope
+ if height != train_height:
+ height_pos = F.interpolate(torch.arange(train_height)[None, None, :].float(), height, mode='linear').squeeze(0, 1)
+ else:
+ height_pos = torch.arange(train_height).float()
+
+ latent_image_ids[..., 1] = latent_image_ids[..., 1] + height_pos[None, :, None]
+
+ # width rope
+ if width != train_width:
+ width_pos = F.interpolate(torch.arange(train_width)[None, None, :].float(), width, mode='linear').squeeze(0, 1)
+ else:
+ width_pos = torch.arange(train_width).float()
+
+ latent_image_ids[..., 2] = latent_image_ids[..., 2] + width_pos[None, None, :]
+
+ latent_image_ids = latent_image_ids[None, :].repeat(batch_size, 1, 1, 1, 1)
+ latent_image_ids = rearrange(latent_image_ids, 'b t h w c -> b (t h w) c')
+
+ return latent_image_ids.to(device=device)
+
+ @torch.no_grad()
+ def _prepare_pyramid_image_ids(self, sample, batch_size, device):
+ image_ids_list = []
+
+ for i_b, sample_ in enumerate(sample):
+ if not isinstance(sample_, list):
+ sample_ = [sample_]
+
+ cur_image_ids = []
+ start_time_stamp = 0
+
+ train_height = sample_[-1].shape[-2] // self.patch_size
+ train_width = sample_[-1].shape[-1] // self.patch_size
+
+ for clip_ in sample_:
+ _, _, temp, height, width = clip_.shape
+ height = height // self.patch_size
+ width = width // self.patch_size
+ cur_image_ids.append(self._prepare_image_ids(batch_size, temp, height, width, train_height, train_width, device, start_time_stamp=start_time_stamp))
+ start_time_stamp += temp
+
+ cur_image_ids = torch.cat(cur_image_ids, dim=1)
+ image_ids_list.append(cur_image_ids)
+
+ return image_ids_list
+
+ def merge_input(self, sample, encoder_hidden_length, encoder_attention_mask):
+ """
+ Merge the input video with different resolutions into one sequence
+ Sample: From low resolution to high resolution
+ """
+ if isinstance(sample[0], list):
+ device = sample[0][-1].device
+ pad_batch_size = sample[0][-1].shape[0]
+ else:
+ device = sample[0].device
+ pad_batch_size = sample[0].shape[0]
+
+ num_stages = len(sample)
+ height_list = [];width_list = [];temp_list = []
+ trainable_token_list = []
+
+ for i_b, sample_ in enumerate(sample):
+ if isinstance(sample_, list):
+ sample_ = sample_[-1]
+ _, _, temp, height, width = sample_.shape
+ height = height // self.patch_size
+ width = width // self.patch_size
+ temp_list.append(temp)
+ height_list.append(height)
+ width_list.append(width)
+ trainable_token_list.append(height * width * temp)
+
+ # prepare the RoPE IDs,
+ image_ids_list = self._prepare_pyramid_image_ids(sample, pad_batch_size, device)
+ text_ids = torch.zeros(pad_batch_size, encoder_attention_mask.shape[1], 3).to(device=device)
+ input_ids_list = [torch.cat([text_ids, image_ids], dim=1) for image_ids in image_ids_list]
+ image_rotary_emb = [self.pos_embed(input_ids) for input_ids in input_ids_list] # [bs, seq_len, 1, head_dim // 2, 2, 2]
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ concat_output = True if self.training else False
+ image_rotary_emb = [all_to_all(x_.repeat(1, 1, sp_group_size, 1, 1, 1), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for x_ in image_rotary_emb]
+ input_ids_list = [all_to_all(input_ids.repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output) for input_ids in input_ids_list]
+
+ hidden_states, hidden_length = [], []
+
+ for sample_ in sample:
+ video_tokens = []
+
+ for each_latent in sample_:
+ each_latent = rearrange(each_latent, 'b c t h w -> b t h w c')
+ each_latent = rearrange(each_latent, 'b t (h p1) (w p2) c -> b (t h w) (p1 p2 c)', p1=self.patch_size, p2=self.patch_size)
+ video_tokens.append(each_latent)
+
+ video_tokens = torch.cat(video_tokens, dim=1)
+ video_tokens = self.x_embedder(video_tokens)
+ hidden_states.append(video_tokens)
+ hidden_length.append(video_tokens.shape[1])
+
+ # prepare the attention mask
+ if self.use_flash_attn:
+ attention_mask = None
+ indices_list = []
+ for i_p, length in enumerate(hidden_length):
+ pad_attention_mask = torch.ones((pad_batch_size, length), dtype=encoder_attention_mask.dtype).to(device)
+ pad_attention_mask = torch.cat([encoder_attention_mask[i_p::num_stages], pad_attention_mask], dim=1)
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ pad_attention_mask = all_to_all(pad_attention_mask.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0)
+ pad_attention_mask = pad_attention_mask.squeeze(2)
+
+ seqlens_in_batch = pad_attention_mask.sum(dim=-1, dtype=torch.int32)
+ indices = torch.nonzero(pad_attention_mask.flatten(), as_tuple=False).flatten()
+
+ indices_list.append(
+ {
+ 'indices': indices,
+ 'seqlens_in_batch': seqlens_in_batch,
+ }
+ )
+ encoder_attention_mask = indices_list
+ else:
+ assert encoder_attention_mask.shape[1] == encoder_hidden_length
+ real_batch_size = encoder_attention_mask.shape[0]
+
+ # prepare text ids
+ text_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, encoder_hidden_length)
+ text_ids = text_ids.to(device)
+ text_ids[encoder_attention_mask == 0] = 0
+
+ # prepare image ids
+ image_ids = torch.arange(1, real_batch_size + 1, dtype=encoder_attention_mask.dtype).unsqueeze(1).repeat(1, max(hidden_length))
+ image_ids = image_ids.to(device)
+ image_ids_list = []
+ for i_p, length in enumerate(hidden_length):
+ image_ids_list.append(image_ids[i_p::num_stages][:, :length])
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ concat_output = True if self.training else False
+ text_ids = all_to_all(text_ids.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2)
+ image_ids_list = [all_to_all(image_ids_.unsqueeze(2).repeat(1, 1, sp_group_size), sp_group, sp_group_size, scatter_dim=2, gather_dim=0, concat_output=concat_output).squeeze(2) for image_ids_ in image_ids_list]
+
+ attention_mask = []
+ for i_p in range(len(hidden_length)):
+ image_ids = image_ids_list[i_p]
+ token_ids = torch.cat([text_ids[i_p::num_stages], image_ids], dim=1)
+ stage_attention_mask = rearrange(token_ids, 'b i -> b 1 i 1') == rearrange(token_ids, 'b j -> b 1 1 j') # [bs, 1, q_len, k_len]
+ if self.use_temporal_causal:
+ input_order_ids = input_ids_list[i_p][:,:,0]
+ temporal_causal_mask = rearrange(input_order_ids, 'b i -> b 1 i 1') >= rearrange(input_order_ids, 'b j -> b 1 1 j')
+ stage_attention_mask = stage_attention_mask & temporal_causal_mask
+ attention_mask.append(stage_attention_mask)
+
+ return hidden_states, hidden_length, temp_list, height_list, width_list, trainable_token_list, encoder_attention_mask, attention_mask, image_rotary_emb
+
+ def split_output(self, batch_hidden_states, hidden_length, temps, heights, widths, trainable_token_list):
+ # To split the hidden states
+ batch_size = batch_hidden_states.shape[0]
+ output_hidden_list = []
+ batch_hidden_states = torch.split(batch_hidden_states, hidden_length, dim=1)
+
+ if is_sequence_parallel_initialized():
+ sp_group_size = get_sequence_parallel_world_size()
+ batch_size = batch_size // sp_group_size
+
+ for i_p, length in enumerate(hidden_length):
+ width, height, temp = widths[i_p], heights[i_p], temps[i_p]
+ trainable_token_num = trainable_token_list[i_p]
+ hidden_states = batch_hidden_states[i_p]
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ hidden_states = all_to_all(hidden_states, sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
+
+ # only the trainable token are taking part in loss computation
+ hidden_states = hidden_states[:, -trainable_token_num:]
+
+ # unpatchify
+ hidden_states = hidden_states.reshape(
+ shape=(batch_size, temp, height, width, self.patch_size, self.patch_size, self.out_channels // 4)
+ )
+ hidden_states = rearrange(hidden_states, "b t h w p1 p2 c -> b t (h p1) (w p2) c")
+ hidden_states = rearrange(hidden_states, "b t h w c -> b c t h w")
+ output_hidden_list.append(hidden_states)
+
+ return output_hidden_list
+
+ def forward(
+ self,
+ sample: torch.FloatTensor, # [num_stages]
+ encoder_hidden_states: torch.Tensor = None,
+ encoder_attention_mask: torch.FloatTensor = None,
+ pooled_projections: torch.Tensor = None,
+ timestep_ratio: torch.LongTensor = None,
+ ):
+ temb = self.time_text_embed(timestep_ratio, pooled_projections)
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
+ encoder_hidden_length = encoder_hidden_states.shape[1]
+
+ # Get the input sequence
+ hidden_states, hidden_length, temps, heights, widths, trainable_token_list, encoder_attention_mask, attention_mask, \
+ image_rotary_emb = self.merge_input(sample, encoder_hidden_length, encoder_attention_mask)
+
+ # split the long latents if necessary
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ concat_output = True if self.training else False
+
+ # sync the input hidden states
+ batch_hidden_states = []
+ for i_p, hidden_states_ in enumerate(hidden_states):
+ assert hidden_states_.shape[1] % sp_group_size == 0, "The sequence length should be divided by sequence parallel size"
+ hidden_states_ = all_to_all(hidden_states_, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
+ hidden_length[i_p] = hidden_length[i_p] // sp_group_size
+ batch_hidden_states.append(hidden_states_)
+
+ # sync the encoder hidden states
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
+ encoder_hidden_states = all_to_all(encoder_hidden_states, sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
+ temb = all_to_all(temb.unsqueeze(1).repeat(1, sp_group_size, 1), sp_group, sp_group_size, scatter_dim=1, gather_dim=0, concat_output=concat_output)
+ temb = temb.squeeze(1)
+ else:
+ hidden_states = torch.cat(hidden_states, dim=1)
+
+ for index_block, block in enumerate(self.transformer_blocks):
+ if self.training and self.gradient_checkpointing and (index_block <= int(len(self.transformer_blocks) * self.gradient_checkpointing_ratio)):
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ encoder_attention_mask,
+ temb,
+ attention_mask,
+ hidden_length,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ encoder_hidden_states, hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_attention_mask=encoder_attention_mask,
+ temb=temb,
+ attention_mask=attention_mask,
+ hidden_length=hidden_length,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ # remerge for single attention block
+ num_stages = len(hidden_length)
+ batch_hidden_states = list(torch.split(hidden_states, hidden_length, dim=1))
+ concat_hidden_length = []
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ encoder_hidden_states = all_to_all(encoder_hidden_states, sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
+
+ for i_p in range(len(hidden_length)):
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
+
+ batch_hidden_states[i_p] = torch.cat([encoder_hidden_states[i_p::num_stages], batch_hidden_states[i_p]], dim=1)
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=1, gather_dim=0)
+
+ concat_hidden_length.append(batch_hidden_states[i_p].shape[1])
+
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
+
+ for index_block, block in enumerate(self.single_transformer_blocks):
+ if self.training and self.gradient_checkpointing and (index_block <= int(len(self.single_transformer_blocks) * self.gradient_checkpointing_ratio)):
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ temb,
+ encoder_attention_mask,
+ attention_mask,
+ concat_hidden_length,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ hidden_states = block(
+ hidden_states=hidden_states,
+ temb=temb,
+ encoder_attention_mask=encoder_attention_mask, # used for
+ attention_mask=attention_mask,
+ hidden_length=concat_hidden_length,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ batch_hidden_states = list(torch.split(hidden_states, concat_hidden_length, dim=1))
+
+ for i_p in range(len(concat_hidden_length)):
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=0, gather_dim=1)
+
+ batch_hidden_states[i_p] = batch_hidden_states[i_p][:, encoder_hidden_length :, ...]
+
+ if is_sequence_parallel_initialized():
+ sp_group = get_sequence_parallel_group()
+ sp_group_size = get_sequence_parallel_world_size()
+ batch_hidden_states[i_p] = all_to_all(batch_hidden_states[i_p], sp_group, sp_group_size, scatter_dim=1, gather_dim=0)
+
+ hidden_states = torch.cat(batch_hidden_states, dim=1)
+ hidden_states = self.norm_out(hidden_states, temb, hidden_length=hidden_length)
+ hidden_states = self.proj_out(hidden_states)
+
+ output = self.split_output(hidden_states, hidden_length, temps, heights, widths, trainable_token_list)
+
+ return output
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_text_encoder.py b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_text_encoder.py
new file mode 100644
index 0000000000000000000000000000000000000000..ab9a8b71accc493fae3e35dc125399a3c0bf0f53
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/flux_modules/modeling_text_encoder.py
@@ -0,0 +1,135 @@
+import torch
+import torch.nn as nn
+import os
+
+from transformers import (
+ CLIPTextModel,
+ CLIPTokenizer,
+ T5EncoderModel,
+ T5TokenizerFast,
+)
+
+from typing import Any, Callable, Dict, List, Optional, Union
+from diffusers.models.modeling_utils import ModelMixin
+
+class FluxTextEncoderWithMask(ModelMixin):
+ def __init__(self, model_path, torch_dtype):
+ super().__init__()
+ # CLIP-G
+ self.tokenizer = CLIPTokenizer.from_pretrained(os.path.join(model_path, 'tokenizer'), torch_dtype=torch_dtype)
+ self.tokenizer_max_length = (
+ self.tokenizer.model_max_length if hasattr(self, "tokenizer") and self.tokenizer is not None else 77
+ )
+ self.text_encoder = CLIPTextModel.from_pretrained(os.path.join(model_path, 'text_encoder'), torch_dtype=torch_dtype)
+
+ # T5
+ self.tokenizer_2 = T5TokenizerFast.from_pretrained(os.path.join(model_path, 'tokenizer_2'))
+ self.text_encoder_2 = T5EncoderModel.from_pretrained(os.path.join(model_path, 'text_encoder_2'), torch_dtype=torch_dtype)
+
+ self._freeze()
+
+ def _freeze(self):
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def _get_t5_prompt_embeds(
+ self,
+ prompt: Union[str, List[str]] = None,
+ num_images_per_prompt: int = 1,
+ max_sequence_length: int = 256,
+ device: Optional[torch.device] = None,
+ ):
+
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ batch_size = len(prompt)
+
+ text_inputs = self.tokenizer_2(
+ prompt,
+ padding="max_length",
+ max_length=max_sequence_length,
+ truncation=True,
+ return_length=False,
+ return_overflowing_tokens=False,
+ return_tensors="pt",
+ )
+ text_input_ids = text_inputs.input_ids
+ prompt_attention_mask = text_inputs.attention_mask
+ prompt_attention_mask = prompt_attention_mask.to(device)
+
+ prompt_embeds = self.text_encoder_2(text_input_ids.to(device), attention_mask=prompt_attention_mask, output_hidden_states=False)[0]
+
+ dtype = self.text_encoder_2.dtype
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
+
+ _, seq_len, _ = prompt_embeds.shape
+
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, seq_len, -1)
+ prompt_attention_mask = prompt_attention_mask.view(batch_size, -1)
+ prompt_attention_mask = prompt_attention_mask.repeat(num_images_per_prompt, 1)
+
+ return prompt_embeds, prompt_attention_mask
+
+ def _get_clip_prompt_embeds(
+ self,
+ prompt: Union[str, List[str]],
+ num_images_per_prompt: int = 1,
+ device: Optional[torch.device] = None,
+ ):
+
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+ batch_size = len(prompt)
+
+ text_inputs = self.tokenizer(
+ prompt,
+ padding="max_length",
+ max_length=self.tokenizer_max_length,
+ truncation=True,
+ return_overflowing_tokens=False,
+ return_length=False,
+ return_tensors="pt",
+ )
+
+ text_input_ids = text_inputs.input_ids
+ prompt_embeds = self.text_encoder(text_input_ids.to(device), output_hidden_states=False)
+
+ # Use pooled output of CLIPTextModel
+ prompt_embeds = prompt_embeds.pooler_output
+ prompt_embeds = prompt_embeds.to(dtype=self.text_encoder.dtype, device=device)
+
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt)
+ prompt_embeds = prompt_embeds.view(batch_size * num_images_per_prompt, -1)
+
+ return prompt_embeds
+
+ def encode_prompt(self,
+ prompt,
+ num_images_per_prompt=1,
+ device=None,
+ ):
+ prompt = [prompt] if isinstance(prompt, str) else prompt
+
+ batch_size = len(prompt)
+
+ pooled_prompt_embeds = self._get_clip_prompt_embeds(
+ prompt=prompt,
+ device=device,
+ num_images_per_prompt=num_images_per_prompt,
+ )
+
+ prompt_embeds, prompt_attention_mask = self._get_t5_prompt_embeds(
+ prompt=prompt,
+ num_images_per_prompt=num_images_per_prompt,
+ device=device,
+ )
+
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds
+
+ #TODO: 这块需要增加一个max_sequence_length
+ def forward(self, input_prompts, device, **kwargs):
+ with torch.no_grad():
+ prompt_embeds, prompt_attention_mask, pooled_prompt_embeds = self.encode_prompt(input_prompts, 1, device=device)
+
+ return prompt_embeds, prompt_attention_mask, pooled_prompt_embeds
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/__init__.py b/One-to-All-Animation/video-generation/opensora/model_variants/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..def78774fd52edf749c83d21e32d54ff210bbcdd
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/__init__.py
@@ -0,0 +1,67 @@
+from .transformer_cogvideo import CogVideoXTransformer3DModel
+from .transformer_mochi import MochiTransformer3DModel
+from .hunyuan_dit_src import HYVideoDiffusionTransformer, HYVideoDiffusionTransformerControlNet
+from .hunyuan_dit_src import HYVideoDiffusionTransformerRef, HYVideoDiffusionTransformerEnd2End, HYVideoDiffusionTransformer_Refextractor, HYVideoDiffusionTransformer_Refextractor_2D, HYVideoDiffusionTransformer_Refextractor_2D_Q
+from .hunyuan_dit_src import HYVideoDiffusionTransformer_Tokenmerge
+from .hunyuan_dit_i2v_src import HYVideoDiffusionTransformer as HYVideoDiffusionTransformerI2V
+from .cogvideo_controlnet import CogVideoXControlnet
+from .wanx_diffusers_src import WanTransformer3DModel_Refextractor,WanTransformer3DModel
+from .wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D
+from .wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D_Pose_Final
+from .wanx_diffusers_src import WanTransformer3DModel_Refextractor_2D_Controlnet_prefix
+from opensora.flux_modules import PyramidFluxTransformer
+
+
+def get_dit(model_name, config_path, weight_dtype):
+ if model_name == 'cogvideo':
+ return CogVideoXTransformer3DModel.from_config(config_path).to(weight_dtype), CogVideoXTransformer3DModel
+ elif model_name == 'mochi':
+ return MochiTransformer3DModel.from_config(config_path).to(weight_dtype), MochiTransformer3DModel
+ elif model_name == 'hunyuan':
+ return HYVideoDiffusionTransformer.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformer
+ elif model_name == 'hunyuanref':
+ return HYVideoDiffusionTransformerRef.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformerRef
+ elif model_name == 'hunyuanend2end':
+ return HYVideoDiffusionTransformerEnd2End.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformerEnd2End
+ elif model_name == 'hunyuan_refextractor':
+ return HYVideoDiffusionTransformer_Refextractor.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformer_Refextractor
+ elif model_name == 'hunyuan_tokenmerge':
+ return HYVideoDiffusionTransformer_Tokenmerge.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformer_Tokenmerge
+ elif model_name == 'hunyuan_i2v':
+ return HYVideoDiffusionTransformerI2V.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformerI2V
+
+ elif model_name == 'wanx_refextractor':
+ return WanTransformer3DModel_Refextractor.from_config(config_path).to(weight_dtype), WanTransformer3DModel_Refextractor
+ elif model_name == 'wanx':
+ return WanTransformer3DModel.from_config(config_path).to(weight_dtype), WanTransformer3DModel
+ elif model_name == 'wanx_refextractor_2d':
+ return WanTransformer3DModel_Refextractor_2D.from_config(config_path).to(weight_dtype), WanTransformer3DModel_Refextractor_2D
+
+ elif model_name == 'hunyuan_refextractor_2d':
+ return HYVideoDiffusionTransformer_Refextractor_2D.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformer_Refextractor_2D
+ elif model_name == 'hunyuan_refextractor_2d_split':
+ return HYVideoDiffusionTransformer_Refextractor_2D_Q.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformer_Refextractor_2D_Q
+
+
+ elif model_name == 'wanx_refextractor_2d_pose_final':
+ return WanTransformer3DModel_Refextractor_2D_Pose_Final.from_config(config_path).to(weight_dtype), WanTransformer3DModel_Refextractor_2D_Pose_Final
+ elif model_name == 'wanx_refextractor_2d_controlnet_prefix':
+ return WanTransformer3DModel_Refextractor_2D_Controlnet_prefix.from_config(config_path).to(weight_dtype), WanTransformer3DModel_Refextractor_2D_Controlnet_prefix
+
+
+ elif model_name == 'pyramid_flow':
+ #TODO: 临时这么写,后续修改
+ model = PyramidFluxTransformer.from_pretrained(
+ config_path, use_gradient_checkpointing=True,
+ gradient_checkpointing_ratio=0.75,
+ torch_dtype=weight_dtype,
+ use_flash_attn=False, use_temporal_causal=True,
+ interp_condition_pos=True, axes_dims_rope=[16, 24, 24],
+ )
+ return model, PyramidFluxTransformer
+
+def get_controlnet(model_name, config_path, weight_dtype):
+ if model_name == 'cogvideo-controlnet':
+ return CogVideoXControlnet.from_config(config_path).to(weight_dtype), CogVideoXControlnet
+ elif model_name == 'hunyuan-controlnet':
+ return HYVideoDiffusionTransformerControlNet.from_config(config_path).to(weight_dtype), HYVideoDiffusionTransformerControlNet
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/activations.py b/One-to-All-Animation/video-generation/opensora/model_variants/activations.py
new file mode 100644
index 0000000000000000000000000000000000000000..750cd09453c2cd327dd474295dab6699b9cec8ab
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/activations.py
@@ -0,0 +1,163 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.utils import deprecate
+from diffusers.utils.import_utils import is_torch_npu_available
+
+
+ACTIVATION_FUNCTIONS = {
+ "swish": nn.SiLU(),
+ "silu": nn.SiLU(),
+ "mish": nn.Mish(),
+ "gelu": nn.GELU(),
+ "relu": nn.ReLU(),
+}
+
+
+def get_activation(act_fn: str) -> nn.Module:
+ """Helper function to get activation function from string.
+
+ Args:
+ act_fn (str): Name of activation function.
+
+ Returns:
+ nn.Module: Activation function.
+ """
+
+ act_fn = act_fn.lower()
+ if act_fn in ACTIVATION_FUNCTIONS:
+ return ACTIVATION_FUNCTIONS[act_fn]
+ else:
+ raise ValueError(f"Unsupported activation function: {act_fn}")
+
+
+class FP32SiLU(nn.Module):
+ r"""
+ SiLU activation function with input upcasted to torch.float32.
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return F.silu(inputs.float(), inplace=False).to(inputs.dtype)
+
+
+class GELU(nn.Module):
+ r"""
+ GELU activation function with tanh approximation support with `approximate="tanh"`.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, approximate: str = "none", bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
+ self.approximate = approximate
+
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
+ if gate.device.type != "mps":
+ return F.gelu(gate, approximate=self.approximate)
+ # mps: gelu is not implemented for float16
+ return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.gelu(hidden_states)
+ return hidden_states
+
+
+class GEGLU(nn.Module):
+ r"""
+ A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out * 2, bias=bias)
+
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
+ if gate.device.type != "mps":
+ return F.gelu(gate)
+ # mps: gelu is not implemented for float16
+ return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
+
+ def forward(self, hidden_states, *args, **kwargs):
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+ hidden_states = self.proj(hidden_states)
+ if is_torch_npu_available():
+ # using torch_npu.npu_geglu can run faster and save memory on NPU.
+ return torch_npu.npu_geglu(hidden_states, dim=-1, approximate=1)[0]
+ else:
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ return hidden_states * self.gelu(gate)
+
+
+class SwiGLU(nn.Module):
+ r"""
+ A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function. It's similar to `GEGLU`
+ but uses SiLU / Swish instead of GeLU.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+
+ self.proj = nn.Linear(dim_in, dim_out * 2, bias=bias)
+ self.activation = nn.SiLU()
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj(hidden_states)
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ return hidden_states * self.activation(gate)
+
+
+class ApproximateGELU(nn.Module):
+ r"""
+ The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
+ [paper](https://arxiv.org/abs/1606.08415).
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.proj(x)
+ return x * torch.sigmoid(1.702 * x)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/attention.py b/One-to-All-Animation/video-generation/opensora/model_variants/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..953c7954957eeb35c867a7fb52753b1670a5c6f2
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/attention.py
@@ -0,0 +1,68 @@
+from typing import Any, Dict, List, Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+from diffusers.utils import deprecate
+
+from .activations import GEGLU, GELU, ApproximateGELU, FP32SiLU, SwiGLU
+
+class FeedForward(nn.Module):
+ r"""
+ A feed-forward layer.
+
+ Parameters:
+ dim (`int`): The number of channels in the input.
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ dim_out: Optional[int] = None,
+ mult: int = 4,
+ dropout: float = 0.0,
+ activation_fn: str = "geglu",
+ final_dropout: bool = False,
+ inner_dim=None,
+ bias: bool = True,
+ ):
+ super().__init__()
+ if inner_dim is None:
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim, bias=bias)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
+ elif activation_fn == "swiglu":
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
+
+ self.net = nn.ModuleList([])
+ # project in
+ self.net.append(act_fn)
+ # project dropout
+ self.net.append(nn.Dropout(dropout))
+ # project out
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/attention_processor.py b/One-to-All-Animation/video-generation/opensora/model_variants/attention_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2500a3e6b2eb9b819c2136122fad916b9596f83
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/attention_processor.py
@@ -0,0 +1,1230 @@
+import inspect
+import math
+from typing import Callable, List, Optional, Tuple, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.utils import deprecate, logging
+from diffusers.utils.import_utils import is_torch_npu_available, is_xformers_available
+from diffusers.utils.torch_utils import is_torch_version, maybe_allow_in_graph
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+if is_torch_npu_available():
+ import torch_npu
+
+if is_xformers_available():
+ import xformers
+ import xformers.ops
+else:
+ xformers = None
+
+
+@maybe_allow_in_graph
+class Attention(nn.Module):
+ r"""
+ A cross attention layer.
+
+ Parameters:
+ query_dim (`int`):
+ The number of channels in the query.
+ cross_attention_dim (`int`, *optional*):
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
+ heads (`int`, *optional*, defaults to 8):
+ The number of heads to use for multi-head attention.
+ kv_heads (`int`, *optional*, defaults to `None`):
+ The number of key and value heads to use for multi-head attention. Defaults to `heads`. If
+ `kv_heads=heads`, the model will use Multi Head Attention (MHA), if `kv_heads=1` the model will use Multi
+ Query Attention (MQA) otherwise GQA is used.
+ dim_head (`int`, *optional*, defaults to 64):
+ The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability to use.
+ bias (`bool`, *optional*, defaults to False):
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
+ upcast_attention (`bool`, *optional*, defaults to False):
+ Set to `True` to upcast the attention computation to `float32`.
+ upcast_softmax (`bool`, *optional*, defaults to False):
+ Set to `True` to upcast the softmax computation to `float32`.
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
+ The number of groups to use for the group norm in the cross attention.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ norm_num_groups (`int`, *optional*, defaults to `None`):
+ The number of groups to use for the group norm in the attention.
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the spatial normalization.
+ out_bias (`bool`, *optional*, defaults to `True`):
+ Set to `True` to use a bias in the output linear layer.
+ scale_qk (`bool`, *optional*, defaults to `True`):
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
+ `added_kv_proj_dim` is not `None`.
+ eps (`float`, *optional*, defaults to 1e-5):
+ An additional value added to the denominator in group normalization that is used for numerical stability.
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
+ A factor to rescale the output by dividing it with this value.
+ residual_connection (`bool`, *optional*, defaults to `False`):
+ Set to `True` to add the residual connection to the output.
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
+ Set to `True` if the attention block is loaded from a deprecated state dict.
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
+ `AttnProcessor` otherwise.
+ """
+
+ def __init__(
+ self,
+ query_dim: int,
+ cross_attention_dim: Optional[int] = None,
+ heads: int = 8,
+ kv_heads: Optional[int] = None,
+ dim_head: int = 64,
+ dropout: float = 0.0,
+ bias: bool = False,
+ upcast_attention: bool = False,
+ upcast_softmax: bool = False,
+ cross_attention_norm: Optional[str] = None,
+ cross_attention_norm_num_groups: int = 32,
+ qk_norm: Optional[str] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ added_proj_bias: Optional[bool] = True,
+ norm_num_groups: Optional[int] = None,
+ spatial_norm_dim: Optional[int] = None,
+ out_bias: bool = True,
+ scale_qk: bool = True,
+ only_cross_attention: bool = False,
+ eps: float = 1e-5,
+ rescale_output_factor: float = 1.0,
+ residual_connection: bool = False,
+ _from_deprecated_attn_block: bool = False,
+ processor: Optional["AttnProcessor"] = None,
+ out_dim: int = None,
+ out_context_dim: int = None,
+ context_pre_only=None,
+ pre_only=False,
+ elementwise_affine: bool = True,
+ is_causal: bool = False,
+ ):
+ super().__init__()
+
+ # To prevent circular import.
+ from .normalization import FP32LayerNorm, LpNorm, RMSNorm
+
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
+ self.inner_kv_dim = self.inner_dim if kv_heads is None else dim_head * kv_heads
+ self.query_dim = query_dim
+ self.use_bias = bias
+ self.is_cross_attention = cross_attention_dim is not None
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
+ self.upcast_attention = upcast_attention
+ self.upcast_softmax = upcast_softmax
+ self.rescale_output_factor = rescale_output_factor
+ self.residual_connection = residual_connection
+ self.dropout = dropout
+ self.fused_projections = False
+ self.out_dim = out_dim if out_dim is not None else query_dim
+ self.out_context_dim = out_context_dim if out_context_dim is not None else query_dim
+ self.context_pre_only = context_pre_only
+ self.pre_only = pre_only
+ self.is_causal = is_causal
+
+ # we make use of this private variable to know whether this class is loaded
+ # with an deprecated state dict so that we can convert it on the fly
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
+
+ self.scale_qk = scale_qk
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
+
+ self.heads = out_dim // dim_head if out_dim is not None else heads
+ # for slice_size > 0 the attention score computation
+ # is split across the batch axis to save memory
+ # You can set slice_size with `set_attention_slice`
+ self.sliceable_head_dim = heads
+
+ self.added_kv_proj_dim = added_kv_proj_dim
+ self.only_cross_attention = only_cross_attention
+
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
+ raise ValueError(
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
+ )
+
+ if norm_num_groups is not None:
+ self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True)
+ else:
+ self.group_norm = None
+
+ if spatial_norm_dim is not None:
+ self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim)
+ else:
+ self.spatial_norm = None
+
+ if qk_norm is None:
+ self.norm_q = None
+ self.norm_k = None
+ elif qk_norm == "layer_norm":
+ self.norm_q = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ self.norm_k = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ elif qk_norm == "fp32_layer_norm":
+ self.norm_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ self.norm_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ elif qk_norm == "layer_norm_across_heads":
+ # Lumina applys qk norm across all heads
+ self.norm_q = nn.LayerNorm(dim_head * heads, eps=eps)
+ self.norm_k = nn.LayerNorm(dim_head * kv_heads, eps=eps)
+ elif qk_norm == "rms_norm":
+ self.norm_q = RMSNorm(dim_head, eps=eps)
+ self.norm_k = RMSNorm(dim_head, eps=eps)
+ elif qk_norm == "l2":
+ self.norm_q = LpNorm(p=2, dim=-1, eps=eps)
+ self.norm_k = LpNorm(p=2, dim=-1, eps=eps)
+ else:
+ raise ValueError(f"unknown qk_norm: {qk_norm}. Should be None,'layer_norm','fp32_layer_norm','rms_norm'")
+
+ if cross_attention_norm is None:
+ self.norm_cross = None
+ elif cross_attention_norm == "layer_norm":
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
+ elif cross_attention_norm == "group_norm":
+ if self.added_kv_proj_dim is not None:
+ # The given `encoder_hidden_states` are initially of shape
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
+ # before the projection, so we need to use `added_kv_proj_dim` as
+ # the number of channels for the group norm.
+ norm_cross_num_channels = added_kv_proj_dim
+ else:
+ norm_cross_num_channels = self.cross_attention_dim
+
+ self.norm_cross = nn.GroupNorm(
+ num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True
+ )
+ else:
+ raise ValueError(
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
+ )
+
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
+
+ if not self.only_cross_attention:
+ # only relevant for the `AddedKVProcessor` classes
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ else:
+ self.to_k = None
+ self.to_v = None
+
+ self.added_proj_bias = added_proj_bias
+ if self.added_kv_proj_dim is not None:
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ if self.context_pre_only is not None:
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+
+ if not self.pre_only:
+ self.to_out = nn.ModuleList([])
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
+ self.to_out.append(nn.Dropout(dropout))
+
+ if self.context_pre_only is not None and not self.context_pre_only:
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_context_dim, bias=out_bias)
+
+ if qk_norm is not None and added_kv_proj_dim is not None:
+ if qk_norm == "fp32_layer_norm":
+ self.norm_added_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ self.norm_added_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ elif qk_norm == "rms_norm":
+ self.norm_added_q = RMSNorm(dim_head, eps=eps)
+ self.norm_added_k = RMSNorm(dim_head, eps=eps)
+ else:
+ raise ValueError(
+ f"unknown qk_norm: {qk_norm}. Should be one of `None,'layer_norm','fp32_layer_norm','rms_norm'`"
+ )
+ else:
+ self.norm_added_q = None
+ self.norm_added_k = None
+
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ if processor is None:
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+ self.set_processor(processor)
+
+ def set_use_npu_flash_attention(self, use_npu_flash_attention: bool) -> None:
+ r"""
+ Set whether to use npu flash attention from `torch_npu` or not.
+
+ """
+ if use_npu_flash_attention:
+ processor = AttnProcessorNPU()
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+ self.set_processor(processor)
+
+ def set_use_memory_efficient_attention_xformers(
+ self, use_memory_efficient_attention_xformers: bool, attention_op: Optional[Callable] = None
+ ) -> None:
+ r"""
+ Set whether to use memory efficient attention from `xformers` or not.
+
+ Args:
+ use_memory_efficient_attention_xformers (`bool`):
+ Whether to use memory efficient attention from `xformers` or not.
+ attention_op (`Callable`, *optional*):
+ The attention operation to use. Defaults to `None` which uses the default attention operation from
+ `xformers`.
+ """
+ is_custom_diffusion = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (CustomDiffusionAttnProcessor, CustomDiffusionXFormersAttnProcessor, CustomDiffusionAttnProcessor2_0),
+ )
+ is_added_kv_processor = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (
+ AttnAddedKVProcessor,
+ AttnAddedKVProcessor2_0,
+ SlicedAttnAddedKVProcessor,
+ XFormersAttnAddedKVProcessor,
+ ),
+ )
+ is_ip_adapter = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0, IPAdapterXFormersAttnProcessor),
+ )
+ if use_memory_efficient_attention_xformers:
+ if is_added_kv_processor and is_custom_diffusion:
+ raise NotImplementedError(
+ f"Memory efficient attention is currently not supported for custom diffusion for attention processor type {self.processor}"
+ )
+ if not is_xformers_available():
+ raise ModuleNotFoundError(
+ (
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
+ " xformers"
+ ),
+ name="xformers",
+ )
+ elif not torch.cuda.is_available():
+ raise ValueError(
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
+ " only available for GPU "
+ )
+ else:
+ try:
+ # Make sure we can run the memory efficient attention
+ _ = xformers.ops.memory_efficient_attention(
+ torch.randn((1, 2, 40), device="cuda"),
+ torch.randn((1, 2, 40), device="cuda"),
+ torch.randn((1, 2, 40), device="cuda"),
+ )
+ except Exception as e:
+ raise e
+
+ if is_custom_diffusion:
+ processor = CustomDiffusionXFormersAttnProcessor(
+ train_kv=self.processor.train_kv,
+ train_q_out=self.processor.train_q_out,
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ attention_op=attention_op,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_custom_diffusion"):
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
+ elif is_added_kv_processor:
+ # TODO(Patrick, Suraj, William) - currently xformers doesn't work for UnCLIP
+ # which uses this type of cross attention ONLY because the attention mask of format
+ # [0, ..., -10.000, ..., 0, ...,] is not supported
+ # throw warning
+ logger.info(
+ "Memory efficient attention with `xformers` might currently not work correctly if an attention mask is required for the attention operation."
+ )
+ processor = XFormersAttnAddedKVProcessor(attention_op=attention_op)
+ elif is_ip_adapter:
+ processor = IPAdapterXFormersAttnProcessor(
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ num_tokens=self.processor.num_tokens,
+ scale=self.processor.scale,
+ attention_op=attention_op,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_ip"):
+ processor.to(
+ device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
+ )
+ else:
+ processor = XFormersAttnProcessor(attention_op=attention_op)
+ else:
+ if is_custom_diffusion:
+ attn_processor_class = (
+ CustomDiffusionAttnProcessor2_0
+ if hasattr(F, "scaled_dot_product_attention")
+ else CustomDiffusionAttnProcessor
+ )
+ processor = attn_processor_class(
+ train_kv=self.processor.train_kv,
+ train_q_out=self.processor.train_q_out,
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_custom_diffusion"):
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
+ elif is_ip_adapter:
+ processor = IPAdapterAttnProcessor2_0(
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ num_tokens=self.processor.num_tokens,
+ scale=self.processor.scale,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_ip"):
+ processor.to(
+ device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
+ )
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0()
+ if hasattr(F, "scaled_dot_product_attention") and self.scale_qk
+ else AttnProcessor()
+ )
+
+ self.set_processor(processor)
+
+ def set_attention_slice(self, slice_size: int) -> None:
+ r"""
+ Set the slice size for attention computation.
+
+ Args:
+ slice_size (`int`):
+ The slice size for attention computation.
+ """
+ if slice_size is not None and slice_size > self.sliceable_head_dim:
+ raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
+
+ if slice_size is not None and self.added_kv_proj_dim is not None:
+ processor = SlicedAttnAddedKVProcessor(slice_size)
+ elif slice_size is not None:
+ processor = SlicedAttnProcessor(slice_size)
+ elif self.added_kv_proj_dim is not None:
+ processor = AttnAddedKVProcessor()
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+
+ self.set_processor(processor)
+
+ def set_processor(self, processor: "AttnProcessor") -> None:
+ r"""
+ Set the attention processor to use.
+
+ Args:
+ processor (`AttnProcessor`):
+ The attention processor to use.
+ """
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
+ # pop `processor` from `self._modules`
+ if (
+ hasattr(self, "processor")
+ and isinstance(self.processor, torch.nn.Module)
+ and not isinstance(processor, torch.nn.Module)
+ ):
+ logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}")
+ self._modules.pop("processor")
+
+ self.processor = processor
+
+ def get_processor(self, return_deprecated_lora: bool = False) -> "AttentionProcessor":
+ r"""
+ Get the attention processor in use.
+
+ Args:
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
+ Set to `True` to return the deprecated LoRA attention processor.
+
+ Returns:
+ "AttentionProcessor": The attention processor in use.
+ """
+ if not return_deprecated_lora:
+ return self.processor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ **cross_attention_kwargs,
+ ) -> torch.Tensor:
+ r"""
+ The forward method of the `Attention` class.
+
+ Args:
+ hidden_states (`torch.Tensor`):
+ The hidden states of the query.
+ encoder_hidden_states (`torch.Tensor`, *optional*):
+ The hidden states of the encoder.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention mask to use. If `None`, no mask is applied.
+ **cross_attention_kwargs:
+ Additional keyword arguments to pass along to the cross attention.
+
+ Returns:
+ `torch.Tensor`: The output of the attention layer.
+ """
+ # The `Attention` class can call different attention processors / attention functions
+ # here we simply pass along all tensors to the selected processor class
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
+
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
+ quiet_attn_parameters = {"ip_adapter_masks"}
+ unused_kwargs = [
+ k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters and k not in quiet_attn_parameters
+ ]
+ if len(unused_kwargs) > 0:
+ logger.warning(
+ f"cross_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
+ )
+ cross_attention_kwargs = {k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters}
+
+ return self.processor(
+ self,
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ **cross_attention_kwargs,
+ )
+
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
+ r"""
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
+ is the number of heads initialized while constructing the `Attention` class.
+
+ Args:
+ tensor (`torch.Tensor`): The tensor to reshape.
+
+ Returns:
+ `torch.Tensor`: The reshaped tensor.
+ """
+ head_size = self.heads
+ batch_size, seq_len, dim = tensor.shape
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
+ return tensor
+
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
+ r"""
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
+ the number of heads initialized while constructing the `Attention` class.
+
+ Args:
+ tensor (`torch.Tensor`): The tensor to reshape.
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
+
+ Returns:
+ `torch.Tensor`: The reshaped tensor.
+ """
+ head_size = self.heads
+ if tensor.ndim == 3:
+ batch_size, seq_len, dim = tensor.shape
+ extra_dim = 1
+ else:
+ batch_size, extra_dim, seq_len, dim = tensor.shape
+ tensor = tensor.reshape(batch_size, seq_len * extra_dim, head_size, dim // head_size)
+ tensor = tensor.permute(0, 2, 1, 3)
+
+ if out_dim == 3:
+ tensor = tensor.reshape(batch_size * head_size, seq_len * extra_dim, dim // head_size)
+
+ return tensor
+
+ def get_attention_scores(
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ r"""
+ Compute the attention scores.
+
+ Args:
+ query (`torch.Tensor`): The query tensor.
+ key (`torch.Tensor`): The key tensor.
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
+
+ Returns:
+ `torch.Tensor`: The attention probabilities/scores.
+ """
+ dtype = query.dtype
+ if self.upcast_attention:
+ query = query.float()
+ key = key.float()
+
+ if attention_mask is None:
+ baddbmm_input = torch.empty(
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
+ )
+ beta = 0
+ else:
+ baddbmm_input = attention_mask
+ beta = 1
+
+ attention_scores = torch.baddbmm(
+ baddbmm_input,
+ query,
+ key.transpose(-1, -2),
+ beta=beta,
+ alpha=self.scale,
+ )
+ del baddbmm_input
+
+ if self.upcast_softmax:
+ attention_scores = attention_scores.float()
+
+ attention_probs = attention_scores.softmax(dim=-1)
+ del attention_scores
+
+ attention_probs = attention_probs.to(dtype)
+
+ return attention_probs
+
+ def prepare_attention_mask(
+ self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
+ ) -> torch.Tensor:
+ r"""
+ Prepare the attention mask for the attention computation.
+
+ Args:
+ attention_mask (`torch.Tensor`):
+ The attention mask to prepare.
+ target_length (`int`):
+ The target length of the attention mask. This is the length of the attention mask after padding.
+ batch_size (`int`):
+ The batch size, which is used to repeat the attention mask.
+ out_dim (`int`, *optional*, defaults to `3`):
+ The output dimension of the attention mask. Can be either `3` or `4`.
+
+ Returns:
+ `torch.Tensor`: The prepared attention mask.
+ """
+ head_size = self.heads
+ if attention_mask is None:
+ return attention_mask
+
+ current_length: int = attention_mask.shape[-1]
+ if current_length != target_length:
+ if attention_mask.device.type == "mps":
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
+ # Instead, we can manually construct the padding tensor.
+ padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
+ padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
+ else:
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
+ # remaining_length: int = target_length - current_length
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
+
+ if out_dim == 3:
+ if attention_mask.shape[0] < batch_size * head_size:
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
+ elif out_dim == 4:
+ attention_mask = attention_mask.unsqueeze(1)
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
+
+ return attention_mask
+
+ def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
+ r"""
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
+ `Attention` class.
+
+ Args:
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
+
+ Returns:
+ `torch.Tensor`: The normalized encoder hidden states.
+ """
+ assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
+
+ if isinstance(self.norm_cross, nn.LayerNorm):
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
+ elif isinstance(self.norm_cross, nn.GroupNorm):
+ # Group norm norms along the channels dimension and expects
+ # input to be in the shape of (N, C, *). In this case, we want
+ # to norm along the hidden dimension, so we need to move
+ # (batch_size, sequence_length, hidden_size) ->
+ # (batch_size, hidden_size, sequence_length)
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
+ else:
+ assert False
+
+ return encoder_hidden_states
+
+ @torch.no_grad()
+ def fuse_projections(self, fuse=True):
+ device = self.to_q.weight.data.device
+ dtype = self.to_q.weight.data.dtype
+
+ if not self.is_cross_attention:
+ # fetch weight matrices.
+ concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ # create a new single projection layer and copy over the weights.
+ self.to_qkv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
+ self.to_qkv.weight.copy_(concatenated_weights)
+ if self.use_bias:
+ concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
+ self.to_qkv.bias.copy_(concatenated_bias)
+
+ else:
+ concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ self.to_kv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
+ self.to_kv.weight.copy_(concatenated_weights)
+ if self.use_bias:
+ concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
+ self.to_kv.bias.copy_(concatenated_bias)
+
+ # handle added projections for SD3 and others.
+ if hasattr(self, "add_q_proj") and hasattr(self, "add_k_proj") and hasattr(self, "add_v_proj"):
+ concatenated_weights = torch.cat(
+ [self.add_q_proj.weight.data, self.add_k_proj.weight.data, self.add_v_proj.weight.data]
+ )
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ self.to_added_qkv = nn.Linear(
+ in_features, out_features, bias=self.added_proj_bias, device=device, dtype=dtype
+ )
+ self.to_added_qkv.weight.copy_(concatenated_weights)
+ if self.added_proj_bias:
+ concatenated_bias = torch.cat(
+ [self.add_q_proj.bias.data, self.add_k_proj.bias.data, self.add_v_proj.bias.data]
+ )
+ self.to_added_qkv.bias.copy_(concatenated_bias)
+
+ self.fused_projections = fuse
+
+class MochiAttnProcessor2_0:
+ """Attention processor used in Mochi."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("MochiAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ query = query.unflatten(2, (attn.heads, -1))
+ key = key.unflatten(2, (attn.heads, -1))
+ value = value.unflatten(2, (attn.heads, -1))
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_query = encoder_query.unflatten(2, (attn.heads, -1))
+ encoder_key = encoder_key.unflatten(2, (attn.heads, -1))
+ encoder_value = encoder_value.unflatten(2, (attn.heads, -1))
+
+ if attn.norm_added_q is not None:
+ encoder_query = attn.norm_added_q(encoder_query)
+ if attn.norm_added_k is not None:
+ encoder_key = attn.norm_added_k(encoder_key)
+
+ if image_rotary_emb is not None:
+
+ def apply_rotary_emb(x, freqs_cos, freqs_sin):
+ x_even = x[..., 0::2].float()
+ x_odd = x[..., 1::2].float()
+
+ cos = (x_even * freqs_cos - x_odd * freqs_sin).to(x.dtype)
+ sin = (x_even * freqs_sin + x_odd * freqs_cos).to(x.dtype)
+
+ return torch.stack([cos, sin], dim=-1).flatten(-2)
+
+ query = apply_rotary_emb(query, *image_rotary_emb)
+ key = apply_rotary_emb(key, *image_rotary_emb)
+
+ query, key, value = query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
+ encoder_query, encoder_key, encoder_value = (
+ encoder_query.transpose(1, 2),
+ encoder_key.transpose(1, 2),
+ encoder_value.transpose(1, 2),
+ )
+
+ sequence_length = query.size(2)
+ encoder_sequence_length = encoder_query.size(2)
+
+ query = torch.cat([query, encoder_query], dim=2)
+ key = torch.cat([key, encoder_key], dim=2)
+ value = torch.cat([value, encoder_value], dim=2)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.to(query.dtype)
+
+ hidden_states, encoder_hidden_states = hidden_states.split_with_sizes(
+ (sequence_length, encoder_sequence_length), dim=1
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if hasattr(attn, "to_add_out"):
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+
+class CogVideoXAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention for the CogVideoX model. It applies a rotary embedding on
+ query and key vectors, but does not include spatial normalization.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("CogVideoXAttnProcessor requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ text_seq_length = encoder_hidden_states.size(1)
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)
+ if not attn.is_cross_attention:
+ key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states, hidden_states = hidden_states.split(
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
+ )
+ return hidden_states, encoder_hidden_states
+
+class FusedCogVideoXAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention for the CogVideoX model. It applies a rotary embedding on
+ query and key vectors, but does not include spatial normalization.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("CogVideoXAttnProcessor requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ text_seq_length = encoder_hidden_states.size(1)
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)
+ if not attn.is_cross_attention:
+ key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states, hidden_states = hidden_states.split(
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
+ )
+ return hidden_states, encoder_hidden_states
+
+
+class FluxAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("FluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ if encoder_hidden_states is not None:
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+class FusedFluxAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FusedFluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_qkv = attn.to_added_qkv(encoder_hidden_states)
+ split_size = encoder_qkv.shape[-1] // 3
+ (
+ encoder_hidden_states_query_proj,
+ encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj,
+ ) = torch.split(encoder_qkv, split_size, dim=-1)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+class MochiVaeAttnProcessor2_0:
+ r"""
+ Attention processor used in Mochi VAE.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ is_single_frame = hidden_states.shape[1] == 1
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if is_single_frame:
+ hidden_states = attn.to_v(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+ return hidden_states
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=attn.is_causal
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/cogvideo_controlnet.py b/One-to-All-Animation/video-generation/opensora/model_variants/cogvideo_controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad36d08b0152f1fe0548cc3f441955c99bd37956
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/cogvideo_controlnet.py
@@ -0,0 +1,422 @@
+# copy from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/controlnets/controlnet_flux.py#L41
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+import torch
+from torch import nn
+from einops import rearrange
+import torch.nn.functional as F
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.attention import Attention, FeedForward
+from diffusers.models.attention_processor import AttentionProcessor, AttnProcessor2_0
+from diffusers.models.normalization import AdaLayerNorm, CogVideoXLayerNormZero, AdaLayerNormZeroSingle
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.controlnets.controlnet import Tuple, zero_module
+from diffusers.models.autoencoders.autoencoder_kl_cogvideox import CogVideoXDownBlock3D, CogVideoXCausalConv3d
+from .embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps, get_2d_sincos_pos_embed, get_3d_rotary_pos_embed
+from .transformer_cogvideo import CogVideoXBlock
+
+def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
+ tw = tgt_width
+ th = tgt_height
+ h, w = src
+ r = h / w
+ if r > (th / tw):
+ resize_height = th
+ resize_width = int(round(th / h * w))
+ else:
+ resize_width = tw
+ resize_height = int(round(tw / w * h))
+
+ crop_top = int(round((th - resize_height) / 2.0))
+ crop_left = int(round((tw - resize_width) / 2.0))
+
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) #在720x480的grid上crop的左上角和右下角
+
+def prepare_rotary_positional_embeddings(
+ height: int,
+ width: int,
+ num_frames: int,
+ vae_scale_factor_spatial: int = 8,
+ patch_size: int = 2,
+ patch_size_t = 1,
+ attention_head_dim: int = 64,
+ device = None,
+ dtype = None,
+ base_height: int = 480,
+ base_width: int = 720,
+):
+ grid_height = height // patch_size
+ grid_width = width // patch_size
+
+ p = patch_size
+ p_t = patch_size_t
+
+ if p_t is None:
+ # CogVideoX 1.0 I2V
+ base_size_width = base_width // p
+ base_size_height = base_height // p
+
+ grid_crops_coords = get_resize_crop_region_for_grid(
+ (grid_height, grid_width), base_size_width, base_size_height
+ )
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
+ embed_dim=attention_head_dim,
+ crops_coords=grid_crops_coords,
+ grid_size=(grid_height, grid_width),
+ temporal_size=num_frames,
+ )
+ else:
+ # CogVideoX 1.5 I2V
+ base_size_width = base_width // p
+ base_size_height = base_height // p
+ base_num_frames = (num_frames + p_t - 1) // p_t
+
+ grid_crops_coords = get_resize_crop_region_for_grid(
+ (grid_height, grid_width), base_size_width, base_size_height
+ )
+
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
+ embed_dim=attention_head_dim,
+ crops_coords=grid_crops_coords,
+ grid_size=(grid_height, grid_width),
+ temporal_size=base_num_frames,
+ grid_type="slice",
+ max_size=(base_size_height, base_size_width),
+ )
+ freqs_cos = freqs_cos.to(device=device, dtype=dtype)
+ freqs_sin = freqs_sin.to(device=device, dtype=dtype)
+ return freqs_cos, freqs_sin
+
+class CogVideoXControlnet(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 48,
+ attention_head_dim: int = 64,
+ vae_channels: int = 16, # 只需要和视频模态交互
+ in_channels: int = 64, # contiditon的编码数量
+ downscale_coef: int = 8,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ time_embed_dim: int = 512,
+ num_layers: int = 8,
+ dropout: float = 0.0,
+ attention_bias: bool = True,
+ sample_width: int = 90,
+ sample_height: int = 60,
+ sample_frames: int = 49,
+ patch_size: int = 2,
+ temporal_compression_ratio: int = 4,
+ max_text_seq_length: int = 226,
+ activation_fn: str = "gelu-approximate",
+ timestep_activation_fn: str = "silu",
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ spatial_interpolation_scale: float = 1.875,
+ temporal_interpolation_scale: float = 1.0,
+ use_rotary_positional_embeddings: bool = False,
+ use_learned_positional_embeddings: bool = False,
+ out_proj :bool = True,
+ block_out_channels = (16, 32, 32, 64),
+ layers_per_block = 3,
+ norm_num_groups = 8,
+ pad_mode = "first",
+ ):
+ super().__init__()
+ inner_dim = num_attention_heads * attention_head_dim
+
+ if not use_rotary_positional_embeddings and use_learned_positional_embeddings:
+ raise ValueError(
+ "There are no CogVideoX checkpoints available with disable rotary embeddings and learned positional "
+ "embeddings. If you're using a custom model and/or believe this should be supported, please open an "
+ "issue at https://github.com/huggingface/diffusers/issues."
+ )
+ out_channels = vae_channels
+ self.controlnet_encode = CogVideoXControlnetEncoder3D(
+ in_channels = in_channels,
+ out_channels = out_channels ,
+ down_block_types = (
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ ),
+ block_out_channels = block_out_channels,
+ layers_per_block = layers_per_block,
+ act_fn = timestep_activation_fn,
+ norm_eps = norm_eps,
+ norm_num_groups = norm_num_groups,
+ dropout = dropout,
+ pad_mode = pad_mode,
+ temporal_compression_ratio = temporal_compression_ratio,
+ )
+ self.vae_channels = vae_channels
+ # 1. Patch embedding
+ self.patch_embed = CogVideoXPatchEmbed(
+ patch_size=patch_size,
+ in_channels=vae_channels,
+ embed_dim=inner_dim,
+ bias=True,
+ sample_width=sample_width,
+ sample_height=sample_height,
+ sample_frames=sample_frames,
+ temporal_compression_ratio=temporal_compression_ratio,
+ spatial_interpolation_scale=spatial_interpolation_scale,
+ temporal_interpolation_scale=temporal_interpolation_scale,
+ use_positional_embeddings=not use_rotary_positional_embeddings,
+ use_learned_positional_embeddings=use_learned_positional_embeddings,
+ )
+
+ self.embedding_dropout = nn.Dropout(dropout)
+
+ # 2. Time embeddings
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
+
+ # 3. Define spatio-temporal transformers blocks
+ self.transformer_blocks = nn.ModuleList(
+ [
+ CogVideoXBlock(
+ dim=inner_dim,
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ time_embed_dim=time_embed_dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ attention_bias=attention_bias,
+ norm_elementwise_affine=norm_elementwise_affine,
+ norm_eps=norm_eps,
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ self.out_projectors = None
+ if out_proj is not None:
+ self.out_projectors = zero_module(nn.ModuleList(
+ [nn.Linear(inner_dim, inner_dim) for _ in range(num_layers)]
+ ))
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def compress_time(self, x, num_frames):
+ x = rearrange(x, '(b f) c h w -> b f c h w', f=num_frames)
+ batch_size, frames, channels, height, width = x.shape
+ x = rearrange(x, 'b f c h w -> (b h w) c f')
+
+ if x.shape[-1] % 2 == 1:
+ x_first, x_rest = x[..., 0], x[..., 1:]
+ if x_rest.shape[-1] > 0:
+ x_rest = F.avg_pool1d(x_rest, kernel_size=2, stride=2)
+
+ x = torch.cat([x_first[..., None], x_rest], dim=-1)
+ else:
+ x = F.avg_pool1d(x, kernel_size=2, stride=2)
+ x = rearrange(x, '(b h w) c f -> (b f) c h w', b=batch_size, h=height, w=width)
+ return x
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: Union[int, float, torch.LongTensor],
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ timestep_cond: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ ):
+ batch_size, channels, num_frames, height, width = controlnet_cond.shape
+ # 0. Controlnet encoder
+ controlnet_cond = self.controlnet_encode(controlnet_cond)
+ controlnet_cond = rearrange(controlnet_cond, 'b c f h w -> b f c h w')
+ hidden_states = hidden_states[:, :, :self.vae_channels, :, :] + controlnet_cond
+ image_rotary_emb = prepare_rotary_positional_embeddings(
+ height=hidden_states.shape[-2], #cogvideox固定分辨率
+ width=hidden_states.shape[-1],
+ num_frames=hidden_states.shape[1],
+ vae_scale_factor_spatial=8,
+ patch_size=2,
+ patch_size_t = self.config.patch_size_t if hasattr(self.config, "patch_size_t") else None,
+ attention_head_dim=self.config.attention_head_dim,
+ base_height=self.config.sample_height,
+ base_width=self.config.sample_width,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype
+ )
+ # 1. Time embedding
+ timesteps = timestep
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
+ hidden_states = self.embedding_dropout(hidden_states)
+
+
+ text_seq_length = encoder_hidden_states.shape[1]
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
+ hidden_states = hidden_states[:, text_seq_length:]
+
+
+ controlnet_hidden_states = ()
+ # 3. Transformer blocks
+ for i, block in enumerate(self.transformer_blocks):
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ emb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ hidden_states, encoder_hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=emb,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ if self.out_projectors is not None:
+ controlnet_hidden_states += (self.out_projectors[i](hidden_states),)
+ else:
+ controlnet_hidden_states += (hidden_states,)
+
+ if not return_dict:
+ return (controlnet_hidden_states,)
+ return Transformer2DModelOutput(sample=controlnet_hidden_states)
+
+class CogVideoXControlnetEncoder3D(nn.Module):
+ _supports_gradient_checkpointing = True
+
+ def __init__(
+ self,
+ in_channels: int = 4,
+ out_channels: int = 16,
+ down_block_types: Tuple[str, ...] = (
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ "CogVideoXDownBlock3D",
+ ),
+ block_out_channels: Tuple[int, ...] = (16, 32, 32, 64),
+ layers_per_block: int = 3,
+ act_fn: str = "silu",
+ norm_eps: float = 1e-6,
+ norm_num_groups: int = 32,
+ dropout: float = 0.0,
+ pad_mode: str = "first",
+ temporal_compression_ratio: float = 4,
+ ):
+ super().__init__()
+
+ # log2 of temporal_compress_times
+ temporal_compress_level = int(np.log2(temporal_compression_ratio))
+
+ self.conv_in = CogVideoXCausalConv3d(in_channels, block_out_channels[0], kernel_size=3, pad_mode=pad_mode)
+ self.down_blocks = nn.ModuleList([])
+
+ # down blocks
+ output_channel = block_out_channels[0]
+ for i, down_block_type in enumerate(down_block_types):
+ input_channel = output_channel
+ output_channel = block_out_channels[i]
+ is_final_block = i == len(block_out_channels) - 1
+ compress_time = i < temporal_compress_level
+
+ if down_block_type == "CogVideoXDownBlock3D":
+ down_block = CogVideoXDownBlock3D(
+ in_channels=input_channel,
+ out_channels=output_channel,
+ temb_channels=0,
+ dropout=dropout,
+ num_layers=layers_per_block,
+ resnet_eps=norm_eps,
+ resnet_act_fn=act_fn,
+ resnet_groups=norm_num_groups,
+ add_downsample=not is_final_block,
+ compress_time=compress_time,
+ )
+ else:
+ raise ValueError("Invalid `down_block_type` encountered. Must be `CogVideoXDownBlock3D`")
+
+ self.down_blocks.append(down_block)
+
+
+ self.norm_out = nn.GroupNorm(norm_num_groups, block_out_channels[-1], eps=1e-6)
+ self.conv_act = nn.SiLU()
+ self.conv_out = zero_module(CogVideoXCausalConv3d(
+ block_out_channels[-1], out_channels, kernel_size=3, pad_mode=pad_mode
+ ))
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ sample: torch.Tensor,
+ temb: Optional[torch.Tensor] = None,
+ conv_cache: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> torch.Tensor:
+ r"""The forward method of the `CogVideoXEncoder3D` class."""
+
+ new_conv_cache = {}
+ conv_cache = conv_cache or {}
+
+ hidden_states, new_conv_cache["conv_in"] = self.conv_in(sample, conv_cache=conv_cache.get("conv_in"))
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ # 1. Down
+ for i, down_block in enumerate(self.down_blocks):
+ conv_cache_key = f"down_block_{i}"
+ hidden_states, new_conv_cache[conv_cache_key] = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(down_block),
+ hidden_states,
+ temb,
+ None,
+ conv_cache.get(conv_cache_key),
+ )
+ else:
+ # 1. Down
+ for i, down_block in enumerate(self.down_blocks):
+ conv_cache_key = f"down_block_{i}"
+ hidden_states, new_conv_cache[conv_cache_key] = down_block(
+ hidden_states, temb, None, conv_cache.get(conv_cache_key)
+ )
+
+ # 3. Post-process
+ hidden_states = self.norm_out(hidden_states)
+ hidden_states = self.conv_act(hidden_states)
+
+ hidden_states, new_conv_cache["conv_out"] = self.conv_out(hidden_states, conv_cache=conv_cache.get("conv_out"))
+
+ return hidden_states
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/embeddings.py b/One-to-All-Animation/video-generation/opensora/model_variants/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..38c30c0dbc2c27307ec9d84ecad835471799cc52
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/embeddings.py
@@ -0,0 +1,932 @@
+import math
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.utils import deprecate
+from .activations import FP32SiLU, get_activation
+from .attention_processor import Attention
+
+
+def get_timestep_embedding(
+ timesteps: torch.Tensor,
+ embedding_dim: int,
+ flip_sin_to_cos: bool = False,
+ downscale_freq_shift: float = 1,
+ scale: float = 1,
+ max_period: int = 10000,
+):
+ """
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
+
+ Args
+ timesteps (torch.Tensor):
+ a 1-D Tensor of N indices, one per batch element. These may be fractional.
+ embedding_dim (int):
+ the dimension of the output.
+ flip_sin_to_cos (bool):
+ Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False)
+ downscale_freq_shift (float):
+ Controls the delta between frequencies between dimensions
+ scale (float):
+ Scaling factor applied to the embeddings.
+ max_period (int):
+ Controls the maximum frequency of the embeddings
+ Returns
+ torch.Tensor: an [N x dim] Tensor of positional embeddings.
+ """
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
+
+ half_dim = embedding_dim // 2
+ exponent = -math.log(max_period) * torch.arange(
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
+ )
+ exponent = exponent / (half_dim - downscale_freq_shift)
+
+ emb = torch.exp(exponent)
+ emb = timesteps[:, None].float() * emb[None, :]
+
+ # scale embeddings
+ emb = scale * emb
+
+ # concat sine and cosine embeddings
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
+
+ # flip sine and cosine embeddings
+ if flip_sin_to_cos:
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
+
+ # zero pad
+ if embedding_dim % 2 == 1:
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
+ return emb
+
+class MochiCombinedTimestepCaptionEmbedding(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ pooled_projection_dim: int,
+ text_embed_dim: int,
+ time_embed_dim: int = 256,
+ num_attention_heads: int = 8,
+ ) -> None:
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0.0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=time_embed_dim, time_embed_dim=embedding_dim)
+ self.pooler = MochiAttentionPool(
+ num_attention_heads=num_attention_heads, embed_dim=text_embed_dim, output_dim=embedding_dim
+ )
+ self.caption_proj = nn.Linear(text_embed_dim, pooled_projection_dim)
+
+ def forward(
+ self,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_attention_mask: torch.Tensor,
+ hidden_dtype: Optional[torch.dtype] = None,
+ ):
+ time_proj = self.time_proj(timestep)
+ time_emb = self.timestep_embedder(time_proj.to(dtype=hidden_dtype))
+
+ pooled_projections = self.pooler(encoder_hidden_states, encoder_attention_mask)
+ caption_proj = self.caption_proj(encoder_hidden_states)
+
+ conditioning = time_emb + pooled_projections
+ return conditioning, caption_proj
+
+class PatchEmbed(nn.Module):
+ """2D Image to Patch Embedding with support for SD3 cropping."""
+
+ def __init__(
+ self,
+ height=224,
+ width=224,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=1,
+ pos_embed_type="sincos",
+ pos_embed_max_size=None, # For SD3 cropping
+ ):
+ super().__init__()
+
+ num_patches = (height // patch_size) * (width // patch_size)
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+ self.pos_embed_max_size = pos_embed_max_size
+
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size = patch_size
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = height // patch_size
+ self.interpolation_scale = interpolation_scale
+
+ # Calculate positional embeddings based on max size or default
+ if pos_embed_max_size:
+ grid_size = pos_embed_max_size
+ else:
+ grid_size = int(num_patches**0.5)
+
+ if pos_embed_type is None:
+ self.pos_embed = None
+ elif pos_embed_type == "sincos":
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, grid_size, base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ persistent = True if pos_embed_max_size else False
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=persistent)
+ else:
+ raise ValueError(f"Unsupported pos_embed_type: {pos_embed_type}")
+
+ def cropped_pos_embed(self, height, width):
+ """Crops positional embeddings for SD3 compatibility."""
+ if self.pos_embed_max_size is None:
+ raise ValueError("`pos_embed_max_size` must be set for cropping.")
+
+ height = height // self.patch_size
+ width = width // self.patch_size
+ if height > self.pos_embed_max_size:
+ raise ValueError(
+ f"Height ({height}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
+ )
+ if width > self.pos_embed_max_size:
+ raise ValueError(
+ f"Width ({width}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
+ )
+
+ top = (self.pos_embed_max_size - height) // 2
+ left = (self.pos_embed_max_size - width) // 2
+ spatial_pos_embed = self.pos_embed.reshape(1, self.pos_embed_max_size, self.pos_embed_max_size, -1)
+ spatial_pos_embed = spatial_pos_embed[:, top : top + height, left : left + width, :]
+ spatial_pos_embed = spatial_pos_embed.reshape(1, -1, spatial_pos_embed.shape[-1])
+ return spatial_pos_embed
+
+ def forward(self, latent):
+ if self.pos_embed_max_size is not None:
+ height, width = latent.shape[-2:]
+ else:
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+
+ latent = self.proj(latent)
+ if self.flatten:
+ latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
+ if self.layer_norm:
+ latent = self.norm(latent)
+ if self.pos_embed is None:
+ return latent.to(latent.dtype)
+ # Interpolate or crop positional embeddings as needed
+ if self.pos_embed_max_size:
+ pos_embed = self.cropped_pos_embed(height, width)
+ else:
+ if self.height != height or self.width != width:
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed).float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+ return (latent + pos_embed).to(latent.dtype)
+
+class CogVideoXPatchEmbed(nn.Module):
+ def __init__(
+ self,
+ patch_size: int = 2,
+ patch_size_t: Optional[int] = None,
+ in_channels: int = 16,
+ embed_dim: int = 1920,
+ text_embed_dim: int = 4096,
+ bias: bool = True,
+ sample_width: int = 90,
+ sample_height: int = 60,
+ sample_frames: int = 49,
+ temporal_compression_ratio: int = 4,
+ max_text_seq_length: int = 226,
+ spatial_interpolation_scale: float = 1.875,
+ temporal_interpolation_scale: float = 1.0,
+ use_positional_embeddings: bool = True,
+ use_learned_positional_embeddings: bool = True,
+ ) -> None:
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.patch_size_t = patch_size_t
+ self.embed_dim = embed_dim
+ self.sample_height = sample_height
+ self.sample_width = sample_width
+ self.sample_frames = sample_frames
+ self.temporal_compression_ratio = temporal_compression_ratio
+ self.max_text_seq_length = max_text_seq_length
+ self.spatial_interpolation_scale = spatial_interpolation_scale
+ self.temporal_interpolation_scale = temporal_interpolation_scale
+ self.use_positional_embeddings = use_positional_embeddings
+ self.use_learned_positional_embeddings = use_learned_positional_embeddings
+
+ if patch_size_t is None:
+ # CogVideoX 1.0 checkpoints
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
+ )
+ else:
+ # CogVideoX 1.5 checkpoints
+ self.proj = nn.Linear(in_channels * patch_size * patch_size * patch_size_t, embed_dim)
+
+ self.text_proj = nn.Linear(text_embed_dim, embed_dim)
+
+ if use_positional_embeddings or use_learned_positional_embeddings:
+ persistent = use_learned_positional_embeddings
+ pos_embedding = self._get_positional_embeddings(sample_height, sample_width, sample_frames)
+ self.register_buffer("pos_embedding", pos_embedding, persistent=persistent)
+
+ def _get_positional_embeddings(self, sample_height: int, sample_width: int, sample_frames: int) -> torch.Tensor:
+ post_patch_height = sample_height // self.patch_size
+ post_patch_width = sample_width // self.patch_size
+ post_time_compression_frames = (sample_frames - 1) // self.temporal_compression_ratio + 1
+ num_patches = post_patch_height * post_patch_width * post_time_compression_frames
+
+ pos_embedding = get_3d_sincos_pos_embed(
+ self.embed_dim,
+ (post_patch_width, post_patch_height),
+ post_time_compression_frames,
+ self.spatial_interpolation_scale,
+ self.temporal_interpolation_scale,
+ )
+ pos_embedding = torch.from_numpy(pos_embedding).flatten(0, 1)
+ joint_pos_embedding = torch.zeros(
+ 1, self.max_text_seq_length + num_patches, self.embed_dim, requires_grad=False
+ )
+ joint_pos_embedding.data[:, self.max_text_seq_length :].copy_(pos_embedding)
+
+ return joint_pos_embedding
+
+ def forward(self, text_embeds: torch.Tensor, image_embeds: torch.Tensor):
+ r"""
+ Args:
+ text_embeds (`torch.Tensor`):
+ Input text embeddings. Expected shape: (batch_size, seq_length, embedding_dim).
+ image_embeds (`torch.Tensor`):
+ Input image embeddings. Expected shape: (batch_size, num_frames, channels, height, width).
+ """
+ text_embeds = self.text_proj(text_embeds)
+
+ batch_size, num_frames, channels, height, width = image_embeds.shape
+
+ if self.patch_size_t is None:
+ image_embeds = image_embeds.reshape(-1, channels, height, width)
+ image_embeds = self.proj(image_embeds)
+ image_embeds = image_embeds.view(batch_size, num_frames, *image_embeds.shape[1:])
+ image_embeds = image_embeds.flatten(3).transpose(2, 3) # [batch, num_frames, height x width, channels]
+ image_embeds = image_embeds.flatten(1, 2) # [batch, num_frames x height x width, channels]
+ else:
+ p = self.patch_size
+ p_t = self.patch_size_t
+
+ image_embeds = image_embeds.permute(0, 1, 3, 4, 2)
+ image_embeds = image_embeds.reshape(
+ batch_size, num_frames // p_t, p_t, height // p, p, width // p, p, channels
+ )
+ image_embeds = image_embeds.permute(0, 1, 3, 5, 7, 2, 4, 6).flatten(4, 7).flatten(1, 3)
+ image_embeds = self.proj(image_embeds)
+
+ embeds = torch.cat(
+ [text_embeds, image_embeds], dim=1
+ ).contiguous() # [batch, seq_length + num_frames x height x width, channels]
+
+ if self.use_positional_embeddings or self.use_learned_positional_embeddings:
+ if self.use_learned_positional_embeddings and (self.sample_width != width or self.sample_height != height):
+ raise ValueError(
+ "It is currently not possible to generate videos at a different resolution that the defaults. This should only be the case with 'THUDM/CogVideoX-5b-I2V'."
+ "If you think this is incorrect, please open an issue at https://github.com/huggingface/diffusers/issues."
+ )
+
+ pre_time_compression_frames = (num_frames - 1) * self.temporal_compression_ratio + 1
+
+ if (
+ self.sample_height != height
+ or self.sample_width != width
+ or self.sample_frames != pre_time_compression_frames
+ ):
+ pos_embedding = self._get_positional_embeddings(height, width, pre_time_compression_frames)
+ pos_embedding = pos_embedding.to(embeds.device, dtype=embeds.dtype)
+ else:
+ pos_embedding = self.pos_embedding
+
+ embeds = embeds + pos_embedding
+
+ return embeds
+
+def get_3d_sincos_pos_embed(
+ embed_dim: int,
+ spatial_size: Union[int, Tuple[int, int]],
+ temporal_size: int,
+ spatial_interpolation_scale: float = 1.0,
+ temporal_interpolation_scale: float = 1.0,
+) -> np.ndarray:
+ r"""
+ Args:
+ embed_dim (`int`):
+ spatial_size (`int` or `Tuple[int, int]`):
+ temporal_size (`int`):
+ spatial_interpolation_scale (`float`, defaults to 1.0):
+ temporal_interpolation_scale (`float`, defaults to 1.0):
+ """
+ if embed_dim % 4 != 0:
+ raise ValueError("`embed_dim` must be divisible by 4")
+ if isinstance(spatial_size, int):
+ spatial_size = (spatial_size, spatial_size)
+
+ embed_dim_spatial = 3 * embed_dim // 4
+ embed_dim_temporal = embed_dim // 4
+
+ # 1. Spatial
+ grid_h = np.arange(spatial_size[1], dtype=np.float32) / spatial_interpolation_scale
+ grid_w = np.arange(spatial_size[0], dtype=np.float32) / spatial_interpolation_scale
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, spatial_size[1], spatial_size[0]])
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(embed_dim_spatial, grid)
+
+ # 2. Temporal
+ grid_t = np.arange(temporal_size, dtype=np.float32) / temporal_interpolation_scale
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(embed_dim_temporal, grid_t)
+
+ # 3. Concat
+ pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
+ pos_embed_spatial = np.repeat(pos_embed_spatial, temporal_size, axis=0) # [T, H*W, D // 4 * 3]
+
+ pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
+ pos_embed_temporal = np.repeat(pos_embed_temporal, spatial_size[0] * spatial_size[1], axis=1) # [T, H*W, D // 4]
+
+ pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1) # [T, H*W, D]
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
+):
+ """
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ if isinstance(grid_size, int):
+ grid_size = (grid_size, grid_size)
+
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
+ return emb
+
+class TimestepEmbedding(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ act_fn: str = "silu",
+ out_dim: int = None,
+ post_act_fn: Optional[str] = None,
+ cond_proj_dim=None,
+ sample_proj_bias=True,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
+
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+
+ self.act = get_activation(act_fn)
+
+ if out_dim is not None:
+ time_embed_dim_out = out_dim
+ else:
+ time_embed_dim_out = time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out, sample_proj_bias)
+
+ if post_act_fn is None:
+ self.post_act = None
+ else:
+ self.post_act = get_activation(post_act_fn)
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+
+ if self.act is not None:
+ sample = self.act(sample)
+
+ sample = self.linear_2(sample)
+
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+
+class Timesteps(nn.Module):
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float, scale: int = 1):
+ super().__init__()
+ self.num_channels = num_channels
+ self.flip_sin_to_cos = flip_sin_to_cos
+ self.downscale_freq_shift = downscale_freq_shift
+ self.scale = scale
+
+ def forward(self, timesteps):
+ t_emb = get_timestep_embedding(
+ timesteps,
+ self.num_channels,
+ flip_sin_to_cos=self.flip_sin_to_cos,
+ downscale_freq_shift=self.downscale_freq_shift,
+ scale=self.scale,
+ )
+ return t_emb
+
+class MochiAttentionPool(nn.Module):
+ def __init__(
+ self,
+ num_attention_heads: int,
+ embed_dim: int,
+ output_dim: Optional[int] = None,
+ ) -> None:
+ super().__init__()
+
+ self.output_dim = output_dim or embed_dim
+ self.num_attention_heads = num_attention_heads
+
+ self.to_kv = nn.Linear(embed_dim, 2 * embed_dim)
+ self.to_q = nn.Linear(embed_dim, embed_dim)
+ self.to_out = nn.Linear(embed_dim, self.output_dim)
+
+ @staticmethod
+ def pool_tokens(x: torch.Tensor, mask: torch.Tensor, *, keepdim=False) -> torch.Tensor:
+ """
+ Pool tokens in x using mask.
+
+ NOTE: We assume x does not require gradients.
+
+ Args:
+ x: (B, L, D) tensor of tokens.
+ mask: (B, L) boolean tensor indicating which tokens are not padding.
+
+ Returns:
+ pooled: (B, D) tensor of pooled tokens.
+ """
+ assert x.size(1) == mask.size(1) # Expected mask to have same length as tokens.
+ assert x.size(0) == mask.size(0) # Expected mask to have same batch size as tokens.
+ mask = mask[:, :, None].to(dtype=x.dtype)
+ mask = mask / mask.sum(dim=1, keepdim=True).clamp(min=1)
+ pooled = (x * mask).sum(dim=1, keepdim=keepdim)
+ return pooled
+
+ def forward(self, x: torch.Tensor, mask: torch.BoolTensor) -> torch.Tensor:
+ r"""
+ Args:
+ x (`torch.Tensor`):
+ Tensor of shape `(B, S, D)` of input tokens.
+ mask (`torch.Tensor`):
+ Boolean ensor of shape `(B, S)` indicating which tokens are not padding.
+
+ Returns:
+ `torch.Tensor`:
+ `(B, D)` tensor of pooled tokens.
+ """
+ D = x.size(2)
+
+ # Construct attention mask, shape: (B, 1, num_queries=1, num_keys=1+L).
+ attn_mask = mask[:, None, None, :].bool() # (B, 1, 1, L).
+ attn_mask = F.pad(attn_mask, (1, 0), value=True) # (B, 1, 1, 1+L).
+
+ # Average non-padding token features. These will be used as the query.
+ x_pool = self.pool_tokens(x, mask, keepdim=True) # (B, 1, D)
+
+ # Concat pooled features to input sequence.
+ x = torch.cat([x_pool, x], dim=1) # (B, L+1, D)
+
+ # Compute queries, keys, values. Only the mean token is used to create a query.
+ kv = self.to_kv(x) # (B, L+1, 2 * D)
+ q = self.to_q(x[:, 0]) # (B, D)
+
+ # Extract heads.
+ head_dim = D // self.num_attention_heads
+ kv = kv.unflatten(2, (2, self.num_attention_heads, head_dim)) # (B, 1+L, 2, H, head_dim)
+ kv = kv.transpose(1, 3) # (B, H, 2, 1+L, head_dim)
+ k, v = kv.unbind(2) # (B, H, 1+L, head_dim)
+ q = q.unflatten(1, (self.num_attention_heads, head_dim)) # (B, H, head_dim)
+ q = q.unsqueeze(2) # (B, H, 1, head_dim)
+
+ # Compute attention.
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0) # (B, H, 1, head_dim)
+
+ # Concatenate heads and run output.
+ x = x.squeeze(2).flatten(1, 2) # (B, D = H * head_dim)
+ x = self.to_out(x)
+ return x
+
+class CombinedTimestepGuidanceTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, guidance, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ guidance_proj = self.time_proj(guidance)
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ time_guidance_emb = timesteps_emb + guidance_emb
+
+ pooled_projections = self.text_embedder(pooled_projection)
+ conditioning = time_guidance_emb + pooled_projections
+
+ return conditioning
+
+class PixArtAlphaTextProjection(nn.Module):
+ """
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
+
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
+ """
+
+ def __init__(self, in_features, hidden_size, out_features=None, act_fn="gelu_tanh"):
+ super().__init__()
+ if out_features is None:
+ out_features = hidden_size
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
+ if act_fn == "gelu_tanh":
+ self.act_1 = nn.GELU(approximate="tanh")
+ elif act_fn == "silu":
+ self.act_1 = nn.SiLU()
+ elif act_fn == "silu_fp32":
+ self.act_1 = FP32SiLU()
+ else:
+ raise ValueError(f"Unknown activation function: {act_fn}")
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=out_features, bias=True)
+
+ def forward(self, caption):
+ hidden_states = self.linear_1(caption)
+ hidden_states = self.act_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+class CombinedTimestepTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ pooled_projections = self.text_embedder(pooled_projection)
+
+ conditioning = timesteps_emb + pooled_projections
+
+ return conditioning
+
+class FluxPosEmbed(nn.Module):
+ # modified from https://github.com/black-forest-labs/flux/blob/c00d7c60b085fce8058b9df845e036090873f2ce/src/flux/modules/layers.py#L11
+ def __init__(self, theta: int, axes_dim: List[int]):
+ super().__init__()
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
+ n_axes = ids.shape[-1]
+ cos_out = []
+ sin_out = []
+ pos = ids.float()
+ is_mps = ids.device.type == "mps"
+ freqs_dtype = torch.float32 if is_mps else torch.float64
+ for i in range(n_axes):
+ cos, sin = get_1d_rotary_pos_embed(
+ self.axes_dim[i], pos[:, i], repeat_interleave_real=True, use_real=True, freqs_dtype=freqs_dtype
+ )
+ cos_out.append(cos)
+ sin_out.append(sin)
+ freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
+ freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
+ return freqs_cos, freqs_sin
+
+class CombinedTimestepLabelEmbeddings(nn.Module):
+ def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.class_embedder = LabelEmbedding(num_classes, embedding_dim, class_dropout_prob)
+
+ def forward(self, timestep, class_labels, hidden_dtype=None):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
+
+ class_labels = self.class_embedder(class_labels) # (N, D)
+
+ conditioning = timesteps_emb + class_labels # (N, D)
+
+ return conditioning
+
+class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):
+ """
+ For PixArt-Alpha.
+
+ Reference:
+ https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
+ """
+
+ def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
+ super().__init__()
+
+ self.outdim = size_emb_dim
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+
+ self.use_additional_conditions = use_additional_conditions
+ if use_additional_conditions:
+ self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
+ self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
+
+ def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
+
+ if self.use_additional_conditions:
+ resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
+ resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
+ aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
+ aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
+ conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
+ else:
+ conditioning = timesteps_emb
+
+ return conditioning
+
+def get_3d_rotary_pos_embed(
+ embed_dim,
+ crops_coords,
+ grid_size,
+ temporal_size,
+ theta: int = 10000,
+ use_real: bool = True,
+ grid_type: str = "linspace",
+ max_size: Optional[Tuple[int, int]] = None,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ """
+ RoPE for video tokens with 3D structure.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size, corresponding to hidden_size_head.
+ crops_coords (`Tuple[int]`):
+ The top-left and bottom-right coordinates of the crop.
+ grid_size (`Tuple[int]`):
+ The grid size of the spatial positional embedding (height, width).
+ temporal_size (`int`):
+ The size of the temporal dimension.
+ theta (`float`):
+ Scaling factor for frequency computation.
+ grid_type (`str`):
+ Whether to use "linspace" or "slice" to compute grids.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `(temporal_size * grid_size[0] * grid_size[1], embed_dim/2)`.
+ """
+ if use_real is not True:
+ raise ValueError(" `use_real = False` is not currently supported for get_3d_rotary_pos_embed")
+ if grid_type == "linspace": #应该是grid_size是token的数量,也就是分辨率;然后crops_coords是2D坐标的取值范围
+ start, stop = crops_coords
+ grid_size_h, grid_size_w = grid_size
+ grid_h = np.linspace(start[0], stop[0], grid_size_h, endpoint=False, dtype=np.float32)
+ grid_w = np.linspace(start[1], stop[1], grid_size_w, endpoint=False, dtype=np.float32)
+ grid_t = np.arange(temporal_size, dtype=np.float32)
+ grid_t = np.linspace(0, temporal_size, temporal_size, endpoint=False, dtype=np.float32)
+ elif grid_type == "slice":
+ max_h, max_w = max_size
+ grid_size_h, grid_size_w = grid_size
+ grid_h = np.arange(max_h, dtype=np.float32) #这里就是直接从中crop一个区域下来了
+ grid_w = np.arange(max_w, dtype=np.float32)
+ grid_t = np.arange(temporal_size, dtype=np.float32)
+ else:
+ raise ValueError("Invalid value passed for `grid_type`.")
+
+ # Compute dimensions for each axis
+ dim_t = embed_dim // 4
+ dim_h = embed_dim // 8 * 3
+ dim_w = embed_dim // 8 * 3
+
+ # Temporal frequencies
+ freqs_t = get_1d_rotary_pos_embed(dim_t, grid_t, use_real=True)
+ # Spatial frequencies for height and width
+ freqs_h = get_1d_rotary_pos_embed(dim_h, grid_h, use_real=True)
+ freqs_w = get_1d_rotary_pos_embed(dim_w, grid_w, use_real=True)
+
+ # BroadCast and concatenate temporal and spaial frequencie (height and width) into a 3d tensor
+ def combine_time_height_width(freqs_t, freqs_h, freqs_w):
+ freqs_t = freqs_t[:, None, None, :].expand(
+ -1, grid_size_h, grid_size_w, -1
+ ) # temporal_size, grid_size_h, grid_size_w, dim_t
+ freqs_h = freqs_h[None, :, None, :].expand(
+ temporal_size, -1, grid_size_w, -1
+ ) # temporal_size, grid_size_h, grid_size_2, dim_h
+ freqs_w = freqs_w[None, None, :, :].expand(
+ temporal_size, grid_size_h, -1, -1
+ ) # temporal_size, grid_size_h, grid_size_2, dim_w
+
+ freqs = torch.cat(
+ [freqs_t, freqs_h, freqs_w], dim=-1
+ ) # temporal_size, grid_size_h, grid_size_w, (dim_t + dim_h + dim_w)
+ freqs = freqs.view(
+ temporal_size * grid_size_h * grid_size_w, -1
+ ) # (temporal_size * grid_size_h * grid_size_w), (dim_t + dim_h + dim_w)
+ return freqs
+
+ t_cos, t_sin = freqs_t # both t_cos and t_sin has shape: temporal_size, dim_t
+ h_cos, h_sin = freqs_h # both h_cos and h_sin has shape: grid_size_h, dim_h
+ w_cos, w_sin = freqs_w # both w_cos and w_sin has shape: grid_size_w, dim_w
+
+ if grid_type == "slice":
+ t_cos, t_sin = t_cos[:temporal_size], t_sin[:temporal_size]
+ h_cos, h_sin = h_cos[:grid_size_h], h_sin[:grid_size_h]
+ w_cos, w_sin = w_cos[:grid_size_w], w_sin[:grid_size_w]
+
+ cos = combine_time_height_width(t_cos, h_cos, w_cos)
+ sin = combine_time_height_width(t_sin, h_sin, w_sin)
+ return cos, sin
+
+def get_1d_rotary_pos_embed(
+ dim: int,
+ pos: Union[np.ndarray, int],
+ theta: float = 10000.0,
+ use_real=False,
+ linear_factor=1.0,
+ ntk_factor=1.0,
+ repeat_interleave_real=True,
+ freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
+):
+ """
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
+
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim' and the end
+ index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64
+ data type.
+
+ Args:
+ dim (`int`): Dimension of the frequency tensor.
+ pos (`np.ndarray` or `int`): Position indices for the frequency tensor. [S] or scalar
+ theta (`float`, *optional*, defaults to 10000.0):
+ Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (`bool`, *optional*):
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+ linear_factor (`float`, *optional*, defaults to 1.0):
+ Scaling factor for the context extrapolation. Defaults to 1.0.
+ ntk_factor (`float`, *optional*, defaults to 1.0):
+ Scaling factor for the NTK-Aware RoPE. Defaults to 1.0.
+ repeat_interleave_real (`bool`, *optional*, defaults to `True`):
+ If `True` and `use_real`, real part and imaginary part are each interleaved with themselves to reach `dim`.
+ Otherwise, they are concateanted with themselves.
+ freqs_dtype (`torch.float32` or `torch.float64`, *optional*, defaults to `torch.float32`):
+ the dtype of the frequency tensor.
+ Returns:
+ `torch.Tensor`: Precomputed frequency tensor with complex exponentials. [S, D/2]
+ """
+ assert dim % 2 == 0
+
+ if isinstance(pos, int):
+ pos = torch.arange(pos)
+ if isinstance(pos, np.ndarray):
+ pos = torch.from_numpy(pos) # type: ignore # [S]
+
+ theta = theta * ntk_factor
+ freqs = (
+ 1.0
+ / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[: (dim // 2)] / dim))
+ / linear_factor
+ ) # [D/2]
+ freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
+ if use_real and repeat_interleave_real:
+ # flux, hunyuan-dit, cogvideox
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
+ return freqs_cos, freqs_sin
+ elif use_real:
+ # stable audio, allegro
+ freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float() # [S, D]
+ freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float() # [S, D]
+ return freqs_cos, freqs_sin
+ else:
+ # lumina
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
+ return freqs_cis
+
+def apply_rotary_emb(
+ x: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
+ use_real: bool = True,
+ use_real_unbind_dim: int = -1,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
+ to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
+ reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
+ tensors contain rotary embeddings and are returned as real tensors.
+
+ Args:
+ x (`torch.Tensor`):
+ Query or key tensor to apply rotary embeddings. [B, H, S, D] xk (torch.Tensor): Key tensor to apply
+ freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+ """
+ if use_real:
+ cos, sin = freqs_cis # [S, D]
+ cos = cos[None, None]
+ sin = sin[None, None]
+ cos, sin = cos.to(x.device), sin.to(x.device)
+
+ if use_real_unbind_dim == -1:
+ # Used for flux, cogvideox, hunyuan-dit
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
+ elif use_real_unbind_dim == -2:
+ # Used for Stable Audio
+ x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, S, H, D//2]
+ x_rotated = torch.cat([-x_imag, x_real], dim=-1)
+ else:
+ raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
+
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
+
+ return out
+ else:
+ # used for lumina
+ x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
+ freqs_cis = freqs_cis.unsqueeze(2)
+ x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
+
+ return x_out.type_as(x)
+
+def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
+ """
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
+ """
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
+
+ emb_sin = np.sin(out) # (M, D/2)
+ emb_cos = np.cos(out) # (M, D/2)
+
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
+ return emb
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/__init__.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ebe2c3ed5ceb92a380f17d8a91aa2fa08798c50
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/__init__.py
@@ -0,0 +1,26 @@
+from .models import HYVideoDiffusionTransformer, HUNYUAN_VIDEO_CONFIG
+
+
+def load_model(args, in_channels, out_channels, factor_kwargs):
+ """load hunyuan video model
+
+ Args:
+ args (dict): model args
+ in_channels (int): input channels number
+ out_channels (int): output channels number
+ factor_kwargs (dict): factor kwargs
+
+ Returns:
+ model (nn.Module): The hunyuan video model
+ """
+ if args.model in HUNYUAN_VIDEO_CONFIG.keys():
+ model = HYVideoDiffusionTransformer(
+ args,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ **HUNYUAN_VIDEO_CONFIG[args.model],
+ **factor_kwargs,
+ )
+ return model
+ else:
+ raise NotImplementedError()
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/activation_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/activation_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8774c26ceef6081482ca0dbbf930b207d4ac03b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/activation_layers.py
@@ -0,0 +1,23 @@
+import torch.nn as nn
+
+
+def get_activation_layer(act_type):
+ """get activation layer
+
+ Args:
+ act_type (str): the activation type
+
+ Returns:
+ torch.nn.functional: the activation layer
+ """
+ if act_type == "gelu":
+ return lambda: nn.GELU()
+ elif act_type == "gelu_tanh":
+ # Approximate `tanh` requires torch >= 1.13
+ return lambda: nn.GELU(approximate="tanh")
+ elif act_type == "relu":
+ return nn.ReLU
+ elif act_type == "silu":
+ return nn.SiLU
+ else:
+ raise ValueError(f"Unknown activation type: {act_type}")
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/attenion.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/attenion.py
new file mode 100644
index 0000000000000000000000000000000000000000..44548793709ce8595e8635938f5edddcf6b328a7
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/attenion.py
@@ -0,0 +1,212 @@
+import importlib.metadata
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+try:
+ import flash_attn
+ from flash_attn.flash_attn_interface import _flash_attn_forward
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func
+except ImportError:
+ flash_attn = None
+ flash_attn_varlen_func = None
+ _flash_attn_forward = None
+
+
+MEMORY_LAYOUT = {
+ "flash": (
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
+ lambda x: x,
+ ),
+ "torch": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+ "vanilla": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+}
+
+
+def get_cu_seqlens(text_mask, img_len):
+ """Calculate cu_seqlens_q, cu_seqlens_kv using text_mask and img_len
+
+ Args:
+ text_mask (torch.Tensor): the mask of text
+ img_len (int): the length of image
+
+ Returns:
+ torch.Tensor: the calculated cu_seqlens for flash attention
+ """
+ batch_size = text_mask.shape[0]
+ text_len = text_mask.sum(dim=1)
+ max_len = text_mask.shape[1] + img_len
+
+ cu_seqlens = torch.zeros([2 * batch_size + 1], dtype=torch.int32, device="cuda")
+
+ for i in range(batch_size):
+ s = text_len[i] + img_len
+ s1 = i * max_len + s
+ s2 = (i + 1) * max_len
+ cu_seqlens[2 * i + 1] = s1
+ cu_seqlens[2 * i + 2] = s2
+
+ return cu_seqlens
+
+
+def attention(
+ q,
+ k,
+ v,
+ mode="flash",
+ drop_rate=0,
+ attn_mask=None,
+ causal=False,
+ cu_seqlens_q=None,
+ cu_seqlens_kv=None,
+ max_seqlen_q=None,
+ max_seqlen_kv=None,
+ batch_size=1,
+):
+ """
+ Perform QKV self attention.
+
+ Args:
+ q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads.
+ k (torch.Tensor): Key tensor with shape [b, s1, a, d]
+ v (torch.Tensor): Value tensor with shape [b, s1, a, d]
+ mode (str): Attention mode. Choose from 'self_flash', 'cross_flash', 'torch', and 'vanilla'.
+ drop_rate (float): Dropout rate in attention map. (default: 0)
+ attn_mask (torch.Tensor): Attention mask with shape [b, s1] (cross_attn), or [b, a, s, s1] (torch or vanilla).
+ (default: None)
+ causal (bool): Whether to use causal attention. (default: False)
+ cu_seqlens_q (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into q.
+ cu_seqlens_kv (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into kv.
+ max_seqlen_q (int): The maximum sequence length in the batch of q.
+ max_seqlen_kv (int): The maximum sequence length in the batch of k and v.
+
+ Returns:
+ torch.Tensor: Output tensor after self attention with shape [b, s, ad]
+ """
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
+ q = pre_attn_layout(q)
+ k = pre_attn_layout(k)
+ v = pre_attn_layout(v)
+
+ if mode == "torch":
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
+ attn_mask = attn_mask.to(q.dtype)
+ x = F.scaled_dot_product_attention(
+ q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal
+ )
+ elif mode == "flash":
+ x = flash_attn_varlen_func(
+ q,
+ k,
+ v,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ )
+ # x with shape [(bxs), a, d]
+ x = x.view(
+ batch_size, max_seqlen_q, x.shape[-2], x.shape[-1]
+ ) # reshape x to [b, s, a, d]
+ elif mode == "vanilla":
+ scale_factor = 1 / math.sqrt(q.size(-1))
+
+ b, a, s, _ = q.shape
+ s1 = k.size(2)
+ attn_bias = torch.zeros(b, a, s, s1, dtype=q.dtype, device=q.device)
+ if causal:
+ # Only applied to self attention
+ assert (
+ attn_mask is None
+ ), "Causal mask and attn_mask cannot be used together"
+ temp_mask = torch.ones(b, a, s, s, dtype=torch.bool, device=q.device).tril(
+ diagonal=0
+ )
+ attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
+ attn_bias.to(q.dtype)
+
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
+ else:
+ attn_bias += attn_mask
+
+ # TODO: Maybe force q and k to be float32 to avoid numerical overflow
+ attn = (q @ k.transpose(-2, -1)) * scale_factor
+ attn += attn_bias
+ attn = attn.softmax(dim=-1)
+ attn = torch.dropout(attn, p=drop_rate, train=True)
+ x = attn @ v
+ else:
+ raise NotImplementedError(f"Unsupported attention mode: {mode}")
+
+ x = post_attn_layout(x)
+ b, s, a, d = x.shape
+ out = x.reshape(b, s, -1)
+ return out
+
+
+def parallel_attention(
+ hybrid_seq_parallel_attn,
+ q,
+ k,
+ v,
+ img_q_len,
+ img_kv_len,
+ cu_seqlens_q,
+ cu_seqlens_kv
+):
+ attn1 = hybrid_seq_parallel_attn(
+ None,
+ q[:, :img_q_len, :, :],
+ k[:, :img_kv_len, :, :],
+ v[:, :img_kv_len, :, :],
+ dropout_p=0.0,
+ causal=False,
+ joint_tensor_query=q[:,img_q_len:cu_seqlens_q[1]],
+ joint_tensor_key=k[:,img_kv_len:cu_seqlens_kv[1]],
+ joint_tensor_value=v[:,img_kv_len:cu_seqlens_kv[1]],
+ joint_strategy="rear",
+ )
+ if flash_attn.__version__ >= '2.7.0':
+ attn2, *_ = _flash_attn_forward(
+ q[:,cu_seqlens_q[1]:],
+ k[:,cu_seqlens_kv[1]:],
+ v[:,cu_seqlens_kv[1]:],
+ dropout_p=0.0,
+ softmax_scale=q.shape[-1] ** (-0.5),
+ causal=False,
+ window_size_left=-1,
+ window_size_right=-1,
+ softcap=0.0,
+ alibi_slopes=None,
+ return_softmax=False,
+ )
+ else:
+ attn2, *_ = _flash_attn_forward(
+ q[:,cu_seqlens_q[1]:],
+ k[:,cu_seqlens_kv[1]:],
+ v[:,cu_seqlens_kv[1]:],
+ dropout_p=0.0,
+ softmax_scale=q.shape[-1] ** (-0.5),
+ causal=False,
+ window_size=(-1, -1),
+ softcap=0.0,
+ alibi_slopes=None,
+ return_softmax=False,
+ )
+ attn = torch.cat([attn1, attn2], dim=1)
+ b, s, a, d = attn.shape
+ attn = attn.reshape(b, s, -1)
+
+ return attn
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/embed_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/embed_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..50939f9e32cfbcf8597e0daf55988840aafb1d9a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/embed_layers.py
@@ -0,0 +1,157 @@
+import math
+import torch
+import torch.nn as nn
+from einops import rearrange, repeat
+
+from .utils import to_2tuple
+
+
+class PatchEmbed(nn.Module):
+ """2D Image to Patch Embedding
+
+ Image to Patch Embedding using Conv2d
+
+ A convolution based approach to patchifying a 2D image w/ embedding projection.
+
+ Based on the impl in https://github.com/google-research/vision_transformer
+
+ Hacked together by / Copyright 2020 Ross Wightman
+
+ Remove the _assert function in forward function to be compatible with multi-resolution images.
+ """
+
+ def __init__(
+ self,
+ patch_size=16,
+ in_chans=3,
+ embed_dim=768,
+ norm_layer=None,
+ flatten=True,
+ bias=True,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ patch_size = to_2tuple(patch_size)
+ self.patch_size = patch_size
+ self.flatten = flatten
+
+ self.proj = nn.Conv3d(
+ in_chans,
+ embed_dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ bias=bias,
+ **factory_kwargs
+ )
+ nn.init.xavier_uniform_(self.proj.weight.view(self.proj.weight.size(0), -1))
+ if bias:
+ nn.init.zeros_(self.proj.bias)
+
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
+
+ def forward(self, x):
+ x = self.proj(x)
+ if self.flatten:
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
+ x = self.norm(x)
+ return x
+
+
+class TextProjection(nn.Module):
+ """
+ Projects text embeddings. Also handles dropout for classifier-free guidance.
+
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
+ """
+
+ def __init__(self, in_channels, hidden_size, act_layer, dtype=None, device=None):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.linear_1 = nn.Linear(
+ in_features=in_channels,
+ out_features=hidden_size,
+ bias=True,
+ **factory_kwargs
+ )
+ self.act_1 = act_layer()
+ self.linear_2 = nn.Linear(
+ in_features=hidden_size,
+ out_features=hidden_size,
+ bias=True,
+ **factory_kwargs
+ )
+
+ def forward(self, caption):
+ hidden_states = self.linear_1(caption)
+ hidden_states = self.act_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+def timestep_embedding(t, dim, max_period=10000):
+ """
+ Create sinusoidal timestep embeddings.
+
+ Args:
+ t (torch.Tensor): a 1-D Tensor of N indices, one per batch element. These may be fractional.
+ dim (int): the dimension of the output.
+ max_period (int): controls the minimum frequency of the embeddings.
+
+ Returns:
+ embedding (torch.Tensor): An (N, D) Tensor of positional embeddings.
+
+ .. ref_link: https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
+ """
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period)
+ * torch.arange(start=0, end=half, dtype=torch.float32)
+ / half
+ ).to(device=t.device)
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+
+class TimestepEmbedder(nn.Module):
+ """
+ Embeds scalar timesteps into vector representations.
+ """
+
+ def __init__(
+ self,
+ hidden_size,
+ act_layer,
+ frequency_embedding_size=256,
+ max_period=10000,
+ out_size=None,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.frequency_embedding_size = frequency_embedding_size
+ self.max_period = max_period
+ if out_size is None:
+ out_size = hidden_size
+
+ self.mlp = nn.Sequential(
+ nn.Linear(
+ frequency_embedding_size, hidden_size, bias=True, **factory_kwargs
+ ),
+ act_layer(),
+ nn.Linear(hidden_size, out_size, bias=True, **factory_kwargs),
+ )
+ nn.init.normal_(self.mlp[0].weight, std=0.02)
+ nn.init.normal_(self.mlp[2].weight, std=0.02)
+
+ def forward(self, t):
+ t_freq = timestep_embedding(
+ t, self.frequency_embedding_size, self.max_period
+ ).type(self.mlp[0].weight.dtype)
+ t_emb = self.mlp(t_freq)
+ return t_emb
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/fp8_optimization.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/fp8_optimization.py
new file mode 100644
index 0000000000000000000000000000000000000000..b95c1f49bf78bda824b616ec7130eb8ff03ed09c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/fp8_optimization.py
@@ -0,0 +1,102 @@
+import os
+
+import torch
+import torch.nn as nn
+from torch.nn import functional as F
+
+def get_fp_maxval(bits=8, mantissa_bit=3, sign_bits=1):
+ _bits = torch.tensor(bits)
+ _mantissa_bit = torch.tensor(mantissa_bit)
+ _sign_bits = torch.tensor(sign_bits)
+ M = torch.clamp(torch.round(_mantissa_bit), 1, _bits - _sign_bits)
+ E = _bits - _sign_bits - M
+ bias = 2 ** (E - 1) - 1
+ mantissa = 1
+ for i in range(mantissa_bit - 1):
+ mantissa += 1 / (2 ** (i+1))
+ maxval = mantissa * 2 ** (2**E - 1 - bias)
+ return maxval
+
+def quantize_to_fp8(x, bits=8, mantissa_bit=3, sign_bits=1):
+ """
+ Default is E4M3.
+ """
+ bits = torch.tensor(bits)
+ mantissa_bit = torch.tensor(mantissa_bit)
+ sign_bits = torch.tensor(sign_bits)
+ M = torch.clamp(torch.round(mantissa_bit), 1, bits - sign_bits)
+ E = bits - sign_bits - M
+ bias = 2 ** (E - 1) - 1
+ mantissa = 1
+ for i in range(mantissa_bit - 1):
+ mantissa += 1 / (2 ** (i+1))
+ maxval = mantissa * 2 ** (2**E - 1 - bias)
+ minval = - maxval
+ minval = - maxval if sign_bits == 1 else torch.zeros_like(maxval)
+ input_clamp = torch.min(torch.max(x, minval), maxval)
+ log_scales = torch.clamp((torch.floor(torch.log2(torch.abs(input_clamp)) + bias)).detach(), 1.0)
+ log_scales = 2.0 ** (log_scales - M - bias.type(x.dtype))
+ # dequant
+ qdq_out = torch.round(input_clamp / log_scales) * log_scales
+ return qdq_out, log_scales
+
+def fp8_tensor_quant(x, scale, bits=8, mantissa_bit=3, sign_bits=1):
+ for i in range(len(x.shape) - 1):
+ scale = scale.unsqueeze(-1)
+ new_x = x / scale
+ quant_dequant_x, log_scales = quantize_to_fp8(new_x, bits=bits, mantissa_bit=mantissa_bit, sign_bits=sign_bits)
+ return quant_dequant_x, scale, log_scales
+
+def fp8_activation_dequant(qdq_out, scale, dtype):
+ qdq_out = qdq_out.type(dtype)
+ quant_dequant_x = qdq_out * scale.to(dtype)
+ return quant_dequant_x
+
+def fp8_linear_forward(cls, original_dtype, input):
+ weight_dtype = cls.weight.dtype
+ #####
+ if cls.weight.dtype != torch.float8_e4m3fn:
+ maxval = get_fp_maxval()
+ scale = torch.max(torch.abs(cls.weight.flatten())) / maxval
+ linear_weight, scale, log_scales = fp8_tensor_quant(cls.weight, scale)
+ linear_weight = linear_weight.to(torch.float8_e4m3fn)
+ weight_dtype = linear_weight.dtype
+ else:
+ scale = cls.fp8_scale.to(cls.weight.device)
+ linear_weight = cls.weight
+ #####
+
+ if weight_dtype == torch.float8_e4m3fn and cls.weight.sum() != 0:
+ if True or len(input.shape) == 3:
+ cls_dequant = fp8_activation_dequant(linear_weight, scale, original_dtype)
+ if cls.bias != None:
+ output = F.linear(input, cls_dequant, cls.bias)
+ else:
+ output = F.linear(input, cls_dequant)
+ return output
+ else:
+ return cls.original_forward(input.to(original_dtype))
+ else:
+ return cls.original_forward(input)
+
+def convert_fp8_linear(module, dit_weight_path, original_dtype, params_to_keep={}):
+ setattr(module, "fp8_matmul_enabled", True)
+
+ # loading fp8 mapping file
+ fp8_map_path = dit_weight_path.replace('.pt', '_map.pt')
+ if os.path.exists(fp8_map_path):
+ fp8_map = torch.load(fp8_map_path, map_location=lambda storage, loc: storage)
+ else:
+ raise ValueError(f"Invalid fp8_map path: {fp8_map_path}.")
+
+ fp8_layers = []
+ for key, layer in module.named_modules():
+ if isinstance(layer, nn.Linear) and ('double_blocks' in key or 'single_blocks' in key):
+ fp8_layers.append(key)
+ original_forward = layer.forward
+ layer.weight = torch.nn.Parameter(layer.weight.to(torch.float8_e4m3fn))
+ setattr(layer, "fp8_scale", fp8_map[key].to(dtype=original_dtype))
+ setattr(layer, "original_forward", original_forward)
+ setattr(layer, "forward", lambda input, m=layer: fp8_linear_forward(m, original_dtype, input))
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/mlp_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/mlp_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..56a91d479ac35e240d405610de89475be9229a2d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/mlp_layers.py
@@ -0,0 +1,118 @@
+# Modified from timm library:
+# https://github.com/huggingface/pytorch-image-models/blob/648aaa41233ba83eb38faf5ba9d415d574823241/timm/layers/mlp.py#L13
+
+from functools import partial
+
+import torch
+import torch.nn as nn
+
+from .modulate_layers import modulate
+from .utils import to_2tuple
+
+
+class MLP(nn.Module):
+ """MLP as used in Vision Transformer, MLP-Mixer and related networks"""
+
+ def __init__(
+ self,
+ in_channels,
+ hidden_channels=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ norm_layer=None,
+ bias=True,
+ drop=0.0,
+ use_conv=False,
+ device=None,
+ dtype=None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ out_features = out_features or in_channels
+ hidden_channels = hidden_channels or in_channels
+ bias = to_2tuple(bias)
+ drop_probs = to_2tuple(drop)
+ linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
+
+ self.fc1 = linear_layer(
+ in_channels, hidden_channels, bias=bias[0], **factory_kwargs
+ )
+ self.act = act_layer()
+ self.drop1 = nn.Dropout(drop_probs[0])
+ self.norm = (
+ norm_layer(hidden_channels, **factory_kwargs)
+ if norm_layer is not None
+ else nn.Identity()
+ )
+ self.fc2 = linear_layer(
+ hidden_channels, out_features, bias=bias[1], **factory_kwargs
+ )
+ self.drop2 = nn.Dropout(drop_probs[1])
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop1(x)
+ x = self.norm(x)
+ x = self.fc2(x)
+ x = self.drop2(x)
+ return x
+
+
+#
+class MLPEmbedder(nn.Module):
+ """copied from https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/layers.py"""
+ def __init__(self, in_dim: int, hidden_dim: int, device=None, dtype=None):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True, **factory_kwargs)
+ self.silu = nn.SiLU()
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True, **factory_kwargs)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.out_layer(self.silu(self.in_layer(x)))
+
+
+class FinalLayer(nn.Module):
+ """The final layer of DiT."""
+
+ def __init__(
+ self, hidden_size, patch_size, out_channels, act_layer, device=None, dtype=None
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ # Just use LayerNorm for the final layer
+ self.norm_final = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ if isinstance(patch_size, int):
+ self.linear = nn.Linear(
+ hidden_size,
+ patch_size * patch_size * out_channels,
+ bias=True,
+ **factory_kwargs
+ )
+ else:
+ self.linear = nn.Linear(
+ hidden_size,
+ patch_size[0] * patch_size[1] * patch_size[2] * out_channels,
+ bias=True,
+ )
+ nn.init.zeros_(self.linear.weight)
+ nn.init.zeros_(self.linear.bias)
+
+ # Here we don't distinguish between the modulate types. Just use the simple one.
+ self.adaLN_modulation = nn.Sequential(
+ act_layer(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
+
+ def forward(self, x, c):
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
+ x = modulate(self.norm_final(x), shift=shift, scale=scale)
+ x = self.linear(x)
+ return x
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/models.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..9da1255022134a7acba69e89512868ab8e4563e3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/models.py
@@ -0,0 +1,958 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+import torch.utils
+import torch.utils.checkpoint
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, parallel_attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate, ckpt_wrapper
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+ self.hybrid_seq_parallel_attn = None
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ condition_type: str = None,
+ token_replace_vec: torch.Tensor = None,
+ frist_frame_token_num: int = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ if condition_type == "token_replace":
+ img_mod1, token_replace_img_mod1 = self.img_mod(vec, condition_type=condition_type, \
+ token_replace_vec=token_replace_vec)
+ (img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate) = img_mod1.chunk(6, dim=-1)
+ (tr_img_mod1_shift,
+ tr_img_mod1_scale,
+ tr_img_mod1_gate,
+ tr_img_mod2_shift,
+ tr_img_mod2_scale,
+ tr_img_mod2_gate) = token_replace_img_mod1.chunk(6, dim=-1)
+ else:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ if condition_type == "token_replace":
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale, condition_type=condition_type,
+ tr_shift=tr_img_mod1_shift, tr_scale=tr_img_mod1_scale,
+ frist_frame_token_num=frist_frame_token_num
+ )
+ else:
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+
+ # attention computation start
+ if not self.hybrid_seq_parallel_attn:
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+ else:
+ attn = parallel_attention(
+ self.hybrid_seq_parallel_attn,
+ q,
+ k,
+ v,
+ img_q_len=img_q.shape[1],
+ img_kv_len=img_k.shape[1],
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv
+ )
+
+ # attention computation end
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ if condition_type == "token_replace":
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate, condition_type=condition_type,
+ tr_gate=tr_img_mod1_gate, frist_frame_token_num=frist_frame_token_num)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale, condition_type=condition_type,
+ tr_shift=tr_img_mod2_shift, tr_scale=tr_img_mod2_scale, frist_frame_token_num=frist_frame_token_num
+ )
+ ),
+ gate=img_mod2_gate, condition_type=condition_type,
+ tr_gate=tr_img_mod2_gate, frist_frame_token_num=frist_frame_token_num
+ )
+ else:
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.hybrid_seq_parallel_attn = None
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ condition_type: str = None,
+ token_replace_vec: torch.Tensor = None,
+ frist_frame_token_num: int = None,
+ ) -> torch.Tensor:
+ if condition_type == "token_replace":
+ mod, tr_mod = self.modulation(vec,
+ condition_type=condition_type,
+ token_replace_vec=token_replace_vec)
+ (mod_shift,
+ mod_scale,
+ mod_gate) = mod.chunk(3, dim=-1)
+ (tr_mod_shift,
+ tr_mod_scale,
+ tr_mod_gate) = tr_mod.chunk(3, dim=-1)
+ else:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ if condition_type == "token_replace":
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale, condition_type=condition_type,
+ tr_shift=tr_mod_shift, tr_scale=tr_mod_scale, frist_frame_token_num=frist_frame_token_num)
+ else:
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+
+ # attention computation start
+ if not self.hybrid_seq_parallel_attn:
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+ else:
+ attn = parallel_attention(
+ self.hybrid_seq_parallel_attn,
+ q,
+ k,
+ v,
+ img_q_len=img_q.shape[1],
+ img_kv_len=img_k.shape[1],
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv
+ )
+ # attention computation end
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+
+ if condition_type == "token_replace":
+ output = x + apply_gate(output, gate=mod_gate, condition_type=condition_type,
+ tr_gate=tr_mod_gate, frist_frame_token_num=frist_frame_token_num)
+ return output
+ else:
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer(ModelMixin, ConfigMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ i2v_condition_type = 'concat',
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.i2v_condition_type = i2v_condition_type
+ self.rope_theta = rope_theta
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+ self.single_stream_block_no_attn_recompute_layers = 0
+ self.double_stream_block_no_attn_recompute_layers = 0
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.Tensor, # Should be in range(0, 1000).
+ encoder_hidden_states: torch.Tensor = None,
+ encoder_attention_mask: torch.Tensor = None, # Now we don't use it.
+ guidance: torch.Tensor = None, # Guidance for modulation, should be cfg_scale x 1000.
+ return_dict: bool = True,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ x = hidden_states
+ t = timestep
+
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ if self.i2v_condition_type == "token_replace":
+ token_replace_t = torch.zeros_like(t)
+ token_replace_vec = self.time_in(token_replace_t)
+ frist_frame_token_num = th * tw
+ else:
+ token_replace_vec = None
+ frist_frame_token_num = None
+
+ # text modulation
+ vec_2 = self.vector_in(text_states_2)
+ vec = vec + vec_2
+
+ if self.i2v_condition_type == "token_replace":
+ token_replace_vec = token_replace_vec + vec_2
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+ # --------------------- Pass through DiT blocks ------------------------
+ for layer_num, block in enumerate(self.double_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing and i >= self.double_stream_block_no_attn_recompute_layers:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ self.i2v_condition_type,
+ token_replace_vec,
+ frist_frame_token_num,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ self.i2v_condition_type,
+ token_replace_vec,
+ frist_frame_token_num,
+ ]
+ img, txt = block(*double_block_args)
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+
+ if len(self.single_blocks) > 0:
+ for i, block in enumerate(self.single_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing and i >= self.single_stream_block_no_attn_recompute_layers:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ self.i2v_condition_type,
+ token_replace_vec,
+ frist_frame_token_num,
+ **ckpt_kwargs,
+ )
+ else:
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ self.i2v_condition_type,
+ token_replace_vec,
+ frist_frame_token_num,
+ ]
+ x = block(*single_block_args)
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ if return_dict:
+ out["x"] = img
+ return out
+ return img
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+ def set_input_tensor(self, input_tensor):
+ pass
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+ "HYVideo-S/2": {
+ "mm_double_blocks_depth": 6,
+ "mm_single_blocks_depth": 12,
+ "rope_dim_list": [12, 42, 42],
+ "hidden_size": 480,
+ "heads_num": 5,
+ "mlp_width_ratio": 4,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/modulate_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/modulate_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..97b29eb0379ec8372bb4848d61e1257dbebee665
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/modulate_layers.py
@@ -0,0 +1,104 @@
+from typing import Callable
+
+import torch
+import torch.nn as nn
+import math
+
+class ModulateDiT(nn.Module):
+ """Modulation layer for DiT."""
+ def __init__(
+ self,
+ hidden_size: int,
+ factor: int,
+ act_layer: Callable,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.act = act_layer()
+ self.linear = nn.Linear(
+ hidden_size, factor * hidden_size, bias=True, **factory_kwargs
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.linear.weight)
+ nn.init.zeros_(self.linear.bias)
+
+ def forward(self, x: torch.Tensor, condition_type=None, token_replace_vec=None) -> torch.Tensor:
+
+ x_out = self.linear(self.act(x))
+
+ if condition_type == "token_replace":
+ x_token_replace_out = self.linear(self.act(token_replace_vec))
+ return x_out, x_token_replace_out
+ else:
+ return x_out
+
+def modulate(x, shift=None, scale=None, condition_type=None,
+ tr_shift=None, tr_scale=None,
+ frist_frame_token_num=None):
+ """modulate by shift and scale
+
+ Args:
+ x (torch.Tensor): input tensor.
+ shift (torch.Tensor, optional): shift tensor. Defaults to None.
+ scale (torch.Tensor, optional): scale tensor. Defaults to None.
+
+ Returns:
+ torch.Tensor: the output tensor after modulate.
+ """
+ if condition_type == "token_replace":
+ x_zero = x[:, :frist_frame_token_num] * (1 + tr_scale.unsqueeze(1)) + tr_shift.unsqueeze(1)
+ x_orig = x[:, frist_frame_token_num:] * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
+ x = torch.concat((x_zero, x_orig), dim=1)
+ return x
+ else:
+ if scale is None and shift is None:
+ return x
+ elif shift is None:
+ return x * (1 + scale.unsqueeze(1))
+ elif scale is None:
+ return x + shift.unsqueeze(1)
+ else:
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
+
+
+def apply_gate(x, gate=None, tanh=False, condition_type=None, tr_gate=None, frist_frame_token_num=None):
+ """AI is creating summary for apply_gate
+
+ Args:
+ x (torch.Tensor): input tensor.
+ gate (torch.Tensor, optional): gate tensor. Defaults to None.
+ tanh (bool, optional): whether to use tanh function. Defaults to False.
+
+ Returns:
+ torch.Tensor: the output tensor after apply gate.
+ """
+ if condition_type == "token_replace":
+ if gate is None:
+ return x
+ if tanh:
+ x_zero = x[:, :frist_frame_token_num] * tr_gate.unsqueeze(1).tanh()
+ x_orig = x[:, frist_frame_token_num:] * gate.unsqueeze(1).tanh()
+ x = torch.concat((x_zero, x_orig), dim=1)
+ return x
+ else:
+ x_zero = x[:, :frist_frame_token_num] * tr_gate.unsqueeze(1)
+ x_orig = x[:, frist_frame_token_num:] * gate.unsqueeze(1)
+ x = torch.concat((x_zero, x_orig), dim=1)
+ return x
+ else:
+ if gate is None:
+ return x
+ if tanh:
+ return x * gate.unsqueeze(1).tanh()
+ else:
+ return x * gate.unsqueeze(1)
+
+
+def ckpt_wrapper(module):
+ def ckpt_forward(*inputs):
+ outputs = module(*inputs)
+ return outputs
+
+ return ckpt_forward
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/norm_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/norm_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c73b1aef6b7b8ca4767c26c4f0bbc0365a122f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/norm_layers.py
@@ -0,0 +1,77 @@
+import torch
+import torch.nn as nn
+
+
+class RMSNorm(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ elementwise_affine=True,
+ eps: float = 1e-6,
+ device=None,
+ dtype=None,
+ ):
+ """
+ Initialize the RMSNorm normalization layer.
+
+ Args:
+ dim (int): The dimension of the input tensor.
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
+
+ Attributes:
+ eps (float): A small value added to the denominator for numerical stability.
+ weight (nn.Parameter): Learnable scaling parameter.
+
+ """
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.eps = eps
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
+
+ def _norm(self, x):
+ """
+ Apply the RMSNorm normalization to the input tensor.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The normalized tensor.
+
+ """
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ """
+ Forward pass through the RMSNorm layer.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The output tensor after applying RMSNorm.
+
+ """
+ output = self._norm(x.float()).type_as(x)
+ if hasattr(self, "weight"):
+ output = output * self.weight
+ return output
+
+
+def get_norm_layer(norm_layer):
+ """
+ Get the normalization layer.
+
+ Args:
+ norm_layer (str): The type of normalization layer.
+
+ Returns:
+ norm_layer (nn.Module): The normalization layer.
+ """
+ if norm_layer == "layer":
+ return nn.LayerNorm
+ elif norm_layer == "rms":
+ return RMSNorm
+ else:
+ raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/posemb_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/posemb_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..dfce82c690540d17a55a51b7997ee7ceb0bdbf44
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/posemb_layers.py
@@ -0,0 +1,310 @@
+import torch
+from typing import Union, Tuple, List
+
+
+def _to_tuple(x, dim=2):
+ if isinstance(x, int):
+ return (x,) * dim
+ elif len(x) == dim:
+ return x
+ else:
+ raise ValueError(f"Expected length {dim} or int, but got {x}")
+
+
+def get_meshgrid_nd(start, *args, dim=2):
+ """
+ Get n-D meshgrid with start, stop and num.
+
+ Args:
+ start (int or tuple): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop,
+ step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. For n-dim, start/stop/num
+ should be int or n-tuple. If n-tuple is provided, the meshgrid will be stacked following the dim order in
+ n-tuples.
+ *args: See above.
+ dim (int): Dimension of the meshgrid. Defaults to 2.
+
+ Returns:
+ grid (np.ndarray): [dim, ...]
+ """
+ if len(args) == 0:
+ # start is grid_size
+ num = _to_tuple(start, dim=dim)
+ start = (0,) * dim
+ stop = num
+ elif len(args) == 1:
+ # start is start, args[0] is stop, step is 1
+ start = _to_tuple(start, dim=dim)
+ stop = _to_tuple(args[0], dim=dim)
+ num = [stop[i] - start[i] for i in range(dim)]
+ elif len(args) == 2:
+ # start is start, args[0] is stop, args[1] is num
+ start = _to_tuple(start, dim=dim) # Left-Top eg: 12,0
+ stop = _to_tuple(args[0], dim=dim) # Right-Bottom eg: 20,32
+ num = _to_tuple(args[1], dim=dim) # Target Size eg: 32,124
+ else:
+ raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
+
+ # PyTorch implement of np.linspace(start[i], stop[i], num[i], endpoint=False)
+ axis_grid = []
+ for i in range(dim):
+ a, b, n = start[i], stop[i], num[i]
+ g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n]
+ axis_grid.append(g)
+ grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D]
+ grid = torch.stack(grid, dim=0) # [dim, W, H, D]
+
+ return grid
+
+
+#################################################################################
+# Rotary Positional Embedding Functions #
+#################################################################################
+# https://github.com/meta-llama/llama/blob/be327c427cc5e89cc1d3ab3d3fec4484df771245/llama/model.py#L80
+
+
+def reshape_for_broadcast(
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
+ x: torch.Tensor,
+ head_first=False,
+):
+ """
+ Reshape frequency tensor for broadcasting it with another tensor.
+
+ This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
+ for the purpose of broadcasting the frequency tensor during element-wise operations.
+
+ Notes:
+ When using FlashMHAModified, head_first should be False.
+ When using Attention, head_first should be True.
+
+ Args:
+ freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Frequency tensor to be reshaped.
+ x (torch.Tensor): Target tensor for broadcasting compatibility.
+ head_first (bool): head dimension first (except batch dim) or not.
+
+ Returns:
+ torch.Tensor: Reshaped frequency tensor.
+
+ Raises:
+ AssertionError: If the frequency tensor doesn't match the expected shape.
+ AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
+ """
+ ndim = x.ndim
+ assert 0 <= 1 < ndim
+
+ if isinstance(freqs_cis, tuple):
+ # freqs_cis: (cos, sin) in real space
+ if head_first:
+ assert freqs_cis[0].shape == (
+ x.shape[-2],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
+ shape = [
+ d if i == ndim - 2 or i == ndim - 1 else 1
+ for i, d in enumerate(x.shape)
+ ]
+ else:
+ assert freqs_cis[0].shape == (
+ x.shape[1],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
+ return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
+ else:
+ # freqs_cis: values in complex space
+ if head_first:
+ assert freqs_cis.shape == (
+ x.shape[-2],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
+ shape = [
+ d if i == ndim - 2 or i == ndim - 1 else 1
+ for i, d in enumerate(x.shape)
+ ]
+ else:
+ assert freqs_cis.shape == (
+ x.shape[1],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
+ return freqs_cis.view(*shape)
+
+
+def rotate_half(x):
+ x_real, x_imag = (
+ x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
+ ) # [B, S, H, D//2]
+ return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
+
+
+def apply_rotary_emb(
+ xq: torch.Tensor,
+ xk: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ head_first: bool = False,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor.
+
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
+ frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
+ returned as real tensors.
+
+ Args:
+ xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D]
+ xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D]
+ freqs_cis (torch.Tensor or tuple): Precomputed frequency tensor for complex exponential.
+ head_first (bool): head dimension first (except batch dim) or not.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+
+ """
+ xk_out = None
+ if isinstance(freqs_cis, tuple):
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
+ # real * cos - imag * sin
+ # imag * cos + real * sin
+ xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq)
+ xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk)
+ else:
+ # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
+ xq_ = torch.view_as_complex(
+ xq.float().reshape(*xq.shape[:-1], -1, 2)
+ ) # [B, S, H, D//2]
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(
+ xq.device
+ ) # [S, D//2] --> [1, S, 1, D//2]
+ # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin)
+ # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real)
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
+ xk_ = torch.view_as_complex(
+ xk.float().reshape(*xk.shape[:-1], -1, 2)
+ ) # [B, S, H, D//2]
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
+
+ return xq_out, xk_out
+
+
+def get_nd_rotary_pos_embed(
+ rope_dim_list,
+ start,
+ *args,
+ theta=10000.0,
+ use_real=False,
+ theta_rescale_factor: Union[float, List[float]] = 1.0,
+ interpolation_factor: Union[float, List[float]] = 1.0,
+):
+ """
+ This is a n-d version of precompute_freqs_cis, which is a RoPE for tokens with n-d structure.
+
+ Args:
+ rope_dim_list (list of int): Dimension of each rope. len(rope_dim_list) should equal to n.
+ sum(rope_dim_list) should equal to head_dim of attention layer.
+ start (int | tuple of int | list of int): If len(args) == 0, start is num; If len(args) == 1, start is start,
+ args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num.
+ *args: See above.
+ theta (float): Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (bool): If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+ Some libraries such as TensorRT does not support complex64 data type. So it is useful to provide a real
+ part and an imaginary part separately.
+ theta_rescale_factor (float): Rescale factor for theta. Defaults to 1.0.
+
+ Returns:
+ pos_embed (torch.Tensor): [HW, D/2]
+ """
+
+ grid = get_meshgrid_nd(
+ start, *args, dim=len(rope_dim_list)
+ ) # [3, W, H, D] / [2, W, H]
+
+ if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float):
+ theta_rescale_factor = [theta_rescale_factor] * len(rope_dim_list)
+ elif isinstance(theta_rescale_factor, list) and len(theta_rescale_factor) == 1:
+ theta_rescale_factor = [theta_rescale_factor[0]] * len(rope_dim_list)
+ assert len(theta_rescale_factor) == len(
+ rope_dim_list
+ ), "len(theta_rescale_factor) should equal to len(rope_dim_list)"
+
+ if isinstance(interpolation_factor, int) or isinstance(interpolation_factor, float):
+ interpolation_factor = [interpolation_factor] * len(rope_dim_list)
+ elif isinstance(interpolation_factor, list) and len(interpolation_factor) == 1:
+ interpolation_factor = [interpolation_factor[0]] * len(rope_dim_list)
+ assert len(interpolation_factor) == len(
+ rope_dim_list
+ ), "len(interpolation_factor) should equal to len(rope_dim_list)"
+
+ # use 1/ndim of dimensions to encode grid_axis
+ embs = []
+ for i in range(len(rope_dim_list)):
+ emb = get_1d_rotary_pos_embed(
+ rope_dim_list[i],
+ grid[i].reshape(-1),
+ theta,
+ use_real=use_real,
+ theta_rescale_factor=theta_rescale_factor[i],
+ interpolation_factor=interpolation_factor[i],
+ ) # 2 x [WHD, rope_dim_list[i]]
+ embs.append(emb)
+
+ if use_real:
+ cos = torch.cat([emb[0] for emb in embs], dim=1) # (WHD, D/2)
+ sin = torch.cat([emb[1] for emb in embs], dim=1) # (WHD, D/2)
+ return cos, sin
+ else:
+ emb = torch.cat(embs, dim=1) # (WHD, D/2)
+ return emb
+
+
+def get_1d_rotary_pos_embed(
+ dim: int,
+ pos: Union[torch.FloatTensor, int],
+ theta: float = 10000.0,
+ use_real: bool = False,
+ theta_rescale_factor: float = 1.0,
+ interpolation_factor: float = 1.0,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ """
+ Precompute the frequency tensor for complex exponential (cis) with given dimensions.
+ (Note: `cis` means `cos + i * sin`, where i is the imaginary unit.)
+
+ This function calculates a frequency tensor with complex exponential using the given dimension 'dim'
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
+ The returned tensor contains complex values in complex64 data type.
+
+ Args:
+ dim (int): Dimension of the frequency tensor.
+ pos (int or torch.FloatTensor): Position indices for the frequency tensor. [S] or scalar
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (bool, optional): If True, return real part and imaginary part separately.
+ Otherwise, return complex numbers.
+ theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0.
+
+ Returns:
+ freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2]
+ freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D]
+ """
+ if isinstance(pos, int):
+ pos = torch.arange(pos).float()
+
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
+ # has some connection to NTK literature
+ if theta_rescale_factor != 1.0:
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
+
+ freqs = 1.0 / (
+ theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
+ ) # [D/2]
+ # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"
+ freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]
+ if use_real:
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
+ return freqs_cos, freqs_sin
+ else:
+ freqs_cis = torch.polar(
+ torch.ones_like(freqs), freqs
+ ) # complex64 # [S, D/2]
+ return freqs_cis
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/token_refiner.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/token_refiner.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf09278e4f792a5e0cb5c2383f317f5bdd302f01
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/token_refiner.py
@@ -0,0 +1,236 @@
+from typing import Optional
+
+from einops import rearrange
+import torch
+import torch.nn as nn
+
+from .activation_layers import get_activation_layer
+from .attenion import attention
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, TextProjection
+from .attenion import attention
+from .mlp_layers import MLP
+from .modulate_layers import modulate, apply_gate
+
+
+class IndividualTokenRefinerBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size,
+ heads_num,
+ mlp_width_ratio: str = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
+ )
+ self.self_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.self_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.self_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.self_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
+ )
+ act_layer = get_activation_layer(act_type)
+ self.mlp = MLP(
+ in_channels=hidden_size,
+ hidden_channels=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=mlp_drop_rate,
+ **factory_kwargs,
+ )
+
+ self.adaLN_modulation = nn.Sequential(
+ act_layer(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ c: torch.Tensor, # timestep_aware_representations + context_aware_representations
+ attn_mask: torch.Tensor = None,
+ ):
+ gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=1)
+
+ norm_x = self.norm1(x)
+ qkv = self.self_attn_qkv(norm_x)
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+ # Apply QK-Norm if needed
+ q = self.self_attn_q_norm(q).to(v)
+ k = self.self_attn_k_norm(k).to(v)
+
+ # Self-Attention
+ attn = attention(q, k, v, mode="torch", attn_mask=attn_mask)
+
+ x = x + apply_gate(self.self_attn_proj(attn), gate_msa)
+
+ # FFN Layer
+ x = x + apply_gate(self.mlp(self.norm2(x)), gate_mlp)
+
+ return x
+
+
+class IndividualTokenRefiner(nn.Module):
+ def __init__(
+ self,
+ hidden_size,
+ heads_num,
+ depth,
+ mlp_width_ratio: float = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.blocks = nn.ModuleList(
+ [
+ IndividualTokenRefinerBlock(
+ hidden_size=hidden_size,
+ heads_num=heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_drop_rate=mlp_drop_rate,
+ act_type=act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(depth)
+ ]
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ c: torch.LongTensor,
+ mask: Optional[torch.Tensor] = None,
+ ):
+ self_attn_mask = None
+ if mask is not None:
+ batch_size = mask.shape[0]
+ seq_len = mask.shape[1]
+ mask = mask.to(x.device)
+ # batch_size x 1 x seq_len x seq_len
+ self_attn_mask_1 = mask.view(batch_size, 1, 1, seq_len).repeat(
+ 1, 1, seq_len, 1
+ )
+ # batch_size x 1 x seq_len x seq_len
+ self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)
+ # batch_size x 1 x seq_len x seq_len, 1 for broadcasting of heads_num
+ self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()
+ # avoids self-attention weight being NaN for padding tokens
+ self_attn_mask[:, :, :, 0] = True
+
+ for block in self.blocks:
+ x = block(x, c, self_attn_mask)
+ return x
+
+
+class SingleTokenRefiner(nn.Module):
+ """
+ A single token refiner block for llm text embedding refine.
+ """
+ def __init__(
+ self,
+ in_channels,
+ hidden_size,
+ heads_num,
+ depth,
+ mlp_width_ratio: float = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ attn_mode: str = "torch",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.attn_mode = attn_mode
+ assert self.attn_mode == "torch", "Only support 'torch' mode for token refiner."
+
+ self.input_embedder = nn.Linear(
+ in_channels, hidden_size, bias=True, **factory_kwargs
+ )
+
+ act_layer = get_activation_layer(act_type)
+ # Build timestep embedding layer
+ self.t_embedder = TimestepEmbedder(hidden_size, act_layer, **factory_kwargs)
+ # Build context embedding layer
+ self.c_embedder = TextProjection(
+ in_channels, hidden_size, act_layer, **factory_kwargs
+ )
+
+ self.individual_token_refiner = IndividualTokenRefiner(
+ hidden_size=hidden_size,
+ heads_num=heads_num,
+ depth=depth,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_drop_rate=mlp_drop_rate,
+ act_type=act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ t: torch.LongTensor,
+ mask: Optional[torch.LongTensor] = None,
+ ):
+ timestep_aware_representations = self.t_embedder(t)
+
+ if mask is None:
+ context_aware_representations = x.mean(dim=1)
+ else:
+ mask_float = mask.float().unsqueeze(-1) # [b, s1, 1]
+ context_aware_representations = (x * mask_float).sum(
+ dim=1
+ ) / mask_float.sum(dim=1)
+ context_aware_representations = self.c_embedder(context_aware_representations)
+ c = timestep_aware_representations + context_aware_representations
+
+ x = self.input_embedder(x)
+
+ x = self.individual_token_refiner(x, c, mask)
+
+ return x
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/utils.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..72ab8cb1feba4ce7782f1ea841fd42c71be7b0d1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_i2v_src/utils.py
@@ -0,0 +1,40 @@
+import collections.abc
+
+from itertools import repeat
+
+
+def _ntuple(n):
+ def parse(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ x = tuple(x)
+ if len(x) == 1:
+ x = tuple(repeat(x[0], n))
+ return x
+ return tuple(repeat(x, n))
+ return parse
+
+
+to_1tuple = _ntuple(1)
+to_2tuple = _ntuple(2)
+to_3tuple = _ntuple(3)
+to_4tuple = _ntuple(4)
+
+
+def as_tuple(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ return tuple(x)
+ if x is None or isinstance(x, (int, float, str)):
+ return (x,)
+ else:
+ raise ValueError(f"Unknown type {type(x)}")
+
+
+def as_list_of_2tuple(x):
+ x = as_tuple(x)
+ if len(x) == 1:
+ x = (x[0], x[0])
+ assert len(x) % 2 == 0, f"Expect even length, got {len(x)}."
+ lst = []
+ for i in range(0, len(x), 2):
+ lst.append((x[i], x[i + 1]))
+ return lst
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/__init__.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..dce032e4c530ddab90add75d7019c51577ff58ac
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/__init__.py
@@ -0,0 +1,31 @@
+from .models import HYVideoDiffusionTransformer, HUNYUAN_VIDEO_CONFIG
+from .controlnet import HYVideoDiffusionTransformerControlNet
+from .models_ref import HYVideoDiffusionTransformerRef
+from .models_end2end import HYVideoDiffusionTransformerEnd2End
+from .models_refextractor import HYVideoDiffusionTransformer_Refextractor
+from .models_reftokenmerge import HYVideoDiffusionTransformer_Tokenmerge
+from .models_refextractor_2d import HYVideoDiffusionTransformer_Refextractor as HYVideoDiffusionTransformer_Refextractor_2D
+from .models_refextractor_2d_split_q import HYVideoDiffusionTransformer_Refextractor as HYVideoDiffusionTransformer_Refextractor_2D_Q
+def load_model(args, in_channels, out_channels, factor_kwargs):
+ """load hunyuan video model
+
+ Args:
+ args (dict): model args
+ in_channels (int): input channels number
+ out_channels (int): output channels number
+ factor_kwargs (dict): factor kwargs
+
+ Returns:
+ model (nn.Module): The hunyuan video model
+ """
+ if args.model in HUNYUAN_VIDEO_CONFIG.keys():
+ model = HYVideoDiffusionTransformer(
+ args,
+ in_channels=in_channels,
+ out_channels=out_channels,
+ **HUNYUAN_VIDEO_CONFIG[args.model],
+ **factor_kwargs,
+ )
+ return model
+ else:
+ raise NotImplementedError()
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/activation_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/activation_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8774c26ceef6081482ca0dbbf930b207d4ac03b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/activation_layers.py
@@ -0,0 +1,23 @@
+import torch.nn as nn
+
+
+def get_activation_layer(act_type):
+ """get activation layer
+
+ Args:
+ act_type (str): the activation type
+
+ Returns:
+ torch.nn.functional: the activation layer
+ """
+ if act_type == "gelu":
+ return lambda: nn.GELU()
+ elif act_type == "gelu_tanh":
+ # Approximate `tanh` requires torch >= 1.13
+ return lambda: nn.GELU(approximate="tanh")
+ elif act_type == "relu":
+ return nn.ReLU
+ elif act_type == "silu":
+ return nn.SiLU
+ else:
+ raise ValueError(f"Unknown activation type: {act_type}")
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/attenion.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/attenion.py
new file mode 100644
index 0000000000000000000000000000000000000000..e17b34d244872cd4a299896ac59cb6aa5b02058b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/attenion.py
@@ -0,0 +1,211 @@
+import importlib.metadata
+import math
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+try:
+ # 优先尝试 FlashAttention 3
+ from flash_attn_interface import flash_attn_varlen_func as flash_attn3_varlen_func
+ flash_attn_backend = "flash-attn-3"
+ print("[INFO] Using FlashAttention 3")
+except ImportError:
+ try:
+ # 回退到 FlashAttention 2
+ from flash_attn.flash_attn_interface import flash_attn_varlen_func as flash_attn2_varlen_func
+ flash_attn_backend = "flash-attn-2"
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ flash_attn_backend = None
+ flash_attn2_varlen_func = None
+ flash_attn3_varlen_func = None
+ print("[WARNING] Neither FlashAttention 2 nor 3 is available!")
+
+MEMORY_LAYOUT = {
+ "flash": (
+ lambda x: x.view(x.shape[0] * x.shape[1], *x.shape[2:]),
+ lambda x: x,
+ ),
+ "torch": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+ "vanilla": (
+ lambda x: x.transpose(1, 2),
+ lambda x: x.transpose(1, 2),
+ ),
+}
+
+
+def get_cu_seqlens(text_mask, img_len):
+ """Calculate cu_seqlens_q, cu_seqlens_kv using text_mask and img_len
+
+ Args:
+ text_mask (torch.Tensor): the mask of text
+ img_len (int): the length of image
+
+ Returns:
+ torch.Tensor: the calculated cu_seqlens for flash attention
+ """
+ batch_size = text_mask.shape[0]
+ text_len = text_mask.sum(dim=1)
+ max_len = text_mask.shape[1] + img_len
+
+ cu_seqlens = torch.zeros([2 * batch_size + 1], dtype=torch.int32, device="cuda")
+
+ for i in range(batch_size):
+ s = text_len[i] + img_len
+ s1 = i * max_len + s
+ s2 = (i + 1) * max_len
+ cu_seqlens[2 * i + 1] = s1
+ cu_seqlens[2 * i + 2] = s2
+
+ return cu_seqlens
+
+def get_cu_seqlens_wotxt(text_mask, img_len):
+ """Calculate cu_seqlens_q, cu_seqlens_kv using text_mask and img_len
+
+ Args:
+ text_mask (torch.Tensor): the mask of text
+ img_len (int): the length of image
+
+ Returns:
+ torch.Tensor: the calculated cu_seqlens for flash attention
+ """
+ batch_size = text_mask.shape[0]
+ text_len = 0
+ max_len = img_len
+
+ cu_seqlens = torch.zeros([2 * batch_size + 1], dtype=torch.int32, device="cuda")
+
+ for i in range(batch_size):
+ s = text_len + img_len
+ s1 = i * max_len + s
+ s2 = (i + 1) * max_len
+ cu_seqlens[2 * i + 1] = s1
+ cu_seqlens[2 * i + 2] = s2
+
+ return cu_seqlens
+
+
+def attention(
+ q,
+ k,
+ v,
+ mode="flash",
+ drop_rate=0,
+ attn_mask=None,
+ causal=False,
+ cu_seqlens_q=None,
+ cu_seqlens_kv=None,
+ max_seqlen_q=None,
+ max_seqlen_kv=None,
+ batch_size=1,
+):
+ """
+ Perform QKV self attention.
+
+ Args:
+ q (torch.Tensor): Query tensor with shape [b, s, a, d], where a is the number of heads.
+ k (torch.Tensor): Key tensor with shape [b, s1, a, d]
+ v (torch.Tensor): Value tensor with shape [b, s1, a, d]
+ mode (str): Attention mode. Choose from 'self_flash', 'cross_flash', 'torch', and 'vanilla'.
+ drop_rate (float): Dropout rate in attention map. (default: 0)
+ attn_mask (torch.Tensor): Attention mask with shape [b, s1] (cross_attn), or [b, a, s, s1] (torch or vanilla).
+ (default: None)
+ causal (bool): Whether to use causal attention. (default: False)
+ cu_seqlens_q (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into q.
+ cu_seqlens_kv (torch.Tensor): dtype torch.int32. The cumulative sequence lengths of the sequences in the batch,
+ used to index into kv.
+ max_seqlen_q (int): The maximum sequence length in the batch of q.
+ max_seqlen_kv (int): The maximum sequence length in the batch of k and v.
+
+ Returns:
+ torch.Tensor: Output tensor after self attention with shape [b, s, ad]
+ """
+ pre_attn_layout, post_attn_layout = MEMORY_LAYOUT[mode]
+ q = pre_attn_layout(q)
+ k = pre_attn_layout(k)
+ v = pre_attn_layout(v)
+
+ if mode == "torch":
+ if attn_mask is not None and attn_mask.dtype != torch.bool:
+ attn_mask = attn_mask.to(q.dtype)
+ x = F.scaled_dot_product_attention(
+ q, k, v, attn_mask=attn_mask, dropout_p=drop_rate, is_causal=causal
+ )
+ elif mode == "flash":
+ if flash_attn_backend == "flash-attn-3":
+ x, _ = flash_attn3_varlen_func(
+ q, k, v,
+ cu_seqlens_q, cu_seqlens_kv,
+ max_seqlen_q, max_seqlen_kv,
+ )
+ elif flash_attn_backend == "flash-attn-2":
+ x = flash_attn2_varlen_func(
+ q, k, v,
+ cu_seqlens_q, cu_seqlens_kv,
+ max_seqlen_q, max_seqlen_kv,
+ )
+ # flash attention3
+ # x, _ = flash_attn_varlen_func(
+ # q,
+ # k,
+ # v,
+ # cu_seqlens_q,
+ # cu_seqlens_kv,
+ # max_seqlen_q,
+ # max_seqlen_kv,
+ # )
+ # flash attention2
+ # x = flash_attn_varlen_func(
+ # q,
+ # k,
+ # v,
+ # cu_seqlens_q,
+ # cu_seqlens_kv,
+ # max_seqlen_q,
+ # max_seqlen_kv,
+ # )
+ # x with shape [(bxs), a, d]
+ x = x.view(
+ batch_size, max_seqlen_q, x.shape[-2], x.shape[-1]
+ ) # reshape x to [b, s, a, d]
+ elif mode == "vanilla":
+ scale_factor = 1 / math.sqrt(q.size(-1))
+
+ b, a, s, _ = q.shape
+ s1 = k.size(2)
+ attn_bias = torch.zeros(b, a, s, s1, dtype=q.dtype, device=q.device)
+ if causal:
+ # Only applied to self attention
+ assert (
+ attn_mask is None
+ ), "Causal mask and attn_mask cannot be used together"
+ temp_mask = torch.ones(b, a, s, s, dtype=torch.bool, device=q.device).tril(
+ diagonal=0
+ )
+ attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
+ attn_bias.to(q.dtype)
+
+ if attn_mask is not None:
+ if attn_mask.dtype == torch.bool:
+ attn_bias.masked_fill_(attn_mask.logical_not(), float("-inf"))
+ else:
+ attn_bias += attn_mask
+
+ # TODO: Maybe force q and k to be float32 to avoid numerical overflow
+ attn = (q @ k.transpose(-2, -1)) * scale_factor
+ attn += attn_bias
+ attn = attn.softmax(dim=-1)
+ attn = torch.dropout(attn, p=drop_rate, train=True)
+ x = attn @ v
+ else:
+ raise NotImplementedError(f"Unsupported attention mode: {mode}")
+
+ x = post_attn_layout(x)
+ b, s, a, d = x.shape
+ out = x.reshape(b, s, -1)
+ return out
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/controlnet.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..92f2056e8f6ef7c6d5cabc1d6cca679164c0c47e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/controlnet.py
@@ -0,0 +1,660 @@
+from dataclasses import dataclass
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from opensora.controlnet_modules.controlnet import ControlNetConditioningEmbedding, zero_module, MiniHunyuanEncoder
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+from .models_refextractor import MMDoubleStreamBlock, MMSingleStreamBlock
+from .models_textfree import MMDoubleStreamBlock as MMDoubleStreamBlockTextFree
+from .models_textfree import MMSingleStreamBlock as MMSingleStreamBlockTextFree
+from .ipablocks import MMDoubleStreamBlockReFuser, MMSingleStreamBlockReFuser
+
+from .utils import ckpt_kwargs
+
+@dataclass
+class ControlNetOutput(BaseOutput):
+ controlnet_block_samples: Tuple[torch.Tensor]
+ controlnet_single_block_samples: Tuple[torch.Tensor]
+
+class HYVideoDiffusionTransformerControlNet(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0, #用默认值
+ conditioning_embedding_channels: int = None,
+ add_ref_img = False,
+ exclude_noise = False,
+ text_free = False,
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.use_refuser = False
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+ self.exclude_noise = exclude_noise
+
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+
+ # zero init emb
+ self.ref_img_in = zero_module(PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )) if add_ref_img else None
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+ self.text_free = text_free
+ if text_free:
+ DoubleStreamBlock = MMDoubleStreamBlockTextFree
+ SingleStreamBlock = MMSingleStreamBlockTextFree
+ else:
+ DoubleStreamBlock = MMDoubleStreamBlock
+ SingleStreamBlock = MMSingleStreamBlock
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ DoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ SingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.double_blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+ self.controlnet_single_blocks = nn.ModuleList([])
+ for _ in range(len(self.single_blocks)):
+ self.controlnet_single_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+ # TODO: refine
+ # 仅限图像condition,直接过原来的block
+ if not exclude_noise:
+ # print("not exclude_noise")
+ if conditioning_embedding_channels is not None: #输入可以用VAE进行压缩,这样不需要这个;当没有用VAE压缩,就需要这里用一个小网络进行额外的压缩
+ # self.input_hint_block = ControlNetConditioningEmbedding(
+ # conditioning_embedding_channels=conditioning_embedding_channels,
+ # block_out_channels=(16, 16, 16, 16)
+ # )
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = conditioning_embedding_channels, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+ self.controlnet_x_embedder = torch.nn.Linear(conditioning_embedding_channels*4, self.hidden_size)
+ else:
+ self.condition_in = zero_module(PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ ))
+ self.input_hint_block = None
+ self.controlnet_x_embedder = zero_module(torch.nn.Linear(self.in_channels, self.hidden_size))
+
+
+ self.gradient_checkpointing = False
+
+
+ def setup_refuser(self, weight_dtype):
+ # only set once
+ if self.text_free:
+ print("text_free has not develop fuser!!!")
+ return
+ if self.use_refuser is True:
+ return
+ from .ipablocks import MMSingleStreamBlockReFuser, MMDoubleStreamBlockReFuser
+ if len(self.double_blocks) > 0:
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ wrapped = MMDoubleStreamBlockReFuser(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ if len(self.single_blocks) > 0:
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ wrapped_sblock = MMSingleStreamBlockReFuser(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ self.use_refuser = True
+
+ def enable_refuser_params_grad(self):
+ if not self.use_refuser:
+ print("[Refuser] Not use Refuser, skip enabling grad.")
+ return
+
+ for block in self.double_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+
+ print("[Refuser] All Refuser params set requires_grad=True.")
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+
+
+ def forward(self,
+ hidden_states,
+ controlnet_cond,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ image_latents = None,
+ ref_block_samples = None,
+ ref_single_block_samples = None,
+ **kwargs, #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ lora_scale = 1.0 #TODO: 作为参数传入
+ # 这个image_latents不要用了,一般都是None
+ image_latents = None
+ assert self.ref_img_in is None or image_latents is not None, "If self.ref_img_in is not None, image_latents must not be None."
+ # 3.11 目前用不到这个!!
+ repeat_t = hidden_states.shape[2]
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x if not self.exclude_noise else controlnet_cond
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # import pdb; pdb.set_trace()
+
+ #TODO: fix
+ if not self.exclude_noise:
+ if self.input_hint_block is not None:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ #注意这里是原始flux模型的patchify方案,和混元的并不一样,为了避免增加更多的参数,这里用这种pixel shuffle的方式进行patchify
+ batch_size, channels, t_pw, height_pw, width_pw = controlnet_cond.shape
+ patch_size_t, patch_size_h, patch_size_w = self.config.patch_size
+ height = height_pw // patch_size_h
+ width = width_pw // patch_size_w
+ t_ = t_pw // patch_size_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels, t_, patch_size_t, height, patch_size_h, width, patch_size_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, height * width * t_, -1)
+
+ img = img + self.controlnet_x_embedder(controlnet_cond)
+ else:
+ img = img + self.condition_in(controlnet_cond)
+
+ # import pdb; pdb.set_trace()
+ if self.ref_img_in:
+ # -3,3
+ image_latents = image_latents.repeat(1, 1, repeat_t, 1, 1)
+ image_latents = self.ref_img_in(image_latents)
+ # -0.7,0.7
+ img = img + image_latents
+
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+ # --------------------- Pass through DiT blocks ------------------------
+ block_samples = ()
+ for index, block in enumerate(self.double_blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ # 注意这里的ref_block_samples一定大于double_blocks
+ interval_ref = len(ref_block_samples) / len(self.double_blocks)
+ ref_latent = ref_block_samples[int(min(index * interval_ref,len(ref_block_samples)-1))]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ]
+
+ img, txt = block(*double_block_args)
+ block_samples = block_samples + (img, ) #NOTE: 这里仅仅处理了image模态数据
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ single_block_samples = ()
+ if len(self.single_blocks) > 0:
+ for index, block in enumerate(self.single_blocks):
+ ref_latent = None
+ if ref_single_block_samples is not None:
+ interval_ref = len(ref_single_block_samples) / len(self.single_blocks)
+ ref_latent = ref_single_block_samples[int(min(index * interval_ref,len(ref_single_block_samples)-1))]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ **ckpt_kwargs,
+ )
+ else:
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ]
+ x = block(*single_block_args)
+
+ single_block_samples = single_block_samples + (x[:, :img.shape[1]], ) #NOTE: 只使用image模态
+
+ controlnet_block_samples = ()
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (block_sample, )
+
+ controlnet_single_block_samples = ()
+ for single_block_sample, controlnet_block in zip(single_block_samples, self.controlnet_single_blocks):
+ single_block_sample = controlnet_block(single_block_sample)
+ controlnet_single_block_samples = controlnet_single_block_samples + (single_block_sample,)
+
+ controlnet_block_samples = [sample * conditioning_scale for sample in controlnet_block_samples]
+ controlnet_single_block_samples = [sample * conditioning_scale for sample in controlnet_single_block_samples]
+ controlnet_block_samples = None if len(controlnet_block_samples) == 0 else controlnet_block_samples
+ controlnet_single_block_samples = (
+ None if len(controlnet_single_block_samples) == 0 else controlnet_single_block_samples
+ )
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (controlnet_block_samples, controlnet_single_block_samples)
+
+ return ControlNetOutput(
+ controlnet_block_samples=controlnet_block_samples,
+ controlnet_single_block_samples=controlnet_single_block_samples,
+ )
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/embed_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/embed_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..50939f9e32cfbcf8597e0daf55988840aafb1d9a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/embed_layers.py
@@ -0,0 +1,157 @@
+import math
+import torch
+import torch.nn as nn
+from einops import rearrange, repeat
+
+from .utils import to_2tuple
+
+
+class PatchEmbed(nn.Module):
+ """2D Image to Patch Embedding
+
+ Image to Patch Embedding using Conv2d
+
+ A convolution based approach to patchifying a 2D image w/ embedding projection.
+
+ Based on the impl in https://github.com/google-research/vision_transformer
+
+ Hacked together by / Copyright 2020 Ross Wightman
+
+ Remove the _assert function in forward function to be compatible with multi-resolution images.
+ """
+
+ def __init__(
+ self,
+ patch_size=16,
+ in_chans=3,
+ embed_dim=768,
+ norm_layer=None,
+ flatten=True,
+ bias=True,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ patch_size = to_2tuple(patch_size)
+ self.patch_size = patch_size
+ self.flatten = flatten
+
+ self.proj = nn.Conv3d(
+ in_chans,
+ embed_dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ bias=bias,
+ **factory_kwargs
+ )
+ nn.init.xavier_uniform_(self.proj.weight.view(self.proj.weight.size(0), -1))
+ if bias:
+ nn.init.zeros_(self.proj.bias)
+
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
+
+ def forward(self, x):
+ x = self.proj(x)
+ if self.flatten:
+ x = x.flatten(2).transpose(1, 2) # BCHW -> BNC
+ x = self.norm(x)
+ return x
+
+
+class TextProjection(nn.Module):
+ """
+ Projects text embeddings. Also handles dropout for classifier-free guidance.
+
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
+ """
+
+ def __init__(self, in_channels, hidden_size, act_layer, dtype=None, device=None):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.linear_1 = nn.Linear(
+ in_features=in_channels,
+ out_features=hidden_size,
+ bias=True,
+ **factory_kwargs
+ )
+ self.act_1 = act_layer()
+ self.linear_2 = nn.Linear(
+ in_features=hidden_size,
+ out_features=hidden_size,
+ bias=True,
+ **factory_kwargs
+ )
+
+ def forward(self, caption):
+ hidden_states = self.linear_1(caption)
+ hidden_states = self.act_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+def timestep_embedding(t, dim, max_period=10000):
+ """
+ Create sinusoidal timestep embeddings.
+
+ Args:
+ t (torch.Tensor): a 1-D Tensor of N indices, one per batch element. These may be fractional.
+ dim (int): the dimension of the output.
+ max_period (int): controls the minimum frequency of the embeddings.
+
+ Returns:
+ embedding (torch.Tensor): An (N, D) Tensor of positional embeddings.
+
+ .. ref_link: https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py
+ """
+ half = dim // 2
+ freqs = torch.exp(
+ -math.log(max_period)
+ * torch.arange(start=0, end=half, dtype=torch.float32)
+ / half
+ ).to(device=t.device)
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+
+class TimestepEmbedder(nn.Module):
+ """
+ Embeds scalar timesteps into vector representations.
+ """
+
+ def __init__(
+ self,
+ hidden_size,
+ act_layer,
+ frequency_embedding_size=256,
+ max_period=10000,
+ out_size=None,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.frequency_embedding_size = frequency_embedding_size
+ self.max_period = max_period
+ if out_size is None:
+ out_size = hidden_size
+
+ self.mlp = nn.Sequential(
+ nn.Linear(
+ frequency_embedding_size, hidden_size, bias=True, **factory_kwargs
+ ),
+ act_layer(),
+ nn.Linear(hidden_size, out_size, bias=True, **factory_kwargs),
+ )
+ nn.init.normal_(self.mlp[0].weight, std=0.02)
+ nn.init.normal_(self.mlp[2].weight, std=0.02)
+
+ def forward(self, t):
+ t_freq = timestep_embedding(
+ t, self.frequency_embedding_size, self.max_period
+ ).type(self.mlp[0].weight.dtype)
+ t_emb = self.mlp(t_freq)
+ return t_emb
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..e6975b4820b45bf51368bfa8a9ffe5f73b70f1b3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks.py
@@ -0,0 +1,985 @@
+# https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+import torch
+import torch.nn as nn
+from typing import Tuple, Optional
+from einops import rearrange
+
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .attenion import attention, get_cu_seqlens
+from .ipadapter import HYVideoAttnProcessor2_0, RefAttnProcessor, RefAttnProcessor_V2
+
+
+
+
+class MMDoubleStreamBlockReFuser_V2(nn.Module):
+
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V2(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ assert ref_latent is not None, "ref_latent not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)# [B, L, 3 * hidden_size]
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Save img_q before applying 3D RoPE, for later use in refuser
+ img_q_2d = img_q.clone() # 👈
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # ----------------------------------------------------------------
+ # add IP-Adapter for img_attn
+ # ----------------------------------------------------------------
+ # IP-Adapter (num_heads, query, image_emb, t)
+ # - query: img_q (shape [B, L, H, D])
+ # IP-Adapter attention need [B, H, L, D]
+ # - image_emb: shape [B, tokens, hidden_size]
+ # - t: timestep
+ # ----------------------------------------------------------------
+
+ query = img_q_2d
+ # freqs_cis_q = freqs_cis
+ # import pdb; pdb.set_trace()
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis
+ )
+ # print("Before addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # print("ip_hidden_states - max:", ip_hidden_states.max(), "min:", ip_hidden_states.min(), "mean:", ip_hidden_states.mean())
+ if ip_hidden_states is not None:
+ # [B, L, hidden_size]
+ img_attn = img_attn + ip_hidden_states
+ # print("After addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockReFuser_V2(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V2(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ assert ref_latent is not None, "ref_latent not be None"
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Save q before applying 3D RoPE, for later use in refuser
+ q_2d = q.clone() # 👈
+
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # attn => [B, L, hidden_size]
+ # ------------------------------------------------------------------
+ # add IP-Adapter
+ # ------------------------------------------------------------------
+ # use q instead of img_q
+ # https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+ # q shape: [B, L, H, D]
+ query = q_2d
+ # freqs_cis_q = freqs_cis
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis,
+ txt_len=txt_len,
+ )
+ if ip_hidden_states is not None:
+ # ip_hidden_states => [B, img_len, hidden_size]
+ if ip_hidden_states.shape[1] < attn.shape[1]:
+ # 2d case
+ assert img_q.shape[1] == ip_hidden_states.shape[1]
+ attn = torch.cat([
+ attn[:, :ip_hidden_states.shape[1]] + ip_hidden_states,
+ attn[:, ip_hidden_states.shape[1]:]
+ ], dim=1)
+ else:
+ attn += ip_hidden_states
+
+
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
+class MMDoubleStreamBlockReFuser(nn.Module):
+
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ assert ref_latent is not None, "ref_latent not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)# [B, L, 3 * hidden_size]
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # ----------------------------------------------------------------
+ # add IP-Adapter for img_attn
+ # ----------------------------------------------------------------
+ # IP-Adapter (num_heads, query, image_emb, t)
+ # - query: img_q (shape [B, L, H, D])
+ # IP-Adapter attention need [B, H, L, D]
+ # - image_emb: shape [B, tokens, hidden_size]
+ # - t: timestep
+ # ----------------------------------------------------------------
+
+ query = img_q
+ # freqs_cis_q = freqs_cis
+ # import pdb; pdb.set_trace()
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis
+ )
+ # print("Before addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # print("ip_hidden_states - max:", ip_hidden_states.max(), "min:", ip_hidden_states.min(), "mean:", ip_hidden_states.mean())
+ if ip_hidden_states is not None:
+ # [B, L, hidden_size]
+ img_attn = img_attn + ip_hidden_states
+ # print("After addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockReFuser(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ assert ref_latent is not None, "ref_latent not be None"
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # attn => [B, L, hidden_size]
+ # ------------------------------------------------------------------
+ # add IP-Adapter
+ # ------------------------------------------------------------------
+ # use q instead of img_q
+ # https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+ # q shape: [B, L, H, D]
+ query = q
+ # freqs_cis_q = freqs_cis
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis,
+ # img_q=img_q,
+ )
+ if ip_hidden_states is not None:
+ # ip_hidden_states => [B, img_len, hidden_size]
+ attn = attn + ip_hidden_states
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
+
+class MMDoubleStreamBlockIPAdapter(nn.Module):
+
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ipadapter_config: dict,
+ ipadapter_scale: float = 1.0,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.ip_adapter = HYVideoAttnProcessor2_0(
+ num_tokens=ipadapter_config["ipadapter_num_tokens"],
+ hidden_size=ipadapter_config["ipadapter_hidden_size"],
+ cross_attention_dim=ipadapter_config["ipadapter_cross_attention_dim"],
+ # for scale
+ scale_start=ipadapter_config["ipadapter_scale_start"],
+ scale_end=ipadapter_config["ipadapter_scale_end"],
+ total_steps=ipadapter_config["ipadapter_total_steps"],
+ )
+ self.ipadapter_scale = ipadapter_config['ipadapter_scale']
+
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_emb = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ assert image_emb is not None, "image_emb not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)# [B, L, 3 * hidden_size]
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # ----------------------------------------------------------------
+ # add IP-Adapter for img_attn
+ # ----------------------------------------------------------------
+ # IP-Adapter (num_heads, query, image_emb, t)
+ # - query: img_q (shape [B, L, H, D]) instead of img_attn q
+ # IP-Adapter attention need [B, H, L, D]
+ # - image_emb: shape [B, tokens, hidden_size]
+ # - t: timestep
+ # ----------------------------------------------------------------
+
+ # img_q => [B, H, L, D]
+ img_q_for_ip = img_q.transpose(1, 2)
+
+ ip_hidden_states = self.ip_adapter(
+ num_heads=self.heads_num,
+ query=img_q_for_ip,
+ image_emb=image_emb,
+ t=t,
+ )
+ if ip_hidden_states is not None:
+ # [B, L, hidden_size]
+ img_attn = img_attn + self.ipadapter_scale * ip_hidden_states
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockIPAdapter(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ipadapter_config: dict,
+ ipadapter_scale: float = 1.0,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.ip_adapter = HYVideoAttnProcessor2_0(
+ num_tokens=ipadapter_config["ipadapter_num_tokens"],
+ hidden_size=ipadapter_config["ipadapter_hidden_size"],
+ cross_attention_dim=ipadapter_config["ipadapter_cross_attention_dim"],
+ # for scale
+ scale_start=ipadapter_config["ipadapter_scale_start"],
+ scale_end=ipadapter_config["ipadapter_scale_end"],
+ total_steps=ipadapter_config["ipadapter_total_steps"],
+ )
+ self.ipadapter_scale = ipadapter_config['ipadapter_scale']
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None, # <-- timestep
+ image_emb = None,
+ ) -> torch.Tensor:
+ assert image_emb is not None, "image_emb not be None"
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # attn => [B, L, hidden_size]
+ # ------------------------------------------------------------------
+ # add IP-Adapter
+ # ------------------------------------------------------------------
+ # use q instead of img_q
+ # https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+ # q shape: [B, L, H, D]
+ img_q_for_ip = q.transpose(1, 2)
+
+ ip_hidden_states = self.ip_adapter(
+ num_heads=self.heads_num,
+ query=img_q_for_ip,
+ image_emb=image_emb,
+ t=t, # timestep
+ )
+ if ip_hidden_states is not None:
+ # ip_hidden_states => [B, img_len, hidden_size]
+ attn = attn + self.ipadapter_scale * ip_hidden_states
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c59620e8a03dbb23f151f6b5d29f270a2ff91e2
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3.py
@@ -0,0 +1,403 @@
+import torch
+import torch.nn as nn
+from typing import Tuple, Optional
+from einops import rearrange
+
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .posemb_layers import apply_rotary_emb, apply_rotary_emb_ignore_t, apply_rotary_emb_single_ignore_t, get_nd_rotary_pos_embed
+from .attenion import attention, get_cu_seqlens
+from diffusers.models.normalization import RMSNorm
+try:
+ # 优先尝试 FlashAttention 3
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ flash_attn_backend = "flash-attn-3"
+ print("[INFO] Using FlashAttention 3")
+except ImportError:
+ try:
+ # 回退到 FlashAttention 2
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ flash_attn_backend = "flash-attn-2"
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ flash_attn_backend = None
+ flash_attn2_func = None
+ flash_attn3_func = None
+ print("[WARNING] Neither FlashAttention 2 nor 3 is available!")
+
+
+# 2d version
+class RefAttnProcessor_V3(nn.Module):
+ def __init__(self, heads_num, hidden_size, cross_attention_dim=None, scale_end = 1):
+ super().__init__()
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.heads_num = heads_num
+ self.scale_end = scale_end
+ # v2 use bias
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=True)
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=True)
+
+ head_dim = hidden_size // heads_num
+ self.attn_k_norm = RMSNorm(head_dim, eps=1e-6, elementwise_affine=True)
+
+
+ def __call__(
+ self,
+ query,
+ ref_latent: torch.FloatTensor,
+ ref_freqs_cis,
+ # img_q = None
+ ) -> torch.FloatTensor:
+
+ scale = self.scale_end
+ ref_k = self.to_k_ip(ref_latent)
+ ref_v = self.to_v_ip(ref_latent)
+ # import pdb; pdb.set_trace()
+ ref_k = rearrange(ref_k, 'B L (H D) -> B L H D', H=self.heads_num)
+ ref_v = rearrange(ref_v, 'B L (H D) -> B L H D', H=self.heads_num)
+
+ ref_k = self.attn_k_norm(ref_k)
+ # query has been apply rotary emb
+ ref_k = apply_rotary_emb_single_ignore_t(ref_k, ref_freqs_cis, head_first=False)
+ if flash_attn_backend == "flash-attn-3":
+ attn,_ = flash_attn3_func(
+ query.to(ref_latent.device).to(ref_latent.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ elif flash_attn_backend == "flash-attn-2":
+ # flash attn2
+ attn = flash_attn2_func(
+ query.to(ref_latent.device).to(ref_latent.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = rearrange(attn, "B L H D -> B L (H D)")
+ attn = attn.to(query.dtype).to(query.device)
+ return scale * attn
+
+
+class MMDoubleStreamBlockReFuser_V3(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V3(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ assert ref_latent is not None, "ref_latent not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)# [B, L, 3 * hidden_size]
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Save img_q before applying 3D RoPE, for later use in refuser
+ fuser_query = apply_rotary_emb_single_ignore_t(img_q, freqs_cis, head_first=False)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # ----------------------------------------------------------------
+ # add IP-Adapter for img_attn
+ # ----------------------------------------------------------------
+ # IP-Adapter (num_heads, query, image_emb, t)
+ # - query: img_q (shape [B, L, H, D])
+ # IP-Adapter attention need [B, H, L, D]
+ # - image_emb: shape [B, tokens, hidden_size]
+ # - t: timestep
+ # ----------------------------------------------------------------
+
+ query = fuser_query
+ # freqs_cis_q = freqs_cis
+ # import pdb; pdb.set_trace()
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis
+ )
+ # print("Before addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # print("ip_hidden_states - max:", ip_hidden_states.max(), "min:", ip_hidden_states.min(), "mean:", ip_hidden_states.mean())
+ if ip_hidden_states is not None:
+ # [B, L, hidden_size]
+ img_attn = img_attn + ip_hidden_states
+ # print("After addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockReFuser_V3(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V3(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ assert ref_latent is not None, "ref_latent not be None"
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ # add here
+ img_fuser_query = apply_rotary_emb_single_ignore_t(img_q, freqs_cis, head_first=False)
+ fuser_query = torch.cat((img_fuser_query, txt_q), dim=1)
+
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # attn => [B, L, hidden_size]
+ # ------------------------------------------------------------------
+ # add IP-Adapter
+ # ------------------------------------------------------------------
+ # use q instead of img_q
+ # https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+ # q shape: [B, L, H, D]
+ query = fuser_query
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis,
+ )
+ if ip_hidden_states is not None:
+ # ip_hidden_states => [B, img_len, hidden_size]
+ attn = attn + ip_hidden_states
+
+
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3_split_q.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3_split_q.py
new file mode 100644
index 0000000000000000000000000000000000000000..885b0023866cb03105475f809be8c3d32a3b5a48
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipablocks_v3_split_q.py
@@ -0,0 +1,446 @@
+# https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+import torch
+import torch.nn as nn
+from typing import Tuple, Optional
+from einops import rearrange
+
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .posemb_layers import apply_rotary_emb, apply_rotary_emb_ignore_t, apply_rotary_emb_single_ignore_t, get_nd_rotary_pos_embed
+from .attenion import attention, get_cu_seqlens
+from diffusers.models.normalization import RMSNorm
+from .norm_layers import get_norm_layer
+try:
+ # 优先尝试 FlashAttention 3
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ flash_attn_backend = "flash-attn-3"
+ print("[INFO] Using FlashAttention 3")
+except ImportError:
+ try:
+ # 回退到 FlashAttention 2
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ flash_attn_backend = "flash-attn-2"
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ flash_attn_backend = None
+ flash_attn2_func = None
+ flash_attn3_func = None
+ print("[WARNING] Neither FlashAttention 2 nor 3 is available!")
+
+
+# 2d version
+class RefAttnProcessor_V3(nn.Module):
+ def __init__(self, heads_num, hidden_size, cross_attention_dim=None, scale_end = 1):
+ super().__init__()
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.heads_num = heads_num
+ self.scale_end = scale_end
+ # v2 use bias
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=True)
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=True)
+
+ head_dim = hidden_size // heads_num
+ self.attn_k_norm = RMSNorm(head_dim, eps=1e-6, elementwise_affine=True)
+
+
+ def __call__(
+ self,
+ query,
+ ref_latent: torch.FloatTensor,
+ ref_freqs_cis,
+ # img_q = None
+ ) -> torch.FloatTensor:
+
+ scale = self.scale_end
+ ref_k = self.to_k_ip(ref_latent)
+ ref_v = self.to_v_ip(ref_latent)
+ # import pdb; pdb.set_trace()
+ ref_k = rearrange(ref_k, 'B L (H D) -> B L H D', H=self.heads_num)
+ ref_v = rearrange(ref_v, 'B L (H D) -> B L H D', H=self.heads_num)
+
+ ref_k = self.attn_k_norm(ref_k)
+ # query has been apply rotary emb
+ ref_k = apply_rotary_emb_single_ignore_t(ref_k, ref_freqs_cis, head_first=False)
+ if flash_attn_backend == "flash-attn-3":
+ attn,_ = flash_attn3_func(
+ query.to(ref_latent.device).to(ref_latent.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ elif flash_attn_backend == "flash-attn-2":
+ # flash attn2
+ attn = flash_attn2_func(
+ query.to(ref_latent.device).to(ref_latent.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = rearrange(attn, "B L H D -> B L (H D)")
+ attn = attn.to(query.dtype).to(query.device)
+ return scale * attn
+
+
+class MMDoubleStreamBlockReFuser_V3(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V3(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ # self.img_attn_q = original_block.img_attn_q
+ # self.img_attn_kv = original_block.img_attn_kv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+ # refuser
+ self.img_refuser_q = nn.Linear(original_block.hidden_size, original_block.hidden_size, bias=True)
+ qk_norm_layer = get_norm_layer("rms")
+ self.img_refuser_q_norm = (
+ qk_norm_layer(original_block.hidden_size // original_block.heads_num, elementwise_affine=True, eps=1e-6,)
+ )
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ assert ref_latent is not None, "ref_latent not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)# [B, L, 3 * hidden_size]
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # split
+ # img_q = self.img_attn_q(img_modulated) # (B, L, H*D)
+ # img_q = rearrange(img_q, "B L (H D) -> B L H D",H=self.heads_num)
+ # img_kv = self.img_attn_kv(img_modulated) # (B, L, 2*H*D)
+ # img_k, img_v = rearrange(img_kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+ # refuser
+ fuser_query = rearrange(self.img_refuser_q(img_modulated), "B L (H D) -> B L H D",H=self.heads_num)
+ fuser_query = self.img_refuser_q_norm(fuser_query).to(img_v)
+
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Save img_q before applying 3D RoPE, for later use in refuser
+ fuser_query = apply_rotary_emb_single_ignore_t(fuser_query, freqs_cis, head_first=False)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # ----------------------------------------------------------------
+ # add IP-Adapter for img_attn
+ # ----------------------------------------------------------------
+ # IP-Adapter (num_heads, query, image_emb, t)
+ # - query: img_q (shape [B, L, H, D])
+ # IP-Adapter attention need [B, H, L, D]
+ # - image_emb: shape [B, tokens, hidden_size]
+ # - t: timestep
+ # ----------------------------------------------------------------
+
+ query = fuser_query
+ # freqs_cis_q = freqs_cis
+ # import pdb; pdb.set_trace()
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis
+ )
+ # print("Before addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # print("ip_hidden_states - max:", ip_hidden_states.max(), "min:", ip_hidden_states.min(), "mean:", ip_hidden_states.mean())
+ if ip_hidden_states is not None:
+ # [B, L, hidden_size]
+ img_attn = img_attn + ip_hidden_states
+ # print("After addition:")
+ # print("img_attn - max:", img_attn.max(), "min:", img_attn.min(), "mean:", img_attn.mean())
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockReFuser_V3(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ ):
+ super().__init__()
+
+ # self.original_block = original_block
+ self.refuser = RefAttnProcessor_V3(
+ heads_num=original_block.heads_num,
+ hidden_size=original_block.hidden_size,
+ )
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ # split
+ # self.linear1_q = original_block.linear1_q
+ # self.linear1_kv_mlp = original_block.linear1_kv_mlp
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ # self.refuser_q = nn.Linear(original_block.hidden_size, original_block.hidden_size, bias=True)
+ # qk_norm_layer = get_norm_layer("rms")
+ # self.refuser_q_norm = (
+ # qk_norm_layer(original_block.hidden_size // original_block.heads_num, elementwise_affine=True, eps=1e-6)
+ # )
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ assert ref_latent is not None, "ref_latent not be None"
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+ # split
+ # q = self.linear1_q(x_mod)
+ # q = rearrange(q, "B L (H D) -> B L H D",H=self.heads_num)
+ # kv_mlp = self.linear1_kv_mlp(x_mod)
+ # kv, mlp = torch.split(kv_mlp, [2 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
+ # k, v = rearrange(kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+ # fuser_query = rearrange(self.refuser_q(x_mod), "B L (H D) -> B L H D",H=self.heads_num)
+ # fuser_query = self.refuser_q_norm(fuser_query).to(v)
+
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+
+ # add here
+ # img_fuser_q, txt_fuser_q = fuser_query[:, :-txt_len, :, :], fuser_query[:, -txt_len:, :, :]
+ img_fuser_q, txt_fuser_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_fuser_q = apply_rotary_emb_single_ignore_t(img_fuser_q, freqs_cis, head_first=False)
+ fuser_query = torch.cat((img_fuser_q, txt_fuser_q), dim=1)
+
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # attn => [B, L, hidden_size]
+ # ------------------------------------------------------------------
+ # add IP-Adapter
+ # ------------------------------------------------------------------
+ # use q instead of img_q
+ # https://github.com/Shakker-Labs/ComfyUI-IPAdapter-Flux/blob/main/flux/layers.py
+
+ # q shape: [B, L, H, D]
+ query = fuser_query
+ ip_hidden_states = self.refuser(
+ query=query,
+ ref_latent=ref_latent,
+ ref_freqs_cis=ref_freqs_cis,
+ )
+ if ip_hidden_states is not None:
+ # ip_hidden_states => [B, img_len, hidden_size]
+ attn = attn + ip_hidden_states
+
+
+ # ----------------------------------------------------------------
+ # finish IP-Adapter
+ # ----------------------------------------------------------------
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipadapter.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipadapter.py
new file mode 100644
index 0000000000000000000000000000000000000000..b62c28debfc707a1664655bd60c95d6d6f835c54
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/ipadapter.py
@@ -0,0 +1,415 @@
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import os
+import logging
+from transformers import AutoProcessor, SiglipVisionModel
+from PIL import Image
+import numpy as np
+from diffusers.models.normalization import RMSNorm
+from einops import rearrange
+# from flash_attn import flash_attn_func
+try:
+ # flash attn 3
+ from flash_attn_interface import flash_attn_func
+ # from flash_attn.flash_attn_interface import flash_attn_func
+except ImportError:
+ flash_attn_func = None
+from .posemb_layers import apply_rotary_emb_k,apply_rotary_emb
+
+
+
+class RefAttnProcessor_V2(nn.Module):
+ def __init__(self, heads_num, hidden_size, cross_attention_dim=None, scale_end = 1):
+ super().__init__()
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.heads_num = heads_num
+ self.scale_end = scale_end
+
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+
+ head_dim = hidden_size // heads_num
+ self.attn_k_norm = RMSNorm(head_dim, eps=1e-6, elementwise_affine=True)
+
+
+ def __call__(
+ self,
+ query,
+ ref_latent: torch.FloatTensor,
+ ref_freqs_cis,
+ txt_len=0,
+ spatialattn_include_txt: bool = False,
+ ) -> torch.FloatTensor:
+
+ scale = self.scale_end
+ ref_k = self.to_k_ip(ref_latent)
+ ref_v = self.to_v_ip(ref_latent)
+ # import pdb; pdb.set_trace()
+
+ ref_k = rearrange(ref_k, 'B L (H D) -> B L H D', H=self.heads_num)
+ ref_v = rearrange(ref_v, 'B L (H D) -> B L H D', H=self.heads_num)
+
+ ref_k = self.attn_k_norm(ref_k)
+
+ # double block
+ if txt_len == 0:
+ img_q = query
+ if ref_k.shape[1] != img_q.shape[1]:
+ # img_q: [B, T*HW, H, D]
+ B, L_q, H, D = img_q.shape
+ L_k = ref_k.shape[1]
+ T = L_q // L_k
+ assert T * L_k == L_q, "img_q length must be divisible by spatial size"
+
+ # reshape img_q -> [B*T, L_k, H, D]
+ img_q = img_q.contiguous().view(B*T, L_k, H, D)
+
+ # repeat ref_k/v -> [B*T,L_k, H, D]
+ ref_k = ref_k.repeat(1, T, 1, 1, 1).view(B * T, L_k, H, D)
+ ref_v = ref_v.repeat(1, T, 1, 1, 1).view(B * T, L_k, H, D)
+
+ img_q, ref_k = apply_rotary_emb(img_q, ref_k, freqs_cis=ref_freqs_cis, head_first=False)
+ # img_q in double block
+ attn,_ = flash_attn_func(
+ img_q.to(ref_k.device).to(ref_k.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=img_q.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = attn.view(B, L_q, H*D)
+ else:
+ # normal case
+ img_q, ref_k = apply_rotary_emb(img_q, ref_k, freqs_cis=ref_freqs_cis, head_first=False)
+ # # img_q in double block
+ attn,_ = flash_attn_func(
+ img_q.to(ref_k.device).to(ref_k.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=img_q.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = rearrange(attn, "B L H D -> B L (H D)")
+
+
+ # single block
+ elif txt_len > 0:
+ img_q, txt_q = query[:, :-txt_len, :, :], query[:, -txt_len:, :, :]
+ # 2d
+ if ref_k.shape[1] != img_q.shape[1]:
+ B, L_q, H, D = img_q.shape
+ L_k = ref_k.shape[1]
+ T = L_q // L_k
+ assert T * L_k == L_q, "img_q length must be divisible by spatial size"
+
+ # reshape img_q -> [B*T, L_k, H, D]
+ img_q = img_q.contiguous().view(B*T, L_k, H, D)
+ # repeat ref_k/v -> [B*T,L_k, H, D]
+ ref_k = ref_k.unsqueeze(1).repeat(1, T, 1, 1, 1).view(B * T, L_k, H, D)
+ ref_v = ref_v.unsqueeze(1).repeat(1, T, 1, 1, 1).view(B * T, L_k, H, D)
+
+ img_q, ref_k = apply_rotary_emb(img_q, ref_k, freqs_cis=ref_freqs_cis, head_first=False)
+
+ if spatialattn_include_txt:
+ txt_q = txt_q.unsqueeze(1).repeat(1, T, 1, 1, 1).view(B * T, txt_len, H, D)
+ query = torch.cat([img_q, txt_q], dim=1) # [B*T, HW+txt_len, H, D]
+ else:
+ query = img_q
+ # query in single block
+ attn,_ = flash_attn_func(
+ query.to(ref_k.device).to(ref_k.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = attn.view(B, L_q, H*D)
+ # 3d
+ else:
+ img_q, ref_k = apply_rotary_emb(img_q, ref_k, freqs_cis=ref_freqs_cis, head_first=False)
+ query = torch.cat([img_q, txt_q], dim=1) # [B, THW+txt_len, H, D]
+ attn,_ = flash_attn_func(
+ query.to(ref_k.device).to(ref_k.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = rearrange(attn, "B L H D -> B L (H D)")
+
+ attn = attn.to(img_q.dtype).to(img_q.device)
+ return scale * attn
+
+
+class RefAttnProcessor(nn.Module):
+ def __init__(self, heads_num, hidden_size, cross_attention_dim=None, scale_end = 1):
+ super().__init__()
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.heads_num = heads_num
+ self.scale_end = scale_end
+
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+
+ head_dim = hidden_size // heads_num
+ self.attn_k_norm = RMSNorm(head_dim, eps=1e-6, elementwise_affine=True)
+
+
+ def __call__(
+ self,
+ query,
+ ref_latent: torch.FloatTensor,
+ ref_freqs_cis,
+ # img_q = None
+ ) -> torch.FloatTensor:
+
+ scale = self.scale_end
+ ref_k = self.to_k_ip(ref_latent)
+ ref_v = self.to_v_ip(ref_latent)
+ # import pdb; pdb.set_trace()
+ ref_k = rearrange(ref_k, 'B L (H D) -> B L H D', H=self.heads_num)
+ ref_v = rearrange(ref_v, 'B L (H D) -> B L H D', H=self.heads_num)
+
+ ref_k = self.attn_k_norm(ref_k)
+ # query has been apply rotary emb
+ # singleblock需要img_q
+ # 4.5改为ref_k
+ # import pdb; pdb.set_trace()
+ ref_k = apply_rotary_emb_k(ref_k, ref_k, ref_freqs_cis, head_first=False)
+ attn,_ = flash_attn_func(
+ query.to(ref_latent.device).to(ref_latent.dtype),
+ ref_k,
+ ref_v,
+ softmax_scale=query.shape[-1]**-0.5,
+ causal=False,
+ )
+ attn = rearrange(attn, "B L H D -> B L (H D)")
+ attn = attn.to(query.dtype).to(query.device)
+
+ return scale * attn
+
+
+# from IPAFluxAttnProcessor2_0Advanced
+class HYVideoAttnProcessor2_0(nn.Module):
+ _instances = set()
+ _global_call_count = 0
+ _last_timestep_printed = None
+ _first_instance_for_timestep = None # Add this line
+
+ def __init__(self, num_tokens, hidden_size, cross_attention_dim=None, scale_start=1.0, scale_end=1.0, total_steps=1, timestep_range=None):
+ super().__init__()
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.scale_start = scale_start
+ self.scale_end = scale_end
+ self.total_steps = total_steps
+ self.num_tokens = num_tokens
+
+ self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+
+ self.norm_added_k = RMSNorm(128, eps=1e-5, elementwise_affine=False)
+ self.norm_added_v = RMSNorm(128, eps=1e-5, elementwise_affine=False)
+ self.timestep_range = timestep_range
+
+ self.seen_timesteps = set()
+ self.steps = 0
+
+ # Add this instance to the set of instances
+ self.__class__._instances.add(self)
+
+ def clear_memory(self):
+ self.seen_timesteps.clear()
+ if hasattr(self, 'to_k_ip'):
+ del self.to_k_ip
+ if hasattr(self, 'to_v_ip'):
+ del self.to_v_ip
+ if hasattr(self, 'norm_added_k'):
+ del self.norm_added_k
+ if hasattr(self, 'norm_added_v'):
+ del self.norm_added_v
+
+ @classmethod
+ def reset_all_instances(cls):
+ """Reset all instances of the class"""
+ cls._global_call_count = 0
+ cls._last_timestep_printed = None
+ cls._first_instance_for_timestep = None # Add this line
+ for instance in cls._instances:
+ instance.seen_timesteps.clear()
+ instance.steps = 0
+
+ def reset_steps(self):
+ """Reset the steps counter and seen timesteps for this instance."""
+ self.seen_timesteps.clear()
+ self.steps = 0
+ self.__class__._last_timestep_printed = None
+ # print(f"Steps and seen timesteps have been reset for this instance.")
+
+ def __del__(self):
+ # Remove this instance from the set when it's deleted
+ self.__class__._instances.remove(self)
+
+ def __call__(
+ self,
+ num_heads,
+ query,
+ image_emb: torch.FloatTensor,
+ t: torch.FloatTensor,
+ ) -> torch.FloatTensor:
+ current_timestep = t[0].item()
+
+ # Reset steps when starting a new sequence (timestep = 1.0)
+ if abs(current_timestep - 1.0) < 1e-6:
+ self.reset_steps()
+
+ if self.timestep_range is not None:
+ if t[0] > self.timestep_range[0] or t[0] < self.timestep_range[1]:
+ return None
+
+ # Only update steps and print for the first instance that sees this timestep
+ if current_timestep not in self.seen_timesteps:
+ self.seen_timesteps.add(current_timestep)
+ self.steps += 1
+
+ # Only print if this is the first instance for this timestep
+ if self.__class__._first_instance_for_timestep is None:
+ self.__class__._first_instance_for_timestep = self
+
+ if (self.__class__._first_instance_for_timestep == self and
+ current_timestep != self.__class__._last_timestep_printed):
+ current_step = min(self.steps, self.total_steps)
+ if self.total_steps > 1:
+ scale = self.scale_start + (self.scale_end - self.scale_start) * (current_step - 1) / (self.total_steps - 1)
+ else:
+ scale = self.scale_end
+
+ # print(f"Timestep: {current_timestep}, Step: {self.steps}/{self.total_steps}, Weight: {scale}")
+ self.__class__._last_timestep_printed = current_timestep
+
+ # Calculate scale for return value
+ current_step = min(self.steps, self.total_steps)
+ if self.total_steps > 1:
+ # scale_end and scale_start to get the scale
+ scale = self.scale_start + (self.scale_end - self.scale_start) * (current_step - 1) / (self.total_steps - 1)
+ else:
+ scale = self.scale_end
+
+ ip_hidden_states = image_emb
+ ip_hidden_states_key_proj = self.to_k_ip(ip_hidden_states)
+ ip_hidden_states_value_proj = self.to_v_ip(ip_hidden_states)
+ # import pdb; pdb.set_trace()
+ ip_hidden_states_key_proj = rearrange(ip_hidden_states_key_proj, 'B L (H D) -> B H L D', H=num_heads)
+ ip_hidden_states_value_proj = rearrange(ip_hidden_states_value_proj, 'B L (H D) -> B H L D', H=num_heads)
+
+ ip_hidden_states_key_proj = self.norm_added_k(ip_hidden_states_key_proj)
+ ip_hidden_states_value_proj = self.norm_added_v(ip_hidden_states_value_proj)
+
+ ip_hidden_states = F.scaled_dot_product_attention(query.to(image_emb.device).to(image_emb.dtype),
+ ip_hidden_states_key_proj,
+ ip_hidden_states_value_proj,
+ dropout_p=0.0, is_causal=False)
+
+ ip_hidden_states = rearrange(ip_hidden_states, "B H L D -> B L (H D)", H=num_heads)
+ ip_hidden_states = ip_hidden_states.to(query.dtype).to(query.device)
+
+ return scale * ip_hidden_states
+
+
+class MLPProjModelAdvanced(torch.nn.Module):
+ def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
+ super().__init__()
+
+ self.cross_attention_dim = cross_attention_dim
+ self.num_tokens = num_tokens
+
+ self.proj = torch.nn.Sequential(
+ torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
+ torch.nn.GELU(),
+ torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
+ )
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
+
+ def forward(self, id_embeds):
+ x = self.proj(id_embeds)
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
+ x = self.norm(x)
+ return x
+
+# from InstantXFluxIPAdapterModelAdvanced
+# not use
+# class HYVideoDiffusionTransformerIPAdapter:
+# def __init__(self, image_encoder_path, ip_ckpt, device, num_tokens=4):
+# self.device = device
+# self.image_encoder_path = image_encoder_path
+# self.ip_ckpt = ip_ckpt
+# self.num_tokens = num_tokens
+# # load image encoder
+# self.image_encoder = SiglipVisionModel.from_pretrained(self.image_encoder_path).to(self.device, dtype=torch.float16)
+# self.clip_image_processor = AutoProcessor.from_pretrained(self.image_encoder_path)
+# # state_dict
+# self.state_dict = torch.load(os.path.join(MODELS_DIR,self.ip_ckpt), map_location="cpu")
+# self.joint_attention_dim = 4096
+# self.hidden_size = 3072
+
+# def init_proj(self):
+# self.image_proj_model = MLPProjModelAdvanced(
+# cross_attention_dim=self.joint_attention_dim,
+# id_embeddings_dim=1152,
+# num_tokens=self.num_tokens,
+# ).to(self.device, dtype=torch.float16)
+
+# def set_ip_adapter(self, hunyuan_model, weight_params, timestep_percent_range=(0.0, 1.0)):
+# weight_start, weight_end, steps = weight_params
+# s = hunyuan_model.model_sampling
+# percent_to_timestep_function = lambda a: s.percent_to_sigma(a)
+# timestep_range = (percent_to_timestep_function(timestep_percent_range[0]), percent_to_timestep_function(timestep_percent_range[1]))
+# ip_attn_procs = {}
+# dsb_count = len(hunyuan_model.diffusion_model.double_blocks)
+# for i in range(dsb_count):
+# name = f"double_blocks.{i}"
+# ip_attn_procs[name] = HYVideoAttnProcessor2_0(
+# hidden_size=self.hidden_size,
+# cross_attention_dim=self.joint_attention_dim,
+# num_tokens=self.num_tokens,
+# scale_start=weight_start,
+# scale_end=weight_end,
+# total_steps=steps,
+# timestep_range=timestep_range
+# ).to(self.device, dtype=torch.float16)
+# ssb_count = len(hunyuan_model.diffusion_model.single_blocks)
+# for i in range(ssb_count):
+# name = f"single_blocks.{i}"
+# ip_attn_procs[name] = HYVideoAttnProcessor2_0(
+# hidden_size=self.hidden_size,
+# cross_attention_dim=self.joint_attention_dim,
+# num_tokens=self.num_tokens,
+# scale_start=weight_start,
+# scale_end=weight_end,
+# total_steps=steps,
+# timestep_range=timestep_range
+# ).to(self.device, dtype=torch.float16)
+# return ip_attn_procs
+
+# def load_ip_adapter(self, hunyuan_model, weight, timestep_percent_range=(0.0, 1.0)):
+# self.image_proj_model.load_state_dict(self.state_dict["image_proj"], strict=True)
+# ip_attn_procs = self.set_ip_adapter(hunyuan_model, weight, timestep_percent_range)
+# ip_layers = torch.nn.ModuleList(ip_attn_procs.values())
+# ip_layers.load_state_dict(self.state_dict["ip_adapter"], strict=True)
+# return ip_attn_procs
+
+# @torch.inference_mode()
+# def get_image_embeds(self, pil_image=None, clip_image_embeds=None):
+# if pil_image is not None:
+# if isinstance(pil_image, Image.Image):
+# pil_image = [pil_image]
+# clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
+# clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=self.image_encoder.dtype)).pooler_output
+# clip_image_embeds = clip_image_embeds.to(dtype=torch.float16)
+# else:
+# clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
+# image_prompt_embeds = self.image_proj_model(clip_image_embeds)
+# return image_prompt_embeds
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/mlp_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/mlp_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..56a91d479ac35e240d405610de89475be9229a2d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/mlp_layers.py
@@ -0,0 +1,118 @@
+# Modified from timm library:
+# https://github.com/huggingface/pytorch-image-models/blob/648aaa41233ba83eb38faf5ba9d415d574823241/timm/layers/mlp.py#L13
+
+from functools import partial
+
+import torch
+import torch.nn as nn
+
+from .modulate_layers import modulate
+from .utils import to_2tuple
+
+
+class MLP(nn.Module):
+ """MLP as used in Vision Transformer, MLP-Mixer and related networks"""
+
+ def __init__(
+ self,
+ in_channels,
+ hidden_channels=None,
+ out_features=None,
+ act_layer=nn.GELU,
+ norm_layer=None,
+ bias=True,
+ drop=0.0,
+ use_conv=False,
+ device=None,
+ dtype=None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ out_features = out_features or in_channels
+ hidden_channels = hidden_channels or in_channels
+ bias = to_2tuple(bias)
+ drop_probs = to_2tuple(drop)
+ linear_layer = partial(nn.Conv2d, kernel_size=1) if use_conv else nn.Linear
+
+ self.fc1 = linear_layer(
+ in_channels, hidden_channels, bias=bias[0], **factory_kwargs
+ )
+ self.act = act_layer()
+ self.drop1 = nn.Dropout(drop_probs[0])
+ self.norm = (
+ norm_layer(hidden_channels, **factory_kwargs)
+ if norm_layer is not None
+ else nn.Identity()
+ )
+ self.fc2 = linear_layer(
+ hidden_channels, out_features, bias=bias[1], **factory_kwargs
+ )
+ self.drop2 = nn.Dropout(drop_probs[1])
+
+ def forward(self, x):
+ x = self.fc1(x)
+ x = self.act(x)
+ x = self.drop1(x)
+ x = self.norm(x)
+ x = self.fc2(x)
+ x = self.drop2(x)
+ return x
+
+
+#
+class MLPEmbedder(nn.Module):
+ """copied from https://github.com/black-forest-labs/flux/blob/main/src/flux/modules/layers.py"""
+ def __init__(self, in_dim: int, hidden_dim: int, device=None, dtype=None):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True, **factory_kwargs)
+ self.silu = nn.SiLU()
+ self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True, **factory_kwargs)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.out_layer(self.silu(self.in_layer(x)))
+
+
+class FinalLayer(nn.Module):
+ """The final layer of DiT."""
+
+ def __init__(
+ self, hidden_size, patch_size, out_channels, act_layer, device=None, dtype=None
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ # Just use LayerNorm for the final layer
+ self.norm_final = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ if isinstance(patch_size, int):
+ self.linear = nn.Linear(
+ hidden_size,
+ patch_size * patch_size * out_channels,
+ bias=True,
+ **factory_kwargs
+ )
+ else:
+ self.linear = nn.Linear(
+ hidden_size,
+ patch_size[0] * patch_size[1] * patch_size[2] * out_channels,
+ bias=True,
+ )
+ nn.init.zeros_(self.linear.weight)
+ nn.init.zeros_(self.linear.bias)
+
+ # Here we don't distinguish between the modulate types. Just use the simple one.
+ self.adaLN_modulation = nn.Sequential(
+ act_layer(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
+
+ def forward(self, x, c):
+ shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
+ x = modulate(self.norm_final(x), shift=shift, scale=scale)
+ x = self.linear(x)
+ return x
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..09b8b1b8bc3bc2a461ec48d5252420bee0684ddd
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models.py
@@ -0,0 +1,1065 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ self.hidden_size = hidden_size
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_ipadapter = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_ipadapter(self, ipadapter_config, weight_dtype):
+ # only set once
+ if self.use_ipadapter is True:
+ return
+
+ if isinstance(ipadapter_config, str):
+ import json
+ with open(ipadapter_config, "r") as f:
+ ipadapter_config = json.load(f)
+ if not ipadapter_config["enable_ipadapter"]:
+ # ("[IP-Adapter] IP-Adapter not enabled in config. Skip.")
+ return
+
+ ipadapter_double_blocks_depth = ipadapter_config["ipadapter_double_blocks_depth"]
+ ipadapter_single_blocks_depth = ipadapter_config["ipadapter_single_blocks_depth"]
+ total_adapters_needed = ipadapter_double_blocks_depth + ipadapter_single_blocks_depth
+ if total_adapters_needed <= 0:
+ return
+
+ from .ipadapter import MLPProjModelAdvanced, HYVideoAttnProcessor2_0
+ from .ipablocks import MMDoubleStreamBlockIPAdapter, MMSingleStreamBlockIPAdapter
+ # MLP (only one)
+ self.ipadapter_proj = MLPProjModelAdvanced(
+ cross_attention_dim=ipadapter_config["mlp_out_dim"],
+ id_embeddings_dim=ipadapter_config["mlp_in_dim"],
+ num_tokens=ipadapter_config["mlp_num_tokens"],
+ ).to(dtype=weight_dtype)
+
+
+ # ip_adapters (a lot of cross attention)
+ interval_double = max(1, int(np.ceil(len(self.double_blocks) / ipadapter_double_blocks_depth
+ ))) if ipadapter_double_blocks_depth > 0 else 999
+ interval_single = max(1, int(np.ceil(len(self.single_blocks) / ipadapter_single_blocks_depth
+ ))) if ipadapter_single_blocks_depth > 0 else 999
+ adapter_idx = 0
+
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ if ipadapter_double_blocks_depth > 0 and i % interval_double == 0:
+
+ wrapped = MMDoubleStreamBlockIPAdapter(
+ original_block=block,
+ ipadapter_config = ipadapter_config,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+
+ adapter_idx += 1
+
+ else:
+ new_double_blocks.append(block)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ assert adapter_idx == ipadapter_double_blocks_depth, (
+ f"IP-Adapter for double_blocks mismatch! "
+ f"adapter_idx={adapter_idx}, ipadapter_double_blocks_depth={ipadapter_double_blocks_depth}"
+ )
+
+ # ---- single_blocks ----
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ if ipadapter_single_blocks_depth > 0 and i % interval_single == 0:
+
+ wrapped_sblock = MMSingleStreamBlockIPAdapter(
+ original_block=block,
+ ipadapter_config = ipadapter_config,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ adapter_idx += 1
+ else:
+ new_single_blocks.append(block)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+
+
+ assert adapter_idx == total_adapters_needed, (
+ f"IP-Adapter for single_blocks mismatch! after double we used {ipadapter_double_blocks_depth}, "
+ f"but total needed is {total_adapters_needed}, "
+ f"currently adapter_idx={adapter_idx}"
+ )
+ self.use_ipadapter = True
+
+
+ def enable_ipadapter_params_grad(self):
+ if not self.use_ipadapter:
+ print("[IP-Adapter] Not use ipadapter, skip enabling grad.")
+ return
+ # mlp
+ if self.ipadapter_proj is not None:
+ for p in self.ipadapter_proj.parameters():
+ p.requires_grad = True
+ # ip
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ for p in block.ip_adapter.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ for p in block.ip_adapter.parameters():
+ p.requires_grad = True
+
+ print("[IP-Adapter] All IP-Adapter params set requires_grad=True.")
+
+
+ def get_ipadapter_params_count(self) -> float:
+ if not self.use_ipadapter:
+ print("[IP-Adapter] Not use ipadapter, skip enabling grad.")
+ return
+ # mlp
+ if self.ipadapter_proj is not None:
+ counts["mlp"] = sum(p.numel() for p in self.ipadapter_proj.parameters())
+ # ip
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ counts["ip_adapters"] += sum(p.numel() for p in block.ip_adapter.parameters())
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ counts["ip_adapters"] += sum(p.numel() for p in block.ip_adapter.parameters())
+
+ counts["total"] = counts["mlp"] + counts["ip_adapters"]
+ return counts
+
+ def get_controlnet_and_ipadapter_trainable_params_count(self) -> dict:
+ controlnet_params = 0.0
+ ipadapter_params = 0.0
+
+ # Count trainable ControlNet parameters
+ if hasattr(self, "controlnet"):
+ controlnet_params = sum(p.numel() for p in self.controlnet.parameters() if p.requires_grad)
+
+ # Count trainable IP-Adapter parameters
+ if self.use_ipadapter:
+ if self.ipadapter_proj is not None:
+ ipadapter_params = sum(p.numel() for p in self.ipadapter_proj.parameters() if p.requires_grad)
+
+ # Iterate through the double_blocks and single_blocks to count trainable IP-Adapter parameters
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ ipadapter_params += sum(p.numel() for p in block.ip_adapter.parameters() if p.requires_grad)
+
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ ipadapter_params += sum(p.numel() for p in block.ip_adapter.parameters() if p.requires_grad)
+ return {
+ "controlnet_params": controlnet_params,
+ "ipadapter_params": ipadapter_params,
+ }
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+ image_emb = None, # ipadapter image_emb
+ image_latents = None, # image_latents for controlnet
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ if self.use_ipadapter:
+ if image_emb is None:
+ ValueError(
+ f"image_emb is None, no input for ip-adapter !!!!"
+ )
+ image_emb = self.ipadapter_proj(image_emb)
+
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = image_latents,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_end2end.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_end2end.py
new file mode 100644
index 0000000000000000000000000000000000000000..d66199183d96124d9caddaf3f1b8eafeeb550fbf
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_end2end.py
@@ -0,0 +1,1082 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformerEnd2End(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0, #用默认值
+ conditioning_embedding_channels: int = None,
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_ipadapter = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+
+ # pose_control_part
+ if conditioning_embedding_channels:
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = conditioning_embedding_channels, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+ self.controlnet_x_embedder = torch.nn.Linear(self.in_channels, self.hidden_size)
+ else:
+ self.input_hint_block = None
+ self.controlnet_x_embedder = zero_module(torch.nn.Linear(self.in_channels, self.hidden_size))
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_ipadapter(self, ipadapter_config, weight_dtype):
+ # only set once
+ if self.use_ipadapter is True:
+ return
+
+ if isinstance(ipadapter_config, str):
+ import json
+ with open(ipadapter_config, "r") as f:
+ ipadapter_config = json.load(f)
+ if not ipadapter_config["enable_ipadapter"]:
+ # ("[IP-Adapter] IP-Adapter not enabled in config. Skip.")
+ return
+
+ ipadapter_double_blocks_depth = ipadapter_config["ipadapter_double_blocks_depth"]
+ ipadapter_single_blocks_depth = ipadapter_config["ipadapter_single_blocks_depth"]
+ total_adapters_needed = ipadapter_double_blocks_depth + ipadapter_single_blocks_depth
+ if total_adapters_needed <= 0:
+ return
+
+ from .ipadapter import MLPProjModelAdvanced, HYVideoAttnProcessor2_0
+ from .ipablocks import MMDoubleStreamBlockIPAdapter, MMSingleStreamBlockIPAdapter
+ # MLP (only one)
+ self.ipadapter_proj = MLPProjModelAdvanced(
+ cross_attention_dim=ipadapter_config["mlp_out_dim"],
+ id_embeddings_dim=ipadapter_config["mlp_in_dim"],
+ num_tokens=ipadapter_config["mlp_num_tokens"],
+ ).to(dtype=weight_dtype)
+
+
+ # ip_adapters (a lot of cross attention)
+ interval_double = max(1, int(np.ceil(len(self.double_blocks) / ipadapter_double_blocks_depth
+ ))) if ipadapter_double_blocks_depth > 0 else 999
+ interval_single = max(1, int(np.ceil(len(self.single_blocks) / ipadapter_single_blocks_depth
+ ))) if ipadapter_single_blocks_depth > 0 else 999
+ adapter_idx = 0
+
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ if ipadapter_double_blocks_depth > 0 and i % interval_double == 0:
+
+ wrapped = MMDoubleStreamBlockIPAdapter(
+ original_block=block,
+ ipadapter_config = ipadapter_config,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+
+ adapter_idx += 1
+
+ else:
+ new_double_blocks.append(block)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ assert adapter_idx == ipadapter_double_blocks_depth, (
+ f"IP-Adapter for double_blocks mismatch! "
+ f"adapter_idx={adapter_idx}, ipadapter_double_blocks_depth={ipadapter_double_blocks_depth}"
+ )
+
+ # ---- single_blocks ----
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ if ipadapter_single_blocks_depth > 0 and i % interval_single == 0:
+
+ wrapped_sblock = MMSingleStreamBlockIPAdapter(
+ original_block=block,
+ ipadapter_config = ipadapter_config,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ adapter_idx += 1
+ else:
+ new_single_blocks.append(block)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+
+
+ assert adapter_idx == total_adapters_needed, (
+ f"IP-Adapter for single_blocks mismatch! after double we used {ipadapter_double_blocks_depth}, "
+ f"but total needed is {total_adapters_needed}, "
+ f"currently adapter_idx={adapter_idx}"
+ )
+ self.use_ipadapter = True
+
+
+ def enable_ipadapter_params_grad(self):
+ if not self.use_ipadapter:
+ print("[IP-Adapter] Not use ipadapter, skip enabling grad.")
+ return
+ # mlp
+ if self.ipadapter_proj is not None:
+ for p in self.ipadapter_proj.parameters():
+ p.requires_grad = True
+ # ip
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ for p in block.ip_adapter.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ for p in block.ip_adapter.parameters():
+ p.requires_grad = True
+
+ print("[IP-Adapter] All IP-Adapter params set requires_grad=True.")
+
+
+ def get_ipadapter_params_count(self) -> float:
+ if not self.use_ipadapter:
+ print("[IP-Adapter] Not use ipadapter, skip enabling grad.")
+ return
+ # mlp
+ if self.ipadapter_proj is not None:
+ counts["mlp"] = sum(p.numel() for p in self.ipadapter_proj.parameters())
+ # ip
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ counts["ip_adapters"] += sum(p.numel() for p in block.ip_adapter.parameters())
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ counts["ip_adapters"] += sum(p.numel() for p in block.ip_adapter.parameters())
+
+ counts["total"] = counts["mlp"] + counts["ip_adapters"]
+ return counts
+
+ def get_controlnet_and_ipadapter_trainable_params_count(self) -> dict:
+ controlnet_params = 0.0
+ ipadapter_params = 0.0
+
+ # Count trainable ControlNet parameters
+ if self.input_hint_block is not None:
+ controlnet_params += sum(p.numel() for p in self.input_hint_block.parameters() if p.requires_grad)
+ if self.controlnet_x_embedder is not None:
+ controlnet_params += sum(p.numel() for p in self.controlnet_x_embedder.parameters() if p.requires_grad)
+ # Count trainable IP-Adapter parameters
+ if self.use_ipadapter:
+ if self.ipadapter_proj is not None:
+ ipadapter_params = sum(p.numel() for p in self.ipadapter_proj.parameters() if p.requires_grad)
+
+ # Iterate through the double_blocks and single_blocks to count trainable IP-Adapter parameters
+ for block in self.double_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ ipadapter_params += sum(p.numel() for p in block.ip_adapter.parameters() if p.requires_grad)
+
+ for block in self.single_blocks:
+ if hasattr(block, 'ip_adapter') and block.ip_adapter is not None:
+ ipadapter_params += sum(p.numel() for p in block.ip_adapter.parameters() if p.requires_grad)
+ return {
+ "controlnet_params": controlnet_params,
+ "ipadapter_params": ipadapter_params,
+ }
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+ image_emb = None, # ipadapter image_emb
+ image_latents = None, # image_latents for controlnet
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ if self.use_ipadapter:
+ if image_emb is None:
+ ValueError(
+ f"image_emb is None, no input for ip-adapter !!!!"
+ )
+ image_emb = self.ipadapter_proj(image_emb)
+
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ if conditioning_scale > 0 and self.input_hint_block is not None:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ img = img + controlnet_cond
+ # Embed image and text.
+ img = self.img_in(img)
+
+ # pose control part
+
+ # batch_size, channels, t_pw, height_pw, width_pw = controlnet_cond.shape
+ # patch_size_t, patch_size_h, patch_size_w = self.config.patch_size
+ # height = height_pw // patch_size_h
+ # width = width_pw // patch_size_w
+ # t_ = t_pw // patch_size_t
+ # controlnet_cond = controlnet_cond.reshape(
+ # batch_size, channels, t_, patch_size_t, height, patch_size_h, width, patch_size_w
+ # )
+ # controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ # controlnet_cond = controlnet_cond.reshape(batch_size, height * width * t_, -1)
+ # # add control here
+ # img = img + self.controlnet_x_embedder(controlnet_cond) * conditioning_scale
+
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_ref.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_ref.py
new file mode 100644
index 0000000000000000000000000000000000000000..d30e3faa9e1165fc96476dfe1b5d8321d1d6cf03
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_ref.py
@@ -0,0 +1,1062 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ref = None,
+ text_mask = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None,
+ image_embed = None,
+ ref = None,
+ img_len = None,
+ text_mask = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformerRef(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_ipadapter = False
+ self.use_ref = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ self.ref_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_refblocks(self, ref_config, weight_dtype):
+ if self.use_ref is True:
+ return
+ if isinstance(ref_config, str):
+ import json
+ with open(ref_config, "r") as f:
+ ref_config = json.load(f)
+ if not ref_config.get("enable_ref", False):
+ print("[Ref-Block] Ref blocks not enabled in config. Skip.")
+ return
+ ref_double_blocks_depth = ref_config.get("ref_double_blocks_depth", 0)
+ ref_single_blocks_depth = ref_config.get("ref_single_blocks_depth", 0)
+ total_ref_blocks_needed = ref_double_blocks_depth + ref_single_blocks_depth
+ if total_ref_blocks_needed <= 0:
+ return
+ hidden_size = ref_config.get("hidden_size", None)
+ if hidden_size is None:
+ if hasattr(self.double_blocks[0], "hidden_size"):
+ hidden_size = self.double_blocks[0].hidden_size
+ else:
+ raise ValueError("hidden_size not provided in ref_config and cannot be inferred from double_blocks[0].")
+ mlp_act_type = ref_config.get("mlp_act_type", "gelu_tanh")
+
+ # 配置单流 block 的变体选择,支持 "default" 或 "kv_only"
+ ref_single_variant = ref_config.get("ref_single_variant", "default") # 默认使用 MMSingleStreamBlockRef
+ interval_double = (
+ max(1, int(np.ceil(len(self.double_blocks) / ref_double_blocks_depth)))
+ if ref_double_blocks_depth > 0
+ else 999
+ )
+ interval_single = (
+ max(1, int(np.ceil(len(self.single_blocks) / ref_single_blocks_depth)))
+ if ref_single_blocks_depth > 0
+ else 999
+ )
+ from .refblocks import MMDoubleStreamBlockRef, MMSingleStreamBlockRef
+ from .refblocks import MMDoubleStreamBlockRefKVOnly, MMSingleStreamBlockRefKVOnly
+
+ adapter_idx = 0
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ if ref_double_blocks_depth > 0 and i % interval_double == 0:
+ adapter_idx += 1
+ if ref_single_variant == "kv_only":
+ wrapped = MMDoubleStreamBlockRefKVOnly(
+ original_block=block,
+ hidden_size=hidden_size,
+ mlp_act_type=mlp_act_type,
+ ).to(dtype=weight_dtype)
+ else:
+ wrapped = MMDoubleStreamBlockRef(
+ original_block=block,
+ hidden_size=hidden_size,
+ mlp_act_type=mlp_act_type,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ else:
+ new_double_blocks.append(block)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+ assert adapter_idx == ref_double_blocks_depth, (
+ f"[Ref-Block] Double blocks: adapter_idx={adapter_idx}, "
+ f"expected {ref_double_blocks_depth}"
+ )
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ if ref_single_blocks_depth > 0 and i % interval_single == 0:
+ adapter_idx += 1
+ if ref_single_variant == "kv_only":
+ wrapped = MMSingleStreamBlockRefKVOnly(
+ original_block=block,
+ hidden_size=hidden_size,
+ mlp_act_type=mlp_act_type,
+ ).to(dtype=weight_dtype)
+ else:
+ wrapped = MMSingleStreamBlockRef(
+ original_block=block,
+ hidden_size=hidden_size,
+ mlp_act_type=mlp_act_type,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped)
+ else:
+ new_single_blocks.append(block)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ assert adapter_idx == total_ref_blocks_needed, (
+ f"[Ref-Block] After single blocks, adapter_idx={adapter_idx}, "
+ f"but total needed is {total_ref_blocks_needed}"
+ )
+ self.use_ref = True
+ print(f"[Ref-Block] Set up ref blocks: {adapter_idx} blocks replaced.")
+
+
+ def enable_refblock_params_grad(self):
+ if hasattr(self, "ref_in"):
+ for p in self.ref_in.parameters():
+ p.requires_grad = True
+
+ for block in self.double_blocks:
+ if hasattr(block, "ref_mlp"):
+ for p in block.ref_mlp.parameters():
+ p.requires_grad = True
+ for p in block.ref_norm.parameters():
+ p.requires_grad = True
+
+ for attr in ["img_attn_qkv", "img_attn_proj", "img_mlp", "img_attn_q_norm", "img_attn_k_norm"]:
+ module = getattr(block, attr, None)
+ if module is not None:
+ for p in module.parameters():
+ p.requires_grad = True
+
+ for block in self.single_blocks:
+ if hasattr(block, "ref_mlp"):
+ for p in block.ref_mlp.parameters():
+ p.requires_grad = True
+ for p in block.ref_norm.parameters():
+ p.requires_grad = True
+
+ for attr in ["linear1", "linear2","q_norm","k_norm"]:
+ module = getattr(block, attr, None)
+ if module is not None:
+ for p in module.parameters():
+ p.requires_grad = True
+ print("[Ref-Block] Enabled grad for selected ref block parameters.")
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+ image_emb = None, # ipadapter image_emb
+ image_latents = None, # image_latents 进入到block
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # import pdb;pdb.set_trace()
+
+ if self.use_ipadapter:
+ if image_emb is None:
+ ValueError(
+ f"image_emb is None, no input for ip-adapter !!!!"
+ )
+ image_emb = self.ipadapter_proj(image_emb)
+
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = image_latents,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ ref = self.ref_in(image_latents)
+
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ ref,
+ text_mask,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ t,
+ image_emb,
+ ref,
+ text_mask,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ ref,
+ img_seq_len,
+ text_mask,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ t,
+ image_emb,
+ ref,
+ img_seq_len,
+ text_mask,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..1213cdc0000f0a6a8440cbddb05ae02b16fdbc65
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor.py
@@ -0,0 +1,1020 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ self.hidden_size = hidden_size
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer_Refextractor(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_refuser = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+ self.controlnet = None
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+ from .refextractor import Refextractor
+ self.refextractor = Refextractor.from_config(refextractor_config).to(weight_dtype)
+
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ controlnet_ref = config.get("controlnet_ref", False)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ if self.controlnet is not None and controlnet_ref:
+ # refextractor的block个数多于controlnet
+ assert len(self.refextractor.double_blocks) >= len(self.controlnet.double_blocks)
+ assert len(self.refextractor.single_blocks) >= len(self.controlnet.single_blocks)
+ self.controlnet.setup_refuser(weight_dtype)
+ self.setup_refuser(weight_dtype)
+
+
+ def setup_refuser(self, weight_dtype):
+ # only set once
+ if self.use_refuser is True:
+ return
+ from .ipablocks import MMSingleStreamBlockReFuser_V2, MMDoubleStreamBlockReFuser_V2
+ if len(self.refextractor.double_blocks) > 0:
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ wrapped = MMDoubleStreamBlockReFuser_V2(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ if len(self.refextractor.single_blocks) > 0:
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ wrapped_sblock = MMSingleStreamBlockReFuser_V2(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ self.use_refuser = True
+
+ def enable_refuser_params_grad(self):
+ if not self.use_refuser:
+ print("[Refuser] Not use Refuser, skip enabling grad.")
+ return
+
+ for block in self.double_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+
+ print("[Refuser] All Refuser params set requires_grad=True.")
+
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+
+ image_latents = None,# ref -> VAE
+ image_emb = None,# 不会用到
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # print("timestep",timestep)
+
+ ot = hidden_states.shape[2]
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, ot, 1, 1)
+ elif image_latents.shape[2] == ot:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == ot:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+
+ ref_block_samples, ref_single_block_samples, ref_freqs_cis = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ embed_cfg_scale = embed_cfg_scale,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = None,
+ ref_block_samples = ref_block_samples,
+ ref_single_block_samples = ref_single_block_samples,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ # import pdb; pdb.set_trace()
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.double_blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # 循环模式
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ ref_latent = None
+ if ref_single_block_samples is not None:
+ interval_ref = len(self.single_blocks) / len(ref_single_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_single_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a74891680c926651b9dc984551713554d9de20f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d.py
@@ -0,0 +1,1019 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+from .utils import ckpt_kwargs
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ self.hidden_size = hidden_size
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer_Refextractor(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_refuser = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+ self.controlnet = None
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+ from .refextractor_2d import Refextractor2D
+ self.refextractor = Refextractor2D.from_config(refextractor_config).to(weight_dtype)
+
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ controlnet_ref = config.get("controlnet_ref", False)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+ # if self.controlnet is not None and controlnet_ref:
+ # # refextractor的block个数多于controlnet
+ # assert len(self.refextractor.double_blocks) >= len(self.controlnet.double_blocks)
+ # assert len(self.refextractor.single_blocks) >= len(self.controlnet.single_blocks)
+ # self.controlnet.setup_refuser(weight_dtype)
+ self.setup_refuser(weight_dtype)
+
+
+ def setup_refuser(self, weight_dtype):
+ # only set once
+ if self.use_refuser is True:
+ return
+ from .ipablocks_v3 import MMSingleStreamBlockReFuser_V3, MMDoubleStreamBlockReFuser_V3
+ if len(self.refextractor.double_blocks) > 0:
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ wrapped = MMDoubleStreamBlockReFuser_V3(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ if len(self.refextractor.single_blocks) > 0:
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ wrapped_sblock = MMSingleStreamBlockReFuser_V3(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ self.use_refuser = True
+
+ def enable_refuser_params_grad(self):
+ if not self.use_refuser:
+ print("[Refuser] Not use Refuser, skip enabling grad.")
+ return
+
+ for block in self.double_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+
+ print("[Refuser] All Refuser params set requires_grad=True.")
+
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+
+ image_latents = None,# ref -> VAE
+ image_emb = None,# 不会用到
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # print("timestep",timestep)
+
+ ot = hidden_states.shape[2]
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, ot, 1, 1)
+ elif image_latents.shape[2] == ot:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == ot:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+
+ ref_block_samples, ref_single_block_samples, ref_freqs_cis = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ embed_cfg_scale = embed_cfg_scale,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = None,
+ ref_block_samples = ref_block_samples,
+ ref_single_block_samples = ref_single_block_samples,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ # import pdb; pdb.set_trace()
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.double_blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # 循环模式
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ ref_latent = None
+ if ref_single_block_samples is not None:
+ interval_ref = len(self.single_blocks) / len(ref_single_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_single_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d_split_q.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d_split_q.py
new file mode 100644
index 0000000000000000000000000000000000000000..737bb19e1db450bb80546fdc17d9380b8cb4ade1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_refextractor_2d_split_q.py
@@ -0,0 +1,1082 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+from .utils import ckpt_kwargs
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ self.hidden_size = hidden_size
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ # split
+ # self.img_attn_q = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
+ # self.img_attn_kv = nn.Linear(hidden_size, hidden_size * 2, bias=qkv_bias, **factory_kwargs)
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+
+ # split
+ # img_q = self.img_attn_q(img_modulated) # (B, L, H*D)
+ # img_q = rearrange(img_q, "B L (H D) -> B L H D",H=self.heads_num)
+ # img_kv = self.img_attn_kv(img_modulated) # (B, L, 2*H*D)
+ # img_k, img_v = rearrange(img_kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+ v = torch.cat((img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # split
+ # self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
+ # self.linear1_kv_mlp = nn.Linear(hidden_size, hidden_size * 2 + mlp_hidden_dim, **factory_kwargs)
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ref_freqs_cis = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # split
+ # q = self.linear1_q(x_mod)
+ # q = rearrange(q, "B L (H D) -> B L H D",H=self.heads_num)
+ # kv_mlp = self.linear1_kv_mlp(x_mod)
+ # kv, mlp = torch.split(kv_mlp, [2 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
+ # k, v = rearrange(kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer_Refextractor(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_refuser = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+ self.controlnet = None
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+ from .refextractor_2d import Refextractor2D
+ self.refextractor = Refextractor2D.from_config(refextractor_config).to(weight_dtype)
+
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ controlnet_ref = config.get("controlnet_ref", False)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+ # if self.controlnet is not None and controlnet_ref:
+ # # refextractor的block个数多于controlnet
+ # assert len(self.refextractor.double_blocks) >= len(self.controlnet.double_blocks)
+ # assert len(self.refextractor.single_blocks) >= len(self.controlnet.single_blocks)
+ # self.controlnet.setup_refuser(weight_dtype)
+ self.setup_refuser(weight_dtype)
+
+
+ def setup_refuser(self, weight_dtype):
+ # only set once
+ if self.use_refuser is True:
+ return
+ from .ipablocks_v3_split_q import MMSingleStreamBlockReFuser_V3, MMDoubleStreamBlockReFuser_V3
+ if len(self.refextractor.double_blocks) > 0:
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ wrapped = MMDoubleStreamBlockReFuser_V3(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ if len(self.refextractor.single_blocks) > 0:
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ wrapped_sblock = MMSingleStreamBlockReFuser_V3(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ self.use_refuser = True
+
+
+ def enable_refuser_params_grad(self):
+ if not self.use_refuser:
+ print("[Refuser] Not use Refuser, skip enabling grad.")
+ return
+
+ for block in self.double_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+
+ print("[Refuser] All Refuser params set requires_grad=True.")
+
+ def load_state_dict(self, state_dict, strict=True):
+ # 直接加载
+ if "img_refuser_q" in state_dict.keys():
+ print("load_directly!!")
+ super().load_state_dict(state_dict, strict=strict)
+ return
+ # 加载原来的ckpt
+ new_state_dict = dict() # 获取当前模型的状态字典
+ for key in state_dict.keys():
+ new_state_dict[key] = state_dict[key]
+
+ if "img_attn_qkv" in key:
+ init_key = key.replace("img_attn_qkv", "img_refuser_q")
+ if init_key in self.state_dict().keys():
+ # init : img_attn_qkv -> img_refuser_q
+ qkv_weight = state_dict[key]
+ hidden_size = self.hidden_size
+ q_weight = qkv_weight[:hidden_size]
+ new_state_dict[init_key] = q_weight
+
+ elif "img_attn_q_norm" in key:
+ init_key = key.replace("img_attn_q_norm", "img_refuser_q_norm")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+ elif "linear1" in key:
+ init_key = key.replace("linear1", "refuser_q")
+ if init_key in self.state_dict().keys():
+ qkv_weight = state_dict[key]
+ hidden_size = self.hidden_size
+ q_weight = qkv_weight[:hidden_size]
+ new_state_dict[init_key] = q_weight
+
+ elif "q_norm" in key:
+ init_key = key.replace("q_norm", "refuser_q_norm")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+ return super().load_state_dict(new_state_dict, strict=strict)
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+
+ image_latents = None,# ref -> VAE
+ image_emb = None,# 不会用到
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # print("timestep",timestep)
+
+ ot = hidden_states.shape[2]
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, ot, 1, 1)
+ elif image_latents.shape[2] == ot:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == ot:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+
+ ref_block_samples, ref_single_block_samples, ref_freqs_cis = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ embed_cfg_scale = embed_cfg_scale,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = None,
+ ref_block_samples = ref_block_samples,
+ ref_single_block_samples = ref_single_block_samples,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ # import pdb; pdb.set_trace()
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.double_blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ img, txt = block(*double_block_args)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # 循环模式
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+
+ # Merge txt and img to pass through single stream blocks.
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ ref_latent = None
+ if ref_single_block_samples is not None:
+ interval_ref = len(self.single_blocks) / len(ref_single_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_single_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ref_freqs_cis,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_reftokenmerge.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_reftokenmerge.py
new file mode 100644
index 0000000000000000000000000000000000000000..6344740abbab2d04bf34868b64eb168f23af140f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_reftokenmerge.py
@@ -0,0 +1,1074 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ self.hidden_size = hidden_size
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ self.txt_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.txt_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.txt_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ self.txt_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.txt_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.txt_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.txt_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ merge_img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ref_latent = None,
+ freqs_cis2d: tuple = None,
+ txt_seq_len = None,
+ img_seq_len = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ merge_img_modulated = self.img_norm1(merge_img)
+ merge_img_modulated = modulate(
+ merge_img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ merge_img_qkv = self.img_attn_qkv(merge_img_modulated)
+ merge_img_q, merge_img_k, merge_img_v = rearrange(
+ merge_img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ merge_img_q = self.img_attn_q_norm(merge_img_q).to(merge_img_v)
+ merge_img_k = self.img_attn_k_norm(merge_img_k).to(merge_img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(merge_img_q[:,:img_seq_len], merge_img_k[:,:img_seq_len], freqs_cis, head_first=False)
+ # assert (
+ # img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ # ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ # Apply 2D RoPE
+ ref_img_qq, ref_img_kk = apply_rotary_emb(merge_img_q[:,img_seq_len:], merge_img_k[:,img_seq_len:], freqs_cis2d, head_first=False)
+ ref_img_q, ref_img_k = ref_img_qq, ref_img_kk
+
+ merge_img_q = torch.cat((img_q, ref_img_q), 1)
+ merge_img_k = torch.cat((img_k, ref_img_k), 1)
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((merge_img_q, txt_q), dim=1)
+ k = torch.cat((merge_img_k, txt_k), dim=1)
+ v = torch.cat((merge_img_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * merge_img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, merge_img.shape[0]:{merge_img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=merge_img_k.shape[0],
+ )
+
+ merge_img_attn, txt_attn = attn[:, : merge_img_k.shape[1]], attn[:, merge_img_k.shape[1] :]
+
+ # Calculate the img bloks.
+ merge_img = merge_img + apply_gate(self.img_attn_proj(merge_img_attn), gate=img_mod1_gate)
+ merge_img = merge_img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(merge_img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return merge_img, txt
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ref_latent = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformer_Tokenmerge(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ self.use_refuser = False
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # for ref img projection
+ self.refimg_in = PatchEmbed(
+ self.patch_size, self.in_channels // 2, self.hidden_size, **factory_kwargs
+ ) if self.in_channels == 32 else None
+
+ # text projection
+ if self.text_projection == "linear":
+ self.txt_in = TextProjection(
+ self.text_states_dim,
+ self.hidden_size,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ elif self.text_projection == "single_refiner":
+ self.txt_in = SingleTokenRefiner(
+ self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ )
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+ self.controlnet = None
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import HYVideoDiffusionTransformerControlNet
+ self.controlnet = HYVideoDiffusionTransformerControlNet.from_config(controlnet_config).to(weight_dtype)
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+ return
+ # from .refextractor import Refextractor
+ # self.refextractor = Refextractor.from_config(refextractor_config).to(weight_dtype)
+
+ # import json
+ # with open(refextractor_config, "r") as f:
+ # config = json.load(f)
+ # controlnet_ref = config.get("controlnet_ref", False)
+ # if self.controlnet is not None and controlnet_ref:
+ # # refextractor的block个数多于controlnet
+ # assert len(self.refextractor.double_blocks) >= len(self.controlnet.double_blocks)
+ # assert len(self.refextractor.single_blocks) >= len(self.controlnet.single_blocks)
+ # self.controlnet.setup_refuser(weight_dtype)
+ # self.setup_refuser(weight_dtype)
+
+
+ def setup_refuser(self, weight_dtype):
+ # only set once
+ if self.use_refuser is True:
+ return
+ from .ipablocks import MMSingleStreamBlockReFuser, MMDoubleStreamBlockReFuser
+ if len(self.refextractor.double_blocks) > 0:
+ # ---- double_blocks ----
+ new_double_blocks = []
+ for i, block in enumerate(self.double_blocks):
+ wrapped = MMDoubleStreamBlockReFuser(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_double_blocks.append(wrapped)
+ self.double_blocks = nn.ModuleList(new_double_blocks)
+
+ if len(self.refextractor.single_blocks) > 0:
+ new_single_blocks = []
+ for i, block in enumerate(self.single_blocks):
+ wrapped_sblock = MMSingleStreamBlockReFuser(
+ original_block=block,
+ ).to(dtype=weight_dtype)
+ new_single_blocks.append(wrapped_sblock)
+ self.single_blocks = nn.ModuleList(new_single_blocks)
+ self.use_refuser = True
+
+ def enable_refuser_params_grad(self):
+ if not self.use_refuser:
+ print("[Refuser] Not use Refuser, skip enabling grad.")
+ return
+
+ for block in self.double_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+ for block in self.single_blocks:
+ if hasattr(block, 'refuser') and block.refuser is not None:
+ for p in block.refuser.parameters():
+ p.requires_grad = True
+
+ print("[Refuser] All Refuser params set requires_grad=True.")
+
+
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ embed_cfg_scale,
+ controlnet_cond,
+ conditioning_scale = 1.0,
+ return_dict = True,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ controlnet_blocks_repeat = False,
+
+ image_latents = None,# ref -> VAE
+ image_emb = None,# 不会用到
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # print("timestep",timestep)
+
+ # 3.25 here
+ # single image_latents
+ ot = hidden_states.shape[2]
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == ot:
+ image_latents = image_latents[:,:,:1,:,:]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+
+ ref_block_samples, ref_single_block_samples = None, None
+ # ref_block_samples, ref_single_block_samples = self.refextractor(
+ # hidden_states = image_latents,
+ # timestep = timestep,
+ # embed_cfg_scale = embed_cfg_scale,
+ # return_dict = False
+ # # 目前不会用到的txt部分
+ # )
+
+ if conditioning_scale > 0:
+ controlnet_block_samples, controlnet_single_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_attention_mask = encoder_attention_mask,
+ embed_cfg_scale = embed_cfg_scale,
+ controlnet_cond = controlnet_cond,
+ conditioning_scale = conditioning_scale, #训练的时候应该固定为1.0
+ return_dict=False,
+ image_latents = None,
+ ref_block_samples = ref_block_samples,
+ ref_single_block_samples = ref_single_block_samples,
+ )
+
+ lora_scale = 1.0 #TODO: 作为参数传入
+
+ x = hidden_states
+ t = timestep
+ text_states, text_states_2 = encoder_hidden_states
+ text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ freqs_cos_2d, freqs_sin_2d = self.get_2d_rotary_pos_embed(oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ ref_img = self.refimg_in(image_latents) if self.refimg_in is not None else self.img_in(image_latents)
+ if self.text_projection == "linear":
+ txt = self.txt_in(txt)
+ elif self.text_projection == "single_refiner":
+ txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ else:
+ raise NotImplementedError(
+ f"Unsupported text_projection: {self.text_projection}"
+ )
+
+ txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ merge_img = torch.cat((img, ref_img), 1)
+
+ merge_img_seq_len = merge_img.shape[1]
+ # Compute cu_squlens and max_seqlen for flash attention
+
+ # double block merge img token
+ cu_seqlens_q = get_cu_seqlens(text_mask, merge_img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = merge_img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+ freqs_cis2d = (freqs_cos_2d, freqs_sin_2d)
+
+
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.double_blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ merge_img, txt = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ merge_img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ freqs_cis2d,
+ txt_seq_len,
+ img_seq_len,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ merge_img,
+ txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ref_latent,
+ freqs_cis2d,
+ txt_seq_len,
+ img_seq_len,
+ ]
+
+ merge_img, txt = block(*double_block_args)
+
+ img = merge_img[:, :img_seq_len, :]
+ ref_img = merge_img[:, img_seq_len:, :]
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.double_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # 循环模式
+ if controlnet_blocks_repeat:
+ img = (
+ img + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ img = img + controlnet_block_samples[index_block // interval_control]
+ merge_img = torch.cat((img, ref_img), 1)
+
+ # single block
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len + txt_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ # Merge txt and img to pass through single stream blocks.
+ img = merge_img[:, :img_seq_len, :]
+
+ x = torch.cat((img, txt), 1)
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ ref_latent = None
+ if ref_single_block_samples is not None:
+ interval_ref = len(self.single_blocks) / len(ref_single_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_single_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ txt_seq_len,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ref_latent,
+ ]
+
+ x = block(*single_block_args)
+
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ x[:, :img.shape[1], ...] = (
+ x[:, :img.shape[1], ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ img = x[:, :img_seq_len, ...]
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if USE_PEFT_BACKEND:
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def get_2d_rotary_pos_embed(self, height, width):
+ target_ndim = 2
+ ndim = 2
+ latents_size = [height, width]
+
+
+ if isinstance(self.config.patch_size, list):
+ assert len(self.config.patch_size) == 3, "3D patch_size should be a list of length 3 [t, h, w]."
+ patch_size_h, patch_size_w = self.config.patch_size[1], self.config.patch_size[2]
+
+ assert height % patch_size_h == 0 and width % patch_size_w == 0, (
+ f"Height ({height}) and width ({width}) must be divisible by patch_size [{patch_size_h}, {patch_size_w}]."
+ )
+ rope_sizes = [height // patch_size_h, width // patch_size_w]
+ else:
+ raise ValueError(f"patch_size should be a list")
+
+
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_h = rope_dim_w = head_dim // 2 # 各占一半
+
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ [rope_dim_h, rope_dim_w],
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_textfree.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_textfree.py
new file mode 100644
index 0000000000000000000000000000000000000000..54201aeb6ee1afb7d19808568380ffd37b1cb6ba
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/models_textfree.py
@@ -0,0 +1,884 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from opensora.controlnet_modules.controlnet import zero_module
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens, get_cu_seqlens_wotxt
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+from dataclasses import dataclass
+
+
+
+# TxT Free!!
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ # self.txt_mod = ModulateDiT(
+ # hidden_size,
+ # factor=6,
+ # act_layer=get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # self.txt_norm1 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+
+ # self.txt_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ # self.txt_attn_q_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_k_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_proj = nn.Linear(
+ # hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ # )
+
+ # self.txt_norm2 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+ # self.txt_mlp = MLP(
+ # hidden_size,
+ # mlp_hidden_dim,
+ # act_layer=get_activation_layer(mlp_act_type),
+ # bias=True,
+ # **factory_kwargs,
+ # )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ # txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ # (
+ # txt_mod1_shift,
+ # txt_mod1_scale,
+ # txt_mod1_gate,
+ # txt_mod2_shift,
+ # txt_mod2_scale,
+ # txt_mod2_gate,
+ # ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ # txt_modulated = self.txt_norm1(txt)
+ # txt_modulated = modulate(
+ # txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ # )
+ # txt_qkv = self.txt_attn_qkv(txt_modulated)
+ # txt_q, txt_k, txt_v = rearrange(
+ # txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ # # Apply QK-Norm if needed.
+ # txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ # txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ # v = torch.cat((img_v, txt_v), dim=1)
+ q = img_q
+ k = img_k
+ v = img_v
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ # img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+ img_attn = attn
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ # txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ # txt = txt + apply_gate(
+ # self.txt_mlp(
+ # modulate(
+ # self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ # )
+ # ),
+ # gate=txt_mod2_gate,
+ # )
+
+ # return img, txt
+ return img
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ # if freqs_cis is not None:
+ # img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ # img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ # img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ # assert (
+ # img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ # ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ # img_q, img_k = img_qq, img_kk
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ if freqs_cis is not None:
+ img_q = q
+ img_k = k
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ q, k = img_qq, img_kk
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class Refextractor(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ # if self.text_projection == "linear":
+ # self.txt_in = TextProjection(
+ # self.text_states_dim,
+ # self.hidden_size,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # elif self.text_projection == "single_refiner":
+ # self.txt_in = SingleTokenRefiner(
+ # self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ # )
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def forward(self,
+ hidden_states,
+ timestep,
+ embed_cfg_scale,
+ encoder_hidden_states = None,
+ encoder_attention_mask = None,
+ return_dict = True,
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ lora_scale = 1.0
+
+ x = hidden_states
+ t = timestep
+ # text_states, text_states_2 = encoder_hidden_states
+ # text_mask, test_mask_2 = encoder_attention_mask
+
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ # out = {}
+ img = x
+ # txt = text_states
+ _, _, ot, oh, ow = x.shape
+ # ref img的t一定是1,考虑后面改成2d rope
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ # vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # if self.text_projection == "linear":
+ # txt = self.txt_in(txt)
+ # elif self.text_projection == "single_refiner":
+ # txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ # cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_q = get_cu_seqlens_wotxt(img, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ block_samples = ()
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+
+ block_samples = block_samples + (img, )
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": True} if is_torch_version(">=", "1.11.0") else {}
+ img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ]
+
+ img = block(*double_block_args)
+
+
+ # Merge txt and img to pass through single stream blocks.
+ # x = torch.cat((img, txt), 1)
+ x = img
+ single_block_samples = ()
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ single_block_samples = single_block_samples + (x,)
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": True} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ]
+
+ x = block(*single_block_args)
+
+ ref_block_samples = ()
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ ref_single_block_samples = ()
+ for single_block_sample, ref_block in zip(single_block_samples, self.ref_single_blocks):
+ single_block_sample = ref_block(single_block_sample)
+ ref_single_block_samples = ref_single_block_samples + (single_block_sample,)
+
+ ref_block_samples = None if len(ref_block_samples) == 0 else ref_block_samples
+ ref_single_block_samples = (
+ None if len(ref_single_block_samples) == 0 else ref_single_block_samples
+ )
+
+
+ if not return_dict:
+ return (ref_block_samples, ref_single_block_samples)
+ return RefextractorOutput(
+ ref_block_samples=ref_block_samples,
+ ref_single_block_samples=ref_single_block_samples,
+ )
+
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/modulate_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/modulate_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..93a57c6d2fdc0fca9bf44aeee6996bf1d8a05901
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/modulate_layers.py
@@ -0,0 +1,76 @@
+from typing import Callable
+
+import torch
+import torch.nn as nn
+
+
+class ModulateDiT(nn.Module):
+ """Modulation layer for DiT."""
+ def __init__(
+ self,
+ hidden_size: int,
+ factor: int,
+ act_layer: Callable,
+ dtype=None,
+ device=None,
+ ):
+ factory_kwargs = {"dtype": dtype, "device": device}
+ super().__init__()
+ self.act = act_layer()
+ self.linear = nn.Linear(
+ hidden_size, factor * hidden_size, bias=True, **factory_kwargs
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.linear.weight)
+ nn.init.zeros_(self.linear.bias)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ return self.linear(self.act(x))
+
+
+def modulate(x, shift=None, scale=None):
+ """modulate by shift and scale
+
+ Args:
+ x (torch.Tensor): input tensor.
+ shift (torch.Tensor, optional): shift tensor. Defaults to None.
+ scale (torch.Tensor, optional): scale tensor. Defaults to None.
+
+ Returns:
+ torch.Tensor: the output tensor after modulate.
+ """
+ if scale is None and shift is None:
+ return x
+ elif shift is None:
+ return x * (1 + scale.unsqueeze(1))
+ elif scale is None:
+ return x + shift.unsqueeze(1)
+ else:
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
+
+
+def apply_gate(x, gate=None, tanh=False):
+ """AI is creating summary for apply_gate
+
+ Args:
+ x (torch.Tensor): input tensor.
+ gate (torch.Tensor, optional): gate tensor. Defaults to None.
+ tanh (bool, optional): whether to use tanh function. Defaults to False.
+
+ Returns:
+ torch.Tensor: the output tensor after apply gate.
+ """
+ if gate is None:
+ return x
+ if tanh:
+ return x * gate.unsqueeze(1).tanh()
+ else:
+ return x * gate.unsqueeze(1)
+
+
+def ckpt_wrapper(module):
+ def ckpt_forward(*inputs):
+ outputs = module(*inputs)
+ return outputs
+
+ return ckpt_forward
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/norm_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/norm_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c73b1aef6b7b8ca4767c26c4f0bbc0365a122f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/norm_layers.py
@@ -0,0 +1,77 @@
+import torch
+import torch.nn as nn
+
+
+class RMSNorm(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ elementwise_affine=True,
+ eps: float = 1e-6,
+ device=None,
+ dtype=None,
+ ):
+ """
+ Initialize the RMSNorm normalization layer.
+
+ Args:
+ dim (int): The dimension of the input tensor.
+ eps (float, optional): A small value added to the denominator for numerical stability. Default is 1e-6.
+
+ Attributes:
+ eps (float): A small value added to the denominator for numerical stability.
+ weight (nn.Parameter): Learnable scaling parameter.
+
+ """
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.eps = eps
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim, **factory_kwargs))
+
+ def _norm(self, x):
+ """
+ Apply the RMSNorm normalization to the input tensor.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The normalized tensor.
+
+ """
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
+
+ def forward(self, x):
+ """
+ Forward pass through the RMSNorm layer.
+
+ Args:
+ x (torch.Tensor): The input tensor.
+
+ Returns:
+ torch.Tensor: The output tensor after applying RMSNorm.
+
+ """
+ output = self._norm(x.float()).type_as(x)
+ if hasattr(self, "weight"):
+ output = output * self.weight
+ return output
+
+
+def get_norm_layer(norm_layer):
+ """
+ Get the normalization layer.
+
+ Args:
+ norm_layer (str): The type of normalization layer.
+
+ Returns:
+ norm_layer (nn.Module): The normalization layer.
+ """
+ if norm_layer == "layer":
+ return nn.LayerNorm
+ elif norm_layer == "rms":
+ return RMSNorm
+ else:
+ raise NotImplementedError(f"Norm layer {norm_layer} is not implemented")
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/posemb_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/posemb_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..198d9ea26c9cf71eb98b7df9e2eece2777ea4b91
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/posemb_layers.py
@@ -0,0 +1,417 @@
+import torch
+from typing import Union, Tuple, List
+
+
+def _to_tuple(x, dim=2):
+ if isinstance(x, int):
+ return (x,) * dim
+ elif len(x) == dim:
+ return x
+ else:
+ raise ValueError(f"Expected length {dim} or int, but got {x}")
+
+
+def get_meshgrid_nd(start, *args, dim=2):
+ """
+ Get n-D meshgrid with start, stop and num.
+
+ Args:
+ start (int or tuple): If len(args) == 0, start is num; If len(args) == 1, start is start, args[0] is stop,
+ step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num. For n-dim, start/stop/num
+ should be int or n-tuple. If n-tuple is provided, the meshgrid will be stacked following the dim order in
+ n-tuples.
+ *args: See above.
+ dim (int): Dimension of the meshgrid. Defaults to 2.
+
+ Returns:
+ grid (np.ndarray): [dim, ...]
+ """
+ # print("args",len(args),args)
+ if len(args) == 0:
+ # start is grid_size
+ num = _to_tuple(start, dim=dim)
+ start = (0,) * dim
+ stop = num
+ elif len(args) == 1:
+ # start is start, args[0] is stop, step is 1
+ start = _to_tuple(start, dim=dim)
+ stop = _to_tuple(args[0], dim=dim)
+ num = [stop[i] - start[i] for i in range(dim)]
+ elif len(args) == 2:
+ # start is start, args[0] is stop, args[1] is num
+ start = _to_tuple(start, dim=dim) # Left-Top eg: 12,0
+ stop = _to_tuple(args[0], dim=dim) # Right-Bottom eg: 20,32
+ num = _to_tuple(args[1], dim=dim) # Target Size eg: 32,124
+ else:
+ raise ValueError(f"len(args) should be 0, 1 or 2, but got {len(args)}")
+
+ # PyTorch implement of np.linspace(start[i], stop[i], num[i], endpoint=False)
+ axis_grid = []
+ for i in range(dim):
+ a, b, n = start[i], stop[i], num[i]
+ g = torch.linspace(a, b, n + 1, dtype=torch.float32)[:n]
+ axis_grid.append(g)
+ grid = torch.meshgrid(*axis_grid, indexing="ij") # dim x [W, H, D]
+ grid = torch.stack(grid, dim=0) # [dim, W, H, D]
+
+ return grid
+
+
+#################################################################################
+# Rotary Positional Embedding Functions #
+#################################################################################
+# https://github.com/meta-llama/llama/blob/be327c427cc5e89cc1d3ab3d3fec4484df771245/llama/model.py#L80
+
+
+def reshape_for_broadcast(
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
+ x: torch.Tensor,
+ head_first=False,
+):
+ """
+ Reshape frequency tensor for broadcasting it with another tensor.
+
+ This function reshapes the frequency tensor to have the same shape as the target tensor 'x'
+ for the purpose of broadcasting the frequency tensor during element-wise operations.
+
+ Notes:
+ When using FlashMHAModified, head_first should be False.
+ When using Attention, head_first should be True.
+
+ Args:
+ freqs_cis (Union[torch.Tensor, Tuple[torch.Tensor]]): Frequency tensor to be reshaped.
+ x (torch.Tensor): Target tensor for broadcasting compatibility.
+ head_first (bool): head dimension first (except batch dim) or not.
+
+ Returns:
+ torch.Tensor: Reshaped frequency tensor.
+
+ Raises:
+ AssertionError: If the frequency tensor doesn't match the expected shape.
+ AssertionError: If the target tensor 'x' doesn't have the expected number of dimensions.
+ """
+ ndim = x.ndim
+ assert 0 <= 1 < ndim
+
+ if isinstance(freqs_cis, tuple):
+ # freqs_cis: (cos, sin) in real space
+ if head_first:
+ assert freqs_cis[0].shape == (
+ x.shape[-2],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
+ shape = [
+ d if i == ndim - 2 or i == ndim - 1 else 1
+ for i, d in enumerate(x.shape)
+ ]
+ else:
+ assert freqs_cis[0].shape == (
+ x.shape[1],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis[0].shape} does not match x shape {x.shape}"
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
+ return freqs_cis[0].view(*shape), freqs_cis[1].view(*shape)
+ else:
+ # freqs_cis: values in complex space
+ if head_first:
+ assert freqs_cis.shape == (
+ x.shape[-2],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
+ shape = [
+ d if i == ndim - 2 or i == ndim - 1 else 1
+ for i, d in enumerate(x.shape)
+ ]
+ else:
+ assert freqs_cis.shape == (
+ x.shape[1],
+ x.shape[-1],
+ ), f"freqs_cis shape {freqs_cis.shape} does not match x shape {x.shape}"
+ shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
+ return freqs_cis.view(*shape)
+
+
+def rotate_half(x):
+ x_real, x_imag = (
+ x.float().reshape(*x.shape[:-1], -1, 2).unbind(-1)
+ ) # [B, S, H, D//2]
+ return torch.stack([-x_imag, x_real], dim=-1).flatten(3)
+
+
+def apply_rotary_emb(
+ xq: torch.Tensor,
+ xk: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ head_first: bool = False,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor.
+
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
+ frequency tensor 'freqs_cis'. The input tensors are reshaped as complex numbers, and the frequency tensor
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
+ returned as real tensors.
+
+ Args:
+ xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D]
+ xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D]
+ freqs_cis (torch.Tensor or tuple): Precomputed frequency tensor for complex exponential.
+ head_first (bool): head dimension first (except batch dim) or not.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+
+ """
+ xk_out = None
+ if isinstance(freqs_cis, tuple):
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
+ # real * cos - imag * sin
+ # imag * cos + real * sin
+ xq_out = (xq.float() * cos + rotate_half(xq.float()) * sin).type_as(xq)
+ xk_out = (xk.float() * cos + rotate_half(xk.float()) * sin).type_as(xk)
+ else:
+ # view_as_complex will pack [..., D/2, 2](real) to [..., D/2](complex)
+ xq_ = torch.view_as_complex(
+ xq.float().reshape(*xq.shape[:-1], -1, 2)
+ ) # [B, S, H, D//2]
+ freqs_cis = reshape_for_broadcast(freqs_cis, xq_, head_first).to(
+ xq.device
+ ) # [S, D//2] --> [1, S, 1, D//2]
+ # (real, imag) * (cos, sin) = (real * cos - imag * sin, imag * cos + real * sin)
+ # view_as_real will expand [..., D/2](complex) to [..., D/2, 2](real)
+ xq_out = torch.view_as_real(xq_ * freqs_cis).flatten(3).type_as(xq)
+ xk_ = torch.view_as_complex(
+ xk.float().reshape(*xk.shape[:-1], -1, 2)
+ ) # [B, S, H, D//2]
+ xk_out = torch.view_as_real(xk_ * freqs_cis).flatten(3).type_as(xk)
+
+ return xq_out, xk_out
+
+# 使用q的freqs_cis,对k做截断
+def apply_rotary_emb_k(
+ xq: torch.Tensor,
+ xk: torch.Tensor,
+ freqs_cis_q: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ head_first: bool = False,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor.
+
+ This function applies rotary embeddings to the given query 'xq' and key 'xk' tensors using the provided
+ frequency tensor 'freqs_cis_q'. The input tensors are reshaped as complex numbers, and the frequency tensor
+ is reshaped for broadcasting compatibility. The resulting tensors contain rotary embeddings and are
+ returned as real tensors.
+
+ Args:
+ xq (torch.Tensor): Query tensor to apply rotary embeddings. [B, S, H, D]
+ xk (torch.Tensor): Key tensor to apply rotary embeddings. [B, S, H, D]
+ freqs_cis_q (torch.Tensor or tuple): Precomputed frequency tensor for complex exponential.
+ head_first (bool): head dimension first (except batch dim) or not.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+
+ """
+ # import pdb ; pdb.set_trace()
+ freqs_cis = freqs_cis_q
+ xk_out = None
+ if isinstance(freqs_cis, tuple):
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first) # [S, D]
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
+ # real * cos - imag * sin
+ # imag * cos + real * sin
+ xk_out = (xk.float() * cos[:, :xk.shape[1], :, :] + rotate_half(xk.float()) * sin[:, :xk.shape[1], :, :]).type_as(xk)
+ else:
+ raise ValueError("freqs_cis should be tuple")
+ return xk_out
+
+
+def apply_rotary_emb_ignore_t(
+ xq: torch.Tensor,
+ xk: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ head_first: bool = False,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors, but ignore rotation along t-axis.
+
+ Args:
+ xq (torch.Tensor): (B, S, H, D)
+ xk (torch.Tensor): (B, S, H, D)
+ freqs_cis (Union[Tensor, Tuple]): (cos, sin) pair or complex tensor
+ rope_dim_list (List[int]): rope dims for each axis (e.g., [t, h, w])
+ head_first (bool): Whether head dim is before or after sequence dim
+ Returns:
+ xq_out, xk_out: tensors after applying rotary embeddings
+ """
+ if isinstance(freqs_cis, tuple):
+ cos, sin = reshape_for_broadcast(freqs_cis, xq, head_first)
+ cos, sin = cos.to(xq.device), sin.to(xq.device)
+ # Create a mask for the time dimension (t-axis)
+ d_t = 16 # For example, adjust this value based on your case
+ mask_cos = cos.clone()
+ mask_sin = sin.clone()
+
+ # Set the time dimension to 1 (cos) and 0 (sin) for ignoring t-axis
+ mask_cos[..., :d_t] = 1.0
+ mask_sin[..., :d_t] = 0.0
+
+ # Apply the modified masks for the rotary embeddings
+ xq_out = (xq.float() * mask_cos + rotate_half(xq.float()) * mask_sin).type_as(xq)
+ xk_out = (xk.float() * mask_cos + rotate_half(xk.float()) * mask_sin).type_as(xk)
+
+ # Apply the modified masks for the rotary embeddings
+ xq_out = (xq.float() * mask_cos + rotate_half(xq.float()) * mask_sin).type_as(xq)
+ xk_out = (xk.float() * mask_cos + rotate_half(xk.float()) * mask_sin).type_as(xk)
+
+ return xq_out, xk_out
+
+
+def apply_rotary_emb_single_ignore_t(
+ x: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]],
+ head_first: bool = False,
+) -> torch.Tensor:
+ # import pdb ; pdb.set_trace()
+ if isinstance(freqs_cis, tuple):
+ cos, sin = reshape_for_broadcast(freqs_cis, x, head_first) # [S, D]
+ cos, sin = cos.to(x.device), sin.to(x.device)
+ # Create a mask for the time dimension (t-axis)
+ d_t = 16 # For example, adjust this value based on your case
+ mask_cos = cos.clone()
+ mask_sin = sin.clone()
+
+ # Set the time dimension to 1 (cos) and 0 (sin) for ignoring t-axis
+ mask_cos[..., :d_t] = 1.0
+ mask_sin[..., :d_t] = 0.0
+
+ # Apply the modified masks for the rotary embeddings
+ x_out = (x.float() * mask_cos + rotate_half(x.float()) * mask_sin).type_as(x)
+ else:
+ raise ValueError("freqs_cis should be tuple")
+
+
+ return x_out
+
+
+def get_nd_rotary_pos_embed(
+ rope_dim_list,
+ start,
+ *args,
+ theta=10000.0,
+ use_real=False,
+ theta_rescale_factor: Union[float, List[float]] = 1.0,
+ interpolation_factor: Union[float, List[float]] = 1.0,
+):
+ """
+ This is a n-d version of precompute_freqs_cis, which is a RoPE for tokens with n-d structure.
+
+ Args:
+ rope_dim_list (list of int): Dimension of each rope. len(rope_dim_list) should equal to n.
+ sum(rope_dim_list) should equal to head_dim of attention layer.
+ start (int | tuple of int | list of int): If len(args) == 0, start is num; If len(args) == 1, start is start,
+ args[0] is stop, step is 1; If len(args) == 2, start is start, args[0] is stop, args[1] is num.
+ *args: See above.
+ theta (float): Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (bool): If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+ Some libraries such as TensorRT does not support complex64 data type. So it is useful to provide a real
+ part and an imaginary part separately.
+ theta_rescale_factor (float): Rescale factor for theta. Defaults to 1.0.
+
+ Returns:
+ pos_embed (torch.Tensor): [HW, D/2]
+ """
+
+ grid = get_meshgrid_nd(
+ start, *args, dim=len(rope_dim_list)
+ ) # [3, W, H, D] / [2, W, H]
+
+ if isinstance(theta_rescale_factor, int) or isinstance(theta_rescale_factor, float):
+ theta_rescale_factor = [theta_rescale_factor] * len(rope_dim_list)
+ elif isinstance(theta_rescale_factor, list) and len(theta_rescale_factor) == 1:
+ theta_rescale_factor = [theta_rescale_factor[0]] * len(rope_dim_list)
+ assert len(theta_rescale_factor) == len(
+ rope_dim_list
+ ), "len(theta_rescale_factor) should equal to len(rope_dim_list)"
+
+ if isinstance(interpolation_factor, int) or isinstance(interpolation_factor, float):
+ interpolation_factor = [interpolation_factor] * len(rope_dim_list)
+ elif isinstance(interpolation_factor, list) and len(interpolation_factor) == 1:
+ interpolation_factor = [interpolation_factor[0]] * len(rope_dim_list)
+ assert len(interpolation_factor) == len(
+ rope_dim_list
+ ), "len(interpolation_factor) should equal to len(rope_dim_list)"
+
+ # use 1/ndim of dimensions to encode grid_axis
+ embs = []
+ for i in range(len(rope_dim_list)):
+ emb = get_1d_rotary_pos_embed(
+ rope_dim_list[i],
+ grid[i].reshape(-1),
+ theta,
+ use_real=use_real,
+ theta_rescale_factor=theta_rescale_factor[i],
+ interpolation_factor=interpolation_factor[i],
+ ) # 2 x [WHD, rope_dim_list[i]]
+ embs.append(emb)
+
+ if use_real:
+ cos = torch.cat([emb[0] for emb in embs], dim=1) # (WHD, D/2)
+ sin = torch.cat([emb[1] for emb in embs], dim=1) # (WHD, D/2)
+ return cos, sin
+ else:
+ emb = torch.cat(embs, dim=1) # (WHD, D/2)
+ return emb
+
+
+def get_1d_rotary_pos_embed(
+ dim: int,
+ pos: Union[torch.FloatTensor, int],
+ theta: float = 10000.0,
+ use_real: bool = False,
+ theta_rescale_factor: float = 1.0,
+ interpolation_factor: float = 1.0,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ """
+ Precompute the frequency tensor for complex exponential (cis) with given dimensions.
+ (Note: `cis` means `cos + i * sin`, where i is the imaginary unit.)
+
+ This function calculates a frequency tensor with complex exponential using the given dimension 'dim'
+ and the end index 'end'. The 'theta' parameter scales the frequencies.
+ The returned tensor contains complex values in complex64 data type.
+
+ Args:
+ dim (int): Dimension of the frequency tensor.
+ pos (int or torch.FloatTensor): Position indices for the frequency tensor. [S] or scalar
+ theta (float, optional): Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (bool, optional): If True, return real part and imaginary part separately.
+ Otherwise, return complex numbers.
+ theta_rescale_factor (float, optional): Rescale factor for theta. Defaults to 1.0.
+
+ Returns:
+ freqs_cis: Precomputed frequency tensor with complex exponential. [S, D/2]
+ freqs_cos, freqs_sin: Precomputed frequency tensor with real and imaginary parts separately. [S, D]
+ """
+ if isinstance(pos, int):
+ pos = torch.arange(pos).float()
+
+ # proposed by reddit user bloc97, to rescale rotary embeddings to longer sequence length without fine-tuning
+ # has some connection to NTK literature
+ if theta_rescale_factor != 1.0:
+ theta *= theta_rescale_factor ** (dim / (dim - 2))
+
+ freqs = 1.0 / (
+ theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim)
+ ) # [D/2]
+ # assert interpolation_factor == 1.0, f"interpolation_factor: {interpolation_factor}"
+ freqs = torch.outer(pos * interpolation_factor, freqs) # [S, D/2]
+ if use_real:
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1) # [S, D]
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1) # [S, D]
+ return freqs_cos, freqs_sin
+ else:
+ freqs_cis = torch.polar(
+ torch.ones_like(freqs), freqs
+ ) # complex64 # [S, D/2]
+ return freqs_cis
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refblocks.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refblocks.py
new file mode 100644
index 0000000000000000000000000000000000000000..edf62474a2891aa13508b82a4a0447652f16ee35
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refblocks.py
@@ -0,0 +1,693 @@
+import torch
+import torch.nn as nn
+from typing import Tuple, Optional
+from einops import rearrange
+
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .attenion import attention, get_cu_seqlens
+from .ipadapter import HYVideoAttnProcessor2_0
+from .mlp_layers import MLP
+from .activation_layers import get_activation_layer
+class MMDoubleStreamBlockRef(nn.Module):
+
+ def __init__(
+ self,
+ original_block: nn.Module,
+ hidden_size: int,
+ mlp_act_type: str = "gelu_tanh",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+
+ ):
+ super().__init__()
+ factory_kwargs = {"device": device, "dtype": dtype}
+ self.ref_mlp = MLP(
+ hidden_size,
+ hidden_size,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+ self.ref_norm = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_emb = None,
+ ref = None,
+ text_mask = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ img_len = img.shape[1]
+ txt_len = txt.shape[1]
+ ref_len = ref.shape[1]
+
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_len + ref_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_len + ref_len + txt_len
+ max_seqlen_kv = max_seqlen_q
+
+ assert ref is not None, "ref not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ # add ref here
+ ref = self.ref_mlp(ref)
+ ref = self.ref_norm(ref)
+
+ img_branch_input = torch.cat([img_modulated, ref], dim=1)
+ img_ref_qkv = self.img_attn_qkv(img_branch_input)# [B, L, 3 * hidden_size]
+ img_ref_q, img_ref_k, img_ref_v = rearrange(
+ img_ref_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_ref_q = self.img_attn_q_norm(img_ref_q).to(img_ref_v)
+ img_ref_k = self.img_attn_k_norm(img_ref_k).to(img_ref_v)
+
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, ref_q = img_ref_q[:, :img_len, :, :], img_ref_q[:, img_len:, :, :]
+ img_k, ref_k = img_ref_k[:, :img_len, :, :], img_ref_k[:, img_len:, :, :]
+
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ img_ref_q = torch.cat([img_q, ref_q],dim=1)
+ img_ref_k = torch.cat([img_k, ref_k],dim=1)
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_ref_q, txt_q), dim=1)
+ k = torch.cat((img_ref_k, txt_k), dim=1)
+ v = torch.cat((img_ref_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ img_attn, txt_attn = attn[:, : img_len], attn[:, img_len+ref_len :]
+
+ # # ----------------------------------------------------------------
+ # # add IP-Adapter for img_attn
+ # # ----------------------------------------------------------------
+ # # IP-Adapter (num_heads, query, image_emb, t)
+ # # - query: img_q (shape [B, L, H, D]) instead of img_attn q
+ # # IP-Adapter attention need [B, H, L, D]
+ # # - image_emb: shape [B, tokens, hidden_size]
+ # # - t: timestep
+ # # ----------------------------------------------------------------
+
+ # # img_q => [B, H, L, D]
+ # img_q_for_ip = img_q.transpose(1, 2)
+
+ # ip_hidden_states = self.ip_adapter(
+ # num_heads=self.heads_num,
+ # query=img_q_for_ip,
+ # image_emb=image_emb,
+ # t=t,
+ # )
+ # if ip_hidden_states is not None:
+ # # [B, L, hidden_size]
+ # img_attn = img_attn + self.ipadapter_scale * ip_hidden_states
+ # # ----------------------------------------------------------------
+ # # finish IP-Adapter
+ # # ----------------------------------------------------------------
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockRef(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ hidden_size: int,
+ mlp_act_type: str = "gelu_tanh",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+
+ ):
+ super().__init__()
+ factory_kwargs = {"device": device, "dtype": dtype}
+ self.ref_mlp = MLP(
+ hidden_size,
+ hidden_size,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+ self.ref_norm = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None, # <-- timestep
+ image_emb = None,
+ ref = None,
+ img_len = None,
+ text_mask = None,
+ ) -> torch.Tensor:
+ assert ref is not None, "ref not be None"
+
+ ref_len = ref.shape[1]
+
+ cu_seqlens_q = get_cu_seqlens(text_mask, img_len + ref_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_len + ref_len + txt_len
+ max_seqlen_kv = max_seqlen_q
+
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+
+ # add ref here
+ # ref_len = ref.shape[1]
+ ref = self.ref_mlp(ref)
+ ref = self.ref_norm(ref)
+ x_mod = torch.cat([x_mod[:,:img_len],ref,x_mod[:,img_len:]],dim=1)
+
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, ref_q, txt_q, = q[:, :img_len, :, :], q[:, img_len:img_len+ref_len, :, :], q[:, img_len+ref_len:, :, :]
+ img_k, ref_k, txt_k, = k[:, :img_len, :, :], k[:, img_len:img_len+ref_len, :, :], k[:, img_len+ref_len:, :, :]
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat([img_q, ref_q, txt_q], dim=1)
+ k = torch.cat([img_k, ref_k, txt_k], dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+ attn = torch.cat([attn[:, : img_len],attn[:, img_len+ref_len :]],dim=1)
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ mlp = torch.cat([mlp[:, : img_len],mlp[:, img_len+ref_len :]],dim=1)
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+
+
+# ================================================
+
+# K V only
+
+# ================================================
+
+
+# Q not include ref
+class MMDoubleStreamBlockRefKVOnly(nn.Module):
+
+ def __init__(
+ self,
+ original_block: nn.Module,
+ hidden_size: int,
+ mlp_act_type: str = "gelu_tanh",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+
+ ):
+ super().__init__()
+ factory_kwargs = {"device": device, "dtype": dtype}
+ self.ref_mlp = MLP(
+ hidden_size,
+ hidden_size,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+ self.ref_norm = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # copy from original_block
+ self.heads_num = original_block.heads_num
+ self.deterministic = original_block.deterministic
+
+ # img
+ self.img_mod = original_block.img_mod
+ self.img_norm1 = original_block.img_norm1
+ self.img_attn_qkv = original_block.img_attn_qkv
+ self.img_attn_q_norm = original_block.img_attn_q_norm
+ self.img_attn_k_norm = original_block.img_attn_k_norm
+ self.img_attn_proj = original_block.img_attn_proj
+ self.img_norm2 = original_block.img_norm2
+ self.img_mlp = original_block.img_mlp
+ # txt
+ self.txt_mod = original_block.txt_mod
+ self.txt_norm1 = original_block.txt_norm1
+ self.txt_attn_qkv = original_block.txt_attn_qkv
+ self.txt_attn_q_norm = original_block.txt_attn_q_norm
+ self.txt_attn_k_norm = original_block.txt_attn_k_norm
+ self.txt_attn_proj = original_block.txt_attn_proj
+ self.txt_norm2 = original_block.txt_norm2
+ self.txt_mlp = original_block.txt_mlp
+
+
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ t: Optional[torch.Tensor] = None,
+ image_emb = None,
+ ref = None,
+ text_mask = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ apply ipadopter after 'img_attn' 。
+ """
+ img_len = img.shape[1]
+ txt_len = txt.shape[1]
+ ref_len = ref.shape[1]
+ # import pdb
+ # pdb.set_trace()
+ # cu_seqlens_q and max_seqlen_q remain the input
+ cu_seqlens_kv = get_cu_seqlens(text_mask, img_len + ref_len)
+ max_seqlen_kv = img_len + ref_len + txt_len
+
+ assert ref is not None, "ref not be None"
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ (
+ txt_mod1_shift,
+ txt_mod1_scale,
+ txt_mod1_gate,
+ txt_mod2_shift,
+ txt_mod2_scale,
+ txt_mod2_gate,
+ ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # print("Double Block:=================================================")
+ # print("before norm: img max:", img.max().item(), "img min:", img.min().item())
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ # print("after norm: img_modulated max:", img_modulated.max().item(), "img_modulated min:", img_modulated.min().item())
+ # add ref here
+ # print("before mlp: ref max:", ref.max().item(), "ref min:", ref.min().item())
+ ref = self.ref_mlp(ref)
+ # print("after mlp: ref max:", ref.max().item(), "ref min:", ref.min().item())
+ ref = self.ref_norm(ref)
+ # print("after norm: ref max:", ref.max().item(), "ref min:", ref.min().item())
+
+ img_branch_input = torch.cat([img_modulated, ref], dim=1)
+ img_ref_qkv = self.img_attn_qkv(img_branch_input)# [B, L, 3 * hidden_size]
+ img_ref_q, img_ref_k, img_ref_v = rearrange(
+ img_ref_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = img_ref_q[:, :img_len, :, :]
+ img_q = self.img_attn_q_norm(img_q).to(img_ref_v)
+ img_ref_k = self.img_attn_k_norm(img_ref_k).to(img_ref_v)
+
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+
+ img_k, ref_k = img_ref_k[:, :img_len, :, :], img_ref_k[:, img_len:, :, :]
+ # print("after attention&norm img_k max:", img_k.max().item(), "after attention&norm img_k min:", img_k.min().item())
+ # print("after attention&norm ref_k max:", ref_k.max().item(), "after attention&norm ref_k min:", ref_k.min().item())
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ img_ref_k = torch.cat([img_k, ref_k],dim=1)
+
+ # Prepare txt for attention.
+ txt_modulated = self.txt_norm1(txt)
+ txt_modulated = modulate(
+ txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ )
+ txt_qkv = self.txt_attn_qkv(txt_modulated)
+ txt_q, txt_k, txt_v = rearrange(
+ txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed.
+ txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ q = torch.cat((img_q, txt_q), dim=1)
+ k = torch.cat((img_ref_k, txt_k), dim=1)
+ v = torch.cat((img_ref_v, txt_v), dim=1)
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+ img_attn, txt_attn = attn[:, : img_len], attn[:, img_len :]
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ txt = txt + apply_gate(
+ self.txt_mlp(
+ modulate(
+ self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ )
+ ),
+ gate=txt_mod2_gate,
+ )
+
+ return img, txt
+
+
+
+class MMSingleStreamBlockRefKVOnly(nn.Module):
+ def __init__(
+ self,
+ original_block: nn.Module,
+ hidden_size: int,
+ mlp_act_type: str = "gelu_tanh",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+
+ ):
+ super().__init__()
+ factory_kwargs = {"device": device, "dtype": dtype}
+ self.ref_mlp = MLP(
+ hidden_size,
+ hidden_size,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+ self.ref_norm = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+
+ self.heads_num = original_block.heads_num
+ self.hidden_size = original_block.hidden_size
+ self.deterministic = original_block.deterministic
+ self.mlp_hidden_dim = original_block.mlp_hidden_dim
+ self.scale = original_block.scale
+
+ self.linear1 = original_block.linear1
+ self.linear2 = original_block.linear2
+ self.q_norm = original_block.q_norm
+ self.k_norm = original_block.k_norm
+ self.pre_norm = original_block.pre_norm
+ self.mlp_act = original_block.mlp_act
+ self.modulation = original_block.modulation
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ txt_len: int,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ t: Optional[torch.Tensor] = None, # <-- timestep
+ image_emb = None,
+ ref = None,
+ img_len = None,
+ text_mask = None,
+ ) -> torch.Tensor:
+ assert ref is not None, "ref not be None"
+ # import pdb
+ # pdb.set_trace()
+ ref_len = ref.shape[1]
+
+
+ # cu_seqlens_q and max_seqlen_q remain the input
+ cu_seqlens_kv = get_cu_seqlens(text_mask, img_len + ref_len)
+ max_seqlen_kv = img_len + ref_len + txt_len
+
+
+ # ----------------------------------------------------------------
+ # original forward
+ # ----------------------------------------------------------------
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ # print("Single Block:=================================================")
+ # print("before norm: x max:", x.max().item(), "x min:", x.min().item())
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ # print("after norm: x_mod max:", x_mod.max().item(), "x min:", x_mod.min().item())
+
+ # add ref here
+ # ref_len = ref.shape[1]
+ # print("before mlp_max: ref max:", ref.max().item(), "ref min:", ref.min().item())
+ ref = self.ref_mlp(ref)
+ # print("after mlp_max: ref max:", ref.max().item(), "ref min:", ref.min().item())
+ ref = self.ref_norm(ref)
+ # print("after norm: ref max:", ref.max().item(), "ref min:", ref.min().item())
+ x_mod = torch.cat([x_mod[:,:img_len], ref, x_mod[:,img_len:]],dim=1)
+
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ q = torch.cat([q[:, : img_len],q[:, img_len+ref_len:]],dim=1)
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q, txt_q = q[:, :img_len, :, :], q[:, img_len:, :, :]
+ img_k, ref_k, txt_k, = k[:, :img_len, :, :], k[:, img_len:img_len+ref_len, :, :], k[:, img_len+ref_len:, :, :]
+ # print("after linear1&norm img_k max:", img_k.max().item(), "after linear1&norm img_k min:", img_k.min().item())
+ # print("after linear1&norm ref_k max:", ref_k.max().item(), "after linear1&norm ref_k min:", ref_k.min().item())
+ # print("after linear1&norm txt_k max:", txt_k.max().item(), "after linear1&norm txt_k min:", txt_k.min().item())
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+ q = torch.cat([img_q, txt_q], dim=1)
+ k = torch.cat([img_k, ref_k, txt_k], dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ mlp = torch.cat([mlp[:, : img_len],mlp[:, img_len+ref_len :]],dim=1)
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bd1b5eb5df4fed937e99806f4b957ad4efb90bf
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor.py
@@ -0,0 +1,943 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from opensora.controlnet_modules.controlnet import zero_module
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens, get_cu_seqlens_wotxt
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+from dataclasses import dataclass
+
+@dataclass
+class RefextractorOutput(BaseOutput):
+ ref_block_samples: Tuple[torch.Tensor]
+ ref_single_block_samples: Tuple[torch.Tensor]
+
+
+# TxT Free!!
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ # self.txt_mod = ModulateDiT(
+ # hidden_size,
+ # factor=6,
+ # act_layer=get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # self.txt_norm1 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+
+ # self.txt_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ # self.txt_attn_q_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_k_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_proj = nn.Linear(
+ # hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ # )
+
+ # self.txt_norm2 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+ # self.txt_mlp = MLP(
+ # hidden_size,
+ # mlp_hidden_dim,
+ # act_layer=get_activation_layer(mlp_act_type),
+ # bias=True,
+ # **factory_kwargs,
+ # )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ # txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ # (
+ # txt_mod1_shift,
+ # txt_mod1_scale,
+ # txt_mod1_gate,
+ # txt_mod2_shift,
+ # txt_mod2_scale,
+ # txt_mod2_gate,
+ # ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ # txt_modulated = self.txt_norm1(txt)
+ # txt_modulated = modulate(
+ # txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ # )
+ # txt_qkv = self.txt_attn_qkv(txt_modulated)
+ # txt_q, txt_k, txt_v = rearrange(
+ # txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ # # Apply QK-Norm if needed.
+ # txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ # txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ # v = torch.cat((img_v, txt_v), dim=1)
+ q = img_q
+ k = img_k
+ v = img_v
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ # img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+ img_attn = attn
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ # txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ # txt = txt + apply_gate(
+ # self.txt_mlp(
+ # modulate(
+ # self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ # )
+ # ),
+ # gate=txt_mod2_gate,
+ # )
+
+ # return img, txt
+ return img
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ # if freqs_cis is not None:
+ # img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ # img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ # img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ # assert (
+ # img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ # ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ # img_q, img_k = img_qq, img_kk
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ if freqs_cis is not None:
+ img_q = q
+ img_k = k
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ q, k = img_qq, img_kk
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class Refextractor(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ # if self.text_projection == "linear":
+ # self.txt_in = TextProjection(
+ # self.text_states_dim,
+ # self.hidden_size,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # elif self.text_projection == "single_refiner":
+ # self.txt_in = SingleTokenRefiner(
+ # self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ # )
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ # self.final_layer = FinalLayer(
+ # self.hidden_size,
+ # self.patch_size,
+ # self.out_channels,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ self.ref_blocks = nn.ModuleList([])
+ if len(self.double_blocks) > 0:
+
+ double_nums = len(self.double_blocks) + 1 if len(self.single_blocks) == 0 else len(self.double_blocks)
+ for _ in range(double_nums):
+ self.ref_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+ self.ref_single_blocks = nn.ModuleList([])
+ if len(self.single_blocks) > 0:
+ for _ in range(len(self.single_blocks)+1):
+ self.ref_single_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def forward(self,
+ hidden_states,
+ timestep,
+ embed_cfg_scale,
+ encoder_hidden_states = None,
+ encoder_attention_mask = None,
+ return_dict = True,
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ lora_scale = 1.0
+
+ x = hidden_states
+ t = timestep
+ # text_states, text_states_2 = encoder_hidden_states
+ # text_mask, test_mask_2 = encoder_attention_mask
+
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ # out = {}
+ img = x
+ # txt = text_states
+ _, _, ot, oh, ow = x.shape
+ # import pdb;pdb.set_trace()
+ # if ot == 1:
+ # freqs_cos, freqs_sin = self.get_2d_rotary_pos_embed(oh, ow)
+
+ # else:
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ # vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # if self.text_projection == "linear":
+ # txt = self.txt_in(txt)
+ # elif self.text_projection == "single_refiner":
+ # txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ # cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_q = get_cu_seqlens_wotxt(img, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ block_samples = ()
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+
+ block_samples = block_samples + (img, )
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ]
+
+ img = block(*double_block_args)
+
+
+ if len(self.single_blocks) == 0:
+ block_samples = block_samples + (img, )
+
+ # Merge txt and img to pass through single stream blocks.
+ # x = torch.cat((img, txt), 1)
+ x = img
+ single_block_samples = ()
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ single_block_samples = single_block_samples + (x,)
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ]
+
+ x = block(*single_block_args)
+ single_block_samples = single_block_samples + (x,)
+
+ ref_block_samples = ()
+ assert len(block_samples) == len(self.ref_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, ref_blocks has length {len(self.ref_blocks)}"
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ ref_single_block_samples = ()
+ assert len(single_block_samples) == len(self.ref_single_blocks), \
+ f"Length mismatch: single_block_samples has length {len(single_block_samples)}, ref_single_blocks has length {len(self.ref_single_blocks)}"
+ for single_block_sample, ref_block in zip(single_block_samples, self.ref_single_blocks):
+ single_block_sample = ref_block(single_block_sample)
+ ref_single_block_samples = ref_single_block_samples + (single_block_sample,)
+
+ ref_block_samples = None if len(ref_block_samples) == 0 else ref_block_samples
+ ref_single_block_samples = (
+ None if len(ref_single_block_samples) == 0 else ref_single_block_samples
+ )
+
+
+ # if not return_dict:
+ return (ref_block_samples, ref_single_block_samples, freqs_cis)
+ # return RefextractorOutput(
+ # ref_block_samples=ref_block_samples,
+ # ref_single_block_samples=ref_single_block_samples,
+ # )
+
+ # def get_2d_rotary_pos_embed(self, height, width):
+ # target_ndim = 2
+ # ndim = 2
+ # latents_size = [height, width]
+
+
+ # if isinstance(self.config.patch_size, list):
+ # assert len(self.config.patch_size) == 3, "3D patch_size should be a list of length 3 [t, h, w]."
+ # patch_size_h, patch_size_w = self.config.patch_size[1], self.config.patch_size[2]
+
+ # assert height % patch_size_h == 0 and width % patch_size_w == 0, (
+ # f"Height ({height}) and width ({width}) must be divisible by patch_size [{patch_size_h}, {patch_size_w}]."
+ # )
+ # rope_sizes = [height // patch_size_h, width // patch_size_w]
+ # else:
+ # raise ValueError(f"patch_size should be a list")
+
+
+ # head_dim = self.config.hidden_size // self.config.heads_num
+ # rope_dim_h = rope_dim_w = head_dim // 2 # 各占一半
+
+ # freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ # [rope_dim_h, rope_dim_w],
+ # rope_sizes,
+ # theta=self.config.rope_theta,
+ # use_real=True,
+ # theta_rescale_factor=1,
+ # )
+ # return freqs_cos, freqs_sin
+
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce1da162ebcb1e86e42abbfef7391b9a74f5f8c7
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d.py
@@ -0,0 +1,912 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from opensora.controlnet_modules.controlnet import zero_module
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens, get_cu_seqlens_wotxt
+from .posemb_layers import apply_rotary_emb_ignore_t, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+from dataclasses import dataclass
+from .utils import ckpt_kwargs
+@dataclass
+class RefextractorOutput(BaseOutput):
+ ref_block_samples: Tuple[torch.Tensor]
+ ref_single_block_samples: Tuple[torch.Tensor]
+
+
+# TxT Free!!
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ # self.txt_mod = ModulateDiT(
+ # hidden_size,
+ # factor=6,
+ # act_layer=get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # self.txt_norm1 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+
+ # self.txt_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ # self.txt_attn_q_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_k_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_proj = nn.Linear(
+ # hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ # )
+
+ # self.txt_norm2 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+ # self.txt_mlp = MLP(
+ # hidden_size,
+ # mlp_hidden_dim,
+ # act_layer=get_activation_layer(mlp_act_type),
+ # bias=True,
+ # **factory_kwargs,
+ # )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ # txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ # (
+ # txt_mod1_shift,
+ # txt_mod1_scale,
+ # txt_mod1_gate,
+ # txt_mod2_shift,
+ # txt_mod2_scale,
+ # txt_mod2_gate,
+ # ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ # txt_modulated = self.txt_norm1(txt)
+ # txt_modulated = modulate(
+ # txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ # )
+ # txt_qkv = self.txt_attn_qkv(txt_modulated)
+ # txt_q, txt_k, txt_v = rearrange(
+ # txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ # # Apply QK-Norm if needed.
+ # txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ # txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ # v = torch.cat((img_v, txt_v), dim=1)
+ q = img_q
+ k = img_k
+ v = img_v
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ # img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+ img_attn = attn
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ # txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ # txt = txt + apply_gate(
+ # self.txt_mlp(
+ # modulate(
+ # self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ # )
+ # ),
+ # gate=txt_mod2_gate,
+ # )
+
+ # return img, txt
+ return img
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ # if freqs_cis is not None:
+ # img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ # img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ # img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ # assert (
+ # img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ # ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ # img_q, img_k = img_qq, img_kk
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ if freqs_cis is not None:
+ img_q = q
+ img_k = k
+ img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ q, k = img_qq, img_kk
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class Refextractor2D(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ # if self.text_projection == "linear":
+ # self.txt_in = TextProjection(
+ # self.text_states_dim,
+ # self.hidden_size,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # elif self.text_projection == "single_refiner":
+ # self.txt_in = SingleTokenRefiner(
+ # self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ # )
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ # self.final_layer = FinalLayer(
+ # self.hidden_size,
+ # self.patch_size,
+ # self.out_channels,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ self.ref_blocks = nn.ModuleList([])
+ if len(self.double_blocks) > 0:
+
+ double_nums = len(self.double_blocks) + 1 if len(self.single_blocks) == 0 else len(self.double_blocks)
+ for _ in range(double_nums):
+ self.ref_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+ self.ref_single_blocks = nn.ModuleList([])
+ if len(self.single_blocks) > 0:
+ for _ in range(len(self.single_blocks)+1):
+ self.ref_single_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def forward(self,
+ hidden_states,
+ timestep,
+ embed_cfg_scale,
+ encoder_hidden_states = None,
+ encoder_attention_mask = None,
+ return_dict = True,
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ lora_scale = 1.0
+
+ x = hidden_states
+ t = timestep
+ # text_states, text_states_2 = encoder_hidden_states
+ # text_mask, test_mask_2 = encoder_attention_mask
+
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ # out = {}
+ img = x
+ # txt = text_states
+ _, _, ot, oh, ow = x.shape
+ # import pdb;pdb.set_trace()
+ assert ot == 1
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ assert ot == 1
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ # vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # if self.text_projection == "linear":
+ # txt = self.txt_in(txt)
+ # elif self.text_projection == "single_refiner":
+ # txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ # cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_q = get_cu_seqlens_wotxt(img, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ block_samples = ()
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+
+ block_samples = block_samples + (img, )
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ]
+
+ img = block(*double_block_args)
+
+
+ if len(self.single_blocks) == 0:
+ block_samples = block_samples + (img, )
+
+ # Merge txt and img to pass through single stream blocks.
+ # x = torch.cat((img, txt), 1)
+ x = img
+ single_block_samples = ()
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ single_block_samples = single_block_samples + (x,)
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ]
+
+ x = block(*single_block_args)
+ single_block_samples = single_block_samples + (x,)
+
+ ref_block_samples = ()
+ assert len(block_samples) == len(self.ref_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, ref_blocks has length {len(self.ref_blocks)}"
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ ref_single_block_samples = ()
+ assert len(single_block_samples) == len(self.ref_single_blocks), \
+ f"Length mismatch: single_block_samples has length {len(single_block_samples)}, ref_single_blocks has length {len(self.ref_single_blocks)}"
+ for single_block_sample, ref_block in zip(single_block_samples, self.ref_single_blocks):
+ single_block_sample = ref_block(single_block_sample)
+ ref_single_block_samples = ref_single_block_samples + (single_block_sample,)
+
+ ref_block_samples = None if len(ref_block_samples) == 0 else ref_block_samples
+ ref_single_block_samples = (
+ None if len(ref_single_block_samples) == 0 else ref_single_block_samples
+ )
+
+
+ # if not return_dict:
+ return (ref_block_samples, ref_single_block_samples, freqs_cis)
+ # return RefextractorOutput(
+ # ref_block_samples=ref_block_samples,
+ # ref_single_block_samples=ref_single_block_samples,
+ # )
+
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d_split_q.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d_split_q.py
new file mode 100644
index 0000000000000000000000000000000000000000..8be1dd4dd59e9e7e40dbee042e99316f7bfa4967
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/refextractor_2d_split_q.py
@@ -0,0 +1,925 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from opensora.controlnet_modules.controlnet import zero_module
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens, get_cu_seqlens_wotxt
+from .posemb_layers import apply_rotary_emb_ignore_t, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+from dataclasses import dataclass
+from .utils import ckpt_kwargs
+@dataclass
+class RefextractorOutput(BaseOutput):
+ ref_block_samples: Tuple[torch.Tensor]
+ ref_single_block_samples: Tuple[torch.Tensor]
+
+
+# TxT Free!!
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ # self.img_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ self.img_attn_q = nn.Linear(hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs)
+ self.img_attn_kv = nn.Linear(hidden_size, hidden_size * 2, bias=qkv_bias, **factory_kwargs)
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ # self.txt_mod = ModulateDiT(
+ # hidden_size,
+ # factor=6,
+ # act_layer=get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # self.txt_norm1 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+
+ # self.txt_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ # self.txt_attn_q_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_k_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_proj = nn.Linear(
+ # hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ # )
+
+ # self.txt_norm2 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+ # self.txt_mlp = MLP(
+ # hidden_size,
+ # mlp_hidden_dim,
+ # act_layer=get_activation_layer(mlp_act_type),
+ # bias=True,
+ # **factory_kwargs,
+ # )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ # txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ # (
+ # txt_mod1_shift,
+ # txt_mod1_scale,
+ # txt_mod1_gate,
+ # txt_mod2_shift,
+ # txt_mod2_scale,
+ # txt_mod2_gate,
+ # ) = self.txt_mod(vec).chunk(6, dim=-1)
+
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ # img_qkv = self.img_attn_qkv(img_modulated)
+ # img_q, img_k, img_v = rearrange(
+ # img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ img_q = self.img_attn_q(img_modulated) # (B, L, H*D)
+ img_q = rearrange(img_q, "B L (H D) -> B L H D",H=self.heads_num)
+ img_kv = self.img_attn_kv(img_modulated) # (B, L, 2*H*D)
+ img_k, img_v = rearrange(img_kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ # txt_modulated = self.txt_norm1(txt)
+ # txt_modulated = modulate(
+ # txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ # )
+ # txt_qkv = self.txt_attn_qkv(txt_modulated)
+ # txt_q, txt_k, txt_v = rearrange(
+ # txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ # # Apply QK-Norm if needed.
+ # txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ # txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ # v = torch.cat((img_v, txt_v), dim=1)
+ q = img_q
+ k = img_k
+ v = img_v
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ # img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+ img_attn = attn
+
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ # txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ # txt = txt + apply_gate(
+ # self.txt_mlp(
+ # modulate(
+ # self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ # )
+ # ),
+ # gate=txt_mod2_gate,
+ # )
+
+ # return img, txt
+ return img
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ # self.linear1 = nn.Linear(
+ # hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ # )
+ self.linear1_q = nn.Linear(hidden_size, hidden_size, **factory_kwargs)
+ self.linear1_kv_mlp = nn.Linear(hidden_size, hidden_size * 2 + mlp_hidden_dim, **factory_kwargs)
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ # qkv, mlp = torch.split(
+ # self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ # )
+ # q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+ q = self.linear1_q(x_mod)
+ q = rearrange(q, "B L (H D) -> B L H D",H=self.heads_num)
+ kv_mlp = self.linear1_kv_mlp(x_mod)
+ kv, mlp = torch.split(kv_mlp, [2 * self.hidden_size, self.mlp_hidden_dim], dim=-1)
+ k, v = rearrange(kv, "B L (K H D) -> K B L H D", K=2, H=self.heads_num)
+
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+
+ # Apply RoPE if needed.
+ # if freqs_cis is not None:
+ # img_q, txt_q = q[:, :-txt_len, :, :], q[:, -txt_len:, :, :]
+ # img_k, txt_k = k[:, :-txt_len, :, :], k[:, -txt_len:, :, :]
+ # img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ # assert (
+ # img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ # ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ # img_q, img_k = img_qq, img_kk
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ if freqs_cis is not None:
+ img_q = q
+ img_k = k
+ img_qq, img_kk = apply_rotary_emb_ignore_t(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ q, k = img_qq, img_kk
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class Refextractor2D(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ embedded_guidance_scale = 6.0 #用默认值
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+ self.embedded_guidance_scale = embedded_guidance_scale
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ # if self.text_projection == "linear":
+ # self.txt_in = TextProjection(
+ # self.text_states_dim,
+ # self.hidden_size,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # elif self.text_projection == "single_refiner":
+ # self.txt_in = SingleTokenRefiner(
+ # self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ # )
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ self.vector_in = MLPEmbedder(
+ self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ # self.final_layer = FinalLayer(
+ # self.hidden_size,
+ # self.patch_size,
+ # self.out_channels,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ self.ref_blocks = nn.ModuleList([])
+ if len(self.double_blocks) > 0:
+
+ double_nums = len(self.double_blocks) + 1 if len(self.single_blocks) == 0 else len(self.double_blocks)
+ for _ in range(double_nums):
+ self.ref_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+ self.ref_single_blocks = nn.ModuleList([])
+ if len(self.single_blocks) > 0:
+ for _ in range(len(self.single_blocks)+1):
+ self.ref_single_blocks.append(zero_module(nn.Linear(self.hidden_size, self.hidden_size)))
+
+
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def forward(self,
+ hidden_states,
+ timestep,
+ embed_cfg_scale,
+ encoder_hidden_states = None,
+ encoder_attention_mask = None,
+ return_dict = True,
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ lora_scale = 1.0
+
+ x = hidden_states
+ t = timestep
+ # text_states, text_states_2 = encoder_hidden_states
+ # text_mask, test_mask_2 = encoder_attention_mask
+
+
+ embedded_guidance_scale = embed_cfg_scale#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ embedded_guidance_scale,
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ # out = {}
+ img = x
+ # txt = text_states
+ _, _, ot, oh, ow = x.shape
+ # import pdb;pdb.set_trace()
+ assert ot == 1
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+ if USE_PEFT_BACKEND:
+ scale_lora_layers(self, lora_scale)
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ # vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # if self.text_projection == "linear":
+ # txt = self.txt_in(txt)
+ # elif self.text_projection == "single_refiner":
+ # txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ # cu_seqlens_q = get_cu_seqlens(text_mask, img_seq_len)
+ cu_seqlens_q = get_cu_seqlens_wotxt(img, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+
+ block_samples = ()
+ # --------------------- Pass through DiT blocks ------------------------
+ for index_block, block in enumerate(self.double_blocks):
+
+ block_samples = block_samples + (img, )
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ **ckpt_kwargs,
+ )
+ else:
+ double_block_args = [
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ ]
+
+ img = block(*double_block_args)
+
+
+ if len(self.single_blocks) == 0:
+ block_samples = block_samples + (img, )
+
+ # Merge txt and img to pass through single stream blocks.
+ # x = torch.cat((img, txt), 1)
+ x = img
+ single_block_samples = ()
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ single_block_samples = single_block_samples + (x,)
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ # flash attn3
+ # ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ **ckpt_kwargs,
+ )
+ else:
+
+ single_block_args = [
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ ]
+
+ x = block(*single_block_args)
+ single_block_samples = single_block_samples + (x,)
+
+ ref_block_samples = ()
+ assert len(block_samples) == len(self.ref_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, ref_blocks has length {len(self.ref_blocks)}"
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ ref_single_block_samples = ()
+ assert len(single_block_samples) == len(self.ref_single_blocks), \
+ f"Length mismatch: single_block_samples has length {len(single_block_samples)}, ref_single_blocks has length {len(self.ref_single_blocks)}"
+ for single_block_sample, ref_block in zip(single_block_samples, self.ref_single_blocks):
+ single_block_sample = ref_block(single_block_sample)
+ ref_single_block_samples = ref_single_block_samples + (single_block_sample,)
+
+ ref_block_samples = None if len(ref_block_samples) == 0 else ref_block_samples
+ ref_single_block_samples = (
+ None if len(ref_single_block_samples) == 0 else ref_single_block_samples
+ )
+
+
+ # if not return_dict:
+ return (ref_block_samples, ref_single_block_samples, freqs_cis)
+ # return RefextractorOutput(
+ # ref_block_samples=ref_block_samples,
+ # ref_single_block_samples=ref_single_block_samples,
+ # )
+
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/token_refiner.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/token_refiner.py
new file mode 100644
index 0000000000000000000000000000000000000000..82edff4efd564b3a1abc798d36effce77ce82904
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/token_refiner.py
@@ -0,0 +1,236 @@
+from typing import Optional
+
+from einops import rearrange
+import torch
+import torch.nn as nn
+
+from .activation_layers import get_activation_layer
+from .attenion import attention
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, TextProjection
+from .attenion import attention
+from .mlp_layers import MLP
+from .modulate_layers import modulate, apply_gate
+
+
+class IndividualTokenRefinerBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size,
+ heads_num,
+ mlp_width_ratio: str = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
+ )
+ self.self_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.self_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.self_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.self_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=True, eps=1e-6, **factory_kwargs
+ )
+ act_layer = get_activation_layer(act_type)
+ self.mlp = MLP(
+ in_channels=hidden_size,
+ hidden_channels=mlp_hidden_dim,
+ act_layer=act_layer,
+ drop=mlp_drop_rate,
+ **factory_kwargs,
+ )
+
+ self.adaLN_modulation = nn.Sequential(
+ act_layer(),
+ nn.Linear(hidden_size, 2 * hidden_size, bias=True, **factory_kwargs),
+ )
+ # Zero-initialize the modulation
+ nn.init.zeros_(self.adaLN_modulation[1].weight)
+ nn.init.zeros_(self.adaLN_modulation[1].bias)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ c: torch.Tensor, # timestep_aware_representations + context_aware_representations
+ attn_mask: torch.Tensor = None,
+ ):
+ gate_msa, gate_mlp = self.adaLN_modulation(c).chunk(2, dim=1)
+
+ norm_x = self.norm1(x)
+ qkv = self.self_attn_qkv(norm_x)
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+ # Apply QK-Norm if needed
+ q = self.self_attn_q_norm(q).to(v)
+ k = self.self_attn_k_norm(k).to(v)
+
+ # Self-Attention
+ attn = attention(q, k, v, mode="torch", attn_mask=attn_mask)
+
+ x = x + apply_gate(self.self_attn_proj(attn), gate_msa)
+
+ # FFN Layer
+ x = x + apply_gate(self.mlp(self.norm2(x)), gate_mlp)
+
+ return x
+
+
+class IndividualTokenRefiner(nn.Module):
+ def __init__(
+ self,
+ hidden_size,
+ heads_num,
+ depth,
+ mlp_width_ratio: float = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.blocks = nn.ModuleList(
+ [
+ IndividualTokenRefinerBlock(
+ hidden_size=hidden_size,
+ heads_num=heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_drop_rate=mlp_drop_rate,
+ act_type=act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+ for _ in range(depth)
+ ]
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ c: torch.LongTensor,
+ mask: Optional[torch.Tensor] = None,
+ ):
+ self_attn_mask = None
+ if mask is not None:
+ batch_size = mask.shape[0]
+ seq_len = mask.shape[1]
+ mask = mask.to(x.device)
+ # batch_size x 1 x seq_len x seq_len
+ self_attn_mask_1 = mask.view(batch_size, 1, 1, seq_len).repeat(
+ 1, 1, seq_len, 1
+ )
+ # batch_size x 1 x seq_len x seq_len
+ self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)
+ # batch_size x 1 x seq_len x seq_len, 1 for broadcasting of heads_num
+ self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()
+ # avoids self-attention weight being NaN for padding tokens
+ self_attn_mask[:, :, :, 0] = True
+
+ for block in self.blocks:
+ x = block(x, c, self_attn_mask)
+ return x
+
+
+class SingleTokenRefiner(nn.Module):
+ """
+ A single token refiner block for llm text embedding refine.
+ """
+ def __init__(
+ self,
+ in_channels,
+ hidden_size,
+ heads_num,
+ depth,
+ mlp_width_ratio: float = 4.0,
+ mlp_drop_rate: float = 0.0,
+ act_type: str = "silu",
+ qk_norm: bool = False,
+ qk_norm_type: str = "layer",
+ qkv_bias: bool = True,
+ attn_mode: str = "torch",
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+ self.attn_mode = attn_mode
+ assert self.attn_mode == "torch", "Only support 'torch' mode for token refiner."
+
+ self.input_embedder = nn.Linear(
+ in_channels, hidden_size, bias=True, **factory_kwargs
+ )
+
+ act_layer = get_activation_layer(act_type)
+ # Build timestep embedding layer
+ self.t_embedder = TimestepEmbedder(hidden_size, act_layer, **factory_kwargs)
+ # Build context embedding layer
+ self.c_embedder = TextProjection(
+ in_channels, hidden_size, act_layer, **factory_kwargs
+ )
+
+ self.individual_token_refiner = IndividualTokenRefiner(
+ hidden_size=hidden_size,
+ heads_num=heads_num,
+ depth=depth,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_drop_rate=mlp_drop_rate,
+ act_type=act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ **factory_kwargs,
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ t: torch.LongTensor,
+ mask: Optional[torch.LongTensor] = None,
+ ):
+ timestep_aware_representations = self.t_embedder(t)
+
+ if mask is None:
+ context_aware_representations = x.mean(dim=1)
+ else:
+ mask_float = mask.unsqueeze(-1) # [b, s1, 1]
+ context_aware_representations = (x * mask_float).sum(
+ dim=1
+ ) / mask_float.sum(dim=1)
+ context_aware_representations = self.c_embedder(context_aware_representations)
+ c = timestep_aware_representations + context_aware_representations
+
+ x = self.input_embedder(x)
+
+ x = self.individual_token_refiner(x, c, mask)
+
+ return x
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/utils.py b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ea946cd5f64aa2ebdeaf984075af5d2f2ec52382
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/hunyuan_dit_src/utils.py
@@ -0,0 +1,54 @@
+import collections.abc
+
+from itertools import repeat
+from diffusers.utils import is_torch_version
+try:
+ # flash attn3 == cuda >= 12.3 == "use_reentrant": True
+ from flash_attn_interface import flash_attn_varlen_func as flash_attn3_varlen_func
+ flash_attn_backend = "flash-attn-3"
+ # print("[INFO] Using FlashAttention 3")
+
+ ckpt_kwargs = {"use_reentrant": True} if is_torch_version(">=", "1.11.0") else {}
+except ImportError:
+ flash_attn_backend = "flash-attn-2"
+ ckpt_kwargs = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+
+
+def _ntuple(n):
+ def parse(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ x = tuple(x)
+ if len(x) == 1:
+ x = tuple(repeat(x[0], n))
+ return x
+ return tuple(repeat(x, n))
+ return parse
+
+
+to_1tuple = _ntuple(1)
+to_2tuple = _ntuple(2)
+to_3tuple = _ntuple(3)
+to_4tuple = _ntuple(4)
+
+
+def as_tuple(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ return tuple(x)
+ if x is None or isinstance(x, (int, float, str)):
+ return (x,)
+ else:
+ raise ValueError(f"Unknown type {type(x)}")
+
+
+def as_list_of_2tuple(x):
+ x = as_tuple(x)
+ if len(x) == 1:
+ x = (x[0], x[0])
+ assert len(x) % 2 == 0, f"Expect even length, got {len(x)}."
+ lst = []
+ for i in range(0, len(x), 2):
+ lst.append((x[i], x[i + 1]))
+ return lst
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/layernorm.py b/One-to-All-Animation/video-generation/opensora/model_variants/layernorm.py
new file mode 100644
index 0000000000000000000000000000000000000000..f1fb9c712d79996f7549353ba7598aa463fcfd91
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/layernorm.py
@@ -0,0 +1,326 @@
+# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
+
+import importlib
+import inspect
+import numbers
+
+import torch
+from torch import Tensor
+from torch.nn import init
+from torch.nn.parameter import Parameter
+
+# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
+
+"""This code is copied fron NVIDIA apex:
+ https://github.com/NVIDIA/apex
+ with some changes. """
+
+try:
+ from apex.normalization.fused_layer_norm import FusedRMSNormAffineMixedDtypesFunction
+except ImportError:
+ FusedRMSNormAffineMixedDtypesFunction = None
+
+
+global fused_layer_norm_cuda
+fused_layer_norm_cuda = None
+
+try:
+ from apex.contrib.layer_norm.layer_norm import FastLayerNormFN
+
+ HAVE_PERSIST_LAYER_NORM = True
+except ImportError:
+ HAVE_PERSIST_LAYER_NORM = False
+
+try:
+ from apex.normalization.fused_layer_norm import FusedLayerNormAffineFunction
+
+ HAVE_FUSED_LAYER_NORM = True
+except ImportError:
+ HAVE_FUSED_LAYER_NORM = False
+
+from apex.normalization.fused_layer_norm import fused_layer_norm
+
+
+def _kernel_make_viewless_tensor(inp, requires_grad):
+ """Make a viewless tensor.
+
+ View tensors have the undesirable side-affect of retaining a reference
+ to the originally-viewed tensor, even after manually setting the '.data'
+ field. This method creates a new tensor that links to the old tensor's
+ data, without linking the viewed tensor, referenced via the '._base'
+ field.
+ """
+ out = torch.empty((1,), dtype=inp.dtype, device=inp.device, requires_grad=requires_grad)
+ out.data = inp.data
+ return out
+
+
+class MakeViewlessTensor(torch.autograd.Function):
+ """
+ Autograd function to make a viewless tensor.
+
+ This function should be used in cases where the computation graph needs
+ to be propagated, but we only want a viewless tensor (e.g.,
+ ParallelTransformer's hidden_states). Call this function by passing
+ 'keep_graph = True' to 'make_viewless_tensor()'.
+ """
+
+ @staticmethod
+ def forward(ctx, inp, requires_grad):
+ """Runs the fwd pass of _kernel_make_viewless_tensor"""
+ return _kernel_make_viewless_tensor(inp, requires_grad)
+
+ @staticmethod
+ def backward(ctx, grad_output):
+ """No-op"""
+ return grad_output, None
+
+
+def make_viewless_tensor(inp, requires_grad, keep_graph):
+ """
+ Entry-point for creating viewless tensors.
+
+ This method should be used, rather than calling 'MakeViewlessTensor'
+ or '_kernel_make_viewless_tensor' directly. This method acts as a
+ switch for determining if an autograd function or a regular method
+ should be used to create the tensor.
+ """
+
+ # return tensor as-is, if not a 'view'
+ if inp._base is None:
+ return inp
+
+ # create viewless tensor
+ if keep_graph:
+ return MakeViewlessTensor.apply(inp, requires_grad)
+ else:
+ return _kernel_make_viewless_tensor(inp, requires_grad)
+
+
+class FusedLayerNorm(torch.nn.Module):
+ """Layer Norm, fused into a single CUDA kernel.
+
+ Args:
+ hidden_size (int): Transformer hidden dimension.
+
+ eps (float): Epsilon added to denominator, for numerical stability.
+
+ persist_layer_norm (bool): Use persistent fused layer norm kernel.
+ This kernel supports only a set of hidden sizes. Please
+ check persist_ln_hidden_sizes if your hidden size is supported.
+
+ zero_centered_gamma (bool): Adjust LayerNorm weights such that they are
+ centered around zero. This improves numerical stability.
+
+ config (TransformerConfig): Transformer config. Include to match custom
+ layer norm interfaces.
+
+ normalization (str): Normalization type, used for Transformer Engine.
+ Must equal 'LayerNorm' here.
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ elementwise_affine: bool = False,
+ eps: float = 1e-5,
+ persist_layer_norm: bool = True,
+ zero_centered_gamma: bool = False,
+ normalization: str = "LayerNorm", # included to match TE interface
+ memory_efficient : bool = False
+ ):
+ super().__init__()
+
+ self.zero_centered_gamma = zero_centered_gamma
+
+
+ # List of hiddens sizes supported in the persistent layer norm kernel
+ # If the hidden size is not supported, fall back to the non-persistent
+ # kernel.
+ persist_ln_hidden_sizes = [
+ 1024,
+ 1536,
+ 2048,
+ 2304,
+ 3072,
+ 3840,
+ 4096,
+ 5120,
+ 6144,
+ 8192,
+ 10240,
+ 12288,
+ 12800,
+ 15360,
+ 16384,
+ 18432,
+ 20480,
+ 24576,
+ 25600,
+ 30720,
+ 32768,
+ 40960,
+ 49152,
+ 65536,
+ ]
+ if hidden_size not in persist_ln_hidden_sizes or not HAVE_PERSIST_LAYER_NORM:
+ persist_layer_norm = False
+
+ if not persist_layer_norm and not HAVE_FUSED_LAYER_NORM:
+ # TODO: Add pytorch only layer norm
+ raise ValueError(f'Apex must be installed to use FusedLayerNorm.')
+
+ if isinstance(hidden_size, numbers.Integral):
+ hidden_size = (hidden_size,)
+ self.hidden_size = torch.Size(hidden_size)
+ self.normalized_shape = torch.Size(hidden_size)
+ self.memory_efficient = memory_efficient
+ self.eps = eps
+ # Parameters need to be initialized with torch.empty rather than torch.Tensor for correct device placement with nemo2.
+ self.elementwise_affine = elementwise_affine
+ if elementwise_affine:
+ self.weight = Parameter(torch.empty(*hidden_size))
+ self.bias = Parameter(torch.empty(*hidden_size))
+ else:
+ self.register_parameter("weight", None)
+ self.register_parameter("bias", None)
+
+ self.reset_parameters()
+ self.persist_layer_norm = persist_layer_norm
+
+ # def reset_parameters(self):
+
+ # if self.zero_centered_gamma:
+ # init.zeros_(self.weight)
+ # init.zeros_(self.bias)
+ # else:
+ # init.ones_(self.weight)
+ # init.zeros_(self.bias)
+
+ def reset_parameters(self) -> None:
+ if self.elementwise_affine:
+ if self.zero_centered_gamma:
+ init.zeros_(self.weight)
+ else:
+ init.ones_(self.weight)
+ if self.bias is not None:
+ init.zeros_(self.bias)
+
+ def forward(self, input: Tensor) -> Tensor:
+
+ if not self.elementwise_affine:
+ return fused_layer_norm(input, self.normalized_shape, self.eps, self.memory_efficient)
+
+ weight = self.weight + 1 if self.zero_centered_gamma else self.weight
+
+ if self.persist_layer_norm:
+ if 'memory_efficient' in inspect.getfullargspec(FastLayerNormFN.forward).args:
+ output = FastLayerNormFN.apply(
+ input, weight, self.bias, self.eps, False
+ )
+ else:
+ output = FastLayerNormFN.apply(input, weight, self.bias, self.eps)
+
+ # Apex's fast layer norm function outputs a 'view' tensor (i.e., has
+ # a populated '_base' field). This will result in schedule.py's
+ # deallocate_output_tensor() throwing an error, so a viewless tensor is
+ # created to prevent this.
+ output = make_viewless_tensor(
+ inp=output, requires_grad=input.requires_grad, keep_graph=True
+ )
+
+ else:
+ if (
+ 'memory_efficient'
+ in inspect.getfullargspec(FusedLayerNormAffineFunction.forward).args
+ ):
+ return FusedLayerNormAffineFunction.apply(
+ input,
+ weight,
+ self.bias,
+ self.hidden_size,
+ self.eps,
+ False,
+ )
+ else:
+ return FusedLayerNormAffineFunction.apply(
+ input, weight, self.bias, self.hidden_size, self.eps
+ )
+
+ return output
+
+
+class MixedFusedRMSNorm(torch.nn.Module):
+
+ def __init__(self,
+ normalized_shape,
+ elementwise_affine=True,
+ eps=1e-5,
+ device = None,
+ dtype = None):
+ super(MixedFusedRMSNorm, self).__init__()
+
+ global fused_layer_norm_cuda
+ fused_layer_norm_cuda = importlib.import_module("fused_layer_norm_cuda")
+
+
+ if isinstance(normalized_shape, numbers.Integral):
+ normalized_shape = (normalized_shape,)
+ self.normalized_shape = torch.Size(normalized_shape)
+ self.eps = eps
+ self.weight = Parameter(torch.Tensor(*normalized_shape))
+ self.reset_parameters()
+
+ # set sequence parallelism flag on weight and bias parameters
+ # setattr(self.weight, 'sequence_parallel', sequence_parallel)
+
+ def reset_parameters(self):
+ init.ones_(self.weight)
+
+ def forward(self, input):
+ try:
+ try:
+ return FusedRMSNormAffineMixedDtypesFunction.apply(input, self.weight, self.normalized_shape, self.eps, True)
+ except:
+ return FusedRMSNormAffineMixedDtypesFunction.apply(input, self.weight, self.normalized_shape, self.eps)
+ except:
+ # `memory_efficient=False` aligns with the old version
+ # `apply` doesn't accept keyword arguments
+ return FusedRMSNormAffineMixedDtypesFunction.apply(input, self.weight, self.normalized_shape, self.eps, False)
+
+
+if __name__ == "__main__":
+ norm = FusedLayerNorm(3072).to("cuda")
+ x = torch.rand(1, 21730, 3072, dtype=torch.float32, device="cuda")
+
+ y = norm(x)
+
+
+ torch.cuda.synchronize()
+ import time
+ N = 100
+ start = time.time()
+ for i in range(N):
+ y1 = norm(x)
+ torch.cuda.synchronize()
+
+ cost = (time.time() - start) / N
+ print(f"apex layernorm cost: {cost}")
+
+
+ from torch import nn
+ start = time.time()
+ layer_norm = nn.LayerNorm(3072).to("cuda")
+ for i in range(N):
+ y2 = layer_norm(x)
+
+ torch.cuda.synchronize()
+
+ print(y1)
+ print(y2)
+
+ print(f"equal: {torch.isclose(y1, y2, rtol=1e-5, atol=1e-8)}")
+
+ cost = (time.time() - start) / N
+ print(f"torch layernorm cost: {cost}")
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/mochi_attn_imports.py b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_attn_imports.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d4a8c1017f3fcd58f66f31ac36357de6fbb3d6d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_attn_imports.py
@@ -0,0 +1,29 @@
+from contextlib import contextmanager
+
+import torch
+
+
+try:
+ from flash_attn import flash_attn_varlen_func as flash_varlen_attn
+except ImportError:
+ flash_varlen_attn = None
+
+try:
+ from sageattention import sageattn as sage_attn
+except ImportError:
+ sage_attn = None
+
+from torch.nn.attention import SDPBackend, sdpa_kernel
+
+training_backends = [SDPBackend.FLASH_ATTENTION, SDPBackend.EFFICIENT_ATTENTION]
+eval_backends = list(training_backends)
+if torch.cuda.get_device_properties(0).major >= 9.0:
+ # Enable fast CuDNN attention on Hopper.
+ # This gives NaN on the backward pass for some reason,
+ # so only use it for evaluation.
+ eval_backends.append(SDPBackend.CUDNN_ATTENTION)
+
+@contextmanager
+def sdpa_attn_ctx(training: bool = False):
+ with sdpa_kernel(training_backends if training else eval_backends):
+ yield
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/mochi_cp.py b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_cp.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0b5c327ccda3431d3ee43770b89ed17688b3091
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_cp.py
@@ -0,0 +1,155 @@
+import torch
+import torch.distributed as dist
+from einops import rearrange
+
+_CONTEXT_PARALLEL_GROUP = None
+_CONTEXT_PARALLEL_RANK = None
+_CONTEXT_PARALLEL_GROUP_SIZE = None
+_CONTEXT_PARALLEL_GROUP_RANKS = None
+
+
+def get_cp_rank_size():
+ if _CONTEXT_PARALLEL_GROUP:
+ return _CONTEXT_PARALLEL_RANK, _CONTEXT_PARALLEL_GROUP_SIZE
+ else:
+ return 0, 1
+
+
+def local_shard(x: torch.Tensor, dim: int = 2) -> torch.Tensor:
+ if not _CONTEXT_PARALLEL_GROUP:
+ return x
+
+ cp_rank, cp_size = get_cp_rank_size()
+ return x.tensor_split(cp_size, dim=dim)[cp_rank]
+
+
+def set_cp_group(cp_group, ranks, global_rank):
+ global _CONTEXT_PARALLEL_GROUP, _CONTEXT_PARALLEL_RANK, _CONTEXT_PARALLEL_GROUP_SIZE, _CONTEXT_PARALLEL_GROUP_RANKS
+ if _CONTEXT_PARALLEL_GROUP is not None:
+ raise RuntimeError("CP group already initialized.")
+ _CONTEXT_PARALLEL_GROUP = cp_group
+ _CONTEXT_PARALLEL_RANK = dist.get_rank(cp_group)
+ _CONTEXT_PARALLEL_GROUP_SIZE = dist.get_world_size(cp_group)
+ _CONTEXT_PARALLEL_GROUP_RANKS = ranks
+
+ assert _CONTEXT_PARALLEL_RANK == ranks.index(
+ global_rank
+ ), f"Rank mismatch: {global_rank} in {ranks} does not have position {_CONTEXT_PARALLEL_RANK} "
+ assert _CONTEXT_PARALLEL_GROUP_SIZE == len(
+ ranks
+ ), f"Group size mismatch: {_CONTEXT_PARALLEL_GROUP_SIZE} != len({ranks})"
+
+
+def get_cp_group():
+ if _CONTEXT_PARALLEL_GROUP is None:
+ raise RuntimeError("CP group not initialized")
+ return _CONTEXT_PARALLEL_GROUP
+
+
+def is_cp_active():
+ return _CONTEXT_PARALLEL_GROUP is not None
+
+
+class AllGatherIntoTensorFunction(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x: torch.Tensor, reduce_dtype, group: dist.ProcessGroup):
+ ctx.reduce_dtype = reduce_dtype
+ ctx.group = group
+ ctx.batch_size = x.size(0)
+ group_size = dist.get_world_size(group)
+
+ x = x.contiguous()
+ output = torch.empty(group_size * x.size(0), *x.shape[1:], dtype=x.dtype, device=x.device)
+ dist.all_gather_into_tensor(output, x, group=group)
+ return output
+
+
+def all_gather(tensor: torch.Tensor) -> torch.Tensor:
+ if not _CONTEXT_PARALLEL_GROUP:
+ return tensor
+
+ return AllGatherIntoTensorFunction.apply(tensor, torch.float32, _CONTEXT_PARALLEL_GROUP)
+
+
+@torch.compiler.disable()
+def _all_to_all_single(output, input, group):
+ # Disable compilation since torch compile changes contiguity.
+ assert input.is_contiguous(), "Input tensor must be contiguous."
+ assert output.is_contiguous(), "Output tensor must be contiguous."
+ return dist.all_to_all_single(output, input, group=group)
+
+
+class CollectTokens(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, qkv: torch.Tensor, group: dist.ProcessGroup, num_heads: int):
+ """Redistribute heads and receive tokens.
+
+ Args:
+ qkv: query, key or value. Shape: [B, M, 3 * num_heads * head_dim]
+
+ Returns:
+ qkv: shape: [3, B, N, local_heads, head_dim]
+
+ where M is the number of local tokens,
+ N = cp_size * M is the number of global tokens,
+ local_heads = num_heads // cp_size is the number of local heads.
+ """
+ ctx.group = group
+ ctx.num_heads = num_heads
+ cp_size = dist.get_world_size(group)
+ assert num_heads % cp_size == 0
+ ctx.local_heads = num_heads // cp_size
+
+ qkv = rearrange(
+ qkv,
+ "B M (qkv G h d) -> G M h B (qkv d)",
+ qkv=3,
+ G=cp_size,
+ h=ctx.local_heads,
+ ).contiguous()
+
+ output_chunks = torch.empty_like(qkv)
+ _all_to_all_single(output_chunks, qkv, group=group)
+
+ return rearrange(output_chunks, "G M h B (qkv d) -> qkv B (G M) h d", qkv=3)
+
+
+def all_to_all_collect_tokens(x: torch.Tensor, num_heads: int) -> torch.Tensor:
+ if not _CONTEXT_PARALLEL_GROUP:
+ # Move QKV dimension to the front.
+ # B M (3 H d) -> 3 B M H d
+ B, M, _ = x.size()
+ x = x.view(B, M, 3, num_heads, -1)
+ return x.permute(2, 0, 1, 3, 4)
+
+ return CollectTokens.apply(x, _CONTEXT_PARALLEL_GROUP, num_heads)
+
+
+class CollectHeads(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x: torch.Tensor, group: dist.ProcessGroup):
+ """Redistribute tokens and receive heads.
+
+ Args:
+ x: Output of attention. Shape: [B, N, local_heads, head_dim]
+
+ Returns:
+ Shape: [B, M, num_heads * head_dim]
+ """
+ ctx.group = group
+ ctx.local_heads = x.size(2)
+ ctx.head_dim = x.size(3)
+ group_size = dist.get_world_size(group)
+ x = rearrange(x, "B (G M) h D -> G h M B D", G=group_size).contiguous()
+ output = torch.empty_like(x)
+ _all_to_all_single(output, x, group=group)
+ del x
+ return rearrange(output, "G h M B D -> B M (G h D)")
+
+
+def all_to_all_collect_heads(x: torch.Tensor) -> torch.Tensor:
+ if not _CONTEXT_PARALLEL_GROUP:
+ # Merge heads.
+ return x.view(x.size(0), x.size(1), x.size(2) * x.size(3))
+
+ return CollectHeads.apply(x, _CONTEXT_PARALLEL_GROUP)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/mochi_layers.py b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_layers.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9fdb79ec5e2c0cc7caae21c371e7e99b832ef5e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_layers.py
@@ -0,0 +1,176 @@
+import collections.abc
+import math
+from itertools import repeat
+from typing import Callable, Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+
+
+# From PyTorch internals
+def _ntuple(n):
+ def parse(x):
+ if isinstance(x, collections.abc.Iterable) and not isinstance(x, str):
+ return tuple(x)
+ return tuple(repeat(x, n))
+
+ return parse
+
+
+to_2tuple = _ntuple(2)
+
+
+class TimestepEmbedder(nn.Module):
+ def __init__(
+ self,
+ hidden_size: int,
+ frequency_embedding_size: int = 256,
+ *,
+ bias: bool = True,
+ timestep_scale: Optional[float] = None,
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ self.mlp = nn.Sequential(
+ nn.Linear(frequency_embedding_size, hidden_size, bias=bias, device=device),
+ nn.SiLU(),
+ nn.Linear(hidden_size, hidden_size, bias=bias, device=device),
+ )
+ self.frequency_embedding_size = frequency_embedding_size
+ self.timestep_scale = timestep_scale
+
+ @staticmethod
+ def timestep_embedding(t, dim, max_period=10000):
+ half = dim // 2
+ freqs = torch.arange(start=0, end=half, dtype=torch.float32, device=t.device)
+ freqs.mul_(-math.log(max_period) / half).exp_()
+ args = t[:, None].float() * freqs[None]
+ embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
+ if dim % 2:
+ embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
+ return embedding
+
+ def forward(self, t):
+ if self.timestep_scale is not None:
+ t = t * self.timestep_scale
+ t_freq = self.timestep_embedding(t, self.frequency_embedding_size)
+ t_emb = self.mlp(t_freq.to(t.dtype))
+ return t_emb
+
+
+class PooledCaptionEmbedder(nn.Module):
+ def __init__(
+ self,
+ caption_feature_dim: int,
+ hidden_size: int,
+ *,
+ bias: bool = True,
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ self.caption_feature_dim = caption_feature_dim
+ self.hidden_size = hidden_size
+ self.mlp = nn.Sequential(
+ nn.Linear(caption_feature_dim, hidden_size, bias=bias, device=device),
+ nn.SiLU(),
+ nn.Linear(hidden_size, hidden_size, bias=bias, device=device),
+ )
+
+ def forward(self, x):
+ return self.mlp(x)
+
+
+class FeedForward(nn.Module):
+ def __init__(
+ self,
+ in_features: int,
+ hidden_size: int,
+ multiple_of: int,
+ ffn_dim_multiplier: Optional[float],
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ # keep parameter count and computation constant compared to standard FFN
+ hidden_size = int(2 * hidden_size / 3)
+ # custom dim factor multiplier
+ if ffn_dim_multiplier is not None:
+ hidden_size = int(ffn_dim_multiplier * hidden_size)
+ hidden_size = multiple_of * ((hidden_size + multiple_of - 1) // multiple_of)
+
+ self.hidden_dim = hidden_size
+ self.w1 = nn.Linear(in_features, 2 * hidden_size, bias=False, device=device)
+ self.w2 = nn.Linear(hidden_size, in_features, bias=False, device=device)
+
+ def forward(self, x):
+ x, gate = self.w1(x).chunk(2, dim=-1)
+ x = self.w2(F.silu(x) * gate)
+ return x
+
+
+class PatchEmbed(nn.Module):
+ def __init__(
+ self,
+ patch_size: int = 16,
+ in_chans: int = 3,
+ embed_dim: int = 768,
+ norm_layer: Optional[Callable] = None,
+ flatten: bool = True,
+ bias: bool = True,
+ dynamic_img_pad: bool = False,
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ self.patch_size = to_2tuple(patch_size)
+ self.flatten = flatten
+ self.dynamic_img_pad = dynamic_img_pad
+
+ self.proj = nn.Conv2d(
+ in_chans,
+ embed_dim,
+ kernel_size=patch_size,
+ stride=patch_size,
+ bias=bias,
+ device=device,
+ )
+ assert norm_layer is None
+ self.norm = norm_layer(embed_dim, device=device) if norm_layer else nn.Identity()
+
+ def forward(self, x):
+ B, _C, T, H, W = x.shape
+ if not self.dynamic_img_pad:
+ assert (
+ H % self.patch_size[0] == 0
+ ), f"Input height ({H}) should be divisible by patch size ({self.patch_size[0]})."
+ assert (
+ W % self.patch_size[1] == 0
+ ), f"Input width ({W}) should be divisible by patch size ({self.patch_size[1]})."
+ else:
+ pad_h = (self.patch_size[0] - H % self.patch_size[0]) % self.patch_size[0]
+ pad_w = (self.patch_size[1] - W % self.patch_size[1]) % self.patch_size[1]
+ x = F.pad(x, (0, pad_w, 0, pad_h))
+
+ x = rearrange(x, "B C T H W -> (B T) C H W", B=B, T=T)
+ x = self.proj(x)
+
+ # Flatten temporal and spatial dimensions.
+ if not self.flatten:
+ raise NotImplementedError("Must flatten output.")
+ x = rearrange(x, "(B T) C H W -> B (T H W) C", B=B, T=T)
+
+ x = self.norm(x)
+ return x
+
+
+class RMSNorm(torch.nn.Module):
+ def __init__(self, hidden_size, eps=1e-5, device=None):
+ super().__init__()
+ self.eps = eps
+ self.weight = torch.nn.Parameter(torch.empty(hidden_size, device=device))
+ self.register_parameter("bias", None)
+
+ def forward(self, x):
+ x_fp32 = x.float()
+ x_normed = x_fp32 * torch.rsqrt(x_fp32.pow(2).mean(-1, keepdim=True) + self.eps)
+ return (x_normed * self.weight).type_as(x)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/mochi_utils.py b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..bde2406f20ff3fb1f352c47aa508203ac91d741b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/mochi_utils.py
@@ -0,0 +1,109 @@
+from typing import Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+def modulate(x, shift, scale):
+ return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
+
+
+def pool_tokens(x: torch.Tensor, mask: torch.Tensor, *, keepdim=False) -> torch.Tensor:
+ """
+ Pool tokens in x using mask.
+
+ NOTE: We assume x does not require gradients.
+
+ Args:
+ x: (B, L, D) tensor of tokens.
+ mask: (B, L) boolean tensor indicating which tokens are not padding.
+
+ Returns:
+ pooled: (B, D) tensor of pooled tokens.
+ """
+ assert x.size(1) == mask.size(1) # Expected mask to have same length as tokens.
+ assert x.size(0) == mask.size(0) # Expected mask to have same batch size as tokens.
+ mask = mask[:, :, None].to(dtype=x.dtype)
+ mask = mask / mask.sum(dim=1, keepdim=True).clamp(min=1)
+ pooled = (x * mask).sum(dim=1, keepdim=keepdim)
+ return pooled
+
+
+class AttentionPool(nn.Module):
+ def __init__(
+ self,
+ embed_dim: int,
+ num_heads: int,
+ output_dim: int = None,
+ device: Optional[torch.device] = None,
+ ):
+ """
+ Args:
+ spatial_dim (int): Number of tokens in sequence length.
+ embed_dim (int): Dimensionality of input tokens.
+ num_heads (int): Number of attention heads.
+ output_dim (int): Dimensionality of output tokens. Defaults to embed_dim.
+ """
+ super().__init__()
+ self.num_heads = num_heads
+ self.to_kv = nn.Linear(embed_dim, 2 * embed_dim, device=device)
+ self.to_q = nn.Linear(embed_dim, embed_dim, device=device)
+ self.to_out = nn.Linear(embed_dim, output_dim or embed_dim, device=device)
+
+ def forward(self, x, mask):
+ """
+ Args:
+ x (torch.Tensor): (B, L, D) tensor of input tokens.
+ mask (torch.Tensor): (B, L) boolean tensor indicating which tokens are not padding.
+
+ NOTE: We assume x does not require gradients.
+
+ Returns:
+ x (torch.Tensor): (B, D) tensor of pooled tokens.
+ """
+ D = x.size(2)
+
+ # Construct attention mask, shape: (B, 1, num_queries=1, num_keys=1+L).
+ attn_mask = mask[:, None, None, :].bool() # (B, 1, 1, L).
+ attn_mask = F.pad(attn_mask, (1, 0), value=True) # (B, 1, 1, 1+L).
+
+ # Average non-padding token features. These will be used as the query.
+ x_pool = pool_tokens(x, mask, keepdim=True) # (B, 1, D)
+
+ # Concat pooled features to input sequence.
+ x = torch.cat([x_pool, x], dim=1) # (B, L+1, D)
+
+ # Compute queries, keys, values. Only the mean token is used to create a query.
+ kv = self.to_kv(x) # (B, L+1, 2 * D)
+ q = self.to_q(x[:, 0]) # (B, D)
+
+ # Extract heads.
+ head_dim = D // self.num_heads
+ kv = kv.unflatten(2, (2, self.num_heads, head_dim)) # (B, 1+L, 2, H, head_dim)
+ kv = kv.transpose(1, 3) # (B, H, 2, 1+L, head_dim)
+ k, v = kv.unbind(2) # (B, H, 1+L, head_dim)
+ q = q.unflatten(1, (self.num_heads, head_dim)) # (B, H, head_dim)
+ q = q.unsqueeze(2) # (B, H, 1, head_dim)
+
+ # Compute attention.
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0) # (B, H, 1, head_dim)
+
+ # Concatenate heads and run output.
+ x = x.squeeze(2).flatten(1, 2) # (B, D = H * head_dim)
+ x = self.to_out(x)
+ return x
+
+
+def pad_and_split_xy(xy, indices, B, N, L, dtype) -> Tuple[torch.Tensor, torch.Tensor]:
+ D = xy.size(1)
+
+ # Pad sequences to (B, N + L, dim).
+ assert indices.ndim == 1
+ indices = indices.unsqueeze(1).expand(-1, D) # (total,) -> (total, num_heads * head_dim)
+ output = torch.zeros(B * (N + L), D, device=xy.device, dtype=dtype)
+ output = torch.scatter(output, 0, indices, xy)
+ xy = output.view(B, N + L, D)
+
+ # Split visual and text tokens along the sequence length.
+ return torch.tensor_split(xy, (N,), dim=1)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/models_i2v_txt_free.py b/One-to-All-Animation/video-generation/opensora/model_variants/models_i2v_txt_free.py
new file mode 100644
index 0000000000000000000000000000000000000000..e446df50d0306287401730c4b2c1e971834c3908
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/models_i2v_txt_free.py
@@ -0,0 +1,897 @@
+from typing import Any, List, Tuple, Optional, Union, Dict
+from einops import rearrange
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import json
+import os
+from functools import reduce
+from diffusers.loaders import PeftAdapterMixin
+
+from diffusers.models import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version
+
+from .activation_layers import get_activation_layer
+from .norm_layers import get_norm_layer
+from .embed_layers import TimestepEmbedder, PatchEmbed, TextProjection
+from .attenion import attention, get_cu_seqlens, get_cu_seqlens_
+from .posemb_layers import apply_rotary_emb, get_nd_rotary_pos_embed
+from .mlp_layers import MLP, MLPEmbedder, FinalLayer
+from .modulate_layers import ModulateDiT, modulate, apply_gate
+from .token_refiner import SingleTokenRefiner
+
+
+class MMDoubleStreamBlock(nn.Module):
+ """
+ A multimodal dit block with seperate modulation for
+ text and image/video, see more details (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qkv_bias: bool = False,
+ action_config: dict = {},
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+
+ self.img_mod = ModulateDiT(
+ hidden_size,
+ factor=6,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ self.img_norm1 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.img_attn_qkv = nn.Linear(
+ hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ )
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.img_attn_q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.img_attn_proj = nn.Linear(
+ hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ )
+
+ self.img_norm2 = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+ self.img_mlp = MLP(
+ hidden_size,
+ mlp_hidden_dim,
+ act_layer=get_activation_layer(mlp_act_type),
+ bias=True,
+ **factory_kwargs,
+ )
+
+ # self.txt_mod = ModulateDiT(
+ # hidden_size,
+ # factor=6,
+ # act_layer=get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # self.txt_norm1 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+
+ # self.txt_attn_qkv = nn.Linear(
+ # hidden_size, hidden_size * 3, bias=qkv_bias, **factory_kwargs
+ # )
+ # self.txt_attn_q_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_k_norm = (
+ # qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ # if qk_norm
+ # else nn.Identity()
+ # )
+ # self.txt_attn_proj = nn.Linear(
+ # hidden_size, hidden_size, bias=qkv_bias, **factory_kwargs
+ # )
+
+ # self.txt_norm2 = nn.LayerNorm(
+ # hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ # )
+ # self.txt_mlp = MLP(
+ # hidden_size,
+ # mlp_hidden_dim,
+ # act_layer=get_activation_layer(mlp_act_type),
+ # bias=True,
+ # **factory_kwargs,
+ # )
+ if len(action_config) != 0:
+ from .motion_module import ActionModule
+ self.action_model = ActionModule(**action_config)
+ else:
+ self.action_model = None
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ img: torch.Tensor,
+ # txt: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: tuple = None,
+ kwargs = None,
+ mouse_condition = None,
+ keyboard_condition = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ (
+ img_mod1_shift,
+ img_mod1_scale,
+ img_mod1_gate,
+ img_mod2_shift,
+ img_mod2_scale,
+ img_mod2_gate,
+ ) = self.img_mod(vec).chunk(6, dim=-1)
+ # (
+ # txt_mod1_shift,
+ # txt_mod1_scale,
+ # txt_mod1_gate,
+ # txt_mod2_shift,
+ # txt_mod2_scale,
+ # txt_mod2_gate,
+ # ) = self.txt_mod(vec).chunk(6, dim=-1)
+ # import ipdb; ipdb.set_trace()
+ # Prepare image for attention.
+ img_modulated = self.img_norm1(img)
+ img_modulated = modulate(
+ img_modulated, shift=img_mod1_shift, scale=img_mod1_scale
+ )
+ img_qkv = self.img_attn_qkv(img_modulated)
+ img_q, img_k, img_v = rearrange(
+ img_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ )
+ # Apply QK-Norm if needed
+ img_q = self.img_attn_q_norm(img_q).to(img_v)
+ img_k = self.img_attn_k_norm(img_k).to(img_v)
+
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ img_q, img_k = img_qq, img_kk
+
+ # Prepare txt for attention.
+ # txt_modulated = self.txt_norm1(txt)
+ # txt_modulated = modulate(
+ # txt_modulated, shift=txt_mod1_shift, scale=txt_mod1_scale
+ # )
+ # txt_qkv = self.txt_attn_qkv(txt_modulated)
+ # txt_q, txt_k, txt_v = rearrange(
+ # txt_qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num
+ # )
+ # # Apply QK-Norm if needed.
+ # txt_q = self.txt_attn_q_norm(txt_q).to(txt_v)
+ # txt_k = self.txt_attn_k_norm(txt_k).to(txt_v)
+
+ # Run actual attention.
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+ # v = torch.cat((img_v, txt_v), dim=1)
+ q = img_q
+ k = img_k
+ v = img_v
+ assert (
+ cu_seqlens_q.shape[0] == 2 * img.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, img.shape[0]:{img.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=img_k.shape[0],
+ )
+
+ # img_attn, txt_attn = attn[:, : img.shape[1]], attn[:, img.shape[1] :]
+ img_attn = attn
+ if (mouse_condition is not None) and (keyboard_condition is not None):
+ mouse_condition.to(img_attn.device, img_attn.dtype)
+ keyboard_condition.to(img_attn.device, img_attn.dtype)
+ img_attn = self.action_model(mouse_condition,keyboard_condition,img_attn,**kwargs)
+ # Calculate the img bloks.
+ img = img + apply_gate(self.img_attn_proj(img_attn), gate=img_mod1_gate)
+ img = img + apply_gate(
+ self.img_mlp(
+ modulate(
+ self.img_norm2(img), shift=img_mod2_shift, scale=img_mod2_scale
+ )
+ ),
+ gate=img_mod2_gate,
+ )
+
+ # Calculate the txt bloks.
+ # txt = txt + apply_gate(self.txt_attn_proj(txt_attn), gate=txt_mod1_gate)
+ # txt = txt + apply_gate(
+ # self.txt_mlp(
+ # modulate(
+ # self.txt_norm2(txt), shift=txt_mod2_shift, scale=txt_mod2_scale
+ # )
+ # ),
+ # gate=txt_mod2_gate,
+ # )
+
+ return img
+
+
+class MMSingleStreamBlock(nn.Module):
+ """
+ A DiT block with parallel linear layers as described in
+ https://arxiv.org/abs/2302.05442 and adapted modulation interface.
+ Also refer to (SD3): https://arxiv.org/abs/2403.03206
+ (Flux.1): https://github.com/black-forest-labs/flux
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ heads_num: int,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ qk_scale: float = None,
+ action_config: dict = {},
+ dtype: Optional[torch.dtype] = None,
+ device: Optional[torch.device] = None,
+ ):
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.deterministic = False
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+ head_dim = hidden_size // heads_num
+ mlp_hidden_dim = int(hidden_size * mlp_width_ratio)
+ self.mlp_hidden_dim = mlp_hidden_dim
+ self.scale = qk_scale or head_dim ** -0.5
+
+ # qkv and mlp_in
+ self.linear1 = nn.Linear(
+ hidden_size, hidden_size * 3 + mlp_hidden_dim, **factory_kwargs
+ )
+ # proj and mlp_out
+ self.linear2 = nn.Linear(
+ hidden_size + mlp_hidden_dim, hidden_size, **factory_kwargs
+ )
+
+ qk_norm_layer = get_norm_layer(qk_norm_type)
+ self.q_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+ self.k_norm = (
+ qk_norm_layer(head_dim, elementwise_affine=True, eps=1e-6, **factory_kwargs)
+ if qk_norm
+ else nn.Identity()
+ )
+
+ self.pre_norm = nn.LayerNorm(
+ hidden_size, elementwise_affine=False, eps=1e-6, **factory_kwargs
+ )
+
+ self.mlp_act = get_activation_layer(mlp_act_type)()
+ self.modulation = ModulateDiT(
+ hidden_size,
+ factor=3,
+ act_layer=get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+ if len(action_config) != 0:
+ from .motion_module import ActionModule
+ self.action_model = ActionModule(**action_config)
+ else:
+ self.action_model = None
+
+ def enable_deterministic(self):
+ self.deterministic = True
+
+ def disable_deterministic(self):
+ self.deterministic = False
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ vec: torch.Tensor,
+ cu_seqlens_q: Optional[torch.Tensor] = None,
+ cu_seqlens_kv: Optional[torch.Tensor] = None,
+ max_seqlen_q: Optional[int] = None,
+ max_seqlen_kv: Optional[int] = None,
+ freqs_cis: Tuple[torch.Tensor, torch.Tensor] = None,
+ kwargs = None,
+ mouse_condition = None,
+ keyboard_condition = None,
+ ) -> torch.Tensor:
+ mod_shift, mod_scale, mod_gate = self.modulation(vec).chunk(3, dim=-1)
+ x_mod = modulate(self.pre_norm(x), shift=mod_shift, scale=mod_scale)
+ qkv, mlp = torch.split(
+ self.linear1(x_mod), [3 * self.hidden_size, self.mlp_hidden_dim], dim=-1
+ )
+
+ q, k, v = rearrange(qkv, "B L (K H D) -> K B L H D", K=3, H=self.heads_num)
+
+ # Apply QK-Norm if needed.
+ q = self.q_norm(q).to(v)
+ k = self.k_norm(k).to(v)
+ # Apply RoPE if needed.
+ if freqs_cis is not None:
+ img_q = q
+ img_k = k
+ img_qq, img_kk = apply_rotary_emb(img_q, img_k, freqs_cis, head_first=False)
+ assert (
+ img_qq.shape == img_q.shape and img_kk.shape == img_k.shape
+ ), f"img_kk: {img_qq.shape}, img_q: {img_q.shape}, img_kk: {img_kk.shape}, img_k: {img_k.shape}"
+ q, k = img_qq, img_kk
+ # q = torch.cat((img_q, txt_q), dim=1)
+ # k = torch.cat((img_k, txt_k), dim=1)
+
+ # Compute attention.
+ assert (
+ cu_seqlens_q.shape[0] == 2 * x.shape[0] + 1
+ ), f"cu_seqlens_q.shape:{cu_seqlens_q.shape}, x.shape[0]:{x.shape[0]}"
+ attn = attention(
+ q,
+ k,
+ v,
+ cu_seqlens_q=cu_seqlens_q,
+ cu_seqlens_kv=cu_seqlens_kv,
+ max_seqlen_q=max_seqlen_q,
+ max_seqlen_kv=max_seqlen_kv,
+ batch_size=x.shape[0],
+ )
+ if (mouse_condition is not None) and (keyboard_condition is not None):
+ image_seq_len = reduce(lambda x, y: x * y, kwargs.values())
+ mouse_condition.to(attn.device, attn.dtype)
+ keyboard_condition.to(attn.device, attn.dtype)
+ # attn[:,:image_seq_len,...] = self.action_model(mouse_condition,keyboard_condition,attn[:,:image_seq_len,...],**kwargs)
+ # img_attn, txt_attn = attn[:,:image_seq_len,...], attn[:,image_seq_len:,...]
+ img_attn = attn
+ attn = self.action_model(mouse_condition,keyboard_condition, img_attn, **kwargs)
+ # attn = torch.cat([img_attn, txt_attn],dim = 1)
+ # Compute activation in mlp stream, cat again and run second linear layer.
+ output = self.linear2(torch.cat((attn, self.mlp_act(mlp)), 2))
+ return x + apply_gate(output, gate=mod_gate)
+
+
+class HYVideoDiffusionTransformerTxtFree(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ HunyuanVideo Transformer backbone
+
+ Inherited from ModelMixin and ConfigMixin for compatibility with diffusers' sampler StableDiffusionPipeline.
+
+ Reference:
+ [1] Flux.1: https://github.com/black-forest-labs/flux
+ [2] MMDiT: http://arxiv.org/abs/2403.03206
+
+ Parameters
+ ----------
+ args: argparse.Namespace
+ The arguments parsed by argparse.
+ patch_size: list
+ The size of the patch.
+ in_channels: int
+ The number of input channels.
+ out_channels: int
+ The number of output channels.
+ hidden_size: int
+ The hidden size of the transformer backbone.
+ heads_num: int
+ The number of attention heads.
+ mlp_width_ratio: float
+ The ratio of the hidden size of the MLP in the transformer block.
+ mlp_act_type: str
+ The activation function of the MLP in the transformer block.
+ depth_double_blocks: int
+ The number of transformer blocks in the double blocks.
+ depth_single_blocks: int
+ The number of transformer blocks in the single blocks.
+ rope_dim_list: list
+ The dimension of the rotary embedding for t, h, w.
+ qkv_bias: bool
+ Whether to use bias in the qkv linear layer.
+ qk_norm: bool
+ Whether to use qk norm.
+ qk_norm_type: str
+ The type of qk norm.
+ guidance_embed: bool
+ Whether to use guidance embedding for distillation.
+ text_projection: str
+ The type of the text projection, default is single_refiner.
+ use_attention_mask: bool
+ Whether to use attention mask for text encoder.
+ dtype: torch.dtype
+ The dtype of the model.
+ device: torch.device
+ The device of the model.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ text_states_dim,
+ text_states_dim_2,
+ patch_size: list = [1, 2, 2],
+ in_channels: int = 4, # Should be VAE.config.latent_channels.
+ out_channels: int = None,
+ hidden_size: int = 3072,
+ heads_num: int = 24,
+ mlp_width_ratio: float = 4.0,
+ mlp_act_type: str = "gelu_tanh",
+ mm_double_blocks_depth: int = 20,
+ mm_single_blocks_depth: int = 40,
+ rope_dim_list: List[int] = [16, 56, 56],
+ qkv_bias: bool = True,
+ qk_norm: bool = True,
+ qk_norm_type: str = "rms",
+ guidance_embed: bool = False, # For modulation.
+ text_projection: str = "single_refiner",
+ use_attention_mask: bool = True,
+ rope_theta = 256,
+ action_config = {},
+ ):
+ device = None
+ dtype = None
+ factory_kwargs = {"device": device, "dtype": dtype}
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.unpatchify_channels = self.out_channels
+ self.guidance_embed = guidance_embed
+ self.rope_dim_list = rope_dim_list
+ self.rope_theta = rope_theta
+
+ # Text projection. Default to linear projection.
+ # Alternative: TokenRefiner. See more details (LI-DiT): http://arxiv.org/abs/2406.11831
+ self.use_attention_mask = use_attention_mask
+ self.text_projection = text_projection
+
+ self.text_states_dim = text_states_dim
+ self.text_states_dim_2 = text_states_dim_2
+
+ if hidden_size % heads_num != 0:
+ raise ValueError(
+ f"Hidden size {hidden_size} must be divisible by heads_num {heads_num}"
+ )
+ pe_dim = hidden_size // heads_num
+ if sum(rope_dim_list) != pe_dim:
+ raise ValueError(
+ f"Got {rope_dim_list} but expected positional dim {pe_dim}"
+ )
+ self.hidden_size = hidden_size
+ self.heads_num = heads_num
+
+ # image projection
+ self.img_in = PatchEmbed(
+ self.patch_size, self.in_channels, self.hidden_size, **factory_kwargs
+ )
+
+ # text projection
+ # if self.text_projection == "linear":
+ # self.txt_in = TextProjection(
+ # self.text_states_dim,
+ # self.hidden_size,
+ # get_activation_layer("silu"),
+ # **factory_kwargs,
+ # )
+ # elif self.text_projection == "single_refiner":
+ # self.txt_in = SingleTokenRefiner(
+ # self.text_states_dim, hidden_size, heads_num, depth=2, **factory_kwargs
+ # )
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # time modulation
+ self.time_in = TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+
+ # text modulation
+ # self.vector_in = MLPEmbedder(
+ # self.text_states_dim_2, self.hidden_size, **factory_kwargs
+ # )
+
+ # guidance modulation
+ self.guidance_in = (
+ TimestepEmbedder(
+ self.hidden_size, get_activation_layer("silu"), **factory_kwargs
+ )
+ if guidance_embed
+ else None
+ )
+
+ # double blocks
+ self.double_blocks = nn.ModuleList(
+ [
+ MMDoubleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ qkv_bias=qkv_bias,
+ action_config = action_config,
+ **factory_kwargs,
+ )
+ for _ in range(mm_double_blocks_depth)
+ ]
+ )
+
+ # single blocks
+ self.single_blocks = nn.ModuleList(
+ [
+ MMSingleStreamBlock(
+ self.hidden_size,
+ self.heads_num,
+ mlp_width_ratio=mlp_width_ratio,
+ mlp_act_type=mlp_act_type,
+ qk_norm=qk_norm,
+ qk_norm_type=qk_norm_type,
+ action_config = action_config,
+ **factory_kwargs,
+ )
+ for _ in range(mm_single_blocks_depth)
+ ]
+ )
+
+ self.final_layer = FinalLayer(
+ self.hidden_size,
+ self.patch_size,
+ self.out_channels,
+ get_activation_layer("silu"),
+ **factory_kwargs,
+ )
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ def enable_deterministic(self):
+ for block in self.double_blocks:
+ block.enable_deterministic()
+ for block in self.single_blocks:
+ block.enable_deterministic()
+
+ def disable_deterministic(self):
+ for block in self.double_blocks:
+ block.disable_deterministic()
+ for block in self.single_blocks:
+ block.disable_deterministic()
+
+ def forward(self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ mouse_condition = None,
+ keyboard_condition = None,
+ return_dict = True,
+ **kwargs #用于后续传入guidance
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ x = hidden_states
+ t = timestep
+ # text_states, text_states_2 = encoder_hidden_states
+ # text_mask, test_mask_2 = encoder_attention_mask
+
+ embedded_guidance_scale = 6.0#TODO: maybe problem
+ guidance = (
+ torch.tensor(
+ [embedded_guidance_scale] * hidden_states.shape[0],
+ dtype=torch.float32,
+ device=hidden_states.device,
+ ).to(hidden_states.dtype)
+ * 1000.0
+ if embedded_guidance_scale is not None
+ else None
+ )
+
+ out = {}
+ img = x
+ # txt = text_states
+ _, _, ot, oh, ow = x.shape
+ freqs_cos, freqs_sin = self.get_rotary_pos_embed(ot, oh, ow)
+ tt, th, tw = (
+ ot // self.patch_size[0],
+ oh // self.patch_size[1],
+ ow // self.patch_size[2],
+ )
+
+ # Prepare modulation vectors.
+ vec = self.time_in(t)
+
+ # text modulation
+ # vec = vec + self.vector_in(text_states_2)
+
+ # guidance modulation
+ if self.guidance_embed:
+ if guidance is None:
+ raise ValueError(
+ "Didn't get guidance strength for guidance distilled model."
+ )
+
+ # our timestep_embedding is merged into guidance_in(TimestepEmbedder)
+ vec = vec + self.guidance_in(guidance)
+
+ # Embed image and text.
+ img = self.img_in(img)
+ # if self.text_projection == "linear":
+ # txt = self.txt_in(txt)
+ # elif self.text_projection == "single_refiner":
+ # txt = self.txt_in(txt, t, text_mask if self.use_attention_mask else None)
+ # else:
+ # raise NotImplementedError(
+ # f"Unsupported text_projection: {self.text_projection}"
+ # )
+
+ # txt_seq_len = txt.shape[1]
+ img_seq_len = img.shape[1]
+
+ # Compute cu_squlens and max_seqlen for flash attention
+ cu_seqlens_q = get_cu_seqlens_(img, img_seq_len)
+ cu_seqlens_kv = cu_seqlens_q
+ max_seqlen_q = img_seq_len
+ max_seqlen_kv = max_seqlen_q
+
+ freqs_cis = (freqs_cos, freqs_sin) if freqs_cos is not None else None
+ # --------------------- Pass through DiT blocks ------------------------
+ for _, block in enumerate(self.double_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ image_kwargs: Dict[str, Any] = {"tt":hidden_states.shape[2] // self.patch_size[0],
+ "th":hidden_states.shape[3] // self.patch_size[1],
+ "tw":hidden_states.shape[4] // self.patch_size[2]}
+ img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ img,
+ # txt,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ image_kwargs,
+ mouse_condition,
+ keyboard_condition,
+ **ckpt_kwargs,
+ )
+ else:
+ image_kwargs: Dict[str, Any] = {"tt":hidden_states.shape[2] // self.patch_size[0],
+ "th":hidden_states.shape[3] // self.patch_size[1],
+ "tw":hidden_states.shape[4] // self.patch_size[2]}
+ double_block_args = [
+ img,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ freqs_cis,
+ image_kwargs,
+ mouse_condition,
+ keyboard_condition,
+ ]
+
+ img = block(*double_block_args)
+
+ # Merge txt and img to pass through single stream blocks.
+ # x = torch.cat((img, txt), 1)
+ x = img
+ if len(self.single_blocks) > 0:
+ for _, block in enumerate(self.single_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ image_kwargs: Dict[str, Any] = {"tt":hidden_states.shape[2] // self.patch_size[0],
+ "th":hidden_states.shape[3] // self.patch_size[1],
+ "tw":hidden_states.shape[4] // self.patch_size[2]}
+ x = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ image_kwargs,
+ mouse_condition,
+ keyboard_condition,
+ **ckpt_kwargs,
+ )
+ else:
+ image_kwargs: Dict[str, Any] = {"tt":hidden_states.shape[2] // self.patch_size[0],
+ "th":hidden_states.shape[3] // self.patch_size[1],
+ "tw":hidden_states.shape[4] // self.patch_size[2]}
+ single_block_args = [
+ x,
+ vec,
+ cu_seqlens_q,
+ cu_seqlens_kv,
+ max_seqlen_q,
+ max_seqlen_kv,
+ (freqs_cos, freqs_sin),
+ image_kwargs,
+ mouse_condition,
+ keyboard_condition,
+ ]
+
+ x = block(*single_block_args)
+
+ img = x
+
+ # ---------------------------- Final layer ------------------------------
+ img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels)
+
+ img = self.unpatchify(img, tt, th, tw)
+ output = img
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+ def get_rotary_pos_embed(self, video_length, height, width):
+ target_ndim = 3
+ ndim = 5 - 2
+ # 884
+ latents_size = [video_length, height, width]
+
+ if isinstance(self.config.patch_size, int):
+ assert all(s % self.config.patch_size == 0 for s in latents_size), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [s // self.config.patch_size for s in latents_size]
+ elif isinstance(self.config.patch_size, list):
+ assert all(
+ s % self.config.patch_size[idx] == 0
+ for idx, s in enumerate(latents_size)
+ ), (
+ f"Latent size(last {ndim} dimensions) should be divisible by patch size({self.config.patch_size}), "
+ f"but got {latents_size}."
+ )
+ rope_sizes = [
+ s // self.config.patch_size[idx] for idx, s in enumerate(latents_size)
+ ]
+
+ if len(rope_sizes) != target_ndim:
+ rope_sizes = [1] * (target_ndim - len(rope_sizes)) + rope_sizes # time axis
+ head_dim = self.config.hidden_size // self.config.heads_num
+ rope_dim_list = self.config.rope_dim_list
+ if rope_dim_list is None:
+ rope_dim_list = [head_dim // target_ndim for _ in range(target_ndim)]
+ assert (
+ sum(rope_dim_list) == head_dim
+ ), "sum(rope_dim_list) should equal to head_dim of attention layer"
+ freqs_cos, freqs_sin = get_nd_rotary_pos_embed(
+ rope_dim_list,
+ rope_sizes,
+ theta=self.config.rope_theta,
+ use_real=True,
+ theta_rescale_factor=1,
+ )
+ return freqs_cos, freqs_sin
+
+ def unpatchify(self, x, t, h, w):
+ """
+ x: (N, T, patch_size**2 * C)
+ imgs: (N, H, W, C)
+ """
+ c = self.unpatchify_channels
+ pt, ph, pw = self.patch_size
+ assert t * h * w == x.shape[1]
+
+ x = x.reshape(shape=(x.shape[0], t, h, w, c, pt, ph, pw))
+ x = torch.einsum("nthwcopq->nctohpwq", x)
+ imgs = x.reshape(shape=(x.shape[0], c, t * pt, h * ph, w * pw))
+
+ return imgs
+
+ def params_count(self):
+ counts = {
+ "double": sum(
+ [
+ sum(p.numel() for p in block.img_attn_qkv.parameters())
+ + sum(p.numel() for p in block.img_attn_proj.parameters())
+ + sum(p.numel() for p in block.img_mlp.parameters())
+ + sum(p.numel() for p in block.txt_attn_qkv.parameters())
+ + sum(p.numel() for p in block.txt_attn_proj.parameters())
+ + sum(p.numel() for p in block.txt_mlp.parameters())
+ for block in self.double_blocks
+ ]
+ ),
+ "single": sum(
+ [
+ sum(p.numel() for p in block.linear1.parameters())
+ + sum(p.numel() for p in block.linear2.parameters())
+ for block in self.single_blocks
+ ]
+ ),
+ "total": sum(p.numel() for p in self.parameters()),
+ }
+ counts["attn+mlp"] = counts["double"] + counts["single"]
+ return counts
+
+
+#################################################################################
+# HunyuanVideo Configs #
+#################################################################################
+
+HUNYUAN_VIDEO_CONFIG = {
+ "HYVideo-T/2": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ },
+ "HYVideo-T/2-cfgdistill": {
+ "mm_double_blocks_depth": 20,
+ "mm_single_blocks_depth": 40,
+ "rope_dim_list": [16, 56, 56],
+ "hidden_size": 3072,
+ "heads_num": 24,
+ "mlp_width_ratio": 4,
+ "guidance_embed": True,
+ },
+}
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/normalization.py b/One-to-All-Animation/video-generation/opensora/model_variants/normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..c7a85e998ce3fb81adb6f4abb46d8cac984ce6c4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/normalization.py
@@ -0,0 +1,350 @@
+import numbers
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from diffusers.utils import is_torch_version
+from .activations import get_activation
+from .embeddings import CombinedTimestepLabelEmbeddings, PixArtAlphaCombinedTimestepSizeEmbeddings
+
+class AdaLayerNormContinuous(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ conditioning_embedding_dim: int,
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
+ # However, this is how it was implemented in the original code, and it's rather likely you should
+ # set `elementwise_affine` to False.
+ elementwise_affine=True,
+ eps=1e-5,
+ bias=True,
+ norm_type="layer_norm",
+ ):
+ super().__init__()
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
+ elif norm_type == "rms_norm":
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
+ else:
+ raise ValueError(f"unknown norm_type {norm_type}")
+
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
+ scale, shift = torch.chunk(emb, 2, dim=1)
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
+ return x
+
+class LuminaLayerNormContinuous(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ conditioning_embedding_dim: int,
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
+ # However, this is how it was implemented in the original code, and it's rather likely you should
+ # set `elementwise_affine` to False.
+ elementwise_affine=True,
+ eps=1e-5,
+ bias=True,
+ norm_type="layer_norm",
+ out_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # AdaLN
+ self.silu = nn.SiLU()
+ self.linear_1 = nn.Linear(conditioning_embedding_dim, embedding_dim, bias=bias)
+
+ if norm_type == "layer_norm":
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
+ elif norm_type == "rms_norm":
+ self.norm = RMSNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
+ else:
+ raise ValueError(f"unknown norm_type {norm_type}")
+
+ self.linear_2 = None
+ if out_dim is not None:
+ self.linear_2 = nn.Linear(embedding_dim, out_dim, bias=bias)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ conditioning_embedding: torch.Tensor,
+ ) -> torch.Tensor:
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
+ emb = self.linear_1(self.silu(conditioning_embedding).to(x.dtype))
+ scale = emb
+ x = self.norm(x) * (1 + scale)[:, None, :]
+
+ if self.linear_2 is not None:
+ x = self.linear_2(x)
+
+ return x
+
+class MochiRMSNormZero(nn.Module):
+ r"""
+ Adaptive RMS Norm used in Mochi.
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ """
+
+ def __init__(
+ self, embedding_dim: int, hidden_dim: int, eps: float = 1e-5, elementwise_affine: bool = False
+ ) -> None:
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, hidden_dim)
+ self.norm = RMSNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
+
+ def forward(
+ self, hidden_states: torch.Tensor, emb: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ emb = self.linear(self.silu(emb))
+ scale_msa, gate_msa, scale_mlp, gate_mlp = emb.chunk(4, dim=1)
+ hidden_states = self.norm(hidden_states) * (1 + scale_msa[:, None])
+
+ return hidden_states, gate_msa, scale_mlp, gate_mlp
+
+
+class RMSNorm(nn.Module):
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ else:
+ self.weight = None
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
+
+ if self.weight is not None:
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+ hidden_states = hidden_states * self.weight
+ else:
+ hidden_states = hidden_states.to(input_dtype)
+
+ return hidden_states
+
+class AdaLayerNorm(nn.Module):
+ r"""
+ Norm layer modified to incorporate timestep embeddings.
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`, *optional*): The size of the embeddings dictionary.
+ output_dim (`int`, *optional*):
+ norm_elementwise_affine (`bool`, defaults to `False):
+ norm_eps (`bool`, defaults to `False`):
+ chunk_dim (`int`, defaults to `0`):
+ """
+
+ def __init__(
+ self,
+ embedding_dim: int,
+ num_embeddings: Optional[int] = None,
+ output_dim: Optional[int] = None,
+ norm_elementwise_affine: bool = False,
+ norm_eps: float = 1e-5,
+ chunk_dim: int = 0,
+ ):
+ super().__init__()
+
+ self.chunk_dim = chunk_dim
+ output_dim = output_dim or embedding_dim * 2
+
+ if num_embeddings is not None:
+ self.emb = nn.Embedding(num_embeddings, embedding_dim)
+ else:
+ self.emb = None
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, output_dim)
+ self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine)
+
+ def forward(
+ self, x: torch.Tensor, timestep: Optional[torch.Tensor] = None, temb: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ if self.emb is not None:
+ temb = self.emb(timestep)
+
+ temb = self.linear(self.silu(temb))
+
+ if self.chunk_dim == 1:
+ # This is a bit weird why we have the order of "shift, scale" here and "scale, shift" in the
+ # other if-branch. This branch is specific to CogVideoX for now.
+ shift, scale = temb.chunk(2, dim=1)
+ shift = shift[:, None, :]
+ scale = scale[:, None, :]
+ else:
+ scale, shift = temb.chunk(2, dim=0)
+
+ x = self.norm(x) * (1 + scale) + shift
+ return x
+
+class CogVideoXLayerNormZero(nn.Module):
+ def __init__(
+ self,
+ conditioning_dim: int,
+ embedding_dim: int,
+ elementwise_affine: bool = True,
+ eps: float = 1e-5,
+ bias: bool = True,
+ ) -> None:
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(conditioning_dim, 6 * embedding_dim, bias=bias)
+ self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
+
+ def forward(
+ self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ shift, scale, gate, enc_shift, enc_scale, enc_gate = self.linear(self.silu(temb)).chunk(6, dim=1)
+ hidden_states = self.norm(hidden_states) * (1 + scale)[:, None, :] + shift[:, None, :]
+ encoder_hidden_states = self.norm(encoder_hidden_states) * (1 + enc_scale)[:, None, :] + enc_shift[:, None, :]
+ return hidden_states, encoder_hidden_states, gate[:, None, :], enc_gate[:, None, :]
+
+if is_torch_version(">=", "2.1.0"):
+ LayerNorm = nn.LayerNorm
+else:
+ # Has optional bias parameter compared to torch layer norm
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
+ class LayerNorm(nn.Module):
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
+ else:
+ self.weight = None
+ self.bias = None
+
+ def forward(self, input):
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
+
+class AdaLayerNormZero(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None, norm_type="layer_norm", bias=True):
+ super().__init__()
+ if num_embeddings is not None:
+ self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
+ else:
+ self.emb = None
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ elif norm_type == "fp32_layer_norm":
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
+ else:
+ raise ValueError(
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ timestep: Optional[torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ hidden_dtype: Optional[torch.dtype] = None,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ if self.emb is not None:
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
+
+
+class AdaLayerNormZeroSingle(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ raise ValueError(
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa
+
+class LpNorm(nn.Module):
+ def __init__(self, p: int = 2, dim: int = -1, eps: float = 1e-12):
+ super().__init__()
+
+ self.p = p
+ self.dim = dim
+ self.eps = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return F.normalize(hidden_states, p=self.p, dim=self.dim, eps=self.eps)
+
+
+class FP32LayerNorm(nn.LayerNorm):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ origin_dtype = inputs.dtype
+ return F.layer_norm(
+ inputs.float(),
+ self.normalized_shape,
+ self.weight.float() if self.weight is not None else None,
+ self.bias.float() if self.bias is not None else None,
+ self.eps,
+ ).to(origin_dtype)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/transformer_cogvideo.py b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_cogvideo.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc6fa0d0c89b0b6f9b194355a7c576a937d30334
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_cogvideo.py
@@ -0,0 +1,824 @@
+# Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
+# All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+import torch
+from torch import nn
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.models.modeling_utils import ModelMixin
+
+from .attention import FeedForward
+from .attention_processor import Attention, CogVideoXAttnProcessor2_0, FusedCogVideoXAttnProcessor2_0
+from .embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps, get_2d_sincos_pos_embed, get_3d_rotary_pos_embed
+from .normalization import AdaLayerNorm, CogVideoXLayerNormZero
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+def get_resize_crop_region_for_grid(src, tgt_width, tgt_height):
+ tw = tgt_width
+ th = tgt_height
+ h, w = src
+ r = h / w
+ if r > (th / tw):
+ resize_height = th
+ resize_width = int(round(th / h * w))
+ else:
+ resize_width = tw
+ resize_height = int(round(tw / w * h))
+
+ crop_top = int(round((th - resize_height) / 2.0))
+ crop_left = int(round((tw - resize_width) / 2.0))
+
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width) #在720x480的grid上crop的左上角和右下角
+
+
+def prepare_rotary_positional_embeddings(
+ height: int,
+ width: int,
+ num_frames: int,
+ vae_scale_factor_spatial: int = 8,
+ patch_size: int = 2,
+ patch_size_t = 1,
+ attention_head_dim: int = 64,
+ device = None,
+ dtype = None,
+ base_height: int = 480,
+ base_width: int = 720,
+):
+ grid_height = height // patch_size
+ grid_width = width // patch_size
+
+ p = patch_size
+ p_t = patch_size_t
+
+ if p_t is None:
+ # CogVideoX 1.0 I2V
+ base_size_width = base_width // p
+ base_size_height = base_height // p
+
+ grid_crops_coords = get_resize_crop_region_for_grid(
+ (grid_height, grid_width), base_size_width, base_size_height
+ )
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
+ embed_dim=attention_head_dim,
+ crops_coords=grid_crops_coords,
+ grid_size=(grid_height, grid_width),
+ temporal_size=num_frames,
+ )
+ else:
+ # CogVideoX 1.5 I2V
+ base_size_width = base_width // p
+ base_size_height = base_height // p
+ base_num_frames = (num_frames + p_t - 1) // p_t
+
+ grid_crops_coords = get_resize_crop_region_for_grid(
+ (grid_height, grid_width), base_size_width, base_size_height
+ )
+
+ freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
+ embed_dim=attention_head_dim,
+ crops_coords=grid_crops_coords,
+ grid_size=(grid_height, grid_width),
+ temporal_size=base_num_frames,
+ grid_type="slice",
+ max_size=(base_size_height, base_size_width),
+ )
+ freqs_cos = freqs_cos.to(device=device, dtype=dtype)
+ freqs_sin = freqs_sin.to(device=device, dtype=dtype)
+ return freqs_cos, freqs_sin
+
+ # grid_height = height // patch_size
+ # grid_width = width // patch_size
+ # base_size_width = base_width // patch_size
+ # base_size_height = base_height // patch_size
+ # base_num_frames = (num_frames + patch_size_t - 1) // patch_size_t
+
+ # grid_crops_coords = get_resize_crop_region_for_grid((grid_height, grid_width), base_size_width, base_size_height)
+ # freqs_cos, freqs_sin = get_3d_rotary_pos_embed(
+ # embed_dim=attention_head_dim,
+ # crops_coords=grid_crops_coords,
+ # grid_size=(grid_height, grid_width),
+ # temporal_size=base_num_frames,
+ # )
+
+ # freqs_cos = freqs_cos.to(device=device, dtype=dtype)
+ # freqs_sin = freqs_sin.to(device=device, dtype=dtype)
+ # return freqs_cos, freqs_sin
+
+@maybe_allow_in_graph
+class CogVideoXBlock(nn.Module):
+ r"""
+ Transformer block used in [CogVideoX](https://github.com/THUDM/CogVideo) model.
+
+ Parameters:
+ dim (`int`):
+ The number of channels in the input and output.
+ num_attention_heads (`int`):
+ The number of heads to use for multi-head attention.
+ attention_head_dim (`int`):
+ The number of channels in each head.
+ time_embed_dim (`int`):
+ The number of channels in timestep embedding.
+ dropout (`float`, defaults to `0.0`):
+ The dropout probability to use.
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
+ Activation function to be used in feed-forward.
+ attention_bias (`bool`, defaults to `False`):
+ Whether or not to use bias in attention projection layers.
+ qk_norm (`bool`, defaults to `True`):
+ Whether or not to use normalization after query and key projections in Attention.
+ norm_elementwise_affine (`bool`, defaults to `True`):
+ Whether to use learnable elementwise affine parameters for normalization.
+ norm_eps (`float`, defaults to `1e-5`):
+ Epsilon value for normalization layers.
+ final_dropout (`bool` defaults to `False`):
+ Whether to apply a final dropout after the last feed-forward layer.
+ ff_inner_dim (`int`, *optional*, defaults to `None`):
+ Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used.
+ ff_bias (`bool`, defaults to `True`):
+ Whether or not to use bias in Feed-forward layer.
+ attention_out_bias (`bool`, defaults to `True`):
+ Whether or not to use bias in Attention output projection layer.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ time_embed_dim: int,
+ dropout: float = 0.0,
+ activation_fn: str = "gelu-approximate",
+ attention_bias: bool = False,
+ qk_norm: bool = True,
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ final_dropout: bool = True,
+ ff_inner_dim: Optional[int] = None,
+ ff_bias: bool = True,
+ attention_out_bias: bool = True,
+ ):
+ super().__init__()
+
+ # 1. Self Attention
+ self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
+
+ self.attn1 = Attention(
+ query_dim=dim,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ qk_norm="layer_norm" if qk_norm else None,
+ eps=1e-6,
+ bias=attention_bias,
+ out_bias=attention_out_bias,
+ processor=CogVideoXAttnProcessor2_0(),
+ )
+
+ # 2. Feed Forward
+ self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
+
+ self.ff = FeedForward(
+ dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ final_dropout=final_dropout,
+ inner_dim=ff_inner_dim,
+ bias=ff_bias,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
+ ) -> torch.Tensor:
+ text_seq_length = encoder_hidden_states.size(1)
+
+ # norm & modulate
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
+ hidden_states, encoder_hidden_states, temb
+ )
+
+ # attention
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=norm_encoder_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ hidden_states = hidden_states + gate_msa * attn_hidden_states
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states
+
+ # norm & modulate
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
+ hidden_states, encoder_hidden_states, temb
+ )
+
+ # feed-forward
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
+ ff_output = self.ff(norm_hidden_states)
+
+ hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:]
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length]
+
+ return hidden_states, encoder_hidden_states
+
+
+class CogVideoXTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ A Transformer model for video-like data in [CogVideoX](https://github.com/THUDM/CogVideo).
+
+ Parameters:
+ num_attention_heads (`int`, defaults to `30`):
+ The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, defaults to `64`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, *optional*, defaults to `16`):
+ The number of channels in the output.
+ flip_sin_to_cos (`bool`, defaults to `True`):
+ Whether to flip the sin to cos in the time embedding.
+ time_embed_dim (`int`, defaults to `512`):
+ Output dimension of timestep embeddings.
+ ofs_embed_dim (`int`, defaults to `512`):
+ Output dimension of "ofs" embeddings used in CogVideoX-5b-I2B in version 1.5
+ text_embed_dim (`int`, defaults to `4096`):
+ Input dimension of text embeddings from the text encoder.
+ num_layers (`int`, defaults to `30`):
+ The number of layers of Transformer blocks to use.
+ dropout (`float`, defaults to `0.0`):
+ The dropout probability to use.
+ attention_bias (`bool`, defaults to `True`):
+ Whether to use bias in the attention projection layers.
+ sample_width (`int`, defaults to `90`):
+ The width of the input latents.
+ sample_height (`int`, defaults to `60`):
+ The height of the input latents.
+ sample_frames (`int`, defaults to `49`):
+ The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49
+ instead of 13 because CogVideoX processed 13 latent frames at once in its default and recommended settings,
+ but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with
+ K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1).
+ patch_size (`int`, defaults to `2`):
+ The size of the patches to use in the patch embedding layer.
+ temporal_compression_ratio (`int`, defaults to `4`):
+ The compression ratio across the temporal dimension. See documentation for `sample_frames`.
+ max_text_seq_length (`int`, defaults to `226`):
+ The maximum sequence length of the input text embeddings.
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
+ Activation function to use in feed-forward.
+ timestep_activation_fn (`str`, defaults to `"silu"`):
+ Activation function to use when generating the timestep embeddings.
+ norm_elementwise_affine (`bool`, defaults to `True`):
+ Whether to use elementwise affine in normalization layers.
+ norm_eps (`float`, defaults to `1e-5`):
+ The epsilon value to use in normalization layers.
+ spatial_interpolation_scale (`float`, defaults to `1.875`):
+ Scaling factor to apply in 3D positional embeddings across spatial dimensions.
+ temporal_interpolation_scale (`float`, defaults to `1.0`):
+ Scaling factor to apply in 3D positional embeddings across temporal dimensions.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 30,
+ attention_head_dim: int = 64,
+ in_channels: int = 16,
+ out_channels: Optional[int] = 16,
+ flip_sin_to_cos: bool = True,
+ freq_shift: int = 0,
+ time_embed_dim: int = 512,
+ ofs_embed_dim: Optional[int] = None,
+ text_embed_dim: int = 4096,
+ num_layers: int = 30,
+ dropout: float = 0.0,
+ attention_bias: bool = True,
+ sample_width: int = 90,
+ sample_height: int = 60,
+ sample_frames: int = 49,
+ patch_size: int = 2,
+ patch_size_t: Optional[int] = None,
+ temporal_compression_ratio: int = 4,
+ max_text_seq_length: int = 226,
+ activation_fn: str = "gelu-approximate",
+ timestep_activation_fn: str = "silu",
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ spatial_interpolation_scale: float = 1.875,
+ temporal_interpolation_scale: float = 1.0,
+ use_rotary_positional_embeddings: bool = False,
+ use_learned_positional_embeddings: bool = False,
+ patch_bias: bool = True,
+ ):
+ super().__init__()
+ inner_dim = num_attention_heads * attention_head_dim
+
+ if not use_rotary_positional_embeddings and use_learned_positional_embeddings:
+ raise ValueError(
+ "There are no CogVideoX checkpoints available with disable rotary embeddings and learned positional "
+ "embeddings. If you're using a custom model and/or believe this should be supported, please open an "
+ "issue at https://github.com/huggingface/diffusers/issues."
+ )
+
+ # 1. Patch embedding
+ self.patch_embed = CogVideoXPatchEmbed(
+ patch_size=patch_size,
+ patch_size_t=patch_size_t,
+ in_channels=in_channels,
+ embed_dim=inner_dim,
+ text_embed_dim=text_embed_dim,
+ bias=patch_bias,
+ sample_width=sample_width,
+ sample_height=sample_height,
+ sample_frames=sample_frames,
+ temporal_compression_ratio=temporal_compression_ratio,
+ max_text_seq_length=max_text_seq_length,
+ spatial_interpolation_scale=spatial_interpolation_scale,
+ temporal_interpolation_scale=temporal_interpolation_scale,
+ use_positional_embeddings=not use_rotary_positional_embeddings,
+ use_learned_positional_embeddings=use_learned_positional_embeddings,
+ )
+ self.embedding_dropout = nn.Dropout(dropout)
+
+ # 2. Time embeddings and ofs embedding(Only CogVideoX1.5-5B I2V have)
+
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
+
+ self.ofs_proj = None
+ self.ofs_embedding = None
+ if ofs_embed_dim:
+ self.ofs_proj = Timesteps(ofs_embed_dim, flip_sin_to_cos, freq_shift)
+ self.ofs_embedding = TimestepEmbedding(
+ ofs_embed_dim, ofs_embed_dim, timestep_activation_fn
+ ) # same as time embeddings, for ofs
+
+ # 3. Define spatio-temporal transformers blocks
+ self.transformer_blocks = nn.ModuleList(
+ [
+ CogVideoXBlock(
+ dim=inner_dim,
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ time_embed_dim=time_embed_dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ attention_bias=attention_bias,
+ norm_elementwise_affine=norm_elementwise_affine,
+ norm_eps=norm_eps,
+ )
+ for _ in range(num_layers)
+ ]
+ )
+ self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
+
+ # 4. Output blocks
+ self.norm_out = AdaLayerNorm(
+ embedding_dim=time_embed_dim,
+ output_dim=2 * inner_dim,
+ norm_elementwise_affine=norm_elementwise_affine,
+ norm_eps=norm_eps,
+ chunk_dim=1,
+ )
+
+ if patch_size_t is None:
+ # For CogVideox 1.0
+ output_dim = patch_size * patch_size * out_channels
+ else:
+ # For CogVideoX 1.5
+ output_dim = patch_size * patch_size * patch_size_t * out_channels
+
+ self.proj_out = nn.Linear(inner_dim, output_dim)
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ self.gradient_checkpointing = value
+
+ @property
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self):
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors):
+ if hasattr(module, "get_processor"):
+ processors[f"{name}.processor"] = module.get_processor()
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor):
+ r"""
+ Sets the attention processor to use to compute attention.
+
+ Parameters:
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ for **all** `Attention` layers.
+
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
+ processor. This is strongly recommended when setting trainable attention processors.
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedCogVideoXAttnProcessor2_0
+ def fuse_qkv_projections(self):
+ """
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
+ are fused. For cross-attention modules, key and value projection matrices are fused.
+
+
+
+ This API is 🧪 experimental.
+
+
+ """
+ self.original_attn_processors = None
+
+ for _, attn_processor in self.attn_processors.items():
+ if "Added" in str(attn_processor.__class__.__name__):
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
+
+ self.original_attn_processors = self.attn_processors
+
+ for module in self.modules():
+ if isinstance(module, Attention):
+ module.fuse_projections(fuse=True)
+
+ self.set_attn_processor(FusedCogVideoXAttnProcessor2_0())
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
+ def unfuse_qkv_projections(self):
+ """Disables the fused QKV projection if enabled.
+
+
+
+ This API is 🧪 experimental.
+
+
+
+ """
+ if self.original_attn_processors is not None:
+ self.set_attn_processor(self.original_attn_processors)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ timestep: Union[int, float, torch.LongTensor],
+ encoder_attention_mask = None,
+ ofs = None,
+ controlnet_states: torch.Tensor = None,
+ controlnet_weights: Optional[Union[float, int, list, np.ndarray, torch.FloatTensor]] = 1.0,
+ return_dict: bool = True,
+ ):
+ timestep_cond = None
+ attention_kwargs = None
+
+ image_rotary_emb = prepare_rotary_positional_embeddings(
+ height=hidden_states.shape[-2], #cogvideox固定分辨率
+ width=hidden_states.shape[-1],
+ num_frames=hidden_states.shape[1],
+ vae_scale_factor_spatial=8,
+ patch_size=2,
+ patch_size_t = self.config.patch_size_t or 1,
+ attention_head_dim=self.config.attention_head_dim,
+ base_height=self.config.sample_height,
+ base_width=self.config.sample_width,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype
+ )
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_frames, channels, height, width = hidden_states.shape
+
+ # 1. Time embedding
+ timesteps = timestep
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.ofs_embedding is not None:
+ ofs_emb = self.ofs_proj(ofs)
+ ofs_emb = ofs_emb.to(dtype=hidden_states.dtype)
+ ofs_emb = self.ofs_embedding(ofs_emb)
+ emb = emb + ofs_emb
+
+ # 2. Patch embedding
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
+ hidden_states = self.embedding_dropout(hidden_states)
+
+ text_seq_length = encoder_hidden_states.shape[1]
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
+ hidden_states = hidden_states[:, text_seq_length:]
+
+ controlnet_states_index = []
+ if controlnet_states is not None:
+ controlnet_states = list(controlnet_states)
+ interval_control, remainder = divmod(len(self.transformer_blocks)// 2, len(controlnet_states))
+ start = len(self.transformer_blocks) // 2
+ for _control_idx in range(len(controlnet_states)):
+ if remainder > 0:
+ control_index = start + interval_control + 1
+ remainder -= 1
+ else:
+ control_index = start + interval_control
+ controlnet_states_index.append(start)
+ start = control_index
+
+ # 3. Transformer blocks
+ for i, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ emb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ hidden_states, encoder_hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=emb,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ if (controlnet_states is not None) and (len(controlnet_states) > 0) and (i in controlnet_states_index):
+ controlnet_states_block = controlnet_states.pop()
+ if isinstance(controlnet_weights, (list, np.ndarray)) or torch.is_tensor(controlnet_weights):
+ controlnet_block_weight = controlnet_weights[i]
+ elif isinstance(controlnet_weights, (float, int)):
+ controlnet_block_weight = controlnet_weights
+ hidden_states = hidden_states + controlnet_states_block * controlnet_block_weight
+
+ if not self.config.use_rotary_positional_embeddings:
+ # CogVideoX-2B
+ hidden_states = self.norm_final(hidden_states)
+ else:
+ # CogVideoX-5B
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+ hidden_states = self.norm_final(hidden_states)
+ hidden_states = hidden_states[:, text_seq_length:]
+
+ # 4. Final block
+ hidden_states = self.norm_out(hidden_states, temb=emb)
+ hidden_states = self.proj_out(hidden_states)
+
+ # 5. Unpatchify
+ p = self.config.patch_size
+ p_t = self.config.patch_size_t
+
+ if p_t is None:
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
+ else:
+ output = hidden_states.reshape(
+ batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p
+ )
+ output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
+
+class CogVideoXTransformer3DModelControlnet(CogVideoXTransformer3DModel):
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ timestep: Union[int, float, torch.LongTensor],
+ encoder_attention_mask = None,
+ ofs: Optional[Union[int, float, torch.LongTensor]] = None,
+ controlnet_states: torch.Tensor = None,
+ controlnet_weights: Optional[Union[float, int, list, np.ndarray, torch.FloatTensor]] = 1.0,
+ return_dict: bool = True,
+ ):
+ timestep_cond = None
+ attention_kwargs = None
+
+ image_rotary_emb = prepare_rotary_positional_embeddings(
+ height=hidden_states.shape[-2], #cogvideox固定分辨率
+ width=hidden_states.shape[-1],
+ num_frames=hidden_states.shape[1],
+ vae_scale_factor_spatial=8,
+ patch_size=2,
+ patch_size_t = self.config.patch_size_t or 1,
+ attention_head_dim=self.config.attention_head_dim,
+ base_height=self.config.sample_height,
+ base_width=self.config.sample_width,
+ device=hidden_states.device,
+ dtype=hidden_states.dtype
+ )
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_frames, channels, height, width = hidden_states.shape
+
+ # 1. Time embedding
+ timesteps = timestep
+ t_emb = self.time_proj(timesteps)
+
+ # timesteps does not contain any weights and will always return f32 tensors
+ # but time_embedding might actually be running in fp16. so we need to cast here.
+ # there might be better ways to encapsulate this.
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
+ emb = self.time_embedding(t_emb, timestep_cond)
+
+ if self.ofs_embedding is not None:
+ ofs_emb = self.ofs_proj(ofs)
+ ofs_emb = ofs_emb.to(dtype=hidden_states.dtype)
+ ofs_emb = self.ofs_embedding(ofs_emb)
+ emb = emb + ofs_emb
+
+ # 2. Patch embedding
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
+ hidden_states = self.embedding_dropout(hidden_states)
+
+ text_seq_length = encoder_hidden_states.shape[1]
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
+ hidden_states = hidden_states[:, text_seq_length:]
+
+ # 3. Controlnet index
+ controlnet_states_index = []
+ if controlnet_states is not None:
+ controlnet_states = list(controlnet_states)
+ interval_control, remainder = divmod(len(self.transformer_blocks)// 2, len(controlnet_states))
+ start = len(self.transformer_blocks) // 2
+ for _control_idx in range(len(controlnet_states)):
+ if remainder > 0:
+ control_index = start + interval_control + 1
+ remainder -= 1
+ else:
+ control_index = start + interval_control
+ controlnet_states_index.append(start)
+ start = control_index
+ # 4. Transformer blocks
+ for i, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ emb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ hidden_states, encoder_hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=emb,
+ image_rotary_emb=image_rotary_emb,
+ )
+ if (controlnet_states is not None) and (len(controlnet_states) > 0) and (i in controlnet_states_index):
+ controlnet_states_block = controlnet_states.pop()
+ if isinstance(controlnet_weights, (list, np.ndarray)) or torch.is_tensor(controlnet_weights):
+ controlnet_block_weight = controlnet_weights[i]
+ elif isinstance(controlnet_weights, (float, int)):
+ controlnet_block_weight = controlnet_weights
+ hidden_states = hidden_states + controlnet_states_block * controlnet_block_weight
+
+ if not self.config.use_rotary_positional_embeddings:
+ # CogVideoX-2B
+ hidden_states = self.norm_final(hidden_states)
+ else:
+ # CogVideoX-5B
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+ hidden_states = self.norm_final(hidden_states)
+ hidden_states = hidden_states[:, text_seq_length:]
+
+ # 4. Final block
+ hidden_states = self.norm_out(hidden_states, temb=emb)
+ hidden_states = self.proj_out(hidden_states)
+
+ # 5. Unpatchify
+ p = self.config.patch_size
+ p_t = self.config.patch_size_t
+
+ if p_t is None:
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
+ else:
+ output = hidden_states.reshape(
+ batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p
+ )
+ output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/transformer_flux.py b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_flux.py
new file mode 100644
index 0000000000000000000000000000000000000000..f679c1bc43a86c4b76ff453d7a0edee6fdac5426
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_flux.py
@@ -0,0 +1,577 @@
+# Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+from typing import Any, Dict, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.utils import USE_PEFT_BACKEND, is_torch_version, logging, scale_lora_layers, unscale_lora_layers
+from diffusers.utils.import_utils import is_torch_npu_available
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention import FeedForward
+from .attention_processor import (
+ Attention,
+ AttentionProcessor,
+ FluxAttnProcessor2_0,
+ FluxAttnProcessor2_0_NPU,
+ FusedFluxAttnProcessor2_0,
+)
+from .normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
+from .embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@maybe_allow_in_graph
+class FluxSingleTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, mlp_ratio=4.0):
+ super().__init__()
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
+
+ self.norm = AdaLayerNormZeroSingle(dim)
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
+ self.act_mlp = nn.GELU(approximate="tanh")
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
+
+ if is_torch_npu_available():
+ processor = FluxAttnProcessor2_0_NPU()
+ else:
+ processor = FluxAttnProcessor2_0()
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ bias=True,
+ processor=processor,
+ qk_norm="rms_norm",
+ eps=1e-6,
+ pre_only=True,
+ )
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ image_rotary_emb=None,
+ joint_attention_kwargs=None,
+ ):
+ residual = hidden_states
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
+ joint_attention_kwargs = joint_attention_kwargs or {}
+ attn_output = self.attn(
+ hidden_states=norm_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ **joint_attention_kwargs,
+ )
+
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
+ gate = gate.unsqueeze(1)
+ hidden_states = gate * self.proj_out(hidden_states)
+ hidden_states = residual + hidden_states
+ if hidden_states.dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+@maybe_allow_in_graph
+class FluxTransformerBlock(nn.Module):
+ r"""
+ A Transformer block following the MMDiT architecture, introduced in Stable Diffusion 3.
+
+ Reference: https://arxiv.org/abs/2403.03206
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ context_pre_only (`bool`): Boolean to determine if we should add some blocks associated with the
+ processing of `context` conditions.
+ """
+
+ def __init__(self, dim, num_attention_heads, attention_head_dim, qk_norm="rms_norm", eps=1e-6):
+ super().__init__()
+
+ self.norm1 = AdaLayerNormZero(dim)
+
+ self.norm1_context = AdaLayerNormZero(dim)
+
+ if hasattr(F, "scaled_dot_product_attention"):
+ processor = FluxAttnProcessor2_0()
+ else:
+ raise ValueError(
+ "The current PyTorch version does not support the `scaled_dot_product_attention` function."
+ )
+ self.attn = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ added_kv_proj_dim=dim,
+ dim_head=attention_head_dim,
+ heads=num_attention_heads,
+ out_dim=dim,
+ context_pre_only=False,
+ bias=True,
+ processor=processor,
+ qk_norm=qk_norm,
+ eps=eps,
+ )
+
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor,
+ temb: torch.FloatTensor,
+ image_rotary_emb=None,
+ joint_attention_kwargs=None,
+ ):
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
+
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
+ encoder_hidden_states, emb=temb
+ )
+ joint_attention_kwargs = joint_attention_kwargs or {}
+ # Attention.
+ attn_output, context_attn_output = self.attn(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=norm_encoder_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ **joint_attention_kwargs,
+ )
+
+ # Process attention outputs for the `hidden_states`.
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ hidden_states = hidden_states + attn_output
+
+ norm_hidden_states = self.norm2(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ ff_output = self.ff(norm_hidden_states)
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+
+ hidden_states = hidden_states + ff_output
+
+ # Process attention outputs for the `encoder_hidden_states`.
+
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
+
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
+
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
+ if encoder_hidden_states.dtype == torch.float16:
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
+
+ return encoder_hidden_states, hidden_states
+
+
+class FluxTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ """
+ The Transformer model introduced in Flux.
+
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
+
+ Parameters:
+ patch_size (`int`): Patch size to turn the input data into small patches.
+ in_channels (`int`, *optional*, defaults to 16): The number of channels in the input.
+ num_layers (`int`, *optional*, defaults to 18): The number of layers of MMDiT blocks to use.
+ num_single_layers (`int`, *optional*, defaults to 18): The number of layers of single DiT blocks to use.
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
+ num_attention_heads (`int`, *optional*, defaults to 18): The number of heads to use for multi-head attention.
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ pooled_projection_dim (`int`): Number of dimensions to use when projecting the `pooled_projections`.
+ guidance_embeds (`bool`, defaults to False): Whether to use guidance embeddings.
+ """
+
+ _supports_gradient_checkpointing = True
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: int = 1,
+ in_channels: int = 64,
+ num_layers: int = 19,
+ num_single_layers: int = 38,
+ attention_head_dim: int = 128,
+ num_attention_heads: int = 24,
+ joint_attention_dim: int = 4096,
+ pooled_projection_dim: int = 768,
+ guidance_embeds: bool = False,
+ axes_dims_rope: Tuple[int] = (16, 56, 56),
+ ):
+ super().__init__()
+ self.out_channels = in_channels
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
+
+ text_time_guidance_cls = (
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
+ )
+ self.time_text_embed = text_time_guidance_cls(
+ embedding_dim=self.inner_dim, pooled_projection_dim=self.config.pooled_projection_dim
+ )
+
+ self.context_embedder = nn.Linear(self.config.joint_attention_dim, self.inner_dim)
+ self.x_embedder = torch.nn.Linear(self.config.in_channels, self.inner_dim)
+
+ self.transformer_blocks = nn.ModuleList(
+ [
+ FluxTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ )
+ for i in range(self.config.num_layers)
+ ]
+ )
+
+ self.single_transformer_blocks = nn.ModuleList(
+ [
+ FluxSingleTransformerBlock(
+ dim=self.inner_dim,
+ num_attention_heads=self.config.num_attention_heads,
+ attention_head_dim=self.config.attention_head_dim,
+ )
+ for i in range(self.config.num_single_layers)
+ ]
+ )
+
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
+
+ self.gradient_checkpointing = False
+
+ @property
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
+ r"""
+ Returns:
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
+ indexed by its weight name.
+ """
+ # set recursively
+ processors = {}
+
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
+ if hasattr(module, "get_processor"):
+ processors[f"{name}.processor"] = module.get_processor()
+
+ for sub_name, child in module.named_children():
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
+
+ return processors
+
+ for name, module in self.named_children():
+ fn_recursive_add_processors(name, module, processors)
+
+ return processors
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
+ r"""
+ Sets the attention processor to use to compute attention.
+
+ Parameters:
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
+ for **all** `Attention` layers.
+
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
+ processor. This is strongly recommended when setting trainable attention processors.
+
+ """
+ count = len(self.attn_processors.keys())
+
+ if isinstance(processor, dict) and len(processor) != count:
+ raise ValueError(
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
+ )
+
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
+ if hasattr(module, "set_processor"):
+ if not isinstance(processor, dict):
+ module.set_processor(processor)
+ else:
+ module.set_processor(processor.pop(f"{name}.processor"))
+
+ for sub_name, child in module.named_children():
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
+
+ for name, module in self.named_children():
+ fn_recursive_attn_processor(name, module, processor)
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
+ def fuse_qkv_projections(self):
+ """
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
+ are fused. For cross-attention modules, key and value projection matrices are fused.
+
+
+
+ This API is 🧪 experimental.
+
+
+ """
+ self.original_attn_processors = None
+
+ for _, attn_processor in self.attn_processors.items():
+ if "Added" in str(attn_processor.__class__.__name__):
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
+
+ self.original_attn_processors = self.attn_processors
+
+ for module in self.modules():
+ if isinstance(module, Attention):
+ module.fuse_projections(fuse=True)
+
+ self.set_attn_processor(FusedFluxAttnProcessor2_0())
+
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
+ def unfuse_qkv_projections(self):
+ """Disables the fused QKV projection if enabled.
+
+
+
+ This API is 🧪 experimental.
+
+
+
+ """
+ if self.original_attn_processors is not None:
+ self.set_attn_processor(self.original_attn_processors)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor = None,
+ pooled_projections: torch.Tensor = None,
+ timestep: torch.LongTensor = None,
+ img_ids: torch.Tensor = None,
+ txt_ids: torch.Tensor = None,
+ guidance: torch.Tensor = None,
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_block_samples=None,
+ controlnet_single_block_samples=None,
+ return_dict: bool = True,
+ controlnet_blocks_repeat: bool = False,
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
+ """
+ The [`FluxTransformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
+ Input `hidden_states`.
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
+ from the embeddings of input conditions.
+ timestep ( `torch.LongTensor`):
+ Used to indicate denoising step.
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
+ A list of tensors that if specified are added to the residuals of transformer blocks.
+ joint_attention_kwargs (`dict`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ if joint_attention_kwargs is not None:
+ joint_attention_kwargs = joint_attention_kwargs.copy()
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+ hidden_states = self.x_embedder(hidden_states) #linear映射
+
+ timestep = timestep.to(hidden_states.dtype) * 1000
+ if guidance is not None:
+ guidance = guidance.to(hidden_states.dtype) * 1000
+ else:
+ guidance = None
+ temb = (
+ self.time_text_embed(timestep, pooled_projections) #timestep进行sincos embedding之后,一些简单的norm和linear的映射。这里比较特殊的应该是timestep的embedding和guidance的embedding和text embedding相加。这里很难理解的是guidance的embedding是怎么被加到一起的,训练的时候是如何实现的?应该是guidance distillation,这样就不用batch_size=2推理了
+ if guidance is None
+ else self.time_text_embed(timestep, guidance, pooled_projections)
+ )
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states) #线性
+
+ if txt_ids.ndim == 3:
+ logger.warning(
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ txt_ids = txt_ids[0]
+ if img_ids.ndim == 3:
+ logger.warning(
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
+ )
+ img_ids = img_ids[0]
+
+ ids = torch.cat((txt_ids, img_ids), dim=0) #concat,text的id是(0,0,0),image的id是(0, h_idx, w_idx)
+ image_rotary_emb = self.pos_embed(ids) #感觉上是为了video的3D结构设计的,这部分需要check一下pf的实现是不是一样的
+
+ for index_block, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ encoder_hidden_states, hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ encoder_hidden_states, hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ joint_attention_kwargs=joint_attention_kwargs,
+ )
+
+ # controlnet residual
+ if controlnet_block_samples is not None:
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ # For Xlabs ControlNet.
+ if controlnet_blocks_repeat:
+ hidden_states = (
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ for index_block, block in enumerate(self.single_transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+
+ else:
+ hidden_states = block(
+ hidden_states=hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ joint_attention_kwargs=joint_attention_kwargs,
+ )
+
+ # controlnet residual
+ if controlnet_single_block_samples is not None:
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
+ + controlnet_single_block_samples[index_block // interval_control]
+ )
+
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
+
+ hidden_states = self.norm_out(hidden_states, temb)
+ output = self.proj_out(hidden_states)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi.py b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi.py
new file mode 100644
index 0000000000000000000000000000000000000000..38fabad19dbc11cf5d0a2dffd024cd2fdd7023e6
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi.py
@@ -0,0 +1,388 @@
+# Copyright 2024 The Genmo team and The HuggingFace Team.
+# All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from typing import Any, Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import is_torch_version, logging
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.models.modeling_utils import ModelMixin
+
+from .attention import FeedForward
+from .attention_processor import Attention, MochiAttnProcessor2_0
+from .embeddings import MochiCombinedTimestepCaptionEmbedding, PatchEmbed
+from .normalization import AdaLayerNormContinuous, LuminaLayerNormContinuous, MochiRMSNormZero, RMSNorm
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+@maybe_allow_in_graph
+class MochiTransformerBlock(nn.Module):
+ r"""
+ Transformer block used in [Mochi](https://huggingface.co/genmo/mochi-1-preview).
+
+ Args:
+ dim (`int`):
+ The number of channels in the input and output.
+ num_attention_heads (`int`):
+ The number of heads to use for multi-head attention.
+ attention_head_dim (`int`):
+ The number of channels in each head.
+ qk_norm (`str`, defaults to `"rms_norm"`):
+ The normalization layer to use.
+ activation_fn (`str`, defaults to `"swiglu"`):
+ Activation function to use in feed-forward.
+ context_pre_only (`bool`, defaults to `False`):
+ Whether or not to process context-related conditions with additional layers.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ pooled_projection_dim: int,
+ qk_norm: str = "rms_norm",
+ activation_fn: str = "swiglu",
+ context_pre_only: bool = False,
+ eps: float = 1e-6,
+ ) -> None:
+ super().__init__()
+
+ self.context_pre_only = context_pre_only
+ self.ff_inner_dim = (4 * dim * 2) // 3
+ self.ff_context_inner_dim = (4 * pooled_projection_dim * 2) // 3
+
+ self.norm1 = MochiRMSNormZero(dim, 4 * dim, eps=eps, elementwise_affine=False)
+
+ if not context_pre_only:
+ self.norm1_context = MochiRMSNormZero(dim, 4 * pooled_projection_dim, eps=eps, elementwise_affine=False)
+ else:
+ self.norm1_context = LuminaLayerNormContinuous(
+ embedding_dim=pooled_projection_dim,
+ conditioning_embedding_dim=dim,
+ eps=eps,
+ elementwise_affine=False,
+ norm_type="rms_norm",
+ out_dim=None,
+ )
+
+ self.attn1 = Attention(
+ query_dim=dim,
+ cross_attention_dim=None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ bias=False,
+ qk_norm=qk_norm,
+ added_kv_proj_dim=pooled_projection_dim,
+ added_proj_bias=False,
+ out_dim=dim,
+ out_context_dim=pooled_projection_dim,
+ context_pre_only=context_pre_only,
+ processor=MochiAttnProcessor2_0(),
+ eps=eps,
+ elementwise_affine=True,
+ )
+
+ # TODO(aryan): norm_context layers are not needed when `context_pre_only` is True
+ self.norm2 = RMSNorm(dim, eps=eps, elementwise_affine=False)
+ self.norm2_context = RMSNorm(pooled_projection_dim, eps=eps, elementwise_affine=False)
+
+ self.norm3 = RMSNorm(dim, eps=eps, elementwise_affine=False)
+ self.norm3_context = RMSNorm(pooled_projection_dim, eps=eps, elementwise_affine=False)
+
+ self.ff = FeedForward(dim, inner_dim=self.ff_inner_dim, activation_fn=activation_fn, bias=False)
+ self.ff_context = None
+ if not context_pre_only:
+ self.ff_context = FeedForward(
+ pooled_projection_dim,
+ inner_dim=self.ff_context_inner_dim,
+ activation_fn=activation_fn,
+ bias=False,
+ )
+
+ self.norm4 = RMSNorm(dim, eps=eps, elementwise_affine=False)
+ self.norm4_context = RMSNorm(pooled_projection_dim, eps=eps, elementwise_affine=False)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ norm_hidden_states, gate_msa, scale_mlp, gate_mlp = self.norm1(hidden_states, temb)
+
+ if not self.context_pre_only:
+ norm_encoder_hidden_states, enc_gate_msa, enc_scale_mlp, enc_gate_mlp = self.norm1_context(
+ encoder_hidden_states, temb
+ )
+ else:
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states, temb)
+
+ attn_hidden_states, context_attn_hidden_states = self.attn1(
+ hidden_states=norm_hidden_states,
+ encoder_hidden_states=norm_encoder_hidden_states,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ hidden_states = hidden_states + self.norm2(attn_hidden_states) * torch.tanh(gate_msa).unsqueeze(1)
+ norm_hidden_states = self.norm3(hidden_states) * (1 + scale_mlp.unsqueeze(1))
+ ff_output = self.ff(norm_hidden_states)
+ hidden_states = hidden_states + self.norm4(ff_output) * torch.tanh(gate_mlp).unsqueeze(1)
+
+ if not self.context_pre_only:
+ encoder_hidden_states = encoder_hidden_states + self.norm2_context(
+ context_attn_hidden_states
+ ) * torch.tanh(enc_gate_msa).unsqueeze(1)
+ norm_encoder_hidden_states = self.norm3_context(encoder_hidden_states) * (1 + enc_scale_mlp.unsqueeze(1))
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states + self.norm4_context(context_ff_output) * torch.tanh(
+ enc_gate_mlp
+ ).unsqueeze(1)
+
+ return hidden_states, encoder_hidden_states
+
+
+class MochiRoPE(nn.Module):
+ r"""
+ RoPE implementation used in [Mochi](https://huggingface.co/genmo/mochi-1-preview).
+
+ Args:
+ base_height (`int`, defaults to `192`):
+ Base height used to compute interpolation scale for rotary positional embeddings.
+ base_width (`int`, defaults to `192`):
+ Base width used to compute interpolation scale for rotary positional embeddings.
+ """
+
+ def __init__(self, base_height: int = 192, base_width: int = 192) -> None:
+ super().__init__()
+
+ self.target_area = base_height * base_width
+
+ def _centers(self, start, stop, num, device, dtype) -> torch.Tensor:
+ edges = torch.linspace(start, stop, num + 1, device=device, dtype=dtype)
+ return (edges[:-1] + edges[1:]) / 2
+
+ def _get_positions(
+ self,
+ num_frames: int,
+ height: int,
+ width: int,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ) -> torch.Tensor:
+ scale = (self.target_area / (height * width)) ** 0.5
+
+ t = torch.arange(num_frames, device=device, dtype=dtype)
+ h = self._centers(-height * scale / 2, height * scale / 2, height, device, dtype)
+ w = self._centers(-width * scale / 2, width * scale / 2, width, device, dtype)
+
+ grid_t, grid_h, grid_w = torch.meshgrid(t, h, w, indexing="ij")
+
+ positions = torch.stack([grid_t, grid_h, grid_w], dim=-1).view(-1, 3)
+ return positions
+
+ def _create_rope(self, freqs: torch.Tensor, pos: torch.Tensor) -> torch.Tensor:
+ freqs = torch.einsum("nd,dhf->nhf", pos, freqs.float())
+ freqs_cos = torch.cos(freqs)
+ freqs_sin = torch.sin(freqs)
+ return freqs_cos, freqs_sin
+
+ def forward(
+ self,
+ pos_frequencies: torch.Tensor,
+ num_frames: int,
+ height: int,
+ width: int,
+ device: Optional[torch.device] = None,
+ dtype: Optional[torch.dtype] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ pos = self._get_positions(num_frames, height, width, device, dtype)
+ rope_cos, rope_sin = self._create_rope(pos_frequencies, pos)
+ return rope_cos, rope_sin
+
+
+@maybe_allow_in_graph
+class MochiTransformer3DModel(ModelMixin, ConfigMixin):
+ r"""
+ A Transformer model for video-like data introduced in [Mochi](https://huggingface.co/genmo/mochi-1-preview).
+
+ Args:
+ patch_size (`int`, defaults to `2`):
+ The size of the patches to use in the patch embedding layer.
+ num_attention_heads (`int`, defaults to `24`):
+ The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ num_layers (`int`, defaults to `48`):
+ The number of layers of Transformer blocks to use.
+ in_channels (`int`, defaults to `12`):
+ The number of channels in the input.
+ out_channels (`int`, *optional*, defaults to `None`):
+ The number of channels in the output.
+ qk_norm (`str`, defaults to `"rms_norm"`):
+ The normalization layer to use.
+ text_embed_dim (`int`, defaults to `4096`):
+ Input dimension of text embeddings from the text encoder.
+ time_embed_dim (`int`, defaults to `256`):
+ Output dimension of timestep embeddings.
+ activation_fn (`str`, defaults to `"swiglu"`):
+ Activation function to use in feed-forward.
+ max_sequence_length (`int`, defaults to `256`):
+ The maximum sequence length of text embeddings supported.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: int = 2,
+ num_attention_heads: int = 24,
+ attention_head_dim: int = 128,
+ num_layers: int = 48,
+ pooled_projection_dim: int = 1536,
+ in_channels: int = 12,
+ out_channels: Optional[int] = None,
+ qk_norm: str = "rms_norm",
+ text_embed_dim: int = 4096,
+ time_embed_dim: int = 256,
+ activation_fn: str = "swiglu",
+ max_sequence_length: int = 256,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.patch_embed = PatchEmbed(
+ patch_size=patch_size,
+ in_channels=in_channels,
+ embed_dim=inner_dim,
+ pos_embed_type=None,
+ )
+
+ self.time_embed = MochiCombinedTimestepCaptionEmbedding(
+ embedding_dim=inner_dim,
+ pooled_projection_dim=pooled_projection_dim,
+ text_embed_dim=text_embed_dim,
+ time_embed_dim=time_embed_dim,
+ num_attention_heads=8,
+ )
+
+ self.pos_frequencies = nn.Parameter(torch.full((3, num_attention_heads, attention_head_dim // 2), 0.0))
+ self.rope = MochiRoPE()
+
+ self.transformer_blocks = nn.ModuleList(
+ [
+ MochiTransformerBlock(
+ dim=inner_dim,
+ num_attention_heads=num_attention_heads,
+ attention_head_dim=attention_head_dim,
+ pooled_projection_dim=pooled_projection_dim,
+ qk_norm=qk_norm,
+ activation_fn=activation_fn,
+ context_pre_only=i == num_layers - 1,
+ )
+ for i in range(num_layers)
+ ]
+ )
+
+ self.norm_out = AdaLayerNormContinuous(
+ inner_dim, inner_dim, elementwise_affine=False, eps=1e-6, norm_type="layer_norm"
+ )
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_attention_mask: torch.Tensor,
+ return_dict: bool = True,
+ ) -> torch.Tensor:
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4)
+ batch_size, num_frames, num_channels, height, width = hidden_states.shape
+ p = self.config.patch_size
+
+ post_patch_height = height // p
+ post_patch_width = width // p
+
+ temb, encoder_hidden_states = self.time_embed( #类似sd3中的操作,这里使用的应该是global pooling的方法,然后和原始的输入计算一个cross attention
+ timestep, encoder_hidden_states, encoder_attention_mask, hidden_dtype=hidden_states.dtype
+ )
+ hidden_states = hidden_states.flatten(0, 1)
+ hidden_states = self.patch_embed(hidden_states) #简单的patch embedding,类似Opensora_plan
+ hidden_states = hidden_states.unflatten(0, (batch_size, -1)).flatten(1, 2)
+
+ image_rotary_emb = self.rope( #这里也是在一个192x192的grid上进行类似crop的形式来缩放的,但是这里更加简单,直接根据面积比来进行相对scale的转换
+ self.pos_frequencies,
+ num_frames,
+ post_patch_height,
+ post_patch_width,
+ device=hidden_states.device,
+ dtype=torch.float32,
+ )
+
+ for i, block in enumerate(self.transformer_blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ hidden_states, encoder_hidden_states = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states,
+ encoder_hidden_states,
+ temb,
+ image_rotary_emb,
+ **ckpt_kwargs,
+ )
+ else:
+ hidden_states, encoder_hidden_states = block(
+ hidden_states=hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ temb=temb,
+ image_rotary_emb=image_rotary_emb,
+ )
+
+ hidden_states = self.norm_out(hidden_states, temb)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(batch_size, num_frames, post_patch_height, post_patch_width, p, p, -1)
+ hidden_states = hidden_states.permute(0, 6, 1, 2, 4, 3, 5)
+ output = hidden_states.reshape(batch_size, -1, num_frames, height, width)
+
+ if not return_dict:
+ return (output,)
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi_2.py b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..593877ccb1ec648924870e055d8cece8697730e3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/transformer_mochi_2.py
@@ -0,0 +1,854 @@
+'''
+原始repo的实现
+'''
+import os
+from typing import Dict, List, Optional, Tuple, Union, cast
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from einops import rearrange
+
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.utils import is_torch_version, logging
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.models.modeling_utils import ModelMixin
+
+from opensora.model_variants.mochi_layers import (
+ FeedForward,
+ PatchEmbed,
+ RMSNorm,
+ TimestepEmbedder,
+)
+
+from opensora.model_variants.mochi_utils import (
+ AttentionPool,
+ modulate,
+ pad_and_split_xy,
+)
+
+import functools
+import math
+
+# Based on Llama3 Implementation.
+import torch
+
+
+def apply_rotary_emb_qk_real(
+ xqk: torch.Tensor,
+ freqs_cos: torch.Tensor,
+ freqs_sin: torch.Tensor,
+) -> torch.Tensor:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor without complex numbers.
+
+ Args:
+ xqk (torch.Tensor): Query and/or Key tensors to apply rotary embeddings. Shape: (B, S, *, num_heads, D)
+ Can be either just query or just key, or both stacked along some batch or * dim.
+ freqs_cos (torch.Tensor): Precomputed cosine frequency tensor.
+ freqs_sin (torch.Tensor): Precomputed sine frequency tensor.
+
+ Returns:
+ torch.Tensor: The input tensor with rotary embeddings applied.
+ """
+ assert xqk.dtype == torch.bfloat16
+ # Split the last dimension into even and odd parts
+ xqk_even = xqk[..., 0::2]
+ xqk_odd = xqk[..., 1::2]
+
+ # Apply rotation
+ cos_part = (xqk_even * freqs_cos - xqk_odd * freqs_sin).type_as(xqk)
+ sin_part = (xqk_even * freqs_sin + xqk_odd * freqs_cos).type_as(xqk)
+
+ # Interleave the results back into the original shape
+ out = torch.stack([cos_part, sin_part], dim=-1).flatten(-2)
+ assert out.dtype == torch.bfloat16
+ return out
+
+def centers(start: float, stop, num, dtype=None, device=None):
+ """linspace through bin centers.
+
+ Args:
+ start (float): Start of the range.
+ stop (float): End of the range.
+ num (int): Number of points.
+ dtype (torch.dtype): Data type of the points.
+ device (torch.device): Device of the points.
+
+ Returns:
+ centers (Tensor): Centers of the bins. Shape: (num,).
+ """
+ edges = torch.linspace(start, stop, num + 1, dtype=dtype, device=device)
+ return (edges[:-1] + edges[1:]) / 2
+
+def create_position_matrix(
+ T: int,
+ pH: int,
+ pW: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ *,
+ target_area: float = 36864,
+):
+ """
+ Args:
+ T: int - Temporal dimension
+ pH: int - Height dimension after patchify
+ pW: int - Width dimension after patchify
+
+ Returns:
+ pos: [T * pH * pW, 3] - position matrix
+ """
+ with torch.no_grad():
+ # Create 1D tensors for each dimension
+ t = torch.arange(T, dtype=dtype)
+
+ # Positionally interpolate to area 36864.
+ # (3072x3072 frame with 16x16 patches = 192x192 latents).
+ # This automatically scales rope positions when the resolution changes.
+ # We use a large target area so the model is more sensitive
+ # to changes in the learned pos_frequencies matrix.
+ scale = math.sqrt(target_area / (pW * pH))
+ w = centers(-pW * scale / 2, pW * scale / 2, pW)
+ h = centers(-pH * scale / 2, pH * scale / 2, pH)
+
+ # Use meshgrid to create 3D grids
+ grid_t, grid_h, grid_w = torch.meshgrid(t, h, w, indexing="ij")
+
+ # Stack and reshape the grids.
+ pos = torch.stack([grid_t, grid_h, grid_w], dim=-1) # [T, pH, pW, 3]
+ pos = pos.view(-1, 3) # [T * pH * pW, 3]
+ pos = pos.to(dtype=dtype, device=device)
+
+ return pos
+
+
+def compute_mixed_rotation(
+ freqs: torch.Tensor,
+ pos: torch.Tensor,
+):
+ """
+ Project each 3-dim position into per-head, per-head-dim 1D frequencies.
+
+ Args:
+ freqs: [3, num_heads, num_freqs] - learned rotation frequency (for t, row, col) for each head position
+ pos: [N, 3] - position of each token
+ num_heads: int
+
+ Returns:
+ freqs_cos: [N, num_heads, num_freqs] - cosine components
+ freqs_sin: [N, num_heads, num_freqs] - sine components
+ """
+ assert freqs.ndim == 3
+ freqs_sum = torch.einsum("Nd,dhf->Nhf", pos.to(freqs), freqs)
+ freqs_cos = torch.cos(freqs_sum)
+ freqs_sin = torch.sin(freqs_sum)
+ return freqs_cos, freqs_sin
+
+
+def residual_tanh_gated_rmsnorm(x, x_res, gate, eps=1e-6):
+ # Convert to fp32 for precision
+ x_res = x_res.float()
+
+ # Compute RMS
+ mean_square = x_res.pow(2).mean(-1, keepdim=True)
+ scale = torch.rsqrt(mean_square + eps)
+
+ # Apply tanh to gate
+ tanh_gate = torch.tanh(gate).unsqueeze(1)
+
+ # Normalize and apply gated scaling
+ x_normed = x_res * scale * tanh_gate
+
+ # Apply residual connection
+ output = x + x_normed.type_as(x)
+ return output
+
+def modulated_rmsnorm(x, scale, eps=1e-6):
+ dtype = x.dtype
+ x = x.float()
+
+ # Compute RMS
+ mean_square = x.pow(2).mean(-1, keepdim=True)
+ inv_rms = torch.rsqrt(mean_square + eps)
+
+ # Normalize and modulate
+ x_normed = x * inv_rms
+ x_modulated = x_normed * (1 + scale.unsqueeze(1).float())
+ return x_modulated.to(dtype)
+
+
+def compute_packed_indices(
+ device: torch.device, text_mask: torch.Tensor, num_latents: int
+) -> Dict[str, Union[torch.Tensor, int]]:
+ """
+ Based on https://github.com/Dao-AILab/flash-attention/blob/765741c1eeb86c96ee71a3291ad6968cfbf4e4a1/flash_attn/bert_padding.py#L60-L80
+
+ Args:
+ num_latents: Number of latent tokens
+ text_mask: (B, L) List of boolean tensor indicating which text tokens are not padding.
+
+ Returns:
+ packed_indices: Dict with keys for Flash Attention:
+ - valid_token_indices_kv: up to (B * (N + L),) tensor of valid token indices (non-padding)
+ in the packed sequence.
+ - cu_seqlens_kv: (B + 1,) tensor of cumulative sequence lengths in the packed sequence.
+ - max_seqlen_in_batch_kv: int of the maximum sequence length in the batch.
+ """
+ # Create an expanded token mask saying which tokens are valid across both visual and text tokens.
+ PATCH_SIZE = 2
+ num_visual_tokens = num_latents // (PATCH_SIZE**2)
+ assert num_visual_tokens > 0
+
+ mask = F.pad(text_mask, (num_visual_tokens, 0), value=True) # (B, N + L)
+ seqlens_in_batch = mask.sum(dim=-1, dtype=torch.int32) # (B,)
+ valid_token_indices = torch.nonzero(mask.flatten(), as_tuple=False).flatten() # up to (B * (N + L),)
+ assert valid_token_indices.size(0) >= text_mask.size(0) * num_visual_tokens # At least (B * N,)
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
+
+ return {
+ "cu_seqlens_kv": cu_seqlens.to(device, non_blocking=True),
+ "max_seqlen_in_batch_kv": cast(int, max_seqlen_in_batch),
+ "valid_token_indices_kv": valid_token_indices.to(device, non_blocking=True),
+ }
+
+class AsymmetricAttention(nn.Module):
+ def __init__(
+ self,
+ dim_x: int,
+ dim_y: int,
+ num_heads: int = 8,
+ qkv_bias: bool = True,
+ qk_norm: bool = False,
+ update_y: bool = True,
+ out_bias: bool = True,
+ attention_mode: str = "flash",
+ softmax_scale: Optional[float] = None,
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ self.attention_mode = attention_mode
+ self.dim_x = dim_x
+ self.dim_y = dim_y
+ self.num_heads = num_heads
+ self.head_dim = dim_x // num_heads
+ self.update_y = update_y
+ self.softmax_scale = softmax_scale
+ if dim_x % num_heads != 0:
+ raise ValueError(f"dim_x={dim_x} should be divisible by num_heads={num_heads}")
+
+ # Input layers.
+ self.qkv_bias = qkv_bias
+ self.qkv_x = nn.Linear(dim_x, 3 * dim_x, bias=qkv_bias, device=device)
+ # Project text features to match visual features (dim_y -> dim_x)
+ self.qkv_y = nn.Linear(dim_y, 3 * dim_x, bias=qkv_bias, device=device)
+
+ # Query and key normalization for stability.
+ assert qk_norm
+ self.q_norm_x = RMSNorm(self.head_dim, device=device)
+ self.k_norm_x = RMSNorm(self.head_dim, device=device)
+ self.q_norm_y = RMSNorm(self.head_dim, device=device)
+ self.k_norm_y = RMSNorm(self.head_dim, device=device)
+
+ # Output layers. y features go back down from dim_x -> dim_y.
+
+ self.proj_x = nn.Linear(dim_x, dim_x, bias=out_bias, device=device)
+ self.proj_y = nn.Linear(dim_x, dim_y, bias=out_bias, device=device) if update_y else nn.Identity()
+
+ def run_qkv_y(self, y):
+ local_heads = self.num_heads
+ qkv_y = self.qkv_y(y) # (B, L, 3 * dim)
+ qkv_y = qkv_y.view(qkv_y.size(0), qkv_y.size(1), 3, local_heads, self.head_dim)
+ q_y, k_y, v_y = qkv_y.unbind(2)
+
+ q_y = self.q_norm_y(q_y)
+ k_y = self.k_norm_y(k_y)
+ return q_y, k_y, v_y
+
+ def prepare_qkv(
+ self,
+ x: torch.Tensor, # (B, M, dim_x)
+ y: torch.Tensor, # (B, L, dim_y)
+ *,
+ scale_x: torch.Tensor,
+ scale_y: torch.Tensor,
+ rope_cos: torch.Tensor,
+ rope_sin: torch.Tensor,
+ valid_token_indices: torch.Tensor,
+ max_seqlen_in_batch: int,
+ ):
+ # Process visual features
+ x = modulated_rmsnorm(x, scale_x) # (B, M, dim_x) where M = N / cp_group_size
+ qkv_x = self.qkv_x(x) # (B, M, 3 * dim_x)
+ assert qkv_x.dtype == torch.bfloat16
+
+ B, M, _ = qkv_x.size()
+ qkv_x = qkv_x.view(B, M, 3, self.num_heads, -1).permute(2, 0, 1, 3, 4)
+
+ # Split qkv_x into q, k, v
+ q_x, k_x, v_x = qkv_x.unbind(0) # (B, N, local_h, head_dim)
+ q_x = self.q_norm_x(q_x)
+ q_x = apply_rotary_emb_qk_real(q_x, rope_cos, rope_sin)
+ k_x = self.k_norm_x(k_x)
+ k_x = apply_rotary_emb_qk_real(k_x, rope_cos, rope_sin)
+
+ # Concatenate streams
+ B, N, num_heads, head_dim = q_x.size()
+ D = num_heads * head_dim
+
+ # Process text features
+ if B == 1:
+ text_seqlen = max_seqlen_in_batch - N
+ if text_seqlen > 0:
+ y = y[:, :text_seqlen] # Remove padding tokens.
+ y = modulated_rmsnorm(y, scale_y) # (B, L, dim_y)
+ q_y, k_y, v_y = self.run_qkv_y(y) # (B, L, local_heads, head_dim)
+
+ q = torch.cat([q_x, q_y], dim=1)
+ k = torch.cat([k_x, k_y], dim=1)
+ v = torch.cat([v_x, v_y], dim=1)
+ else:
+ q, k, v = q_x, k_x, v_x
+ else:
+ y = modulated_rmsnorm(y, scale_y) # (B, L, dim_y)
+ q_y, k_y, v_y = self.run_qkv_y(y) # (B, L, local_heads, head_dim)
+
+ indices = valid_token_indices[:, None].expand(-1, D)
+ q = torch.cat([q_x, q_y], dim=1).view(-1, D).gather(0, indices) # (total, D)
+ k = torch.cat([k_x, k_y], dim=1).view(-1, D).gather(0, indices) # (total, D)
+ v = torch.cat([v_x, v_y], dim=1).view(-1, D).gather(0, indices) # (total, D)
+
+ q = q.view(-1, num_heads, head_dim)
+ k = k.view(-1, num_heads, head_dim)
+ v = v.view(-1, num_heads, head_dim)
+ return q, k, v
+
+ def sdpa_attention(self, q, k, v):
+ out = F.scaled_dot_product_attention(
+ q, k, v,
+ attn_mask=None,
+ dropout_p=0.0,
+ is_causal=False,
+ )
+ return out
+
+ def run_attention(
+ self,
+ q: torch.Tensor, # (total <= B * (N + L), num_heads, head_dim)
+ k: torch.Tensor, # (total <= B * (N + L), num_heads, head_dim)
+ v: torch.Tensor, # (total <= B * (N + L), num_heads, head_dim)
+ *,
+ B: int,
+ cu_seqlens: Optional[torch.Tensor] = None,
+ max_seqlen_in_batch: Optional[int] = None,
+ ):
+ local_heads = self.num_heads
+ local_dim = local_heads * self.head_dim
+ # Check shapes
+ assert q.ndim == 3 and k.ndim == 3 and v.ndim == 3
+ total = q.size(0)
+ assert k.size(0) == total and v.size(0) == total
+ assert B == 1, \
+ f"Non-flash attention mode {self.attention_mode} only supports batch size 1, got {B}"
+ q = rearrange(q, "(b s) h d -> b h s d", b=B)
+ k = rearrange(k, "(b s) h d -> b h s d", b=B)
+ v = rearrange(v, "(b s) h d -> b h s d", b=B)
+ out = self.sdpa_attention(q, k, v)
+ out = rearrange(out, "b h s d -> (b s) (h d)")
+ return out
+
+ def post_attention(
+ self,
+ out: torch.Tensor,
+ B: int,
+ M: int,
+ L: int,
+ dtype: torch.dtype,
+ valid_token_indices: torch.Tensor,
+ ):
+ """
+ Args:
+ out: (total <= B * (N + L), local_dim)
+ valid_token_indices: (total <= B * (N + L),)
+ B: Batch size
+ M: Number of visual tokens per context parallel rank
+ L: Number of text tokens
+ dtype: Data type of the input and output tensors
+
+ Returns:
+ x: (B, N, dim_x) tensor of visual tokens where N = M * cp_size
+ y: (B, L, dim_y) tensor of text token features
+ """
+ local_heads = self.num_heads
+ local_dim = local_heads * self.head_dim
+ N = M
+
+ # Split sequence into visual and text tokens, adding back padding.
+ if B == 1:
+ out = out.view(B, -1, local_dim)
+ if out.size(1) > N:
+ x, y = torch.tensor_split(out, (N,), dim=1) # (B, N, local_dim), (B, <= L, local_dim)
+ y = F.pad(y, (0, 0, 0, L - y.size(1))) # (B, L, local_dim)
+ else:
+ # Empty prompt.
+ x, y = out, out.new_zeros(B, L, local_dim)
+ else:
+ x, y = pad_and_split_xy(out, valid_token_indices, B, N, L, dtype)
+ assert x.size() == (B, M, local_dim)
+ assert y.size() == (B, L, local_dim)
+
+ # Communicate across context parallel ranks.
+ x = x.view(B, N, local_heads, self.head_dim)
+ x = x.view(x.size(0), x.size(1), x.size(2) * x.size(3)) # (B, M, dim_x = num_heads * head_dim)
+ x = self.proj_x(x)
+ y = self.proj_y(y)
+ return x, y
+
+ def forward(
+ self,
+ x: torch.Tensor, # (B, M, dim_x)
+ y: torch.Tensor, # (B, L, dim_y)
+ *,
+ scale_x: torch.Tensor, # (B, dim_x), modulation for pre-RMSNorm.
+ scale_y: torch.Tensor, # (B, dim_y), modulation for pre-RMSNorm.
+ packed_indices: Dict[str, torch.Tensor] = None,
+ **rope_rotation,
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Forward pass of asymmetric multi-modal attention.
+
+ Args:
+ x: (B, M, dim_x) tensor of visual tokens
+ y: (B, L, dim_y) tensor of text token features
+ packed_indices: Dict with keys for Flash Attention
+ num_frames: Number of frames in the video. N = num_frames * num_spatial_tokens
+
+ Returns:
+ x: (B, M, dim_x) tensor of visual tokens after multi-modal attention
+ y: (B, L, dim_y) tensor of text token features after multi-modal attention
+ """
+ B, L, _ = y.shape
+ _, M, _ = x.shape
+
+ # Predict a packed QKV tensor from visual and text features.
+ q, k, v = self.prepare_qkv(
+ x=x,
+ y=y,
+ scale_x=scale_x,
+ scale_y=scale_y,
+ rope_cos=rope_rotation.get("rope_cos"),
+ rope_sin=rope_rotation.get("rope_sin"),
+ valid_token_indices=packed_indices["valid_token_indices_kv"],
+ max_seqlen_in_batch=packed_indices["max_seqlen_in_batch_kv"],
+ ) # (total <= B * (N + L), 3, local_heads, head_dim)
+
+ # Self-attention is expensive, so don't checkpoint it.
+ out = self.run_attention(
+ q, k, v, B=B,
+ cu_seqlens=packed_indices["cu_seqlens_kv"],
+ max_seqlen_in_batch=packed_indices["max_seqlen_in_batch_kv"],
+ )
+
+ x, y = self.post_attention(
+ out,
+ B=B, M=M, L=L,
+ dtype=v.dtype,
+ valid_token_indices=packed_indices["valid_token_indices_kv"],
+ )
+ return x, y
+
+
+class AsymmetricJointBlock(nn.Module):
+ def __init__(
+ self,
+ hidden_size_x: int,
+ hidden_size_y: int,
+ num_heads: int,
+ *,
+ mlp_ratio_x: float = 8.0, # Ratio of hidden size to d_model for MLP for visual tokens.
+ mlp_ratio_y: float = 4.0, # Ratio of hidden size to d_model for MLP for text tokens.
+ update_y: bool = True, # Whether to update text tokens in this block.
+ device: Optional[torch.device] = None,
+ **block_kwargs,
+ ):
+ super().__init__()
+ self.update_y = update_y
+ self.hidden_size_x = hidden_size_x
+ self.hidden_size_y = hidden_size_y
+ self.mod_x = nn.Linear(hidden_size_x, 4 * hidden_size_x, device=device)
+ if self.update_y:
+ self.mod_y = nn.Linear(hidden_size_x, 4 * hidden_size_y, device=device)
+ else:
+ self.mod_y = nn.Linear(hidden_size_x, hidden_size_y, device=device)
+
+ # Self-attention:
+ self.attn = AsymmetricAttention(
+ hidden_size_x,
+ hidden_size_y,
+ num_heads=num_heads,
+ update_y=update_y,
+ device=device,
+ **block_kwargs,
+ )
+
+ # MLP.
+ mlp_hidden_dim_x = int(hidden_size_x * mlp_ratio_x)
+ assert mlp_hidden_dim_x == int(1536 * 8)
+ self.mlp_x = FeedForward(
+ in_features=hidden_size_x,
+ hidden_size=mlp_hidden_dim_x,
+ multiple_of=256,
+ ffn_dim_multiplier=None,
+ device=device,
+ )
+
+ # MLP for text not needed in last block.
+ if self.update_y:
+ mlp_hidden_dim_y = int(hidden_size_y * mlp_ratio_y)
+ self.mlp_y = FeedForward(
+ in_features=hidden_size_y,
+ hidden_size=mlp_hidden_dim_y,
+ multiple_of=256,
+ ffn_dim_multiplier=None,
+ device=device,
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ c: torch.Tensor,
+ y: torch.Tensor,
+ rope_cos,
+ rope_sin,
+ packed_indices,
+ ):
+ """Forward pass of a block.
+
+ Args:
+ x: (B, N, dim) tensor of visual tokens
+ c: (B, dim) tensor of conditioned features
+ y: (B, L, dim) tensor of text tokens
+ num_frames: Number of frames in the video. N = num_frames * num_spatial_tokens
+
+ Returns:
+ x: (B, N, dim) tensor of visual tokens after block
+ y: (B, L, dim) tensor of text tokens after block
+ """
+ N = x.size(1)
+
+ c = F.silu(c)
+ mod_x = self.mod_x(c)
+ scale_msa_x, gate_msa_x, scale_mlp_x, gate_mlp_x = mod_x.chunk(4, dim=1)
+
+ mod_y = self.mod_y(c)
+ if self.update_y:
+ scale_msa_y, gate_msa_y, scale_mlp_y, gate_mlp_y = mod_y.chunk(4, dim=1)
+ else:
+ scale_msa_y = mod_y
+
+ # Self-attention block.
+ x_attn, y_attn = self.attn(
+ x,
+ y,
+ scale_x=scale_msa_x,
+ scale_y=scale_msa_y,
+ rope_cos=rope_cos,
+ rope_sin=rope_sin,
+ packed_indices=packed_indices,
+ )
+
+ assert x_attn.size(1) == N
+ x = residual_tanh_gated_rmsnorm(x, x_attn, gate_msa_x)
+ if self.update_y:
+ y = residual_tanh_gated_rmsnorm(y, y_attn, gate_msa_y)
+
+ # MLP block.
+ x = self.ff_block_x(x, scale_mlp_x, gate_mlp_x)
+ if self.update_y:
+ y = self.ff_block_y(y, scale_mlp_y, gate_mlp_y)
+
+ return x, y
+
+ def ff_block_x(self, x, scale_x, gate_x):
+ x_mod = modulated_rmsnorm(x, scale_x)
+ x_res = self.mlp_x(x_mod)
+ x = residual_tanh_gated_rmsnorm(x, x_res, gate_x) # Sandwich norm
+ return x
+
+ def ff_block_y(self, y, scale_y, gate_y):
+ y_mod = modulated_rmsnorm(y, scale_y)
+ y_res = self.mlp_y(y_mod)
+ y = residual_tanh_gated_rmsnorm(y, y_res, gate_y) # Sandwich norm
+ return y
+
+class FinalLayer(nn.Module):
+ """
+ The final layer of DiT.
+ """
+
+ def __init__(
+ self,
+ hidden_size,
+ patch_size,
+ out_channels,
+ device: Optional[torch.device] = None,
+ ):
+ super().__init__()
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6, device=device)
+ self.mod = nn.Linear(hidden_size, 2 * hidden_size, device=device)
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, device=device)
+
+ def forward(self, x, c):
+ c = F.silu(c)
+ shift, scale = self.mod(c).chunk(2, dim=1)
+ x = modulate(self.norm_final(x), shift, scale)
+ x = self.linear(x)
+ return x
+
+
+@maybe_allow_in_graph
+class MochiTransformer3DModel(ModelMixin, ConfigMixin):
+ """
+ Diffusion model with a Transformer backbone.
+
+ Ingests text embeddings instead of a label.
+ """
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size=2,
+ num_attention_heads: int = 24,
+ attention_head_dim: int = 128,
+ num_layers: int = 48,
+ pooled_projection_dim: int = 1536,
+ in_channels: int = 12,
+ out_channels: Optional[int] = None,
+ qk_norm: str = "rms_norm",
+ text_embed_dim: int = 4096,
+ time_embed_dim: int = 256,
+ activation_fn: str = "swiglu",
+ max_sequence_length: int = 256,
+ ):
+ super().__init__()
+
+ hidden_size_x = num_attention_heads * attention_head_dim
+ hidden_size_y = pooled_projection_dim
+ depth = num_layers
+ num_heads = num_attention_heads
+ mlp_ratio_x=4.0
+ mlp_ratio_y=4.0
+ t5_feat_dim = text_embed_dim
+ t5_token_length = max_sequence_length
+ patch_embed_bias = True
+ timestep_mlp_bias = True
+ timestep_scale=1000.0
+ use_extended_posenc = False
+ rope_theta=10000.0
+ device = torch.device("cpu")
+
+ block_kwargs = {
+ "qk_norm":True,
+ "qkv_bias":False,
+ "out_bias":True,
+ "attention_mode": "sdpa"
+ }
+
+ self.in_channels = in_channels
+ self.out_channels = in_channels
+ self.patch_size = patch_size
+ self.num_heads = num_heads
+ self.hidden_size_x = hidden_size_x
+ self.hidden_size_y = hidden_size_y
+ self.head_dim = hidden_size_x // num_heads # Head dimension and count is determined by visual.
+ self.use_extended_posenc = use_extended_posenc
+ self.t5_token_length = t5_token_length
+ self.t5_feat_dim = t5_feat_dim
+ self.rope_theta = rope_theta # Scaling factor for frequency computation for temporal RoPE.
+
+ self.x_embedder = PatchEmbed(
+ patch_size=patch_size,
+ in_chans=in_channels,
+ embed_dim=hidden_size_x,
+ bias=patch_embed_bias,
+ device=device,
+ )
+ # Conditionings
+ # Timestep
+ self.t_embedder = TimestepEmbedder(hidden_size_x, bias=timestep_mlp_bias, timestep_scale=timestep_scale)
+
+ # Caption Pooling (T5)
+ self.t5_y_embedder = AttentionPool(t5_feat_dim, num_heads=8, output_dim=hidden_size_x, device=device)
+
+ # Dense Embedding Projection (T5)
+ self.t5_yproj = nn.Linear(t5_feat_dim, hidden_size_y, bias=True, device=device)
+
+ # Initialize pos_frequencies as an empty parameter.
+ self.pos_frequencies = nn.Parameter(torch.empty(3, self.num_heads, self.head_dim // 2, device=device))
+
+ # for depth 48:
+ # b = 0: AsymmetricJointBlock, update_y=True
+ # b = 1: AsymmetricJointBlock, update_y=True
+ # ...
+ # b = 46: AsymmetricJointBlock, update_y=True
+ # b = 47: AsymmetricJointBlock, update_y=False. No need to update text features.
+ blocks = []
+ for b in range(depth):
+ # Joint multi-modal block
+ update_y = b < depth - 1
+ block = AsymmetricJointBlock(
+ hidden_size_x,
+ hidden_size_y,
+ num_heads,
+ mlp_ratio_x=mlp_ratio_x,
+ mlp_ratio_y=mlp_ratio_y,
+ update_y=update_y,
+ device=device,
+ **block_kwargs,
+ )
+
+ blocks.append(block)
+ self.blocks = nn.ModuleList(blocks)
+
+ self.final_layer = FinalLayer(hidden_size_x, patch_size, self.out_channels, device=device)
+
+ self.gradient_checkpointing = False
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def embed_x(self, x: torch.Tensor) -> torch.Tensor:
+ """
+ Args:
+ x: (B, C=12, T, H, W) tensor of visual tokens
+
+ Returns:
+ x: (B, C=3072, N) tensor of visual tokens with positional embedding.
+ """
+ return self.x_embedder(x) # Convert BcTHW to BCN
+
+ def prepare(
+ self,
+ x: torch.Tensor,
+ sigma: torch.Tensor,
+ t5_feat: torch.Tensor,
+ t5_mask: torch.Tensor,
+ ):
+ """Prepare input and conditioning embeddings."""
+
+
+ # Visual patch embeddings with positional encoding.
+ T, H, W = x.shape[-3:]
+ pH, pW = H // self.patch_size, W // self.patch_size
+ x = self.embed_x(x) # (B, N, D), where N = T * H * W / patch_size ** 2
+ assert x.ndim == 3
+ B = x.size(0)
+
+ # Construct position array of size [N, 3].
+ # pos[:, 0] is the frame index for each location,
+ # pos[:, 1] is the row index for each location, and
+ # pos[:, 2] is the column index for each location.
+ N = T * pH * pW
+ assert x.size(1) == N
+ pos = create_position_matrix(T, pH=pH, pW=pW, device=x.device, dtype=torch.float32) # (N, 3)
+ rope_cos, rope_sin = compute_mixed_rotation(
+ freqs=self.pos_frequencies, pos=pos
+ ) # Each are (N, num_heads, dim // 2)
+
+ # Global vector embedding for conditionings.
+ c_t = self.t_embedder(1 - sigma) # (B, D)
+
+
+ # Pool T5 tokens using attention pooler
+ # Note y_feat[1] contains T5 token features.
+ assert (
+ t5_feat.size(1) == self.t5_token_length
+ ), f"Expected L={self.t5_token_length}, got {t5_feat.shape} for y_feat."
+ t5_y_pool = self.t5_y_embedder(t5_feat, t5_mask) # (B, D)
+ assert t5_y_pool.size(0) == B, f"Expected B={B}, got {t5_y_pool.shape} for t5_y_pool."
+
+ c = c_t + t5_y_pool
+
+ y_feat = self.t5_yproj(t5_feat) # (B, L, t5_feat_dim) --> (B, L, D)
+
+ return x, c, y_feat, rope_cos, rope_sin
+
+ def forward(
+ self,
+ hidden_states,
+ encoder_hidden_states,
+ timestep,
+ encoder_attention_mask,
+ return_dict: bool = True,
+ ):
+ """Forward pass of DiT.
+
+ Args:
+ x: (B, C, T, H, W) tensor of spatial inputs (images or latent representations of images)
+ sigma: (B,) tensor of noise standard deviations
+ y_feat: List((B, L, y_feat_dim) tensor of caption token features. For SDXL text encoders: L=77, y_feat_dim=2048)
+ y_mask: List((B, L) boolean tensor indicating which tokens are not padding)
+ packed_indices: Dict with keys for Flash Attention. Result of compute_packed_indices.
+ """
+ sigma = timestep / 1000
+ sigma = 1 - sigma
+ sigma = sigma.to(hidden_states.dtype)
+ x = hidden_states
+ y_feat = [encoder_hidden_states]
+ y_mask = [encoder_attention_mask]
+ B, _, T, H, W = x.shape
+ packed_indices = compute_packed_indices(x.device, y_mask[0], T*H*W) #TODO: 是否会影响到梯度计算
+
+ x, c, y_feat, rope_cos, rope_sin = self.prepare(x, sigma, y_feat[0], y_mask[0])
+
+ N = x.size(1)
+ M = N
+
+ for i, block in enumerate(self.blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ def create_custom_forward(module):
+ def custom_forward(*inputs):
+ return module(*inputs)
+ return custom_forward
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ x, y_feat = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ x,
+ c,
+ y_feat,
+ rope_cos,
+ rope_sin,
+ packed_indices,
+ **ckpt_kwargs,
+ )
+ else:
+ x, y_feat = block(
+ x,
+ c,
+ y_feat,
+ rope_cos=rope_cos,
+ rope_sin=rope_sin,
+ packed_indices=packed_indices,
+ )
+
+ x = self.final_layer(x, c) # (B, M, patch_size ** 2 * out_channels)
+
+ patch = x.size(2)
+ x = rearrange(x, "(G B) M P -> B (G M) P", G=1, P=patch)
+ x = rearrange(
+ x,
+ "B (T hp wp) (p1 p2 c) -> B c T (hp p1) (wp p2)",
+ T=T,
+ hp=H // self.patch_size,
+ wp=W // self.patch_size,
+ p1=self.patch_size,
+ p2=self.patch_size,
+ c=self.out_channels,
+ )
+ if not return_dict:
+ return (x, )
+
+ return Transformer2DModelOutput(sample=x)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/__init__.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..5b47575cc2dbb6b23d85bd5040a143b06ed1b5eb
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/__init__.py
@@ -0,0 +1,11 @@
+from .transformer_wan import WanTransformer3DModel
+from .transformer_wan_refextractor import WanTransformer3DModel as WanTransformer3DModel_Refextractor
+from .transformer_wan_controlnet import WanTransformer3DModel as WanTransformer3DModel_Controlnet
+# from .transformer_wan_refextractor_pose import WanTransformer3DModel as WanTransformer3DModel_Refextractor_Pose
+from .transformer_wan_refextractor_2d import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D
+from .transformer_wan_refextractor_2d_split_q import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D_Q
+from .transformer_wan_refextractor_2d_split_q_pose import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D_Q_Pose
+from .transformer_wan_refextractor_2d_pose import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D_Pose
+from .transformer_wan_refextractor_2d_pose_last import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D_Pose_Final
+from .transformer_wan_pose import WanTransformer3DModel as WanTransformer3DModel_Pose
+from .transformer_wan_refextractor_2d_controlnet_last_prefix import WanTransformer3DModel as WanTransformer3DModel_Refextractor_2D_Controlnet_prefix
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/activations.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/activations.py
new file mode 100644
index 0000000000000000000000000000000000000000..03a07a80a95a419351b143b7dfaed5e0f5438b52
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/activations.py
@@ -0,0 +1,177 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.utils import deprecate
+from diffusers.utils.import_utils import is_torch_npu_available, is_torch_version
+
+if is_torch_npu_available():
+ import torch_npu
+
+ACT2CLS = {
+ "swish": nn.SiLU,
+ "silu": nn.SiLU,
+ "mish": nn.Mish,
+ "gelu": nn.GELU,
+ "relu": nn.ReLU,
+}
+
+
+def get_activation(act_fn: str) -> nn.Module:
+ """Helper function to get activation function from string.
+
+ Args:
+ act_fn (str): Name of activation function.
+
+ Returns:
+ nn.Module: Activation function.
+ """
+
+ act_fn = act_fn.lower()
+ if act_fn in ACT2CLS:
+ return ACT2CLS[act_fn]()
+ else:
+ raise ValueError(f"activation function {act_fn} not found in ACT2FN mapping {list(ACT2CLS.keys())}")
+
+
+class FP32SiLU(nn.Module):
+ r"""
+ SiLU activation function with input upcasted to torch.float32.
+ """
+
+ def __init__(self):
+ super().__init__()
+
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return F.silu(inputs.float(), inplace=False).to(inputs.dtype)
+
+
+class GELU(nn.Module):
+ r"""
+ GELU activation function with tanh approximation support with `approximate="tanh"`.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ approximate (`str`, *optional*, defaults to `"none"`): If `"tanh"`, use tanh approximation.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, approximate: str = "none", bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
+ self.approximate = approximate
+
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
+ if gate.device.type == "mps" and is_torch_version("<", "2.0.0"):
+ # fp16 gelu not supported on mps before torch 2.0
+ return F.gelu(gate.to(dtype=torch.float32), approximate=self.approximate).to(dtype=gate.dtype)
+ return F.gelu(gate, approximate=self.approximate)
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.gelu(hidden_states)
+ return hidden_states
+
+
+class GEGLU(nn.Module):
+ r"""
+ A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out * 2, bias=bias)
+
+ def gelu(self, gate: torch.Tensor) -> torch.Tensor:
+ if gate.device.type == "mps" and is_torch_version("<", "2.0.0"):
+ # fp16 gelu not supported on mps before torch 2.0
+ return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
+ return F.gelu(gate)
+
+ def forward(self, hidden_states, *args, **kwargs):
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+ hidden_states = self.proj(hidden_states)
+ if is_torch_npu_available():
+ # using torch_npu.npu_geglu can run faster and save memory on NPU.
+ return torch_npu.npu_geglu(hidden_states, dim=-1, approximate=1)[0]
+ else:
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ return hidden_states * self.gelu(gate)
+
+
+class SwiGLU(nn.Module):
+ r"""
+ A [variant](https://arxiv.org/abs/2002.05202) of the gated linear unit activation function. It's similar to `GEGLU`
+ but uses SiLU / Swish instead of GeLU.
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+
+ self.proj = nn.Linear(dim_in, dim_out * 2, bias=bias)
+ self.activation = nn.SiLU()
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj(hidden_states)
+ hidden_states, gate = hidden_states.chunk(2, dim=-1)
+ return hidden_states * self.activation(gate)
+
+
+class ApproximateGELU(nn.Module):
+ r"""
+ The approximate form of the Gaussian Error Linear Unit (GELU). For more details, see section 2 of this
+ [paper](https://arxiv.org/abs/1606.08415).
+
+ Parameters:
+ dim_in (`int`): The number of channels in the input.
+ dim_out (`int`): The number of channels in the output.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True):
+ super().__init__()
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ x = self.proj(x)
+ return x * torch.sigmoid(1.702 * x)
+
+
+class LinearActivation(nn.Module):
+ def __init__(self, dim_in: int, dim_out: int, bias: bool = True, activation: str = "silu"):
+ super().__init__()
+
+ self.proj = nn.Linear(dim_in, dim_out, bias=bias)
+ self.activation = get_activation(activation)
+
+ def forward(self, hidden_states):
+ hidden_states = self.proj(hidden_states)
+ return self.activation(hidden_states)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..022fce0dcffa9aacbea6bab271c1dd8d0613eb01
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention.py
@@ -0,0 +1,84 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+from typing import Any, Dict, List, Optional, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from .activations import GEGLU, GELU, ApproximateGELU, FP32SiLU, LinearActivation, SwiGLU
+
+
+class FeedForward(nn.Module):
+ r"""
+ A feed-forward layer.
+
+ Parameters:
+ dim (`int`): The number of channels in the input.
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ dim_out: Optional[int] = None,
+ mult: int = 4,
+ dropout: float = 0.0,
+ activation_fn: str = "geglu",
+ final_dropout: bool = False,
+ inner_dim=None,
+ bias: bool = True,
+ ):
+ super().__init__()
+ if inner_dim is None:
+ inner_dim = int(dim * mult)
+ dim_out = dim_out if dim_out is not None else dim
+
+ if activation_fn == "gelu":
+ act_fn = GELU(dim, inner_dim, bias=bias)
+ if activation_fn == "gelu-approximate":
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
+ elif activation_fn == "geglu":
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
+ elif activation_fn == "geglu-approximate":
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
+ elif activation_fn == "swiglu":
+ act_fn = SwiGLU(dim, inner_dim, bias=bias)
+ elif activation_fn == "linear-silu":
+ act_fn = LinearActivation(dim, inner_dim, bias=bias, activation="silu")
+
+ self.net = nn.ModuleList([])
+ # project in
+ self.net.append(act_fn)
+ # project dropout
+ self.net.append(nn.Dropout(dropout))
+ # project out
+ self.net.append(nn.Linear(inner_dim, dim_out, bias=bias))
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
+ if final_dropout:
+ self.net.append(nn.Dropout(dropout))
+
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+ for module in self.net:
+ hidden_states = module(hidden_states)
+ return hidden_states
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention_processor.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention_processor.py
new file mode 100644
index 0000000000000000000000000000000000000000..db142ad04d7a51bacc572403f633b2b2f08cbc43
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/attention_processor.py
@@ -0,0 +1,6240 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import inspect
+import math
+from typing import Callable, List, Optional, Tuple, Union
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.image_processor import IPAdapterMaskProcessor
+from diffusers.utils import deprecate, is_torch_xla_available, logging
+from diffusers.utils.import_utils import is_torch_npu_available, is_torch_xla_version, is_xformers_available
+from diffusers.utils.torch_utils import is_torch_version, maybe_allow_in_graph
+
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+if is_torch_npu_available():
+ import torch_npu
+
+if is_xformers_available():
+ import xformers
+ import xformers.ops
+else:
+ xformers = None
+
+if is_torch_xla_available():
+ # flash attention pallas kernel is introduced in the torch_xla 2.3 release.
+ if is_torch_xla_version(">", "2.2"):
+ from torch_xla.experimental.custom_kernel import flash_attention
+ from torch_xla.runtime import is_spmd
+ XLA_AVAILABLE = True
+else:
+ XLA_AVAILABLE = False
+
+
+@maybe_allow_in_graph
+class Attention(nn.Module):
+ r"""
+ A cross attention layer.
+
+ Parameters:
+ query_dim (`int`):
+ The number of channels in the query.
+ cross_attention_dim (`int`, *optional*):
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
+ heads (`int`, *optional*, defaults to 8):
+ The number of heads to use for multi-head attention.
+ kv_heads (`int`, *optional*, defaults to `None`):
+ The number of key and value heads to use for multi-head attention. Defaults to `heads`. If
+ `kv_heads=heads`, the model will use Multi Head Attention (MHA), if `kv_heads=1` the model will use Multi
+ Query Attention (MQA) otherwise GQA is used.
+ dim_head (`int`, *optional*, defaults to 64):
+ The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability to use.
+ bias (`bool`, *optional*, defaults to False):
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
+ upcast_attention (`bool`, *optional*, defaults to False):
+ Set to `True` to upcast the attention computation to `float32`.
+ upcast_softmax (`bool`, *optional*, defaults to False):
+ Set to `True` to upcast the softmax computation to `float32`.
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
+ The number of groups to use for the group norm in the cross attention.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ norm_num_groups (`int`, *optional*, defaults to `None`):
+ The number of groups to use for the group norm in the attention.
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the spatial normalization.
+ out_bias (`bool`, *optional*, defaults to `True`):
+ Set to `True` to use a bias in the output linear layer.
+ scale_qk (`bool`, *optional*, defaults to `True`):
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
+ `added_kv_proj_dim` is not `None`.
+ eps (`float`, *optional*, defaults to 1e-5):
+ An additional value added to the denominator in group normalization that is used for numerical stability.
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
+ A factor to rescale the output by dividing it with this value.
+ residual_connection (`bool`, *optional*, defaults to `False`):
+ Set to `True` to add the residual connection to the output.
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
+ Set to `True` if the attention block is loaded from a deprecated state dict.
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
+ `AttnProcessor` otherwise.
+ """
+
+ def __init__(
+ self,
+ query_dim: int,
+ cross_attention_dim: Optional[int] = None,
+ heads: int = 8,
+ kv_heads: Optional[int] = None,
+ dim_head: int = 64,
+ dropout: float = 0.0,
+ bias: bool = False,
+ upcast_attention: bool = False,
+ upcast_softmax: bool = False,
+ cross_attention_norm: Optional[str] = None,
+ cross_attention_norm_num_groups: int = 32,
+ qk_norm: Optional[str] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ added_proj_bias: Optional[bool] = True,
+ norm_num_groups: Optional[int] = None,
+ spatial_norm_dim: Optional[int] = None,
+ out_bias: bool = True,
+ scale_qk: bool = True,
+ only_cross_attention: bool = False,
+ eps: float = 1e-5,
+ rescale_output_factor: float = 1.0,
+ residual_connection: bool = False,
+ _from_deprecated_attn_block: bool = False,
+ processor: Optional["AttnProcessor"] = None,
+ out_dim: int = None,
+ out_context_dim: int = None,
+ context_pre_only=None,
+ pre_only=False,
+ elementwise_affine: bool = True,
+ is_causal: bool = False,
+ add_fuser_q: bool = False,
+ ):
+ super().__init__()
+
+ # To prevent circular import.
+ from .normalization import FP32LayerNorm, LpNorm, RMSNorm
+
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
+ self.inner_kv_dim = self.inner_dim if kv_heads is None else dim_head * kv_heads
+ self.query_dim = query_dim
+ self.use_bias = bias
+ self.is_cross_attention = cross_attention_dim is not None
+ self.cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
+ self.upcast_attention = upcast_attention
+ self.upcast_softmax = upcast_softmax
+ self.rescale_output_factor = rescale_output_factor
+ self.residual_connection = residual_connection
+ self.dropout = dropout
+ self.fused_projections = False
+ self.out_dim = out_dim if out_dim is not None else query_dim
+ self.out_context_dim = out_context_dim if out_context_dim is not None else query_dim
+ self.context_pre_only = context_pre_only
+ self.pre_only = pre_only
+ self.is_causal = is_causal
+
+ # we make use of this private variable to know whether this class is loaded
+ # with an deprecated state dict so that we can convert it on the fly
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
+
+ self.scale_qk = scale_qk
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
+
+ self.heads = out_dim // dim_head if out_dim is not None else heads
+ # for slice_size > 0 the attention score computation
+ # is split across the batch axis to save memory
+ # You can set slice_size with `set_attention_slice`
+ self.sliceable_head_dim = heads
+
+ self.added_kv_proj_dim = added_kv_proj_dim
+ self.only_cross_attention = only_cross_attention
+
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
+ raise ValueError(
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
+ )
+
+ if norm_num_groups is not None:
+ self.group_norm = nn.GroupNorm(num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True)
+ else:
+ self.group_norm = None
+
+ if spatial_norm_dim is not None:
+ self.spatial_norm = SpatialNorm(f_channels=query_dim, zq_channels=spatial_norm_dim)
+ else:
+ self.spatial_norm = None
+
+ if qk_norm is None:
+ self.norm_q = None
+ self.norm_k = None
+ elif qk_norm == "layer_norm":
+ self.norm_q = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ self.norm_k = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ elif qk_norm == "fp32_layer_norm":
+ self.norm_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ self.norm_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ elif qk_norm == "layer_norm_across_heads":
+ # Lumina applies qk norm across all heads
+ self.norm_q = nn.LayerNorm(dim_head * heads, eps=eps)
+ self.norm_k = nn.LayerNorm(dim_head * kv_heads, eps=eps)
+ elif qk_norm == "rms_norm":
+ self.norm_q = RMSNorm(dim_head, eps=eps)
+ self.norm_k = RMSNorm(dim_head, eps=eps)
+ elif qk_norm == "rms_norm_across_heads":
+ # LTX applies qk norm across all heads
+ self.norm_q = RMSNorm(dim_head * heads, eps=eps)
+ self.norm_k = RMSNorm(dim_head * kv_heads, eps=eps)
+ elif qk_norm == "l2":
+ self.norm_q = LpNorm(p=2, dim=-1, eps=eps)
+ self.norm_k = LpNorm(p=2, dim=-1, eps=eps)
+ else:
+ raise ValueError(
+ f"unknown qk_norm: {qk_norm}. Should be one of None, 'layer_norm', 'fp32_layer_norm', 'layer_norm_across_heads', 'rms_norm', 'rms_norm_across_heads', 'l2'."
+ )
+
+ if cross_attention_norm is None:
+ self.norm_cross = None
+ elif cross_attention_norm == "layer_norm":
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
+ elif cross_attention_norm == "group_norm":
+ if self.added_kv_proj_dim is not None:
+ # The given `encoder_hidden_states` are initially of shape
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
+ # before the projection, so we need to use `added_kv_proj_dim` as
+ # the number of channels for the group norm.
+ norm_cross_num_channels = added_kv_proj_dim
+ else:
+ norm_cross_num_channels = self.cross_attention_dim
+
+ self.norm_cross = nn.GroupNorm(
+ num_channels=norm_cross_num_channels, num_groups=cross_attention_norm_num_groups, eps=1e-5, affine=True
+ )
+ else:
+ raise ValueError(
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
+ )
+
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
+ if add_fuser_q:
+ self.fuser_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
+ assert qk_norm == "rms_norm_across_heads"
+ self.fuser_norm_q = RMSNorm(dim_head * heads, eps=eps)
+
+ if not self.only_cross_attention:
+ # only relevant for the `AddedKVProcessor` classes
+ self.to_k = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ self.to_v = nn.Linear(self.cross_attention_dim, self.inner_kv_dim, bias=bias)
+ else:
+ self.to_k = None
+ self.to_v = None
+
+ self.added_proj_bias = added_proj_bias
+ if self.added_kv_proj_dim is not None:
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_kv_dim, bias=added_proj_bias)
+ if self.context_pre_only is not None:
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+ else:
+ self.add_q_proj = None
+ self.add_k_proj = None
+ self.add_v_proj = None
+
+ if not self.pre_only:
+ self.to_out = nn.ModuleList([])
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
+ self.to_out.append(nn.Dropout(dropout))
+ else:
+ self.to_out = None
+
+ if self.context_pre_only is not None and not self.context_pre_only:
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_context_dim, bias=out_bias)
+ else:
+ self.to_add_out = None
+
+ if qk_norm is not None and added_kv_proj_dim is not None:
+ if qk_norm == "layer_norm":
+ self.norm_added_q = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ self.norm_added_k = nn.LayerNorm(dim_head, eps=eps, elementwise_affine=elementwise_affine)
+ elif qk_norm == "fp32_layer_norm":
+ self.norm_added_q = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ self.norm_added_k = FP32LayerNorm(dim_head, elementwise_affine=False, bias=False, eps=eps)
+ elif qk_norm == "rms_norm":
+ self.norm_added_q = RMSNorm(dim_head, eps=eps)
+ self.norm_added_k = RMSNorm(dim_head, eps=eps)
+ elif qk_norm == "rms_norm_across_heads":
+ # Wan applies qk norm across all heads
+ # Wan also doesn't apply a q norm
+ self.norm_added_q = None
+ self.norm_added_k = RMSNorm(dim_head * kv_heads, eps=eps)
+ else:
+ raise ValueError(
+ f"unknown qk_norm: {qk_norm}. Should be one of `None,'layer_norm','fp32_layer_norm','rms_norm'`"
+ )
+ else:
+ self.norm_added_q = None
+ self.norm_added_k = None
+
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ if processor is None:
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+ self.set_processor(processor)
+
+ def set_use_xla_flash_attention(
+ self,
+ use_xla_flash_attention: bool,
+ partition_spec: Optional[Tuple[Optional[str], ...]] = None,
+ is_flux=False,
+ ) -> None:
+ r"""
+ Set whether to use xla flash attention from `torch_xla` or not.
+
+ Args:
+ use_xla_flash_attention (`bool`):
+ Whether to use pallas flash attention kernel from `torch_xla` or not.
+ partition_spec (`Tuple[]`, *optional*):
+ Specify the partition specification if using SPMD. Otherwise None.
+ """
+ if use_xla_flash_attention:
+ if not is_torch_xla_available:
+ raise "torch_xla is not available"
+ elif is_torch_xla_version("<", "2.3"):
+ raise "flash attention pallas kernel is supported from torch_xla version 2.3"
+ elif is_spmd() and is_torch_xla_version("<", "2.4"):
+ raise "flash attention pallas kernel using SPMD is supported from torch_xla version 2.4"
+ else:
+ if is_flux:
+ processor = XLAFluxFlashAttnProcessor2_0(partition_spec)
+ else:
+ processor = XLAFlashAttnProcessor2_0(partition_spec)
+ else:
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+ self.set_processor(processor)
+
+ def set_use_npu_flash_attention(self, use_npu_flash_attention: bool) -> None:
+ r"""
+ Set whether to use npu flash attention from `torch_npu` or not.
+
+ """
+ if use_npu_flash_attention:
+ processor = AttnProcessorNPU()
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+ self.set_processor(processor)
+
+ def set_use_memory_efficient_attention_xformers(
+ self, use_memory_efficient_attention_xformers: bool, attention_op: Optional[Callable] = None
+ ) -> None:
+ r"""
+ Set whether to use memory efficient attention from `xformers` or not.
+
+ Args:
+ use_memory_efficient_attention_xformers (`bool`):
+ Whether to use memory efficient attention from `xformers` or not.
+ attention_op (`Callable`, *optional*):
+ The attention operation to use. Defaults to `None` which uses the default attention operation from
+ `xformers`.
+ """
+ is_custom_diffusion = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (CustomDiffusionAttnProcessor, CustomDiffusionXFormersAttnProcessor, CustomDiffusionAttnProcessor2_0),
+ )
+ is_added_kv_processor = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (
+ AttnAddedKVProcessor,
+ AttnAddedKVProcessor2_0,
+ SlicedAttnAddedKVProcessor,
+ XFormersAttnAddedKVProcessor,
+ ),
+ )
+ is_ip_adapter = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (IPAdapterAttnProcessor, IPAdapterAttnProcessor2_0, IPAdapterXFormersAttnProcessor),
+ )
+ is_joint_processor = hasattr(self, "processor") and isinstance(
+ self.processor,
+ (
+ JointAttnProcessor2_0,
+ XFormersJointAttnProcessor,
+ ),
+ )
+
+ if use_memory_efficient_attention_xformers:
+ if is_added_kv_processor and is_custom_diffusion:
+ raise NotImplementedError(
+ f"Memory efficient attention is currently not supported for custom diffusion for attention processor type {self.processor}"
+ )
+ if not is_xformers_available():
+ raise ModuleNotFoundError(
+ (
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
+ " xformers"
+ ),
+ name="xformers",
+ )
+ elif not torch.cuda.is_available():
+ raise ValueError(
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
+ " only available for GPU "
+ )
+ else:
+ try:
+ # Make sure we can run the memory efficient attention
+ dtype = None
+ if attention_op is not None:
+ op_fw, op_bw = attention_op
+ dtype, *_ = op_fw.SUPPORTED_DTYPES
+ q = torch.randn((1, 2, 40), device="cuda", dtype=dtype)
+ _ = xformers.ops.memory_efficient_attention(q, q, q)
+ except Exception as e:
+ raise e
+
+ if is_custom_diffusion:
+ processor = CustomDiffusionXFormersAttnProcessor(
+ train_kv=self.processor.train_kv,
+ train_q_out=self.processor.train_q_out,
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ attention_op=attention_op,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_custom_diffusion"):
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
+ elif is_added_kv_processor:
+ # TODO(Patrick, Suraj, William) - currently xformers doesn't work for UnCLIP
+ # which uses this type of cross attention ONLY because the attention mask of format
+ # [0, ..., -10.000, ..., 0, ...,] is not supported
+ # throw warning
+ logger.info(
+ "Memory efficient attention with `xformers` might currently not work correctly if an attention mask is required for the attention operation."
+ )
+ processor = XFormersAttnAddedKVProcessor(attention_op=attention_op)
+ elif is_ip_adapter:
+ processor = IPAdapterXFormersAttnProcessor(
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ num_tokens=self.processor.num_tokens,
+ scale=self.processor.scale,
+ attention_op=attention_op,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_ip"):
+ processor.to(
+ device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
+ )
+ elif is_joint_processor:
+ processor = XFormersJointAttnProcessor(attention_op=attention_op)
+ else:
+ processor = XFormersAttnProcessor(attention_op=attention_op)
+ else:
+ if is_custom_diffusion:
+ attn_processor_class = (
+ CustomDiffusionAttnProcessor2_0
+ if hasattr(F, "scaled_dot_product_attention")
+ else CustomDiffusionAttnProcessor
+ )
+ processor = attn_processor_class(
+ train_kv=self.processor.train_kv,
+ train_q_out=self.processor.train_q_out,
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_custom_diffusion"):
+ processor.to(self.processor.to_k_custom_diffusion.weight.device)
+ elif is_ip_adapter:
+ processor = IPAdapterAttnProcessor2_0(
+ hidden_size=self.processor.hidden_size,
+ cross_attention_dim=self.processor.cross_attention_dim,
+ num_tokens=self.processor.num_tokens,
+ scale=self.processor.scale,
+ )
+ processor.load_state_dict(self.processor.state_dict())
+ if hasattr(self.processor, "to_k_ip"):
+ processor.to(
+ device=self.processor.to_k_ip[0].weight.device, dtype=self.processor.to_k_ip[0].weight.dtype
+ )
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0()
+ if hasattr(F, "scaled_dot_product_attention") and self.scale_qk
+ else AttnProcessor()
+ )
+
+ self.set_processor(processor)
+
+ def set_attention_slice(self, slice_size: int) -> None:
+ r"""
+ Set the slice size for attention computation.
+
+ Args:
+ slice_size (`int`):
+ The slice size for attention computation.
+ """
+ if slice_size is not None and slice_size > self.sliceable_head_dim:
+ raise ValueError(f"slice_size {slice_size} has to be smaller or equal to {self.sliceable_head_dim}.")
+
+ if slice_size is not None and self.added_kv_proj_dim is not None:
+ processor = SlicedAttnAddedKVProcessor(slice_size)
+ elif slice_size is not None:
+ processor = SlicedAttnProcessor(slice_size)
+ elif self.added_kv_proj_dim is not None:
+ processor = AttnAddedKVProcessor()
+ else:
+ # set attention processor
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
+ processor = (
+ AttnProcessor2_0() if hasattr(F, "scaled_dot_product_attention") and self.scale_qk else AttnProcessor()
+ )
+
+ self.set_processor(processor)
+
+ def set_processor(self, processor: "AttnProcessor") -> None:
+ r"""
+ Set the attention processor to use.
+
+ Args:
+ processor (`AttnProcessor`):
+ The attention processor to use.
+ """
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
+ # pop `processor` from `self._modules`
+ if (
+ hasattr(self, "processor")
+ and isinstance(self.processor, torch.nn.Module)
+ and not isinstance(processor, torch.nn.Module)
+ ):
+ logger.info(f"You are removing possibly trained weights of {self.processor} with {processor}")
+ self._modules.pop("processor")
+
+ self.processor = processor
+
+ def get_processor(self, return_deprecated_lora: bool = False) -> "AttentionProcessor":
+ r"""
+ Get the attention processor in use.
+
+ Args:
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
+ Set to `True` to return the deprecated LoRA attention processor.
+
+ Returns:
+ "AttentionProcessor": The attention processor in use.
+ """
+ if not return_deprecated_lora:
+ return self.processor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ **cross_attention_kwargs,
+ ) -> torch.Tensor:
+ r"""
+ The forward method of the `Attention` class.
+
+ Args:
+ hidden_states (`torch.Tensor`):
+ The hidden states of the query.
+ encoder_hidden_states (`torch.Tensor`, *optional*):
+ The hidden states of the encoder.
+ attention_mask (`torch.Tensor`, *optional*):
+ The attention mask to use. If `None`, no mask is applied.
+ **cross_attention_kwargs:
+ Additional keyword arguments to pass along to the cross attention.
+
+ Returns:
+ `torch.Tensor`: The output of the attention layer.
+ """
+ # The `Attention` class can call different attention processors / attention functions
+ # here we simply pass along all tensors to the selected processor class
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
+
+ attn_parameters = set(inspect.signature(self.processor.__call__).parameters.keys())
+ quiet_attn_parameters = {"ip_adapter_masks", "ip_hidden_states"}
+ unused_kwargs = [
+ k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters and k not in quiet_attn_parameters
+ ]
+ if len(unused_kwargs) > 0:
+ logger.warning(
+ f"cross_attention_kwargs {unused_kwargs} are not expected by {self.processor.__class__.__name__} and will be ignored."
+ )
+ cross_attention_kwargs = {k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters}
+
+ return self.processor(
+ self,
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ **cross_attention_kwargs,
+ )
+
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
+ r"""
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
+ is the number of heads initialized while constructing the `Attention` class.
+
+ Args:
+ tensor (`torch.Tensor`): The tensor to reshape.
+
+ Returns:
+ `torch.Tensor`: The reshaped tensor.
+ """
+ head_size = self.heads
+ batch_size, seq_len, dim = tensor.shape
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
+ return tensor
+
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
+ r"""
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
+ the number of heads initialized while constructing the `Attention` class.
+
+ Args:
+ tensor (`torch.Tensor`): The tensor to reshape.
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
+
+ Returns:
+ `torch.Tensor`: The reshaped tensor.
+ """
+ head_size = self.heads
+ if tensor.ndim == 3:
+ batch_size, seq_len, dim = tensor.shape
+ extra_dim = 1
+ else:
+ batch_size, extra_dim, seq_len, dim = tensor.shape
+ tensor = tensor.reshape(batch_size, seq_len * extra_dim, head_size, dim // head_size)
+ tensor = tensor.permute(0, 2, 1, 3)
+
+ if out_dim == 3:
+ tensor = tensor.reshape(batch_size * head_size, seq_len * extra_dim, dim // head_size)
+
+ return tensor
+
+ def get_attention_scores(
+ self, query: torch.Tensor, key: torch.Tensor, attention_mask: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ r"""
+ Compute the attention scores.
+
+ Args:
+ query (`torch.Tensor`): The query tensor.
+ key (`torch.Tensor`): The key tensor.
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
+
+ Returns:
+ `torch.Tensor`: The attention probabilities/scores.
+ """
+ dtype = query.dtype
+ if self.upcast_attention:
+ query = query.float()
+ key = key.float()
+
+ if attention_mask is None:
+ baddbmm_input = torch.empty(
+ query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device
+ )
+ beta = 0
+ else:
+ baddbmm_input = attention_mask
+ beta = 1
+
+ attention_scores = torch.baddbmm(
+ baddbmm_input,
+ query,
+ key.transpose(-1, -2),
+ beta=beta,
+ alpha=self.scale,
+ )
+ del baddbmm_input
+
+ if self.upcast_softmax:
+ attention_scores = attention_scores.float()
+
+ attention_probs = attention_scores.softmax(dim=-1)
+ del attention_scores
+
+ attention_probs = attention_probs.to(dtype)
+
+ return attention_probs
+
+ def prepare_attention_mask(
+ self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
+ ) -> torch.Tensor:
+ r"""
+ Prepare the attention mask for the attention computation.
+
+ Args:
+ attention_mask (`torch.Tensor`):
+ The attention mask to prepare.
+ target_length (`int`):
+ The target length of the attention mask. This is the length of the attention mask after padding.
+ batch_size (`int`):
+ The batch size, which is used to repeat the attention mask.
+ out_dim (`int`, *optional*, defaults to `3`):
+ The output dimension of the attention mask. Can be either `3` or `4`.
+
+ Returns:
+ `torch.Tensor`: The prepared attention mask.
+ """
+ head_size = self.heads
+ if attention_mask is None:
+ return attention_mask
+
+ current_length: int = attention_mask.shape[-1]
+ if current_length != target_length:
+ if attention_mask.device.type == "mps":
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
+ # Instead, we can manually construct the padding tensor.
+ padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
+ padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
+ else:
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
+ # remaining_length: int = target_length - current_length
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
+
+ if out_dim == 3:
+ if attention_mask.shape[0] < batch_size * head_size:
+ attention_mask = attention_mask.repeat_interleave(
+ head_size, dim=0, output_size=attention_mask.shape[0] * head_size
+ )
+ elif out_dim == 4:
+ attention_mask = attention_mask.unsqueeze(1)
+ attention_mask = attention_mask.repeat_interleave(
+ head_size, dim=1, output_size=attention_mask.shape[1] * head_size
+ )
+
+ return attention_mask
+
+ def norm_encoder_hidden_states(self, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
+ r"""
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
+ `Attention` class.
+
+ Args:
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
+
+ Returns:
+ `torch.Tensor`: The normalized encoder hidden states.
+ """
+ assert self.norm_cross is not None, "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
+
+ if isinstance(self.norm_cross, nn.LayerNorm):
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
+ elif isinstance(self.norm_cross, nn.GroupNorm):
+ # Group norm norms along the channels dimension and expects
+ # input to be in the shape of (N, C, *). In this case, we want
+ # to norm along the hidden dimension, so we need to move
+ # (batch_size, sequence_length, hidden_size) ->
+ # (batch_size, hidden_size, sequence_length)
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
+ else:
+ assert False
+
+ return encoder_hidden_states
+
+ @torch.no_grad()
+ def fuse_projections(self, fuse=True):
+ device = self.to_q.weight.data.device
+ dtype = self.to_q.weight.data.dtype
+
+ if not self.is_cross_attention:
+ # fetch weight matrices.
+ concatenated_weights = torch.cat([self.to_q.weight.data, self.to_k.weight.data, self.to_v.weight.data])
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ # create a new single projection layer and copy over the weights.
+ self.to_qkv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
+ self.to_qkv.weight.copy_(concatenated_weights)
+ if self.use_bias:
+ concatenated_bias = torch.cat([self.to_q.bias.data, self.to_k.bias.data, self.to_v.bias.data])
+ self.to_qkv.bias.copy_(concatenated_bias)
+
+ else:
+ concatenated_weights = torch.cat([self.to_k.weight.data, self.to_v.weight.data])
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ self.to_kv = nn.Linear(in_features, out_features, bias=self.use_bias, device=device, dtype=dtype)
+ self.to_kv.weight.copy_(concatenated_weights)
+ if self.use_bias:
+ concatenated_bias = torch.cat([self.to_k.bias.data, self.to_v.bias.data])
+ self.to_kv.bias.copy_(concatenated_bias)
+
+ # handle added projections for SD3 and others.
+ if (
+ getattr(self, "add_q_proj", None) is not None
+ and getattr(self, "add_k_proj", None) is not None
+ and getattr(self, "add_v_proj", None) is not None
+ ):
+ concatenated_weights = torch.cat(
+ [self.add_q_proj.weight.data, self.add_k_proj.weight.data, self.add_v_proj.weight.data]
+ )
+ in_features = concatenated_weights.shape[1]
+ out_features = concatenated_weights.shape[0]
+
+ self.to_added_qkv = nn.Linear(
+ in_features, out_features, bias=self.added_proj_bias, device=device, dtype=dtype
+ )
+ self.to_added_qkv.weight.copy_(concatenated_weights)
+ if self.added_proj_bias:
+ concatenated_bias = torch.cat(
+ [self.add_q_proj.bias.data, self.add_k_proj.bias.data, self.add_v_proj.bias.data]
+ )
+ self.to_added_qkv.bias.copy_(concatenated_bias)
+
+ self.fused_projections = fuse
+
+
+class SanaMultiscaleAttentionProjection(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ num_attention_heads: int,
+ kernel_size: int,
+ ) -> None:
+ super().__init__()
+
+ channels = 3 * in_channels
+ self.proj_in = nn.Conv2d(
+ channels,
+ channels,
+ kernel_size,
+ padding=kernel_size // 2,
+ groups=channels,
+ bias=False,
+ )
+ self.proj_out = nn.Conv2d(channels, channels, 1, 1, 0, groups=3 * num_attention_heads, bias=False)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.proj_in(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+ return hidden_states
+
+
+class SanaMultiscaleLinearAttention(nn.Module):
+ r"""Lightweight multi-scale linear attention"""
+
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ num_attention_heads: Optional[int] = None,
+ attention_head_dim: int = 8,
+ mult: float = 1.0,
+ norm_type: str = "batch_norm",
+ kernel_sizes: Tuple[int, ...] = (5,),
+ eps: float = 1e-15,
+ residual_connection: bool = False,
+ ):
+ super().__init__()
+
+ # To prevent circular import
+ from .normalization import get_normalization
+
+ self.eps = eps
+ self.attention_head_dim = attention_head_dim
+ self.norm_type = norm_type
+ self.residual_connection = residual_connection
+
+ num_attention_heads = (
+ int(in_channels // attention_head_dim * mult) if num_attention_heads is None else num_attention_heads
+ )
+ inner_dim = num_attention_heads * attention_head_dim
+
+ self.to_q = nn.Linear(in_channels, inner_dim, bias=False)
+ self.to_k = nn.Linear(in_channels, inner_dim, bias=False)
+ self.to_v = nn.Linear(in_channels, inner_dim, bias=False)
+
+ self.to_qkv_multiscale = nn.ModuleList()
+ for kernel_size in kernel_sizes:
+ self.to_qkv_multiscale.append(
+ SanaMultiscaleAttentionProjection(inner_dim, num_attention_heads, kernel_size)
+ )
+
+ self.nonlinearity = nn.ReLU()
+ self.to_out = nn.Linear(inner_dim * (1 + len(kernel_sizes)), out_channels, bias=False)
+ self.norm_out = get_normalization(norm_type, num_features=out_channels)
+
+ self.processor = SanaMultiscaleAttnProcessor2_0()
+
+ def apply_linear_attention(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
+ value = F.pad(value, (0, 0, 0, 1), mode="constant", value=1) # Adds padding
+ scores = torch.matmul(value, key.transpose(-1, -2))
+ hidden_states = torch.matmul(scores, query)
+
+ hidden_states = hidden_states.to(dtype=torch.float32)
+ hidden_states = hidden_states[:, :, :-1] / (hidden_states[:, :, -1:] + self.eps)
+ return hidden_states
+
+ def apply_quadratic_attention(self, query: torch.Tensor, key: torch.Tensor, value: torch.Tensor) -> torch.Tensor:
+ scores = torch.matmul(key.transpose(-1, -2), query)
+ scores = scores.to(dtype=torch.float32)
+ scores = scores / (torch.sum(scores, dim=2, keepdim=True) + self.eps)
+ hidden_states = torch.matmul(value, scores.to(value.dtype))
+ return hidden_states
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return self.processor(self, hidden_states)
+
+
+class MochiAttention(nn.Module):
+ def __init__(
+ self,
+ query_dim: int,
+ added_kv_proj_dim: int,
+ processor: "MochiAttnProcessor2_0",
+ heads: int = 8,
+ dim_head: int = 64,
+ dropout: float = 0.0,
+ bias: bool = False,
+ added_proj_bias: bool = True,
+ out_dim: Optional[int] = None,
+ out_context_dim: Optional[int] = None,
+ out_bias: bool = True,
+ context_pre_only: bool = False,
+ eps: float = 1e-5,
+ ):
+ super().__init__()
+ from .normalization import MochiRMSNorm
+
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
+ self.out_dim = out_dim if out_dim is not None else query_dim
+ self.out_context_dim = out_context_dim if out_context_dim else query_dim
+ self.context_pre_only = context_pre_only
+
+ self.heads = out_dim // dim_head if out_dim is not None else heads
+
+ self.norm_q = MochiRMSNorm(dim_head, eps, True)
+ self.norm_k = MochiRMSNorm(dim_head, eps, True)
+ self.norm_added_q = MochiRMSNorm(dim_head, eps, True)
+ self.norm_added_k = MochiRMSNorm(dim_head, eps, True)
+
+ self.to_q = nn.Linear(query_dim, self.inner_dim, bias=bias)
+ self.to_k = nn.Linear(query_dim, self.inner_dim, bias=bias)
+ self.to_v = nn.Linear(query_dim, self.inner_dim, bias=bias)
+
+ self.add_k_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+ self.add_v_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+ if self.context_pre_only is not None:
+ self.add_q_proj = nn.Linear(added_kv_proj_dim, self.inner_dim, bias=added_proj_bias)
+
+ self.to_out = nn.ModuleList([])
+ self.to_out.append(nn.Linear(self.inner_dim, self.out_dim, bias=out_bias))
+ self.to_out.append(nn.Dropout(dropout))
+
+ if not self.context_pre_only:
+ self.to_add_out = nn.Linear(self.inner_dim, self.out_context_dim, bias=out_bias)
+
+ self.processor = processor
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ **kwargs,
+ ):
+ return self.processor(
+ self,
+ hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=attention_mask,
+ **kwargs,
+ )
+
+
+class MochiAttnProcessor2_0:
+ """Attention processor used in Mochi."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("MochiAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: "MochiAttention",
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: torch.Tensor,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ query = query.unflatten(2, (attn.heads, -1))
+ key = key.unflatten(2, (attn.heads, -1))
+ value = value.unflatten(2, (attn.heads, -1))
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_query = encoder_query.unflatten(2, (attn.heads, -1))
+ encoder_key = encoder_key.unflatten(2, (attn.heads, -1))
+ encoder_value = encoder_value.unflatten(2, (attn.heads, -1))
+
+ if attn.norm_added_q is not None:
+ encoder_query = attn.norm_added_q(encoder_query)
+ if attn.norm_added_k is not None:
+ encoder_key = attn.norm_added_k(encoder_key)
+
+ if image_rotary_emb is not None:
+
+ def apply_rotary_emb(x, freqs_cos, freqs_sin):
+ x_even = x[..., 0::2].float()
+ x_odd = x[..., 1::2].float()
+
+ cos = (x_even * freqs_cos - x_odd * freqs_sin).to(x.dtype)
+ sin = (x_even * freqs_sin + x_odd * freqs_cos).to(x.dtype)
+
+ return torch.stack([cos, sin], dim=-1).flatten(-2)
+
+ query = apply_rotary_emb(query, *image_rotary_emb)
+ key = apply_rotary_emb(key, *image_rotary_emb)
+
+ query, key, value = query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2)
+ encoder_query, encoder_key, encoder_value = (
+ encoder_query.transpose(1, 2),
+ encoder_key.transpose(1, 2),
+ encoder_value.transpose(1, 2),
+ )
+
+ sequence_length = query.size(2)
+ encoder_sequence_length = encoder_query.size(2)
+ total_length = sequence_length + encoder_sequence_length
+
+ batch_size, heads, _, dim = query.shape
+ attn_outputs = []
+ for idx in range(batch_size):
+ mask = attention_mask[idx][None, :]
+ valid_prompt_token_indices = torch.nonzero(mask.flatten(), as_tuple=False).flatten()
+
+ valid_encoder_query = encoder_query[idx : idx + 1, :, valid_prompt_token_indices, :]
+ valid_encoder_key = encoder_key[idx : idx + 1, :, valid_prompt_token_indices, :]
+ valid_encoder_value = encoder_value[idx : idx + 1, :, valid_prompt_token_indices, :]
+
+ valid_query = torch.cat([query[idx : idx + 1], valid_encoder_query], dim=2)
+ valid_key = torch.cat([key[idx : idx + 1], valid_encoder_key], dim=2)
+ valid_value = torch.cat([value[idx : idx + 1], valid_encoder_value], dim=2)
+
+ attn_output = F.scaled_dot_product_attention(
+ valid_query, valid_key, valid_value, dropout_p=0.0, is_causal=False
+ )
+ valid_sequence_length = attn_output.size(2)
+ attn_output = F.pad(attn_output, (0, 0, 0, total_length - valid_sequence_length))
+ attn_outputs.append(attn_output)
+
+ hidden_states = torch.cat(attn_outputs, dim=0)
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+
+ hidden_states, encoder_hidden_states = hidden_states.split_with_sizes(
+ (sequence_length, encoder_sequence_length), dim=1
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if hasattr(attn, "to_add_out"):
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+
+
+class AttnProcessor:
+ r"""
+ Default processor for performing attention-related computations.
+ """
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ query = attn.head_to_batch_dim(query)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
+ hidden_states = torch.bmm(attention_probs, value)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class CustomDiffusionAttnProcessor(nn.Module):
+ r"""
+ Processor for implementing attention for the Custom Diffusion method.
+
+ Args:
+ train_kv (`bool`, defaults to `True`):
+ Whether to newly train the key and value matrices corresponding to the text features.
+ train_q_out (`bool`, defaults to `True`):
+ Whether to newly train query matrices corresponding to the latent image features.
+ hidden_size (`int`, *optional*, defaults to `None`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
+ The number of channels in the `encoder_hidden_states`.
+ out_bias (`bool`, defaults to `True`):
+ Whether to include the bias parameter in `train_q_out`.
+ dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability to use.
+ """
+
+ def __init__(
+ self,
+ train_kv: bool = True,
+ train_q_out: bool = True,
+ hidden_size: Optional[int] = None,
+ cross_attention_dim: Optional[int] = None,
+ out_bias: bool = True,
+ dropout: float = 0.0,
+ ):
+ super().__init__()
+ self.train_kv = train_kv
+ self.train_q_out = train_q_out
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+
+ # `_custom_diffusion` id for easy serialization and loading.
+ if self.train_kv:
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ if self.train_q_out:
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.to_out_custom_diffusion = nn.ModuleList([])
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ batch_size, sequence_length, _ = hidden_states.shape
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ if self.train_q_out:
+ query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
+ else:
+ query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
+
+ if encoder_hidden_states is None:
+ crossattn = False
+ encoder_hidden_states = hidden_states
+ else:
+ crossattn = True
+ if attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ if self.train_kv:
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
+ key = key.to(attn.to_q.weight.dtype)
+ value = value.to(attn.to_q.weight.dtype)
+ else:
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if crossattn:
+ detach = torch.ones_like(key)
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
+ key = detach * key + (1 - detach) * key.detach()
+ value = detach * value + (1 - detach) * value.detach()
+
+ query = attn.head_to_batch_dim(query)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
+ hidden_states = torch.bmm(attention_probs, value)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ if self.train_q_out:
+ # linear proj
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
+ # dropout
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
+ else:
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class AttnAddedKVProcessor:
+ r"""
+ Processor for performing attention-related computations with extra learnable key and value matrices for the text
+ encoder.
+ """
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+ query = attn.head_to_batch_dim(query)
+
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
+
+ if not attn.only_cross_attention:
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
+ else:
+ key = encoder_hidden_states_key_proj
+ value = encoder_hidden_states_value_proj
+
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
+ hidden_states = torch.bmm(attention_probs, value)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+class AttnAddedKVProcessor2_0:
+ r"""
+ Processor for performing scaled dot-product attention (enabled by default if you're using PyTorch 2.0), with extra
+ learnable key and value matrices for the text encoder.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "AttnAddedKVProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size, out_dim=4)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+ query = attn.head_to_batch_dim(query, out_dim=4)
+
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj, out_dim=4)
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj, out_dim=4)
+
+ if not attn.only_cross_attention:
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+ key = attn.head_to_batch_dim(key, out_dim=4)
+ value = attn.head_to_batch_dim(value, out_dim=4)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+ else:
+ key = encoder_hidden_states_key_proj
+ value = encoder_hidden_states_value_proj
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, residual.shape[1])
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+class JointAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("JointAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ batch_size = hidden_states.shape[0]
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=2)
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=2)
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=2)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ # Split the attention outputs.
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, : residual.shape[1]],
+ hidden_states[:, residual.shape[1] :],
+ )
+ if not attn.context_pre_only:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if encoder_hidden_states is not None:
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class PAGJointAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGJointAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ input_ndim = hidden_states.ndim
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+ context_input_ndim = encoder_hidden_states.ndim
+ if context_input_ndim == 4:
+ batch_size, channel, height, width = encoder_hidden_states.shape
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ # store the length of image patch sequences to create a mask that prevents interaction between patches
+ # similar to making the self-attention map an identity matrix
+ identity_block_size = hidden_states.shape[1]
+
+ # chunk
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
+ encoder_hidden_states_org, encoder_hidden_states_ptb = encoder_hidden_states.chunk(2)
+
+ ################## original path ##################
+ batch_size = encoder_hidden_states_org.shape[0]
+
+ # `sample` projections.
+ query_org = attn.to_q(hidden_states_org)
+ key_org = attn.to_k(hidden_states_org)
+ value_org = attn.to_v(hidden_states_org)
+
+ # `context` projections.
+ encoder_hidden_states_org_query_proj = attn.add_q_proj(encoder_hidden_states_org)
+ encoder_hidden_states_org_key_proj = attn.add_k_proj(encoder_hidden_states_org)
+ encoder_hidden_states_org_value_proj = attn.add_v_proj(encoder_hidden_states_org)
+
+ # attention
+ query_org = torch.cat([query_org, encoder_hidden_states_org_query_proj], dim=1)
+ key_org = torch.cat([key_org, encoder_hidden_states_org_key_proj], dim=1)
+ value_org = torch.cat([value_org, encoder_hidden_states_org_value_proj], dim=1)
+
+ inner_dim = key_org.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query_org = query_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key_org = key_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value_org = value_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ hidden_states_org = F.scaled_dot_product_attention(
+ query_org, key_org, value_org, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query_org.dtype)
+
+ # Split the attention outputs.
+ hidden_states_org, encoder_hidden_states_org = (
+ hidden_states_org[:, : residual.shape[1]],
+ hidden_states_org[:, residual.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+ if not attn.context_pre_only:
+ encoder_hidden_states_org = attn.to_add_out(encoder_hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+ if context_input_ndim == 4:
+ encoder_hidden_states_org = encoder_hidden_states_org.transpose(-1, -2).reshape(
+ batch_size, channel, height, width
+ )
+
+ ################## perturbed path ##################
+
+ batch_size = encoder_hidden_states_ptb.shape[0]
+
+ # `sample` projections.
+ query_ptb = attn.to_q(hidden_states_ptb)
+ key_ptb = attn.to_k(hidden_states_ptb)
+ value_ptb = attn.to_v(hidden_states_ptb)
+
+ # `context` projections.
+ encoder_hidden_states_ptb_query_proj = attn.add_q_proj(encoder_hidden_states_ptb)
+ encoder_hidden_states_ptb_key_proj = attn.add_k_proj(encoder_hidden_states_ptb)
+ encoder_hidden_states_ptb_value_proj = attn.add_v_proj(encoder_hidden_states_ptb)
+
+ # attention
+ query_ptb = torch.cat([query_ptb, encoder_hidden_states_ptb_query_proj], dim=1)
+ key_ptb = torch.cat([key_ptb, encoder_hidden_states_ptb_key_proj], dim=1)
+ value_ptb = torch.cat([value_ptb, encoder_hidden_states_ptb_value_proj], dim=1)
+
+ inner_dim = key_ptb.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query_ptb = query_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key_ptb = key_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value_ptb = value_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # create a full mask with all entries set to 0
+ seq_len = query_ptb.size(2)
+ full_mask = torch.zeros((seq_len, seq_len), device=query_ptb.device, dtype=query_ptb.dtype)
+
+ # set the attention value between image patches to -inf
+ full_mask[:identity_block_size, :identity_block_size] = float("-inf")
+
+ # set the diagonal of the attention value between image patches to 0
+ full_mask[:identity_block_size, :identity_block_size].fill_diagonal_(0)
+
+ # expand the mask to match the attention weights shape
+ full_mask = full_mask.unsqueeze(0).unsqueeze(0) # Add batch and num_heads dimensions
+
+ hidden_states_ptb = F.scaled_dot_product_attention(
+ query_ptb, key_ptb, value_ptb, attn_mask=full_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_ptb = hidden_states_ptb.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_ptb = hidden_states_ptb.to(query_ptb.dtype)
+
+ # split the attention outputs.
+ hidden_states_ptb, encoder_hidden_states_ptb = (
+ hidden_states_ptb[:, : residual.shape[1]],
+ hidden_states_ptb[:, residual.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+ if not attn.context_pre_only:
+ encoder_hidden_states_ptb = attn.to_add_out(encoder_hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+ if context_input_ndim == 4:
+ encoder_hidden_states_ptb = encoder_hidden_states_ptb.transpose(-1, -2).reshape(
+ batch_size, channel, height, width
+ )
+
+ ################ concat ###############
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+ encoder_hidden_states = torch.cat([encoder_hidden_states_org, encoder_hidden_states_ptb])
+
+ return hidden_states, encoder_hidden_states
+
+
+class PAGCFGJointAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGCFGJointAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ input_ndim = hidden_states.ndim
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+ context_input_ndim = encoder_hidden_states.ndim
+ if context_input_ndim == 4:
+ batch_size, channel, height, width = encoder_hidden_states.shape
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ identity_block_size = hidden_states.shape[
+ 1
+ ] # patch embeddings width * height (correspond to self-attention map width or height)
+
+ # chunk
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
+
+ (
+ encoder_hidden_states_uncond,
+ encoder_hidden_states_org,
+ encoder_hidden_states_ptb,
+ ) = encoder_hidden_states.chunk(3)
+ encoder_hidden_states_org = torch.cat([encoder_hidden_states_uncond, encoder_hidden_states_org])
+
+ ################## original path ##################
+ batch_size = encoder_hidden_states_org.shape[0]
+
+ # `sample` projections.
+ query_org = attn.to_q(hidden_states_org)
+ key_org = attn.to_k(hidden_states_org)
+ value_org = attn.to_v(hidden_states_org)
+
+ # `context` projections.
+ encoder_hidden_states_org_query_proj = attn.add_q_proj(encoder_hidden_states_org)
+ encoder_hidden_states_org_key_proj = attn.add_k_proj(encoder_hidden_states_org)
+ encoder_hidden_states_org_value_proj = attn.add_v_proj(encoder_hidden_states_org)
+
+ # attention
+ query_org = torch.cat([query_org, encoder_hidden_states_org_query_proj], dim=1)
+ key_org = torch.cat([key_org, encoder_hidden_states_org_key_proj], dim=1)
+ value_org = torch.cat([value_org, encoder_hidden_states_org_value_proj], dim=1)
+
+ inner_dim = key_org.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query_org = query_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key_org = key_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value_org = value_org.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ hidden_states_org = F.scaled_dot_product_attention(
+ query_org, key_org, value_org, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query_org.dtype)
+
+ # Split the attention outputs.
+ hidden_states_org, encoder_hidden_states_org = (
+ hidden_states_org[:, : residual.shape[1]],
+ hidden_states_org[:, residual.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+ if not attn.context_pre_only:
+ encoder_hidden_states_org = attn.to_add_out(encoder_hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+ if context_input_ndim == 4:
+ encoder_hidden_states_org = encoder_hidden_states_org.transpose(-1, -2).reshape(
+ batch_size, channel, height, width
+ )
+
+ ################## perturbed path ##################
+
+ batch_size = encoder_hidden_states_ptb.shape[0]
+
+ # `sample` projections.
+ query_ptb = attn.to_q(hidden_states_ptb)
+ key_ptb = attn.to_k(hidden_states_ptb)
+ value_ptb = attn.to_v(hidden_states_ptb)
+
+ # `context` projections.
+ encoder_hidden_states_ptb_query_proj = attn.add_q_proj(encoder_hidden_states_ptb)
+ encoder_hidden_states_ptb_key_proj = attn.add_k_proj(encoder_hidden_states_ptb)
+ encoder_hidden_states_ptb_value_proj = attn.add_v_proj(encoder_hidden_states_ptb)
+
+ # attention
+ query_ptb = torch.cat([query_ptb, encoder_hidden_states_ptb_query_proj], dim=1)
+ key_ptb = torch.cat([key_ptb, encoder_hidden_states_ptb_key_proj], dim=1)
+ value_ptb = torch.cat([value_ptb, encoder_hidden_states_ptb_value_proj], dim=1)
+
+ inner_dim = key_ptb.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query_ptb = query_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key_ptb = key_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value_ptb = value_ptb.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # create a full mask with all entries set to 0
+ seq_len = query_ptb.size(2)
+ full_mask = torch.zeros((seq_len, seq_len), device=query_ptb.device, dtype=query_ptb.dtype)
+
+ # set the attention value between image patches to -inf
+ full_mask[:identity_block_size, :identity_block_size] = float("-inf")
+
+ # set the diagonal of the attention value between image patches to 0
+ full_mask[:identity_block_size, :identity_block_size].fill_diagonal_(0)
+
+ # expand the mask to match the attention weights shape
+ full_mask = full_mask.unsqueeze(0).unsqueeze(0) # Add batch and num_heads dimensions
+
+ hidden_states_ptb = F.scaled_dot_product_attention(
+ query_ptb, key_ptb, value_ptb, attn_mask=full_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_ptb = hidden_states_ptb.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_ptb = hidden_states_ptb.to(query_ptb.dtype)
+
+ # split the attention outputs.
+ hidden_states_ptb, encoder_hidden_states_ptb = (
+ hidden_states_ptb[:, : residual.shape[1]],
+ hidden_states_ptb[:, residual.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+ if not attn.context_pre_only:
+ encoder_hidden_states_ptb = attn.to_add_out(encoder_hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+ if context_input_ndim == 4:
+ encoder_hidden_states_ptb = encoder_hidden_states_ptb.transpose(-1, -2).reshape(
+ batch_size, channel, height, width
+ )
+
+ ################ concat ###############
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+ encoder_hidden_states = torch.cat([encoder_hidden_states_org, encoder_hidden_states_ptb])
+
+ return hidden_states, encoder_hidden_states
+
+
+class FusedJointAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ input_ndim = hidden_states.ndim
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+ context_input_ndim = encoder_hidden_states.ndim
+ if context_input_ndim == 4:
+ batch_size, channel, height, width = encoder_hidden_states.shape
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size = encoder_hidden_states.shape[0]
+
+ # `sample` projections.
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ # `context` projections.
+ encoder_qkv = attn.to_added_qkv(encoder_hidden_states)
+ split_size = encoder_qkv.shape[-1] // 3
+ (
+ encoder_hidden_states_query_proj,
+ encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj,
+ ) = torch.split(encoder_qkv, split_size, dim=-1)
+
+ # attention
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=1)
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=1)
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # Split the attention outputs.
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, : residual.shape[1]],
+ hidden_states[:, residual.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ if not attn.context_pre_only:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+ if context_input_ndim == 4:
+ encoder_hidden_states = encoder_hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ return hidden_states, encoder_hidden_states
+
+
+class XFormersJointAttnProcessor:
+ r"""
+ Processor for implementing memory efficient attention using xFormers.
+
+ Args:
+ attention_op (`Callable`, *optional*, defaults to `None`):
+ The base
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
+ operator.
+ """
+
+ def __init__(self, attention_op: Optional[Callable] = None):
+ self.attention_op = attention_op
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ residual = hidden_states
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ query = attn.head_to_batch_dim(query).contiguous()
+ key = attn.head_to_batch_dim(key).contiguous()
+ value = attn.head_to_batch_dim(value).contiguous()
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = attn.head_to_batch_dim(encoder_hidden_states_query_proj).contiguous()
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj).contiguous()
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj).contiguous()
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=1)
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=1)
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=1)
+
+ hidden_states = xformers.ops.memory_efficient_attention(
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
+ )
+ hidden_states = hidden_states.to(query.dtype)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ if encoder_hidden_states is not None:
+ # Split the attention outputs.
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, : residual.shape[1]],
+ hidden_states[:, residual.shape[1] :],
+ )
+ if not attn.context_pre_only:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if encoder_hidden_states is not None:
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class AllegroAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the Allegro model. It applies a normalization layer and rotary embedding on the query and key vector.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "AllegroAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None and not attn.is_cross_attention:
+ from .embeddings import apply_rotary_emb_allegro
+
+ query = apply_rotary_emb_allegro(query, image_rotary_emb[0], image_rotary_emb[1])
+ key = apply_rotary_emb_allegro(key, image_rotary_emb[0], image_rotary_emb[1])
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class AuraFlowAttnProcessor2_0:
+ """Attention processor used typically in processing Aura Flow."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention") and is_torch_version("<", "2.1"):
+ raise ImportError(
+ "AuraFlowAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to at least 2.1 or above as we use `scale` in `F.scaled_dot_product_attention()`. "
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ batch_size = hidden_states.shape[0]
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ # Reshape.
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query = query.view(batch_size, -1, attn.heads, head_dim)
+ key = key.view(batch_size, -1, attn.heads, head_dim)
+ value = value.view(batch_size, -1, attn.heads, head_dim)
+
+ # Apply QK norm.
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Concatenate the projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ )
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(batch_size, -1, attn.heads, head_dim)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ )
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_q(encoder_hidden_states_key_proj)
+
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=1)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
+
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # Attention.
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, scale=attn.scale, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # Split the attention outputs.
+ if encoder_hidden_states is not None:
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ if encoder_hidden_states is not None:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ if encoder_hidden_states is not None:
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FusedAuraFlowAttnProcessor2_0:
+ """Attention processor used typically in processing Aura Flow with fused projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention") and is_torch_version("<", "2.1"):
+ raise ImportError(
+ "FusedAuraFlowAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to at least 2.1 or above as we use `scale` in `F.scaled_dot_product_attention()`. "
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ batch_size = hidden_states.shape[0]
+
+ # `sample` projections.
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_qkv = attn.to_added_qkv(encoder_hidden_states)
+ split_size = encoder_qkv.shape[-1] // 3
+ (
+ encoder_hidden_states_query_proj,
+ encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj,
+ ) = torch.split(encoder_qkv, split_size, dim=-1)
+
+ # Reshape.
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+ query = query.view(batch_size, -1, attn.heads, head_dim)
+ key = key.view(batch_size, -1, attn.heads, head_dim)
+ value = value.view(batch_size, -1, attn.heads, head_dim)
+
+ # Apply QK norm.
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Concatenate the projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ )
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(batch_size, -1, attn.heads, head_dim)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ )
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_q(encoder_hidden_states_key_proj)
+
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=1)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
+
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # Attention.
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, scale=attn.scale, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # Split the attention outputs.
+ if encoder_hidden_states is not None:
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ if encoder_hidden_states is not None:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ if encoder_hidden_states is not None:
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FluxAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("FluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ if encoder_hidden_states is not None:
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FluxAttnProcessor2_0_NPU:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FluxAttnProcessor2_0_NPU requires PyTorch 2.0 and torch NPU, to use it, please upgrade PyTorch to 2.0 and install torch NPU"
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ if encoder_hidden_states is not None:
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ if query.dtype in (torch.float16, torch.bfloat16):
+ hidden_states = torch_npu.npu_fusion_attention(
+ query,
+ key,
+ value,
+ attn.heads,
+ input_layout="BNSD",
+ pse=None,
+ scale=1.0 / math.sqrt(query.shape[-1]),
+ pre_tockens=65536,
+ next_tockens=65536,
+ keep_prob=1.0,
+ sync=False,
+ inner_precise=0,
+ )[0]
+ else:
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FusedFluxAttnProcessor2_0:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FusedFluxAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_qkv = attn.to_added_qkv(encoder_hidden_states)
+ split_size = encoder_qkv.shape[-1] // 3
+ (
+ encoder_hidden_states_query_proj,
+ encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj,
+ ) = torch.split(encoder_qkv, split_size, dim=-1)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FusedFluxAttnProcessor2_0_NPU:
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FluxAttnProcessor2_0_NPU requires PyTorch 2.0 and torch NPU, to use it, please upgrade PyTorch to 2.0, and install torch NPU"
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_qkv = attn.to_added_qkv(encoder_hidden_states)
+ split_size = encoder_qkv.shape[-1] // 3
+ (
+ encoder_hidden_states_query_proj,
+ encoder_hidden_states_key_proj,
+ encoder_hidden_states_value_proj,
+ ) = torch.split(encoder_qkv, split_size, dim=-1)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ if query.dtype in (torch.float16, torch.bfloat16):
+ hidden_states = torch_npu.npu_fusion_attention(
+ query,
+ key,
+ value,
+ attn.heads,
+ input_layout="BNSD",
+ pse=None,
+ scale=1.0 / math.sqrt(query.shape[-1]),
+ pre_tockens=65536,
+ next_tockens=65536,
+ keep_prob=1.0,
+ sync=False,
+ inner_precise=0,
+ )[0]
+ else:
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class FluxIPAdapterJointAttnProcessor2_0(torch.nn.Module):
+ """Flux Attention processor for IP-Adapter."""
+
+ def __init__(
+ self, hidden_size: int, cross_attention_dim: int, num_tokens=(4,), scale=1.0, device=None, dtype=None
+ ):
+ super().__init__()
+
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+
+ if not isinstance(num_tokens, (tuple, list)):
+ num_tokens = [num_tokens]
+
+ if not isinstance(scale, list):
+ scale = [scale] * len(num_tokens)
+ if len(scale) != len(num_tokens):
+ raise ValueError("`scale` should be a list of integers with the same length as `num_tokens`.")
+ self.scale = scale
+
+ self.to_k_ip = nn.ModuleList(
+ [
+ nn.Linear(cross_attention_dim, hidden_size, bias=True, device=device, dtype=dtype)
+ for _ in range(len(num_tokens))
+ ]
+ )
+ self.to_v_ip = nn.ModuleList(
+ [
+ nn.Linear(cross_attention_dim, hidden_size, bias=True, device=device, dtype=dtype)
+ for _ in range(len(num_tokens))
+ ]
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ip_hidden_states: Optional[List[torch.Tensor]] = None,
+ ip_adapter_masks: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ hidden_states_query_proj = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ hidden_states_query_proj = hidden_states_query_proj.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ hidden_states_query_proj = attn.norm_q(hidden_states_query_proj)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ if encoder_hidden_states is not None:
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, hidden_states_query_proj], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ # IP-adapter
+ ip_query = hidden_states_query_proj
+ ip_attn_output = torch.zeros_like(hidden_states)
+
+ for current_ip_hidden_states, scale, to_k_ip, to_v_ip in zip(
+ ip_hidden_states, self.scale, self.to_k_ip, self.to_v_ip
+ ):
+ ip_key = to_k_ip(current_ip_hidden_states)
+ ip_value = to_v_ip(current_ip_hidden_states)
+
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ current_ip_hidden_states = F.scaled_dot_product_attention(
+ ip_query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+ current_ip_hidden_states = current_ip_hidden_states.transpose(1, 2).reshape(
+ batch_size, -1, attn.heads * head_dim
+ )
+ current_ip_hidden_states = current_ip_hidden_states.to(ip_query.dtype)
+ ip_attn_output += scale * current_ip_hidden_states
+
+ return hidden_states, encoder_hidden_states, ip_attn_output
+ else:
+ return hidden_states
+
+
+class CogVideoXAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention for the CogVideoX model. It applies a rotary embedding on
+ query and key vectors, but does not include spatial normalization.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("CogVideoXAttnProcessor requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ text_seq_length = encoder_hidden_states.size(1)
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)
+ if not attn.is_cross_attention:
+ key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states, hidden_states = hidden_states.split(
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
+ )
+ return hidden_states, encoder_hidden_states
+
+
+class FusedCogVideoXAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention for the CogVideoX model. It applies a rotary embedding on
+ query and key vectors, but does not include spatial normalization.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("CogVideoXAttnProcessor requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ text_seq_length = encoder_hidden_states.size(1)
+
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query[:, :, text_seq_length:] = apply_rotary_emb(query[:, :, text_seq_length:], image_rotary_emb)
+ if not attn.is_cross_attention:
+ key[:, :, text_seq_length:] = apply_rotary_emb(key[:, :, text_seq_length:], image_rotary_emb)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states, hidden_states = hidden_states.split(
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
+ )
+ return hidden_states, encoder_hidden_states
+
+
+class XFormersAttnAddedKVProcessor:
+ r"""
+ Processor for implementing memory efficient attention using xFormers.
+
+ Args:
+ attention_op (`Callable`, *optional*, defaults to `None`):
+ The base
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
+ operator.
+ """
+
+ def __init__(self, attention_op: Optional[Callable] = None):
+ self.attention_op = attention_op
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+ query = attn.head_to_batch_dim(query)
+
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
+
+ if not attn.only_cross_attention:
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
+ else:
+ key = encoder_hidden_states_key_proj
+ value = encoder_hidden_states_value_proj
+
+ hidden_states = xformers.ops.memory_efficient_attention(
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
+ )
+ hidden_states = hidden_states.to(query.dtype)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+class XFormersAttnProcessor:
+ r"""
+ Processor for implementing memory efficient attention using xFormers.
+
+ Args:
+ attention_op (`Callable`, *optional*, defaults to `None`):
+ The base
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
+ operator.
+ """
+
+ def __init__(self, attention_op: Optional[Callable] = None):
+ self.attention_op = attention_op
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, key_tokens, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, key_tokens, batch_size)
+ if attention_mask is not None:
+ # expand our mask's singleton query_tokens dimension:
+ # [batch*heads, 1, key_tokens] ->
+ # [batch*heads, query_tokens, key_tokens]
+ # so that it can be added as a bias onto the attention scores that xformers computes:
+ # [batch*heads, query_tokens, key_tokens]
+ # we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
+ _, query_tokens, _ = hidden_states.shape
+ attention_mask = attention_mask.expand(-1, query_tokens, -1)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ query = attn.head_to_batch_dim(query).contiguous()
+ key = attn.head_to_batch_dim(key).contiguous()
+ value = attn.head_to_batch_dim(value).contiguous()
+
+ hidden_states = xformers.ops.memory_efficient_attention(
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
+ )
+ hidden_states = hidden_states.to(query.dtype)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class AttnProcessorNPU:
+ r"""
+ Processor for implementing flash attention using torch_npu. Torch_npu supports only fp16 and bf16 data types. If
+ fp32 is used, F.scaled_dot_product_attention will be used for computation, but the acceleration effect on NPU is
+ not significant.
+
+ """
+
+ def __init__(self):
+ if not is_torch_npu_available():
+ raise ImportError("AttnProcessorNPU requires torch_npu extensions and is supported only on npu devices.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+ attention_mask = attention_mask.repeat(1, 1, hidden_states.shape[1], 1)
+ if attention_mask.dtype == torch.bool:
+ attention_mask = torch.logical_not(attention_mask.bool())
+ else:
+ attention_mask = attention_mask.bool()
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ if query.dtype in (torch.float16, torch.bfloat16):
+ hidden_states = torch_npu.npu_fusion_attention(
+ query,
+ key,
+ value,
+ attn.heads,
+ input_layout="BNSD",
+ pse=None,
+ atten_mask=attention_mask,
+ scale=1.0 / math.sqrt(query.shape[-1]),
+ pre_tockens=65536,
+ next_tockens=65536,
+ keep_prob=1.0,
+ sync=False,
+ inner_precise=0,
+ )[0]
+ else:
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class AttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class XLAFlashAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention with pallas flash attention kernel if using `torch_xla`.
+ """
+
+ def __init__(self, partition_spec: Optional[Tuple[Optional[str], ...]] = None):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "XLAFlashAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+ if is_torch_xla_version("<", "2.3"):
+ raise ImportError("XLA flash attention requires torch_xla version >= 2.3.")
+ if is_spmd() and is_torch_xla_version("<", "2.4"):
+ raise ImportError("SPMD support for XLA flash attention needs torch_xla version >= 2.4.")
+ self.partition_spec = partition_spec
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ if all(tensor.shape[2] >= 4096 for tensor in [query, key, value]):
+ if attention_mask is not None:
+ attention_mask = attention_mask.view(batch_size, 1, 1, attention_mask.shape[-1])
+ # Convert mask to float and replace 0s with -inf and 1s with 0
+ attention_mask = (
+ attention_mask.float()
+ .masked_fill(attention_mask == 0, float("-inf"))
+ .masked_fill(attention_mask == 1, float(0.0))
+ )
+
+ # Apply attention mask to key
+ key = key + attention_mask
+ query /= math.sqrt(query.shape[3])
+ partition_spec = self.partition_spec if is_spmd() else None
+ hidden_states = flash_attention(query, key, value, causal=False, partition_spec=partition_spec)
+ else:
+ logger.warning(
+ "Unable to use the flash attention pallas kernel API call due to QKV sequence length < 4096."
+ )
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class XLAFluxFlashAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention with pallas flash attention kernel if using `torch_xla`.
+ """
+
+ def __init__(self, partition_spec: Optional[Tuple[Optional[str], ...]] = None):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "XLAFlashAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+ if is_torch_xla_version("<", "2.3"):
+ raise ImportError("XLA flash attention requires torch_xla version >= 2.3.")
+ if is_spmd() and is_torch_xla_version("<", "2.4"):
+ raise ImportError("SPMD support for XLA flash attention needs torch_xla version >= 2.4.")
+ self.partition_spec = partition_spec
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.FloatTensor:
+ batch_size, _, _ = hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the attention in FluxSingleTransformerBlock does not use `encoder_hidden_states`
+ if encoder_hidden_states is not None:
+ # `context` projections.
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ # attention
+ query = torch.cat([encoder_hidden_states_query_proj, query], dim=2)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=2)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=2)
+
+ if image_rotary_emb is not None:
+ from .embeddings import apply_rotary_emb
+
+ query = apply_rotary_emb(query, image_rotary_emb)
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ query /= math.sqrt(head_dim)
+ hidden_states = flash_attention(query, key, value, causal=False)
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ encoder_hidden_states, hidden_states = (
+ hidden_states[:, : encoder_hidden_states.shape[1]],
+ hidden_states[:, encoder_hidden_states.shape[1] :],
+ )
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class MochiVaeAttnProcessor2_0:
+ r"""
+ Attention processor used in Mochi VAE.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ is_single_frame = hidden_states.shape[1] == 1
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if is_single_frame:
+ hidden_states = attn.to_v(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+ return hidden_states
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=attn.is_causal
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class StableAudioAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the Stable Audio model. It applies rotary embedding on query and key vector, and allows MHA, GQA or MQA.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "StableAudioAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def apply_partial_rotary_emb(
+ self,
+ x: torch.Tensor,
+ freqs_cis: Tuple[torch.Tensor],
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ rot_dim = freqs_cis[0].shape[-1]
+ x_to_rotate, x_unrotated = x[..., :rot_dim], x[..., rot_dim:]
+
+ x_rotated = apply_rotary_emb(x_to_rotate, freqs_cis, use_real=True, use_real_unbind_dim=-2)
+
+ out = torch.cat((x_rotated, x_unrotated), dim=-1)
+ return out
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ residual = hidden_states
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ head_dim = query.shape[-1] // attn.heads
+ kv_heads = key.shape[-1] // head_dim
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, kv_heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, kv_heads, head_dim).transpose(1, 2)
+
+ if kv_heads != attn.heads:
+ # if GQA or MQA, repeat the key/value heads to reach the number of query heads.
+ heads_per_kv_head = attn.heads // kv_heads
+ key = torch.repeat_interleave(key, heads_per_kv_head, dim=1, output_size=key.shape[1] * heads_per_kv_head)
+ value = torch.repeat_interleave(
+ value, heads_per_kv_head, dim=1, output_size=value.shape[1] * heads_per_kv_head
+ )
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if rotary_emb is not None:
+ query_dtype = query.dtype
+ key_dtype = key.dtype
+ query = query.to(torch.float32)
+ key = key.to(torch.float32)
+
+ rot_dim = rotary_emb[0].shape[-1]
+ query_to_rotate, query_unrotated = query[..., :rot_dim], query[..., rot_dim:]
+ query_rotated = apply_rotary_emb(query_to_rotate, rotary_emb, use_real=True, use_real_unbind_dim=-2)
+
+ query = torch.cat((query_rotated, query_unrotated), dim=-1)
+
+ if not attn.is_cross_attention:
+ key_to_rotate, key_unrotated = key[..., :rot_dim], key[..., rot_dim:]
+ key_rotated = apply_rotary_emb(key_to_rotate, rotary_emb, use_real=True, use_real_unbind_dim=-2)
+
+ key = torch.cat((key_rotated, key_unrotated), dim=-1)
+
+ query = query.to(query_dtype)
+ key = key.to(key_dtype)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class HunyuanAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the HunyuanDiT model. It applies a s normalization layer and rotary embedding on query and key vector.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ query = apply_rotary_emb(query, image_rotary_emb)
+ if not attn.is_cross_attention:
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class FusedHunyuanAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0) with fused
+ projection layers. This is used in the HunyuanDiT model. It applies a s normalization layer and rotary embedding on
+ query and key vector.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FusedHunyuanAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ if encoder_hidden_states is None:
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+ else:
+ if attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+ query = attn.to_q(hidden_states)
+
+ kv = attn.to_kv(encoder_hidden_states)
+ split_size = kv.shape[-1] // 2
+ key, value = torch.split(kv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ query = apply_rotary_emb(query, image_rotary_emb)
+ if not attn.is_cross_attention:
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class PAGHunyuanAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the HunyuanDiT model. It applies a normalization layer and rotary embedding on query and key vector. This
+ variant of the processor employs [Pertubed Attention Guidance](https://arxiv.org/abs/2403.17377).
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGHunyuanAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ # chunk
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
+
+ # 1. Original Path
+ batch_size, sequence_length, _ = (
+ hidden_states_org.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states_org)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states_org
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ query = apply_rotary_emb(query, image_rotary_emb)
+ if not attn.is_cross_attention:
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states_org = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query.dtype)
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # 2. Perturbed Path
+ if attn.group_norm is not None:
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
+
+ hidden_states_ptb = attn.to_v(hidden_states_ptb)
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # cat
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class PAGCFGHunyuanAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the HunyuanDiT model. It applies a normalization layer and rotary embedding on query and key vector. This
+ variant of the processor employs [Pertubed Attention Guidance](https://arxiv.org/abs/2403.17377).
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGCFGHunyuanAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ image_rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ # chunk
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
+
+ # 1. Original Path
+ batch_size, sequence_length, _ = (
+ hidden_states_org.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states_org)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states_org
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # Apply RoPE if needed
+ if image_rotary_emb is not None:
+ query = apply_rotary_emb(query, image_rotary_emb)
+ if not attn.is_cross_attention:
+ key = apply_rotary_emb(key, image_rotary_emb)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states_org = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query.dtype)
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # 2. Perturbed Path
+ if attn.group_norm is not None:
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
+
+ hidden_states_ptb = attn.to_v(hidden_states_ptb)
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # cat
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class LuminaAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
+ used in the LuminaNextDiT model. It applies a s normalization layer and rotary embedding on query and key vector.
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ attention_mask: Optional[torch.Tensor] = None,
+ query_rotary_emb: Optional[torch.Tensor] = None,
+ key_rotary_emb: Optional[torch.Tensor] = None,
+ base_sequence_length: Optional[int] = None,
+ ) -> torch.Tensor:
+ from .embeddings import apply_rotary_emb
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ # Get Query-Key-Value Pair
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ query_dim = query.shape[-1]
+ inner_dim = key.shape[-1]
+ head_dim = query_dim // attn.heads
+ dtype = query.dtype
+
+ # Get key-value heads
+ kv_heads = inner_dim // head_dim
+
+ # Apply Query-Key Norm if needed
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.view(batch_size, -1, attn.heads, head_dim)
+
+ key = key.view(batch_size, -1, kv_heads, head_dim)
+ value = value.view(batch_size, -1, kv_heads, head_dim)
+
+ # Apply RoPE if needed
+ if query_rotary_emb is not None:
+ query = apply_rotary_emb(query, query_rotary_emb, use_real=False)
+ if key_rotary_emb is not None:
+ key = apply_rotary_emb(key, key_rotary_emb, use_real=False)
+
+ query, key = query.to(dtype), key.to(dtype)
+
+ # Apply proportional attention if true
+ if key_rotary_emb is None:
+ softmax_scale = None
+ else:
+ if base_sequence_length is not None:
+ softmax_scale = math.sqrt(math.log(sequence_length, base_sequence_length)) * attn.scale
+ else:
+ softmax_scale = attn.scale
+
+ # perform Grouped-qurey Attention (GQA)
+ n_rep = attn.heads // kv_heads
+ if n_rep >= 1:
+ key = key.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
+ value = value.unsqueeze(3).repeat(1, 1, 1, n_rep, 1).flatten(2, 3)
+
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.bool().view(batch_size, 1, 1, -1)
+ attention_mask = attention_mask.expand(-1, attn.heads, sequence_length, -1)
+
+ query = query.transpose(1, 2)
+ key = key.transpose(1, 2)
+ value = value.transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, scale=softmax_scale
+ )
+ hidden_states = hidden_states.transpose(1, 2).to(dtype)
+
+ return hidden_states
+
+
+class FusedAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). It uses
+ fused projection layers. For self-attention modules, all projection matrices (i.e., query, key, value) are fused.
+ For cross-attention modules, key and value projection matrices are fused.
+
+
+
+ This API is currently 🧪 experimental in nature and can change in future.
+
+
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "FusedAttnProcessor2_0 requires at least PyTorch 2.0, to use it. Please upgrade PyTorch to > 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ *args,
+ **kwargs,
+ ) -> torch.Tensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ if encoder_hidden_states is None:
+ qkv = attn.to_qkv(hidden_states)
+ split_size = qkv.shape[-1] // 3
+ query, key, value = torch.split(qkv, split_size, dim=-1)
+ else:
+ if attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+ query = attn.to_q(hidden_states)
+
+ kv = attn.to_kv(encoder_hidden_states)
+ split_size = kv.shape[-1] // 2
+ key, value = torch.split(kv, split_size, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class CustomDiffusionXFormersAttnProcessor(nn.Module):
+ r"""
+ Processor for implementing memory efficient attention using xFormers for the Custom Diffusion method.
+
+ Args:
+ train_kv (`bool`, defaults to `True`):
+ Whether to newly train the key and value matrices corresponding to the text features.
+ train_q_out (`bool`, defaults to `True`):
+ Whether to newly train query matrices corresponding to the latent image features.
+ hidden_size (`int`, *optional*, defaults to `None`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
+ The number of channels in the `encoder_hidden_states`.
+ out_bias (`bool`, defaults to `True`):
+ Whether to include the bias parameter in `train_q_out`.
+ dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability to use.
+ attention_op (`Callable`, *optional*, defaults to `None`):
+ The base
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to use
+ as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best operator.
+ """
+
+ def __init__(
+ self,
+ train_kv: bool = True,
+ train_q_out: bool = False,
+ hidden_size: Optional[int] = None,
+ cross_attention_dim: Optional[int] = None,
+ out_bias: bool = True,
+ dropout: float = 0.0,
+ attention_op: Optional[Callable] = None,
+ ):
+ super().__init__()
+ self.train_kv = train_kv
+ self.train_q_out = train_q_out
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.attention_op = attention_op
+
+ # `_custom_diffusion` id for easy serialization and loading.
+ if self.train_kv:
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ if self.train_q_out:
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.to_out_custom_diffusion = nn.ModuleList([])
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if self.train_q_out:
+ query = self.to_q_custom_diffusion(hidden_states).to(attn.to_q.weight.dtype)
+ else:
+ query = attn.to_q(hidden_states.to(attn.to_q.weight.dtype))
+
+ if encoder_hidden_states is None:
+ crossattn = False
+ encoder_hidden_states = hidden_states
+ else:
+ crossattn = True
+ if attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ if self.train_kv:
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
+ key = key.to(attn.to_q.weight.dtype)
+ value = value.to(attn.to_q.weight.dtype)
+ else:
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if crossattn:
+ detach = torch.ones_like(key)
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
+ key = detach * key + (1 - detach) * key.detach()
+ value = detach * value + (1 - detach) * value.detach()
+
+ query = attn.head_to_batch_dim(query).contiguous()
+ key = attn.head_to_batch_dim(key).contiguous()
+ value = attn.head_to_batch_dim(value).contiguous()
+
+ hidden_states = xformers.ops.memory_efficient_attention(
+ query, key, value, attn_bias=attention_mask, op=self.attention_op, scale=attn.scale
+ )
+ hidden_states = hidden_states.to(query.dtype)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ if self.train_q_out:
+ # linear proj
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
+ # dropout
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
+ else:
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class CustomDiffusionAttnProcessor2_0(nn.Module):
+ r"""
+ Processor for implementing attention for the Custom Diffusion method using PyTorch 2.0’s memory-efficient scaled
+ dot-product attention.
+
+ Args:
+ train_kv (`bool`, defaults to `True`):
+ Whether to newly train the key and value matrices corresponding to the text features.
+ train_q_out (`bool`, defaults to `True`):
+ Whether to newly train query matrices corresponding to the latent image features.
+ hidden_size (`int`, *optional*, defaults to `None`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`, *optional*, defaults to `None`):
+ The number of channels in the `encoder_hidden_states`.
+ out_bias (`bool`, defaults to `True`):
+ Whether to include the bias parameter in `train_q_out`.
+ dropout (`float`, *optional*, defaults to 0.0):
+ The dropout probability to use.
+ """
+
+ def __init__(
+ self,
+ train_kv: bool = True,
+ train_q_out: bool = True,
+ hidden_size: Optional[int] = None,
+ cross_attention_dim: Optional[int] = None,
+ out_bias: bool = True,
+ dropout: float = 0.0,
+ ):
+ super().__init__()
+ self.train_kv = train_kv
+ self.train_q_out = train_q_out
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+
+ # `_custom_diffusion` id for easy serialization and loading.
+ if self.train_kv:
+ self.to_k_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ self.to_v_custom_diffusion = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
+ if self.train_q_out:
+ self.to_q_custom_diffusion = nn.Linear(hidden_size, hidden_size, bias=False)
+ self.to_out_custom_diffusion = nn.ModuleList([])
+ self.to_out_custom_diffusion.append(nn.Linear(hidden_size, hidden_size, bias=out_bias))
+ self.to_out_custom_diffusion.append(nn.Dropout(dropout))
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ batch_size, sequence_length, _ = hidden_states.shape
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ if self.train_q_out:
+ query = self.to_q_custom_diffusion(hidden_states)
+ else:
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ crossattn = False
+ encoder_hidden_states = hidden_states
+ else:
+ crossattn = True
+ if attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ if self.train_kv:
+ key = self.to_k_custom_diffusion(encoder_hidden_states.to(self.to_k_custom_diffusion.weight.dtype))
+ value = self.to_v_custom_diffusion(encoder_hidden_states.to(self.to_v_custom_diffusion.weight.dtype))
+ key = key.to(attn.to_q.weight.dtype)
+ value = value.to(attn.to_q.weight.dtype)
+
+ else:
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if crossattn:
+ detach = torch.ones_like(key)
+ detach[:, :1, :] = detach[:, :1, :] * 0.0
+ key = detach * key + (1 - detach) * key.detach()
+ value = detach * value + (1 - detach) * value.detach()
+
+ inner_dim = hidden_states.shape[-1]
+
+ head_dim = inner_dim // attn.heads
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if self.train_q_out:
+ # linear proj
+ hidden_states = self.to_out_custom_diffusion[0](hidden_states)
+ # dropout
+ hidden_states = self.to_out_custom_diffusion[1](hidden_states)
+ else:
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class SlicedAttnProcessor:
+ r"""
+ Processor for implementing sliced attention.
+
+ Args:
+ slice_size (`int`, *optional*):
+ The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
+ `attention_head_dim` must be a multiple of the `slice_size`.
+ """
+
+ def __init__(self, slice_size: int):
+ self.slice_size = slice_size
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+ dim = query.shape[-1]
+ query = attn.head_to_batch_dim(query)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+
+ batch_size_attention, query_tokens, _ = query.shape
+ hidden_states = torch.zeros(
+ (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
+ )
+
+ for i in range((batch_size_attention - 1) // self.slice_size + 1):
+ start_idx = i * self.slice_size
+ end_idx = (i + 1) * self.slice_size
+
+ query_slice = query[start_idx:end_idx]
+ key_slice = key[start_idx:end_idx]
+ attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
+
+ attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
+
+ attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
+
+ hidden_states[start_idx:end_idx] = attn_slice
+
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class SlicedAttnAddedKVProcessor:
+ r"""
+ Processor for implementing sliced attention with extra learnable key and value matrices for the text encoder.
+
+ Args:
+ slice_size (`int`, *optional*):
+ The number of steps to compute attention. Uses as many slices as `attention_head_dim // slice_size`, and
+ `attention_head_dim` must be a multiple of the `slice_size`.
+ """
+
+ def __init__(self, slice_size):
+ self.slice_size = slice_size
+
+ def __call__(
+ self,
+ attn: "Attention",
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ hidden_states = hidden_states.view(hidden_states.shape[0], hidden_states.shape[1], -1).transpose(1, 2)
+
+ batch_size, sequence_length, _ = hidden_states.shape
+
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+ dim = query.shape[-1]
+ query = attn.head_to_batch_dim(query)
+
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_key_proj = attn.head_to_batch_dim(encoder_hidden_states_key_proj)
+ encoder_hidden_states_value_proj = attn.head_to_batch_dim(encoder_hidden_states_value_proj)
+
+ if not attn.only_cross_attention:
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+ key = torch.cat([encoder_hidden_states_key_proj, key], dim=1)
+ value = torch.cat([encoder_hidden_states_value_proj, value], dim=1)
+ else:
+ key = encoder_hidden_states_key_proj
+ value = encoder_hidden_states_value_proj
+
+ batch_size_attention, query_tokens, _ = query.shape
+ hidden_states = torch.zeros(
+ (batch_size_attention, query_tokens, dim // attn.heads), device=query.device, dtype=query.dtype
+ )
+
+ for i in range((batch_size_attention - 1) // self.slice_size + 1):
+ start_idx = i * self.slice_size
+ end_idx = (i + 1) * self.slice_size
+
+ query_slice = query[start_idx:end_idx]
+ key_slice = key[start_idx:end_idx]
+ attn_mask_slice = attention_mask[start_idx:end_idx] if attention_mask is not None else None
+
+ attn_slice = attn.get_attention_scores(query_slice, key_slice, attn_mask_slice)
+
+ attn_slice = torch.bmm(attn_slice, value[start_idx:end_idx])
+
+ hidden_states[start_idx:end_idx] = attn_slice
+
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ hidden_states = hidden_states.transpose(-1, -2).reshape(residual.shape)
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+class SpatialNorm(nn.Module):
+ """
+ Spatially conditioned normalization as defined in https://arxiv.org/abs/2209.09002.
+
+ Args:
+ f_channels (`int`):
+ The number of channels for input to group normalization layer, and output of the spatial norm layer.
+ zq_channels (`int`):
+ The number of channels for the quantized vector as described in the paper.
+ """
+
+ def __init__(
+ self,
+ f_channels: int,
+ zq_channels: int,
+ ):
+ super().__init__()
+ self.norm_layer = nn.GroupNorm(num_channels=f_channels, num_groups=32, eps=1e-6, affine=True)
+ self.conv_y = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
+ self.conv_b = nn.Conv2d(zq_channels, f_channels, kernel_size=1, stride=1, padding=0)
+
+ def forward(self, f: torch.Tensor, zq: torch.Tensor) -> torch.Tensor:
+ f_size = f.shape[-2:]
+ zq = F.interpolate(zq, size=f_size, mode="nearest")
+ norm_f = self.norm_layer(f)
+ new_f = norm_f * self.conv_y(zq) + self.conv_b(zq)
+ return new_f
+
+
+class IPAdapterAttnProcessor(nn.Module):
+ r"""
+ Attention processor for Multiple IP-Adapters.
+
+ Args:
+ hidden_size (`int`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`):
+ The number of channels in the `encoder_hidden_states`.
+ num_tokens (`int`, `Tuple[int]` or `List[int]`, defaults to `(4,)`):
+ The context length of the image features.
+ scale (`float` or List[`float`], defaults to 1.0):
+ the weight scale of image prompt.
+ """
+
+ def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=(4,), scale=1.0):
+ super().__init__()
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+
+ if not isinstance(num_tokens, (tuple, list)):
+ num_tokens = [num_tokens]
+ self.num_tokens = num_tokens
+
+ if not isinstance(scale, list):
+ scale = [scale] * len(num_tokens)
+ if len(scale) != len(num_tokens):
+ raise ValueError("`scale` should be a list of integers with the same length as `num_tokens`.")
+ self.scale = scale
+
+ self.to_k_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+ self.to_v_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ scale: float = 1.0,
+ ip_adapter_masks: Optional[torch.Tensor] = None,
+ ):
+ residual = hidden_states
+
+ # separate ip_hidden_states from encoder_hidden_states
+ if encoder_hidden_states is not None:
+ if isinstance(encoder_hidden_states, tuple):
+ encoder_hidden_states, ip_hidden_states = encoder_hidden_states
+ else:
+ deprecation_message = (
+ "You have passed a tensor as `encoder_hidden_states`. This is deprecated and will be removed in a future release."
+ " Please make sure to update your script to pass `encoder_hidden_states` as a tuple to suppress this warning."
+ )
+ deprecate("encoder_hidden_states not a tuple", "1.0.0", deprecation_message, standard_warn=False)
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens[0]
+ encoder_hidden_states, ip_hidden_states = (
+ encoder_hidden_states[:, :end_pos, :],
+ [encoder_hidden_states[:, end_pos:, :]],
+ )
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ query = attn.head_to_batch_dim(query)
+ key = attn.head_to_batch_dim(key)
+ value = attn.head_to_batch_dim(value)
+
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
+ hidden_states = torch.bmm(attention_probs, value)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ if ip_adapter_masks is not None:
+ if not isinstance(ip_adapter_masks, List):
+ # for backward compatibility, we accept `ip_adapter_mask` as a tensor of shape [num_ip_adapter, 1, height, width]
+ ip_adapter_masks = list(ip_adapter_masks.unsqueeze(1))
+ if not (len(ip_adapter_masks) == len(self.scale) == len(ip_hidden_states)):
+ raise ValueError(
+ f"Length of ip_adapter_masks array ({len(ip_adapter_masks)}) must match "
+ f"length of self.scale array ({len(self.scale)}) and number of ip_hidden_states "
+ f"({len(ip_hidden_states)})"
+ )
+ else:
+ for index, (mask, scale, ip_state) in enumerate(zip(ip_adapter_masks, self.scale, ip_hidden_states)):
+ if mask is None:
+ continue
+ if not isinstance(mask, torch.Tensor) or mask.ndim != 4:
+ raise ValueError(
+ "Each element of the ip_adapter_masks array should be a tensor with shape "
+ "[1, num_images_for_ip_adapter, height, width]."
+ " Please use `IPAdapterMaskProcessor` to preprocess your mask"
+ )
+ if mask.shape[1] != ip_state.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of ip images ({ip_state.shape[1]}) at index {index}"
+ )
+ if isinstance(scale, list) and not len(scale) == mask.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of scales ({len(scale)}) at index {index}"
+ )
+ else:
+ ip_adapter_masks = [None] * len(self.scale)
+
+ # for ip-adapter
+ for current_ip_hidden_states, scale, to_k_ip, to_v_ip, mask in zip(
+ ip_hidden_states, self.scale, self.to_k_ip, self.to_v_ip, ip_adapter_masks
+ ):
+ skip = False
+ if isinstance(scale, list):
+ if all(s == 0 for s in scale):
+ skip = True
+ elif scale == 0:
+ skip = True
+ if not skip:
+ if mask is not None:
+ if not isinstance(scale, list):
+ scale = [scale] * mask.shape[1]
+
+ current_num_images = mask.shape[1]
+ for i in range(current_num_images):
+ ip_key = to_k_ip(current_ip_hidden_states[:, i, :, :])
+ ip_value = to_v_ip(current_ip_hidden_states[:, i, :, :])
+
+ ip_key = attn.head_to_batch_dim(ip_key)
+ ip_value = attn.head_to_batch_dim(ip_value)
+
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
+ _current_ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
+ _current_ip_hidden_states = attn.batch_to_head_dim(_current_ip_hidden_states)
+
+ mask_downsample = IPAdapterMaskProcessor.downsample(
+ mask[:, i, :, :],
+ batch_size,
+ _current_ip_hidden_states.shape[1],
+ _current_ip_hidden_states.shape[2],
+ )
+
+ mask_downsample = mask_downsample.to(dtype=query.dtype, device=query.device)
+
+ hidden_states = hidden_states + scale[i] * (_current_ip_hidden_states * mask_downsample)
+ else:
+ ip_key = to_k_ip(current_ip_hidden_states)
+ ip_value = to_v_ip(current_ip_hidden_states)
+
+ ip_key = attn.head_to_batch_dim(ip_key)
+ ip_value = attn.head_to_batch_dim(ip_value)
+
+ ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
+ current_ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
+ current_ip_hidden_states = attn.batch_to_head_dim(current_ip_hidden_states)
+
+ hidden_states = hidden_states + scale * current_ip_hidden_states
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class IPAdapterAttnProcessor2_0(torch.nn.Module):
+ r"""
+ Attention processor for IP-Adapter for PyTorch 2.0.
+
+ Args:
+ hidden_size (`int`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`):
+ The number of channels in the `encoder_hidden_states`.
+ num_tokens (`int`, `Tuple[int]` or `List[int]`, defaults to `(4,)`):
+ The context length of the image features.
+ scale (`float` or `List[float]`, defaults to 1.0):
+ the weight scale of image prompt.
+ """
+
+ def __init__(self, hidden_size, cross_attention_dim=None, num_tokens=(4,), scale=1.0):
+ super().__init__()
+
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ f"{self.__class__.__name__} requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+
+ if not isinstance(num_tokens, (tuple, list)):
+ num_tokens = [num_tokens]
+ self.num_tokens = num_tokens
+
+ if not isinstance(scale, list):
+ scale = [scale] * len(num_tokens)
+ if len(scale) != len(num_tokens):
+ raise ValueError("`scale` should be a list of integers with the same length as `num_tokens`.")
+ self.scale = scale
+
+ self.to_k_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+ self.to_v_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ temb: Optional[torch.Tensor] = None,
+ scale: float = 1.0,
+ ip_adapter_masks: Optional[torch.Tensor] = None,
+ ):
+ residual = hidden_states
+
+ # separate ip_hidden_states from encoder_hidden_states
+ if encoder_hidden_states is not None:
+ if isinstance(encoder_hidden_states, tuple):
+ encoder_hidden_states, ip_hidden_states = encoder_hidden_states
+ else:
+ deprecation_message = (
+ "You have passed a tensor as `encoder_hidden_states`. This is deprecated and will be removed in a future release."
+ " Please make sure to update your script to pass `encoder_hidden_states` as a tuple to suppress this warning."
+ )
+ deprecate("encoder_hidden_states not a tuple", "1.0.0", deprecation_message, standard_warn=False)
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens[0]
+ encoder_hidden_states, ip_hidden_states = (
+ encoder_hidden_states[:, :end_pos, :],
+ [encoder_hidden_states[:, end_pos:, :]],
+ )
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if ip_adapter_masks is not None:
+ if not isinstance(ip_adapter_masks, List):
+ # for backward compatibility, we accept `ip_adapter_mask` as a tensor of shape [num_ip_adapter, 1, height, width]
+ ip_adapter_masks = list(ip_adapter_masks.unsqueeze(1))
+ if not (len(ip_adapter_masks) == len(self.scale) == len(ip_hidden_states)):
+ raise ValueError(
+ f"Length of ip_adapter_masks array ({len(ip_adapter_masks)}) must match "
+ f"length of self.scale array ({len(self.scale)}) and number of ip_hidden_states "
+ f"({len(ip_hidden_states)})"
+ )
+ else:
+ for index, (mask, scale, ip_state) in enumerate(zip(ip_adapter_masks, self.scale, ip_hidden_states)):
+ if mask is None:
+ continue
+ if not isinstance(mask, torch.Tensor) or mask.ndim != 4:
+ raise ValueError(
+ "Each element of the ip_adapter_masks array should be a tensor with shape "
+ "[1, num_images_for_ip_adapter, height, width]."
+ " Please use `IPAdapterMaskProcessor` to preprocess your mask"
+ )
+ if mask.shape[1] != ip_state.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of ip images ({ip_state.shape[1]}) at index {index}"
+ )
+ if isinstance(scale, list) and not len(scale) == mask.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of scales ({len(scale)}) at index {index}"
+ )
+ else:
+ ip_adapter_masks = [None] * len(self.scale)
+
+ # for ip-adapter
+ for current_ip_hidden_states, scale, to_k_ip, to_v_ip, mask in zip(
+ ip_hidden_states, self.scale, self.to_k_ip, self.to_v_ip, ip_adapter_masks
+ ):
+ skip = False
+ if isinstance(scale, list):
+ if all(s == 0 for s in scale):
+ skip = True
+ elif scale == 0:
+ skip = True
+ if not skip:
+ if mask is not None:
+ if not isinstance(scale, list):
+ scale = [scale] * mask.shape[1]
+
+ current_num_images = mask.shape[1]
+ for i in range(current_num_images):
+ ip_key = to_k_ip(current_ip_hidden_states[:, i, :, :])
+ ip_value = to_v_ip(current_ip_hidden_states[:, i, :, :])
+
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ _current_ip_hidden_states = F.scaled_dot_product_attention(
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+
+ _current_ip_hidden_states = _current_ip_hidden_states.transpose(1, 2).reshape(
+ batch_size, -1, attn.heads * head_dim
+ )
+ _current_ip_hidden_states = _current_ip_hidden_states.to(query.dtype)
+
+ mask_downsample = IPAdapterMaskProcessor.downsample(
+ mask[:, i, :, :],
+ batch_size,
+ _current_ip_hidden_states.shape[1],
+ _current_ip_hidden_states.shape[2],
+ )
+
+ mask_downsample = mask_downsample.to(dtype=query.dtype, device=query.device)
+ hidden_states = hidden_states + scale[i] * (_current_ip_hidden_states * mask_downsample)
+ else:
+ ip_key = to_k_ip(current_ip_hidden_states)
+ ip_value = to_v_ip(current_ip_hidden_states)
+
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ current_ip_hidden_states = F.scaled_dot_product_attention(
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+
+ current_ip_hidden_states = current_ip_hidden_states.transpose(1, 2).reshape(
+ batch_size, -1, attn.heads * head_dim
+ )
+ current_ip_hidden_states = current_ip_hidden_states.to(query.dtype)
+
+ hidden_states = hidden_states + scale * current_ip_hidden_states
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class IPAdapterXFormersAttnProcessor(torch.nn.Module):
+ r"""
+ Attention processor for IP-Adapter using xFormers.
+
+ Args:
+ hidden_size (`int`):
+ The hidden size of the attention layer.
+ cross_attention_dim (`int`):
+ The number of channels in the `encoder_hidden_states`.
+ num_tokens (`int`, `Tuple[int]` or `List[int]`, defaults to `(4,)`):
+ The context length of the image features.
+ scale (`float` or `List[float]`, defaults to 1.0):
+ the weight scale of image prompt.
+ attention_op (`Callable`, *optional*, defaults to `None`):
+ The base
+ [operator](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.AttentionOpBase) to
+ use as the attention operator. It is recommended to set to `None`, and allow xFormers to choose the best
+ operator.
+ """
+
+ def __init__(
+ self,
+ hidden_size,
+ cross_attention_dim=None,
+ num_tokens=(4,),
+ scale=1.0,
+ attention_op: Optional[Callable] = None,
+ ):
+ super().__init__()
+
+ self.hidden_size = hidden_size
+ self.cross_attention_dim = cross_attention_dim
+ self.attention_op = attention_op
+
+ if not isinstance(num_tokens, (tuple, list)):
+ num_tokens = [num_tokens]
+ self.num_tokens = num_tokens
+
+ if not isinstance(scale, list):
+ scale = [scale] * len(num_tokens)
+ if len(scale) != len(num_tokens):
+ raise ValueError("`scale` should be a list of integers with the same length as `num_tokens`.")
+ self.scale = scale
+
+ self.to_k_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+ self.to_v_ip = nn.ModuleList(
+ [nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) for _ in range(len(num_tokens))]
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ temb: Optional[torch.FloatTensor] = None,
+ scale: float = 1.0,
+ ip_adapter_masks: Optional[torch.FloatTensor] = None,
+ ):
+ residual = hidden_states
+
+ # separate ip_hidden_states from encoder_hidden_states
+ if encoder_hidden_states is not None:
+ if isinstance(encoder_hidden_states, tuple):
+ encoder_hidden_states, ip_hidden_states = encoder_hidden_states
+ else:
+ deprecation_message = (
+ "You have passed a tensor as `encoder_hidden_states`. This is deprecated and will be removed in a future release."
+ " Please make sure to update your script to pass `encoder_hidden_states` as a tuple to suppress this warning."
+ )
+ deprecate("encoder_hidden_states not a tuple", "1.0.0", deprecation_message, standard_warn=False)
+ end_pos = encoder_hidden_states.shape[1] - self.num_tokens[0]
+ encoder_hidden_states, ip_hidden_states = (
+ encoder_hidden_states[:, :end_pos, :],
+ [encoder_hidden_states[:, end_pos:, :]],
+ )
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # expand our mask's singleton query_tokens dimension:
+ # [batch*heads, 1, key_tokens] ->
+ # [batch*heads, query_tokens, key_tokens]
+ # so that it can be added as a bias onto the attention scores that xformers computes:
+ # [batch*heads, query_tokens, key_tokens]
+ # we do this explicitly because xformers doesn't broadcast the singleton dimension for us.
+ _, query_tokens, _ = hidden_states.shape
+ attention_mask = attention_mask.expand(-1, query_tokens, -1)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ query = attn.head_to_batch_dim(query).contiguous()
+ key = attn.head_to_batch_dim(key).contiguous()
+ value = attn.head_to_batch_dim(value).contiguous()
+
+ hidden_states = xformers.ops.memory_efficient_attention(
+ query, key, value, attn_bias=attention_mask, op=self.attention_op
+ )
+ hidden_states = hidden_states.to(query.dtype)
+ hidden_states = attn.batch_to_head_dim(hidden_states)
+
+ if ip_hidden_states:
+ if ip_adapter_masks is not None:
+ if not isinstance(ip_adapter_masks, List):
+ # for backward compatibility, we accept `ip_adapter_mask` as a tensor of shape [num_ip_adapter, 1, height, width]
+ ip_adapter_masks = list(ip_adapter_masks.unsqueeze(1))
+ if not (len(ip_adapter_masks) == len(self.scale) == len(ip_hidden_states)):
+ raise ValueError(
+ f"Length of ip_adapter_masks array ({len(ip_adapter_masks)}) must match "
+ f"length of self.scale array ({len(self.scale)}) and number of ip_hidden_states "
+ f"({len(ip_hidden_states)})"
+ )
+ else:
+ for index, (mask, scale, ip_state) in enumerate(
+ zip(ip_adapter_masks, self.scale, ip_hidden_states)
+ ):
+ if mask is None:
+ continue
+ if not isinstance(mask, torch.Tensor) or mask.ndim != 4:
+ raise ValueError(
+ "Each element of the ip_adapter_masks array should be a tensor with shape "
+ "[1, num_images_for_ip_adapter, height, width]."
+ " Please use `IPAdapterMaskProcessor` to preprocess your mask"
+ )
+ if mask.shape[1] != ip_state.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of ip images ({ip_state.shape[1]}) at index {index}"
+ )
+ if isinstance(scale, list) and not len(scale) == mask.shape[1]:
+ raise ValueError(
+ f"Number of masks ({mask.shape[1]}) does not match "
+ f"number of scales ({len(scale)}) at index {index}"
+ )
+ else:
+ ip_adapter_masks = [None] * len(self.scale)
+
+ # for ip-adapter
+ for current_ip_hidden_states, scale, to_k_ip, to_v_ip, mask in zip(
+ ip_hidden_states, self.scale, self.to_k_ip, self.to_v_ip, ip_adapter_masks
+ ):
+ skip = False
+ if isinstance(scale, list):
+ if all(s == 0 for s in scale):
+ skip = True
+ elif scale == 0:
+ skip = True
+ if not skip:
+ if mask is not None:
+ mask = mask.to(torch.float16)
+ if not isinstance(scale, list):
+ scale = [scale] * mask.shape[1]
+
+ current_num_images = mask.shape[1]
+ for i in range(current_num_images):
+ ip_key = to_k_ip(current_ip_hidden_states[:, i, :, :])
+ ip_value = to_v_ip(current_ip_hidden_states[:, i, :, :])
+
+ ip_key = attn.head_to_batch_dim(ip_key).contiguous()
+ ip_value = attn.head_to_batch_dim(ip_value).contiguous()
+
+ _current_ip_hidden_states = xformers.ops.memory_efficient_attention(
+ query, ip_key, ip_value, op=self.attention_op
+ )
+ _current_ip_hidden_states = _current_ip_hidden_states.to(query.dtype)
+ _current_ip_hidden_states = attn.batch_to_head_dim(_current_ip_hidden_states)
+
+ mask_downsample = IPAdapterMaskProcessor.downsample(
+ mask[:, i, :, :],
+ batch_size,
+ _current_ip_hidden_states.shape[1],
+ _current_ip_hidden_states.shape[2],
+ )
+
+ mask_downsample = mask_downsample.to(dtype=query.dtype, device=query.device)
+ hidden_states = hidden_states + scale[i] * (_current_ip_hidden_states * mask_downsample)
+ else:
+ ip_key = to_k_ip(current_ip_hidden_states)
+ ip_value = to_v_ip(current_ip_hidden_states)
+
+ ip_key = attn.head_to_batch_dim(ip_key).contiguous()
+ ip_value = attn.head_to_batch_dim(ip_value).contiguous()
+
+ current_ip_hidden_states = xformers.ops.memory_efficient_attention(
+ query, ip_key, ip_value, op=self.attention_op
+ )
+ current_ip_hidden_states = current_ip_hidden_states.to(query.dtype)
+ current_ip_hidden_states = attn.batch_to_head_dim(current_ip_hidden_states)
+
+ hidden_states = hidden_states + scale * current_ip_hidden_states
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class SD3IPAdapterJointAttnProcessor2_0(torch.nn.Module):
+ """
+ Attention processor for IP-Adapter used typically in processing the SD3-like self-attention projections, with
+ additional image-based information and timestep embeddings.
+
+ Args:
+ hidden_size (`int`):
+ The number of hidden channels.
+ ip_hidden_states_dim (`int`):
+ The image feature dimension.
+ head_dim (`int`):
+ The number of head channels.
+ timesteps_emb_dim (`int`, defaults to 1280):
+ The number of input channels for timestep embedding.
+ scale (`float`, defaults to 0.5):
+ IP-Adapter scale.
+ """
+
+ def __init__(
+ self,
+ hidden_size: int,
+ ip_hidden_states_dim: int,
+ head_dim: int,
+ timesteps_emb_dim: int = 1280,
+ scale: float = 0.5,
+ ):
+ super().__init__()
+
+ # To prevent circular import
+ from .normalization import AdaLayerNorm, RMSNorm
+
+ self.norm_ip = AdaLayerNorm(timesteps_emb_dim, output_dim=ip_hidden_states_dim * 2, norm_eps=1e-6, chunk_dim=1)
+ self.to_k_ip = nn.Linear(ip_hidden_states_dim, hidden_size, bias=False)
+ self.to_v_ip = nn.Linear(ip_hidden_states_dim, hidden_size, bias=False)
+ self.norm_q = RMSNorm(head_dim, 1e-6)
+ self.norm_k = RMSNorm(head_dim, 1e-6)
+ self.norm_ip_k = RMSNorm(head_dim, 1e-6)
+ self.scale = scale
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: torch.FloatTensor = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ ip_hidden_states: torch.FloatTensor = None,
+ temb: torch.FloatTensor = None,
+ ) -> torch.FloatTensor:
+ """
+ Perform the attention computation, integrating image features (if provided) and timestep embeddings.
+
+ If `ip_hidden_states` is `None`, this is equivalent to using JointAttnProcessor2_0.
+
+ Args:
+ attn (`Attention`):
+ Attention instance.
+ hidden_states (`torch.FloatTensor`):
+ Input `hidden_states`.
+ encoder_hidden_states (`torch.FloatTensor`, *optional*):
+ The encoder hidden states.
+ attention_mask (`torch.FloatTensor`, *optional*):
+ Attention mask.
+ ip_hidden_states (`torch.FloatTensor`, *optional*):
+ Image embeddings.
+ temb (`torch.FloatTensor`, *optional*):
+ Timestep embeddings.
+
+ Returns:
+ `torch.FloatTensor`: Output hidden states.
+ """
+ residual = hidden_states
+
+ batch_size = hidden_states.shape[0]
+
+ # `sample` projections.
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ img_query = query
+ img_key = key
+ img_value = value
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # `context` projections.
+ if encoder_hidden_states is not None:
+ encoder_hidden_states_query_proj = attn.add_q_proj(encoder_hidden_states)
+ encoder_hidden_states_key_proj = attn.add_k_proj(encoder_hidden_states)
+ encoder_hidden_states_value_proj = attn.add_v_proj(encoder_hidden_states)
+
+ encoder_hidden_states_query_proj = encoder_hidden_states_query_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_key_proj = encoder_hidden_states_key_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+ encoder_hidden_states_value_proj = encoder_hidden_states_value_proj.view(
+ batch_size, -1, attn.heads, head_dim
+ ).transpose(1, 2)
+
+ if attn.norm_added_q is not None:
+ encoder_hidden_states_query_proj = attn.norm_added_q(encoder_hidden_states_query_proj)
+ if attn.norm_added_k is not None:
+ encoder_hidden_states_key_proj = attn.norm_added_k(encoder_hidden_states_key_proj)
+
+ query = torch.cat([query, encoder_hidden_states_query_proj], dim=2)
+ key = torch.cat([key, encoder_hidden_states_key_proj], dim=2)
+ value = torch.cat([value, encoder_hidden_states_value_proj], dim=2)
+
+ hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ if encoder_hidden_states is not None:
+ # Split the attention outputs.
+ hidden_states, encoder_hidden_states = (
+ hidden_states[:, : residual.shape[1]],
+ hidden_states[:, residual.shape[1] :],
+ )
+ if not attn.context_pre_only:
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
+
+ # IP Adapter
+ if self.scale != 0 and ip_hidden_states is not None:
+ # Norm image features
+ norm_ip_hidden_states = self.norm_ip(ip_hidden_states, temb=temb)
+
+ # To k and v
+ ip_key = self.to_k_ip(norm_ip_hidden_states)
+ ip_value = self.to_v_ip(norm_ip_hidden_states)
+
+ # Reshape
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # Norm
+ query = self.norm_q(img_query)
+ img_key = self.norm_k(img_key)
+ ip_key = self.norm_ip_k(ip_key)
+
+ # cat img
+ key = torch.cat([img_key, ip_key], dim=2)
+ value = torch.cat([img_value, ip_value], dim=2)
+
+ ip_hidden_states = F.scaled_dot_product_attention(query, key, value, dropout_p=0.0, is_causal=False)
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).view(batch_size, -1, attn.heads * head_dim)
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
+
+ hidden_states = hidden_states + ip_hidden_states * self.scale
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if encoder_hidden_states is not None:
+ return hidden_states, encoder_hidden_states
+ else:
+ return hidden_states
+
+
+class PAGIdentitySelfAttnProcessor2_0:
+ r"""
+ Processor for implementing PAG using scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ PAG reference: https://arxiv.org/abs/2403.17377
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGIdentitySelfAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ temb: Optional[torch.FloatTensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ # chunk
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
+
+ # original path
+ batch_size, sequence_length, _ = hidden_states_org.shape
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states_org)
+ key = attn.to_k(hidden_states_org)
+ value = attn.to_v(hidden_states_org)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states_org = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query.dtype)
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # perturbed path (identity attention)
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
+
+ if attn.group_norm is not None:
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
+
+ hidden_states_ptb = attn.to_v(hidden_states_ptb)
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # cat
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class PAGCFGIdentitySelfAttnProcessor2_0:
+ r"""
+ Processor for implementing PAG using scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ PAG reference: https://arxiv.org/abs/2403.17377
+ """
+
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "PAGCFGIdentitySelfAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0."
+ )
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ temb: Optional[torch.FloatTensor] = None,
+ ) -> torch.Tensor:
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ # chunk
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
+
+ # original path
+ batch_size, sequence_length, _ = hidden_states_org.shape
+
+ if attention_mask is not None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states_org = attn.group_norm(hidden_states_org.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states_org)
+ key = attn.to_k(hidden_states_org)
+ value = attn.to_v(hidden_states_org)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ hidden_states_org = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+
+ hidden_states_org = hidden_states_org.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states_org = hidden_states_org.to(query.dtype)
+
+ # linear proj
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ # dropout
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ if input_ndim == 4:
+ hidden_states_org = hidden_states_org.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # perturbed path (identity attention)
+ batch_size, sequence_length, _ = hidden_states_ptb.shape
+
+ if attn.group_norm is not None:
+ hidden_states_ptb = attn.group_norm(hidden_states_ptb.transpose(1, 2)).transpose(1, 2)
+
+ value = attn.to_v(hidden_states_ptb)
+ hidden_states_ptb = value
+ hidden_states_ptb = hidden_states_ptb.to(query.dtype)
+
+ # linear proj
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ # dropout
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ if input_ndim == 4:
+ hidden_states_ptb = hidden_states_ptb.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ # cat
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ return hidden_states
+
+
+class SanaMultiscaleAttnProcessor2_0:
+ r"""
+ Processor for implementing multiscale quadratic attention.
+ """
+
+ def __call__(self, attn: SanaMultiscaleLinearAttention, hidden_states: torch.Tensor) -> torch.Tensor:
+ height, width = hidden_states.shape[-2:]
+ if height * width > attn.attention_head_dim:
+ use_linear_attention = True
+ else:
+ use_linear_attention = False
+
+ residual = hidden_states
+
+ batch_size, _, height, width = list(hidden_states.size())
+ original_dtype = hidden_states.dtype
+
+ hidden_states = hidden_states.movedim(1, -1)
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(hidden_states)
+ value = attn.to_v(hidden_states)
+ hidden_states = torch.cat([query, key, value], dim=3)
+ hidden_states = hidden_states.movedim(-1, 1)
+
+ multi_scale_qkv = [hidden_states]
+ for block in attn.to_qkv_multiscale:
+ multi_scale_qkv.append(block(hidden_states))
+
+ hidden_states = torch.cat(multi_scale_qkv, dim=1)
+
+ if use_linear_attention:
+ # for linear attention upcast hidden_states to float32
+ hidden_states = hidden_states.to(dtype=torch.float32)
+
+ hidden_states = hidden_states.reshape(batch_size, -1, 3 * attn.attention_head_dim, height * width)
+
+ query, key, value = hidden_states.chunk(3, dim=2)
+ query = attn.nonlinearity(query)
+ key = attn.nonlinearity(key)
+
+ if use_linear_attention:
+ hidden_states = attn.apply_linear_attention(query, key, value)
+ hidden_states = hidden_states.to(dtype=original_dtype)
+ else:
+ hidden_states = attn.apply_quadratic_attention(query, key, value)
+
+ hidden_states = torch.reshape(hidden_states, (batch_size, -1, height, width))
+ hidden_states = attn.to_out(hidden_states.movedim(1, -1)).movedim(-1, 1)
+
+ if attn.norm_type == "rms_norm":
+ hidden_states = attn.norm_out(hidden_states.movedim(1, -1)).movedim(-1, 1)
+ else:
+ hidden_states = attn.norm_out(hidden_states)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ return hidden_states
+
+
+class LoRAAttnProcessor:
+ r"""
+ Processor for implementing attention with LoRA.
+ """
+
+ def __init__(self):
+ pass
+
+
+class LoRAAttnProcessor2_0:
+ r"""
+ Processor for implementing attention with LoRA (enabled by default if you're using PyTorch 2.0).
+ """
+
+ def __init__(self):
+ pass
+
+
+class LoRAXFormersAttnProcessor:
+ r"""
+ Processor for implementing attention with LoRA using xFormers.
+ """
+
+ def __init__(self):
+ pass
+
+
+class LoRAAttnAddedKVProcessor:
+ r"""
+ Processor for implementing attention with LoRA with extra learnable key and value matrices for the text encoder.
+ """
+
+ def __init__(self):
+ pass
+
+
+class FluxSingleAttnProcessor2_0(FluxAttnProcessor2_0):
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ """
+
+ def __init__(self):
+ deprecation_message = "`FluxSingleAttnProcessor2_0` is deprecated and will be removed in a future version. Please use `FluxAttnProcessor2_0` instead."
+ deprecate("FluxSingleAttnProcessor2_0", "0.32.0", deprecation_message)
+ super().__init__()
+
+
+class SanaLinearAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product linear attention.
+ """
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ original_dtype = hidden_states.dtype
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.transpose(1, 2).unflatten(1, (attn.heads, -1))
+ key = key.transpose(1, 2).unflatten(1, (attn.heads, -1)).transpose(2, 3)
+ value = value.transpose(1, 2).unflatten(1, (attn.heads, -1))
+
+ query = F.relu(query)
+ key = F.relu(key)
+
+ query, key, value = query.float(), key.float(), value.float()
+
+ value = F.pad(value, (0, 0, 0, 1), mode="constant", value=1.0)
+ scores = torch.matmul(value, key)
+ hidden_states = torch.matmul(scores, query)
+
+ hidden_states = hidden_states[:, :, :-1] / (hidden_states[:, :, -1:] + 1e-15)
+ hidden_states = hidden_states.flatten(1, 2).transpose(1, 2)
+ hidden_states = hidden_states.to(original_dtype)
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if original_dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+class PAGCFGSanaLinearAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product linear attention.
+ """
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ original_dtype = hidden_states.dtype
+
+ hidden_states_uncond, hidden_states_org, hidden_states_ptb = hidden_states.chunk(3)
+ hidden_states_org = torch.cat([hidden_states_uncond, hidden_states_org])
+
+ query = attn.to_q(hidden_states_org)
+ key = attn.to_k(hidden_states_org)
+ value = attn.to_v(hidden_states_org)
+
+ query = query.transpose(1, 2).unflatten(1, (attn.heads, -1))
+ key = key.transpose(1, 2).unflatten(1, (attn.heads, -1)).transpose(2, 3)
+ value = value.transpose(1, 2).unflatten(1, (attn.heads, -1))
+
+ query = F.relu(query)
+ key = F.relu(key)
+
+ query, key, value = query.float(), key.float(), value.float()
+
+ value = F.pad(value, (0, 0, 0, 1), mode="constant", value=1.0)
+ scores = torch.matmul(value, key)
+ hidden_states_org = torch.matmul(scores, query)
+
+ hidden_states_org = hidden_states_org[:, :, :-1] / (hidden_states_org[:, :, -1:] + 1e-15)
+ hidden_states_org = hidden_states_org.flatten(1, 2).transpose(1, 2)
+ hidden_states_org = hidden_states_org.to(original_dtype)
+
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ # perturbed path (identity attention)
+ hidden_states_ptb = attn.to_v(hidden_states_ptb).to(original_dtype)
+
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if original_dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+class PAGIdentitySanaLinearAttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product linear attention.
+ """
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ original_dtype = hidden_states.dtype
+
+ hidden_states_org, hidden_states_ptb = hidden_states.chunk(2)
+
+ query = attn.to_q(hidden_states_org)
+ key = attn.to_k(hidden_states_org)
+ value = attn.to_v(hidden_states_org)
+
+ query = query.transpose(1, 2).unflatten(1, (attn.heads, -1))
+ key = key.transpose(1, 2).unflatten(1, (attn.heads, -1)).transpose(2, 3)
+ value = value.transpose(1, 2).unflatten(1, (attn.heads, -1))
+
+ query = F.relu(query)
+ key = F.relu(key)
+
+ query, key, value = query.float(), key.float(), value.float()
+
+ value = F.pad(value, (0, 0, 0, 1), mode="constant", value=1.0)
+ scores = torch.matmul(value, key)
+ hidden_states_org = torch.matmul(scores, query)
+
+ if hidden_states_org.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states_org = hidden_states_org.float()
+
+ hidden_states_org = hidden_states_org[:, :, :-1] / (hidden_states_org[:, :, -1:] + 1e-15)
+ hidden_states_org = hidden_states_org.flatten(1, 2).transpose(1, 2)
+ hidden_states_org = hidden_states_org.to(original_dtype)
+
+ hidden_states_org = attn.to_out[0](hidden_states_org)
+ hidden_states_org = attn.to_out[1](hidden_states_org)
+
+ # perturbed path (identity attention)
+ hidden_states_ptb = attn.to_v(hidden_states_ptb).to(original_dtype)
+
+ hidden_states_ptb = attn.to_out[0](hidden_states_ptb)
+ hidden_states_ptb = attn.to_out[1](hidden_states_ptb)
+
+ hidden_states = torch.cat([hidden_states_org, hidden_states_ptb])
+
+ if original_dtype == torch.float16:
+ hidden_states = hidden_states.clip(-65504, 65504)
+
+ return hidden_states
+
+
+ADDED_KV_ATTENTION_PROCESSORS = (
+ AttnAddedKVProcessor,
+ SlicedAttnAddedKVProcessor,
+ AttnAddedKVProcessor2_0,
+ XFormersAttnAddedKVProcessor,
+)
+
+CROSS_ATTENTION_PROCESSORS = (
+ AttnProcessor,
+ AttnProcessor2_0,
+ XFormersAttnProcessor,
+ SlicedAttnProcessor,
+ IPAdapterAttnProcessor,
+ IPAdapterAttnProcessor2_0,
+ FluxIPAdapterJointAttnProcessor2_0,
+)
+
+AttentionProcessor = Union[
+ AttnProcessor,
+ CustomDiffusionAttnProcessor,
+ AttnAddedKVProcessor,
+ AttnAddedKVProcessor2_0,
+ JointAttnProcessor2_0,
+ PAGJointAttnProcessor2_0,
+ PAGCFGJointAttnProcessor2_0,
+ FusedJointAttnProcessor2_0,
+ AllegroAttnProcessor2_0,
+ AuraFlowAttnProcessor2_0,
+ FusedAuraFlowAttnProcessor2_0,
+ FluxAttnProcessor2_0,
+ FluxAttnProcessor2_0_NPU,
+ FusedFluxAttnProcessor2_0,
+ FusedFluxAttnProcessor2_0_NPU,
+ CogVideoXAttnProcessor2_0,
+ FusedCogVideoXAttnProcessor2_0,
+ XFormersAttnAddedKVProcessor,
+ XFormersAttnProcessor,
+ XLAFlashAttnProcessor2_0,
+ AttnProcessorNPU,
+ AttnProcessor2_0,
+ MochiVaeAttnProcessor2_0,
+ MochiAttnProcessor2_0,
+ StableAudioAttnProcessor2_0,
+ HunyuanAttnProcessor2_0,
+ FusedHunyuanAttnProcessor2_0,
+ PAGHunyuanAttnProcessor2_0,
+ PAGCFGHunyuanAttnProcessor2_0,
+ LuminaAttnProcessor2_0,
+ FusedAttnProcessor2_0,
+ CustomDiffusionXFormersAttnProcessor,
+ CustomDiffusionAttnProcessor2_0,
+ SlicedAttnProcessor,
+ SlicedAttnAddedKVProcessor,
+ SanaLinearAttnProcessor2_0,
+ PAGCFGSanaLinearAttnProcessor2_0,
+ PAGIdentitySanaLinearAttnProcessor2_0,
+ SanaMultiscaleLinearAttention,
+ SanaMultiscaleAttnProcessor2_0,
+ SanaMultiscaleAttentionProjection,
+ IPAdapterAttnProcessor,
+ IPAdapterAttnProcessor2_0,
+ IPAdapterXFormersAttnProcessor,
+ SD3IPAdapterJointAttnProcessor2_0,
+ PAGIdentitySelfAttnProcessor2_0,
+ PAGCFGIdentitySelfAttnProcessor2_0,
+ LoRAAttnProcessor,
+ LoRAAttnProcessor2_0,
+ LoRAXFormersAttnProcessor,
+ LoRAAttnAddedKVProcessor,
+]
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..c81aad068f439295a1f73ae7f77c4e3300b1b232
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet.py
@@ -0,0 +1,535 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from diffusers.utils import is_torch_version
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = self.attn_fn(
+ query, key_img, value_img, None
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanControlNet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ conditioning_embedding_channels: int = None,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+ # 复用miniencoder
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = conditioning_embedding_channels, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+
+ # make sure conditioning_embedding_channels==in_channels // 8
+ self.controlnet_x_embedder = torch.nn.Linear(conditioning_embedding_channels*4, inner_dim)
+ self.gradient_checkpointing = False
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ # flash attn3 {"use_reentrant": True}
+ def _gradient_checkpointing_func(module, *args):
+ ckpt_kwargs = {"use_reentrant": True} if is_torch_version(">=", "1.11.0") else {}
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+ self._gradient_checkpointing_func_flash_attn3 = _gradient_checkpointing_func
+ print("set {use_reentrant: True}")
+ # self._set_gradient_checkpointing(enable=True, gradient_checkpointing_func=gradient_checkpointing_func)
+ except:
+ self._gradient_checkpointing_func_flash_attn3 = None
+ pass
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # =============== control part ===============
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ #pixel shuffle的方式进行patchify
+ batch_size_c, channels_c, num_frames_c, height_c, width_c = controlnet_cond.shape
+ height_c = height_c // p_h
+ width_c = width_c // p_w
+ num_frames_c = num_frames_c // p_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels_c, num_frames_c, p_t, height_c, p_h, width_c, p_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, num_frames_c * height_c * width_c, -1)
+
+
+ # ============== add control here ===============
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for block in self.blocks:
+ # no gradient_checkpointing
+ # no gradient_checkpointing to speed up!
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_flash_attn3(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ ) if self._gradient_checkpointing_func_flash_attn3 is not None else self._gradient_checkpointing_func(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ block_samples = block_samples + (hidden_states, )
+
+
+ controlnet_block_samples = ()
+ assert len(block_samples) == len(self.controlnet_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, controlnet_blocks has length {len(self.controlnet_blocks)}"
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ controlnet_block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (controlnet_block_sample, )
+
+ return controlnet_block_samples
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_free.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_free.py
new file mode 100644
index 0000000000000000000000000000000000000000..c01f61219e14385b7413aa5a97d8de93eb45714e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_free.py
@@ -0,0 +1,520 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ # try:
+ # from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ # self.attn_backend = "flash-attn-2"
+ # self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ # print("[INFO] Using FlashAttention 2")
+ # except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = self.attn_fn(
+ query, key_img, value_img, None
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ # self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ hidden_states: torch.Tensor,
+ # encoder_hidden_states: torch.Tensor = None,
+ # encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ # encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ # if encoder_hidden_states_image is not None:
+ # encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ # self.attn2 = Attention(
+ # query_dim=dim,
+ # heads=num_heads,
+ # kv_heads=num_heads,
+ # dim_head=dim // num_heads,
+ # qk_norm=qk_norm,
+ # eps=eps,
+ # bias=True,
+ # cross_attention_dim=None,
+ # out_bias=True,
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ # processor=WanAttnProcessor2_0(),
+ # )
+ # self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ # norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ # attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ # hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanControlNet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ conditioning_embedding_channels: int = None,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+ # 复用miniencoder
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = conditioning_embedding_channels, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+
+ # make sure conditioning_embedding_channels==in_channels // 8
+ self.controlnet_x_embedder = torch.nn.Linear(conditioning_embedding_channels*4, inner_dim)
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ encoder_hidden_states = None
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # =============== control part ===============
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ #pixel shuffle的方式进行patchify
+ batch_size_c, channels_c, num_frames_c, height_c, width_c = controlnet_cond.shape
+ height_c = height_c // p_h
+ width_c = width_c // p_w
+ num_frames_c = num_frames_c // p_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels_c, num_frames_c, p_t, height_c, p_h, width_c, p_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, num_frames_c * height_c * width_c, -1)
+
+
+ # ============== add control here ===============
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
+
+ # temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ # timestep, encoder_hidden_states, encoder_hidden_states_image
+ # )
+ temb, timestep_proj = self.condition_embedder(timestep,hidden_states)
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for block in self.blocks:
+ # no gradient_checkpointing
+ # no gradient_checkpointing to speed up!
+ # if torch.is_grad_enabled() and self.gradient_checkpointing:
+ # hidden_states = self._gradient_checkpointing_func(
+ # block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ # )
+ # else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ block_samples = block_samples + (hidden_states, )
+
+
+ controlnet_block_samples = ()
+ assert len(block_samples) == len(self.controlnet_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, controlnet_blocks has length {len(self.controlnet_blocks)}"
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ controlnet_block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (controlnet_block_sample, )
+
+ return controlnet_block_samples
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref.py
new file mode 100644
index 0000000000000000000000000000000000000000..e1eb3f6e049150826280670cdb79a56c376bb565
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref.py
@@ -0,0 +1,264 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from diffusers.utils import is_torch_version
+from .transformer_wan_refextractor_2d_controlnet_last import WanRotaryPosEmbed, WanTimeTextImageEmbedding, WanTransformerBlock
+from .utils import ckpt_kwargs
+import numpy as np
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+class WanControlNet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ conditioning_embedding_channels: int = None,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+ # 复用miniencoder
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = conditioning_embedding_channels, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+
+ # make sure conditioning_embedding_channels==in_channels // 8
+ self.controlnet_x_embedder = torch.nn.Linear(conditioning_embedding_channels*4, inner_dim)
+ self.gradient_checkpointing = False
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ ref_block_samples = None,
+ ref_rotary_emb = None,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # =============== control part ===============
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ #pixel shuffle的方式进行patchify
+ batch_size_c, channels_c, num_frames_c, height_c, width_c = controlnet_cond.shape
+ height_c = height_c // p_h
+ width_c = width_c // p_w
+ num_frames_c = num_frames_c // p_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels_c, num_frames_c, p_t, height_c, p_h, width_c, p_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, num_frames_c * height_c * width_c, -1)
+
+
+ # ============== add control here ===============
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
+
+ if token_replace:
+ t_token_replace = torch.zeros_like(timestep)
+ # 5 frames -> VAE -> 2 frames
+ replace_token_num = 2 * post_patch_height * post_patch_width
+ else:
+ t_token_replace = None
+ replace_token_num = None
+
+
+ temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image, t_token_replace
+ )
+
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+ if timestep_proj_token_replace is not None:
+ timestep_proj_token_replace = timestep_proj_token_replace.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+ # ref_block_samples >= controlnet blocks
+ if ref_block_samples is not None:
+ indices = np.linspace(0, len(ref_block_samples) - 1, len(self.blocks)).round().astype(int)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+
+ ref_latent = ref_block_samples[indices[index_block]]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num)
+
+ block_samples = block_samples + (hidden_states, )
+
+
+ controlnet_block_samples = ()
+ assert len(block_samples) == len(self.controlnet_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, controlnet_blocks has length {len(self.controlnet_blocks)}"
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ controlnet_block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (controlnet_block_sample, )
+
+ return controlnet_block_samples
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref2.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref2.py
new file mode 100644
index 0000000000000000000000000000000000000000..87f59f3238ef44dde753a1abf5cc2569248d5764
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/controlnet_ref2.py
@@ -0,0 +1,240 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from diffusers.utils import is_torch_version
+from .transformer_wan_refextractor_2d_controlnet_last import WanRotaryPosEmbed, WanTimeTextImageEmbedding, WanTransformerBlock
+from .utils import ckpt_kwargs
+import numpy as np
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+class WanControlNet(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ conditioning_embedding_channels: int = None,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+ self.controlnet_blocks = nn.ModuleList([])
+ for _ in range(len(self.blocks)):
+ self.controlnet_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+
+ self.gradient_checkpointing = False
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ ref_block_samples = None,
+ ref_rotary_emb = None,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # ============== add control here ===============
+ hidden_states = hidden_states + controlnet_cond
+
+ if token_replace:
+ t_token_replace = torch.zeros_like(timestep)
+ # 5 frames -> VAE -> 2 frames
+ replace_token_num = 2 * post_patch_height * post_patch_width
+ else:
+ t_token_replace = None
+ replace_token_num = None
+
+
+ temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image, t_token_replace
+ )
+
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+ if timestep_proj_token_replace is not None:
+ timestep_proj_token_replace = timestep_proj_token_replace.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+ # ref_block_samples >= controlnet blocks
+ if ref_block_samples is not None:
+ indices = np.linspace(0, len(ref_block_samples) - 1, len(self.blocks)).round().astype(int)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+
+ ref_latent = ref_block_samples[indices[index_block]]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num)
+
+ block_samples = block_samples + (hidden_states, )
+
+
+ controlnet_block_samples = ()
+ assert len(block_samples) == len(self.controlnet_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, controlnet_blocks has length {len(self.controlnet_blocks)}"
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
+ controlnet_block_sample = controlnet_block(block_sample)
+ controlnet_block_samples = controlnet_block_samples + (controlnet_block_sample, )
+
+ return controlnet_block_samples
+
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/embeddings.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/embeddings.py
new file mode 100644
index 0000000000000000000000000000000000000000..af67405e920f1f61b01ab2fdd0d64f2532b1d3f3
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/embeddings.py
@@ -0,0 +1,2623 @@
+# Copyright 2024 The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+import math
+from typing import List, Optional, Tuple, Union
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from torch import nn
+
+from diffusers.utils import deprecate
+from .activations import FP32SiLU, get_activation
+from .attention_processor import Attention
+
+
+def get_timestep_embedding(
+ timesteps: torch.Tensor,
+ embedding_dim: int,
+ flip_sin_to_cos: bool = False,
+ downscale_freq_shift: float = 1,
+ scale: float = 1,
+ max_period: int = 10000,
+):
+ """
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
+
+ Args
+ timesteps (torch.Tensor):
+ a 1-D Tensor of N indices, one per batch element. These may be fractional.
+ embedding_dim (int):
+ the dimension of the output.
+ flip_sin_to_cos (bool):
+ Whether the embedding order should be `cos, sin` (if True) or `sin, cos` (if False)
+ downscale_freq_shift (float):
+ Controls the delta between frequencies between dimensions
+ scale (float):
+ Scaling factor applied to the embeddings.
+ max_period (int):
+ Controls the maximum frequency of the embeddings
+ Returns
+ torch.Tensor: an [N x dim] Tensor of positional embeddings.
+ """
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
+
+ half_dim = embedding_dim // 2
+ exponent = -math.log(max_period) * torch.arange(
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
+ )
+ exponent = exponent / (half_dim - downscale_freq_shift)
+
+ emb = torch.exp(exponent)
+ emb = timesteps[:, None].float() * emb[None, :]
+
+ # scale embeddings
+ emb = scale * emb
+
+ # concat sine and cosine embeddings
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
+
+ # flip sine and cosine embeddings
+ if flip_sin_to_cos:
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
+
+ # zero pad
+ if embedding_dim % 2 == 1:
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
+ return emb
+
+
+def get_3d_sincos_pos_embed(
+ embed_dim: int,
+ spatial_size: Union[int, Tuple[int, int]],
+ temporal_size: int,
+ spatial_interpolation_scale: float = 1.0,
+ temporal_interpolation_scale: float = 1.0,
+ device: Optional[torch.device] = None,
+ output_type: str = "np",
+) -> torch.Tensor:
+ r"""
+ Creates 3D sinusoidal positional embeddings.
+
+ Args:
+ embed_dim (`int`):
+ The embedding dimension of inputs. It must be divisible by 16.
+ spatial_size (`int` or `Tuple[int, int]`):
+ The spatial dimension of positional embeddings. If an integer is provided, the same size is applied to both
+ spatial dimensions (height and width).
+ temporal_size (`int`):
+ The temporal dimension of postional embeddings (number of frames).
+ spatial_interpolation_scale (`float`, defaults to 1.0):
+ Scale factor for spatial grid interpolation.
+ temporal_interpolation_scale (`float`, defaults to 1.0):
+ Scale factor for temporal grid interpolation.
+
+ Returns:
+ `torch.Tensor`:
+ The 3D sinusoidal positional embeddings of shape `[temporal_size, spatial_size[0] * spatial_size[1],
+ embed_dim]`.
+ """
+ if output_type == "np":
+ return _get_3d_sincos_pos_embed_np(
+ embed_dim=embed_dim,
+ spatial_size=spatial_size,
+ temporal_size=temporal_size,
+ spatial_interpolation_scale=spatial_interpolation_scale,
+ temporal_interpolation_scale=temporal_interpolation_scale,
+ )
+ if embed_dim % 4 != 0:
+ raise ValueError("`embed_dim` must be divisible by 4")
+ if isinstance(spatial_size, int):
+ spatial_size = (spatial_size, spatial_size)
+
+ embed_dim_spatial = 3 * embed_dim // 4
+ embed_dim_temporal = embed_dim // 4
+
+ # 1. Spatial
+ grid_h = torch.arange(spatial_size[1], device=device, dtype=torch.float32) / spatial_interpolation_scale
+ grid_w = torch.arange(spatial_size[0], device=device, dtype=torch.float32) / spatial_interpolation_scale
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy") # here w goes first
+ grid = torch.stack(grid, dim=0)
+
+ grid = grid.reshape([2, 1, spatial_size[1], spatial_size[0]])
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(embed_dim_spatial, grid, output_type="pt")
+
+ # 2. Temporal
+ grid_t = torch.arange(temporal_size, device=device, dtype=torch.float32) / temporal_interpolation_scale
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(embed_dim_temporal, grid_t, output_type="pt")
+
+ # 3. Concat
+ pos_embed_spatial = pos_embed_spatial[None, :, :]
+ pos_embed_spatial = pos_embed_spatial.repeat_interleave(
+ temporal_size, dim=0, output_size=pos_embed_spatial.shape[0] * temporal_size
+ ) # [T, H*W, D // 4 * 3]
+
+ pos_embed_temporal = pos_embed_temporal[:, None, :]
+ pos_embed_temporal = pos_embed_temporal.repeat_interleave(
+ spatial_size[0] * spatial_size[1], dim=1
+ ) # [T, H*W, D // 4]
+
+ pos_embed = torch.concat([pos_embed_temporal, pos_embed_spatial], dim=-1) # [T, H*W, D]
+ return pos_embed
+
+
+def _get_3d_sincos_pos_embed_np(
+ embed_dim: int,
+ spatial_size: Union[int, Tuple[int, int]],
+ temporal_size: int,
+ spatial_interpolation_scale: float = 1.0,
+ temporal_interpolation_scale: float = 1.0,
+) -> np.ndarray:
+ r"""
+ Creates 3D sinusoidal positional embeddings.
+
+ Args:
+ embed_dim (`int`):
+ The embedding dimension of inputs. It must be divisible by 16.
+ spatial_size (`int` or `Tuple[int, int]`):
+ The spatial dimension of positional embeddings. If an integer is provided, the same size is applied to both
+ spatial dimensions (height and width).
+ temporal_size (`int`):
+ The temporal dimension of postional embeddings (number of frames).
+ spatial_interpolation_scale (`float`, defaults to 1.0):
+ Scale factor for spatial grid interpolation.
+ temporal_interpolation_scale (`float`, defaults to 1.0):
+ Scale factor for temporal grid interpolation.
+
+ Returns:
+ `np.ndarray`:
+ The 3D sinusoidal positional embeddings of shape `[temporal_size, spatial_size[0] * spatial_size[1],
+ embed_dim]`.
+ """
+ deprecation_message = (
+ "`get_3d_sincos_pos_embed` uses `torch` and supports `device`."
+ " `from_numpy` is no longer required."
+ " Pass `output_type='pt' to use the new version now."
+ )
+ deprecate("output_type=='np'", "0.33.0", deprecation_message, standard_warn=False)
+ if embed_dim % 4 != 0:
+ raise ValueError("`embed_dim` must be divisible by 4")
+ if isinstance(spatial_size, int):
+ spatial_size = (spatial_size, spatial_size)
+
+ embed_dim_spatial = 3 * embed_dim // 4
+ embed_dim_temporal = embed_dim // 4
+
+ # 1. Spatial
+ grid_h = np.arange(spatial_size[1], dtype=np.float32) / spatial_interpolation_scale
+ grid_w = np.arange(spatial_size[0], dtype=np.float32) / spatial_interpolation_scale
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, spatial_size[1], spatial_size[0]])
+ pos_embed_spatial = get_2d_sincos_pos_embed_from_grid(embed_dim_spatial, grid)
+
+ # 2. Temporal
+ grid_t = np.arange(temporal_size, dtype=np.float32) / temporal_interpolation_scale
+ pos_embed_temporal = get_1d_sincos_pos_embed_from_grid(embed_dim_temporal, grid_t)
+
+ # 3. Concat
+ pos_embed_spatial = pos_embed_spatial[np.newaxis, :, :]
+ pos_embed_spatial = np.repeat(pos_embed_spatial, temporal_size, axis=0) # [T, H*W, D // 4 * 3]
+
+ pos_embed_temporal = pos_embed_temporal[:, np.newaxis, :]
+ pos_embed_temporal = np.repeat(pos_embed_temporal, spatial_size[0] * spatial_size[1], axis=1) # [T, H*W, D // 4]
+
+ pos_embed = np.concatenate([pos_embed_temporal, pos_embed_spatial], axis=-1) # [T, H*W, D]
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed(
+ embed_dim,
+ grid_size,
+ cls_token=False,
+ extra_tokens=0,
+ interpolation_scale=1.0,
+ base_size=16,
+ device: Optional[torch.device] = None,
+ output_type: str = "np",
+):
+ """
+ Creates 2D sinusoidal positional embeddings.
+
+ Args:
+ embed_dim (`int`):
+ The embedding dimension.
+ grid_size (`int`):
+ The size of the grid height and width.
+ cls_token (`bool`, defaults to `False`):
+ Whether or not to add a classification token.
+ extra_tokens (`int`, defaults to `0`):
+ The number of extra tokens to add.
+ interpolation_scale (`float`, defaults to `1.0`):
+ The scale of the interpolation.
+
+ Returns:
+ pos_embed (`torch.Tensor`):
+ Shape is either `[grid_size * grid_size, embed_dim]` if not using cls_token, or `[1 + grid_size*grid_size,
+ embed_dim]` if using cls_token
+ """
+ if output_type == "np":
+ deprecation_message = (
+ "`get_2d_sincos_pos_embed` uses `torch` and supports `device`."
+ " `from_numpy` is no longer required."
+ " Pass `output_type='pt' to use the new version now."
+ )
+ deprecate("output_type=='np'", "0.33.0", deprecation_message, standard_warn=False)
+ return get_2d_sincos_pos_embed_np(
+ embed_dim=embed_dim,
+ grid_size=grid_size,
+ cls_token=cls_token,
+ extra_tokens=extra_tokens,
+ interpolation_scale=interpolation_scale,
+ base_size=base_size,
+ )
+ if isinstance(grid_size, int):
+ grid_size = (grid_size, grid_size)
+
+ grid_h = (
+ torch.arange(grid_size[0], device=device, dtype=torch.float32)
+ / (grid_size[0] / base_size)
+ / interpolation_scale
+ )
+ grid_w = (
+ torch.arange(grid_size[1], device=device, dtype=torch.float32)
+ / (grid_size[1] / base_size)
+ / interpolation_scale
+ )
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy") # here w goes first
+ grid = torch.stack(grid, dim=0)
+
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid, output_type=output_type)
+ if cls_token and extra_tokens > 0:
+ pos_embed = torch.concat([torch.zeros([extra_tokens, embed_dim]), pos_embed], dim=0)
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed_from_grid(embed_dim, grid, output_type="np"):
+ r"""
+ This function generates 2D sinusoidal positional embeddings from a grid.
+
+ Args:
+ embed_dim (`int`): The embedding dimension.
+ grid (`torch.Tensor`): Grid of positions with shape `(H * W,)`.
+
+ Returns:
+ `torch.Tensor`: The 2D sinusoidal positional embeddings with shape `(H * W, embed_dim)`
+ """
+ if output_type == "np":
+ deprecation_message = (
+ "`get_2d_sincos_pos_embed_from_grid` uses `torch` and supports `device`."
+ " `from_numpy` is no longer required."
+ " Pass `output_type='pt' to use the new version now."
+ )
+ deprecate("output_type=='np'", "0.33.0", deprecation_message, standard_warn=False)
+ return get_2d_sincos_pos_embed_from_grid_np(
+ embed_dim=embed_dim,
+ grid=grid,
+ )
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0], output_type=output_type) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1], output_type=output_type) # (H*W, D/2)
+
+ emb = torch.concat([emb_h, emb_w], dim=1) # (H*W, D)
+ return emb
+
+
+def get_1d_sincos_pos_embed_from_grid(embed_dim, pos, output_type="np"):
+ """
+ This function generates 1D positional embeddings from a grid.
+
+ Args:
+ embed_dim (`int`): The embedding dimension `D`
+ pos (`torch.Tensor`): 1D tensor of positions with shape `(M,)`
+
+ Returns:
+ `torch.Tensor`: Sinusoidal positional embeddings of shape `(M, D)`.
+ """
+ if output_type == "np":
+ deprecation_message = (
+ "`get_1d_sincos_pos_embed_from_grid` uses `torch` and supports `device`."
+ " `from_numpy` is no longer required."
+ " Pass `output_type='pt' to use the new version now."
+ )
+ deprecate("output_type=='np'", "0.34.0", deprecation_message, standard_warn=False)
+ return get_1d_sincos_pos_embed_from_grid_np(embed_dim=embed_dim, pos=pos)
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ omega = torch.arange(embed_dim // 2, device=pos.device, dtype=torch.float64)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = torch.outer(pos, omega) # (M, D/2), outer product
+
+ emb_sin = torch.sin(out) # (M, D/2)
+ emb_cos = torch.cos(out) # (M, D/2)
+
+ emb = torch.concat([emb_sin, emb_cos], dim=1) # (M, D)
+ return emb
+
+
+def get_2d_sincos_pos_embed_np(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16
+):
+ """
+ Creates 2D sinusoidal positional embeddings.
+
+ Args:
+ embed_dim (`int`):
+ The embedding dimension.
+ grid_size (`int`):
+ The size of the grid height and width.
+ cls_token (`bool`, defaults to `False`):
+ Whether or not to add a classification token.
+ extra_tokens (`int`, defaults to `0`):
+ The number of extra tokens to add.
+ interpolation_scale (`float`, defaults to `1.0`):
+ The scale of the interpolation.
+
+ Returns:
+ pos_embed (`np.ndarray`):
+ Shape is either `[grid_size * grid_size, embed_dim]` if not using cls_token, or `[1 + grid_size*grid_size,
+ embed_dim]` if using cls_token
+ """
+ if isinstance(grid_size, int):
+ grid_size = (grid_size, grid_size)
+
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size) / interpolation_scale
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size) / interpolation_scale
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
+ pos_embed = get_2d_sincos_pos_embed_from_grid_np(embed_dim, grid)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed_from_grid_np(embed_dim, grid):
+ r"""
+ This function generates 2D sinusoidal positional embeddings from a grid.
+
+ Args:
+ embed_dim (`int`): The embedding dimension.
+ grid (`np.ndarray`): Grid of positions with shape `(H * W,)`.
+
+ Returns:
+ `np.ndarray`: The 2D sinusoidal positional embeddings with shape `(H * W, embed_dim)`
+ """
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_sincos_pos_embed_from_grid_np(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid_np(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
+ return emb
+
+
+def get_1d_sincos_pos_embed_from_grid_np(embed_dim, pos):
+ """
+ This function generates 1D positional embeddings from a grid.
+
+ Args:
+ embed_dim (`int`): The embedding dimension `D`
+ pos (`numpy.ndarray`): 1D tensor of positions with shape `(M,)`
+
+ Returns:
+ `numpy.ndarray`: Sinusoidal positional embeddings of shape `(M, D)`.
+ """
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
+
+ emb_sin = np.sin(out) # (M, D/2)
+ emb_cos = np.cos(out) # (M, D/2)
+
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
+ return emb
+
+
+class PatchEmbed(nn.Module):
+ """
+ 2D Image to Patch Embedding with support for SD3 cropping.
+
+ Args:
+ height (`int`, defaults to `224`): The height of the image.
+ width (`int`, defaults to `224`): The width of the image.
+ patch_size (`int`, defaults to `16`): The size of the patches.
+ in_channels (`int`, defaults to `3`): The number of input channels.
+ embed_dim (`int`, defaults to `768`): The output dimension of the embedding.
+ layer_norm (`bool`, defaults to `False`): Whether or not to use layer normalization.
+ flatten (`bool`, defaults to `True`): Whether or not to flatten the output.
+ bias (`bool`, defaults to `True`): Whether or not to use bias.
+ interpolation_scale (`float`, defaults to `1`): The scale of the interpolation.
+ pos_embed_type (`str`, defaults to `"sincos"`): The type of positional embedding.
+ pos_embed_max_size (`int`, defaults to `None`): The maximum size of the positional embedding.
+ """
+
+ def __init__(
+ self,
+ height=224,
+ width=224,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=1,
+ pos_embed_type="sincos",
+ pos_embed_max_size=None, # For SD3 cropping
+ ):
+ super().__init__()
+
+ num_patches = (height // patch_size) * (width // patch_size)
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+ self.pos_embed_max_size = pos_embed_max_size
+
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size = patch_size
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = height // patch_size
+ self.interpolation_scale = interpolation_scale
+
+ # Calculate positional embeddings based on max size or default
+ if pos_embed_max_size:
+ grid_size = pos_embed_max_size
+ else:
+ grid_size = int(num_patches**0.5)
+
+ if pos_embed_type is None:
+ self.pos_embed = None
+ elif pos_embed_type == "sincos":
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim,
+ grid_size,
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ output_type="pt",
+ )
+ persistent = True if pos_embed_max_size else False
+ self.register_buffer("pos_embed", pos_embed.float().unsqueeze(0), persistent=persistent)
+ else:
+ raise ValueError(f"Unsupported pos_embed_type: {pos_embed_type}")
+
+ def cropped_pos_embed(self, height, width):
+ """Crops positional embeddings for SD3 compatibility."""
+ if self.pos_embed_max_size is None:
+ raise ValueError("`pos_embed_max_size` must be set for cropping.")
+
+ height = height // self.patch_size
+ width = width // self.patch_size
+ if height > self.pos_embed_max_size:
+ raise ValueError(
+ f"Height ({height}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
+ )
+ if width > self.pos_embed_max_size:
+ raise ValueError(
+ f"Width ({width}) cannot be greater than `pos_embed_max_size`: {self.pos_embed_max_size}."
+ )
+
+ top = (self.pos_embed_max_size - height) // 2
+ left = (self.pos_embed_max_size - width) // 2
+ spatial_pos_embed = self.pos_embed.reshape(1, self.pos_embed_max_size, self.pos_embed_max_size, -1)
+ spatial_pos_embed = spatial_pos_embed[:, top : top + height, left : left + width, :]
+ spatial_pos_embed = spatial_pos_embed.reshape(1, -1, spatial_pos_embed.shape[-1])
+ return spatial_pos_embed
+
+ def forward(self, latent):
+ if self.pos_embed_max_size is not None:
+ height, width = latent.shape[-2:]
+ else:
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ latent = self.proj(latent)
+ if self.flatten:
+ latent = latent.flatten(2).transpose(1, 2) # BCHW -> BNC
+ if self.layer_norm:
+ latent = self.norm(latent)
+ if self.pos_embed is None:
+ return latent.to(latent.dtype)
+ # Interpolate or crop positional embeddings as needed
+ if self.pos_embed_max_size:
+ pos_embed = self.cropped_pos_embed(height, width)
+ else:
+ if self.height != height or self.width != width:
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ device=latent.device,
+ output_type="pt",
+ )
+ pos_embed = pos_embed.float().unsqueeze(0)
+ else:
+ pos_embed = self.pos_embed
+
+ return (latent + pos_embed).to(latent.dtype)
+
+
+class LuminaPatchEmbed(nn.Module):
+ """
+ 2D Image to Patch Embedding with support for Lumina-T2X
+
+ Args:
+ patch_size (`int`, defaults to `2`): The size of the patches.
+ in_channels (`int`, defaults to `4`): The number of input channels.
+ embed_dim (`int`, defaults to `768`): The output dimension of the embedding.
+ bias (`bool`, defaults to `True`): Whether or not to use bias.
+ """
+
+ def __init__(self, patch_size=2, in_channels=4, embed_dim=768, bias=True):
+ super().__init__()
+ self.patch_size = patch_size
+ self.proj = nn.Linear(
+ in_features=patch_size * patch_size * in_channels,
+ out_features=embed_dim,
+ bias=bias,
+ )
+
+ def forward(self, x, freqs_cis):
+ """
+ Patchifies and embeds the input tensor(s).
+
+ Args:
+ x (List[torch.Tensor] | torch.Tensor): The input tensor(s) to be patchified and embedded.
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor, List[Tuple[int, int]], torch.Tensor]: A tuple containing the patchified
+ and embedded tensor(s), the mask indicating the valid patches, the original image size(s), and the
+ frequency tensor(s).
+ """
+ freqs_cis = freqs_cis.to(x[0].device)
+ patch_height = patch_width = self.patch_size
+ batch_size, channel, height, width = x.size()
+ height_tokens, width_tokens = height // patch_height, width // patch_width
+
+ x = x.view(batch_size, channel, height_tokens, patch_height, width_tokens, patch_width).permute(
+ 0, 2, 4, 1, 3, 5
+ )
+ x = x.flatten(3)
+ x = self.proj(x)
+ x = x.flatten(1, 2)
+
+ mask = torch.ones(x.shape[0], x.shape[1], dtype=torch.int32, device=x.device)
+
+ return (
+ x,
+ mask,
+ [(height, width)] * batch_size,
+ freqs_cis[:height_tokens, :width_tokens].flatten(0, 1).unsqueeze(0),
+ )
+
+
+class CogVideoXPatchEmbed(nn.Module):
+ def __init__(
+ self,
+ patch_size: int = 2,
+ patch_size_t: Optional[int] = None,
+ in_channels: int = 16,
+ embed_dim: int = 1920,
+ text_embed_dim: int = 4096,
+ bias: bool = True,
+ sample_width: int = 90,
+ sample_height: int = 60,
+ sample_frames: int = 49,
+ temporal_compression_ratio: int = 4,
+ max_text_seq_length: int = 226,
+ spatial_interpolation_scale: float = 1.875,
+ temporal_interpolation_scale: float = 1.0,
+ use_positional_embeddings: bool = True,
+ use_learned_positional_embeddings: bool = True,
+ ) -> None:
+ super().__init__()
+
+ self.patch_size = patch_size
+ self.patch_size_t = patch_size_t
+ self.embed_dim = embed_dim
+ self.sample_height = sample_height
+ self.sample_width = sample_width
+ self.sample_frames = sample_frames
+ self.temporal_compression_ratio = temporal_compression_ratio
+ self.max_text_seq_length = max_text_seq_length
+ self.spatial_interpolation_scale = spatial_interpolation_scale
+ self.temporal_interpolation_scale = temporal_interpolation_scale
+ self.use_positional_embeddings = use_positional_embeddings
+ self.use_learned_positional_embeddings = use_learned_positional_embeddings
+
+ if patch_size_t is None:
+ # CogVideoX 1.0 checkpoints
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=bias
+ )
+ else:
+ # CogVideoX 1.5 checkpoints
+ self.proj = nn.Linear(in_channels * patch_size * patch_size * patch_size_t, embed_dim)
+
+ self.text_proj = nn.Linear(text_embed_dim, embed_dim)
+
+ if use_positional_embeddings or use_learned_positional_embeddings:
+ persistent = use_learned_positional_embeddings
+ pos_embedding = self._get_positional_embeddings(sample_height, sample_width, sample_frames)
+ self.register_buffer("pos_embedding", pos_embedding, persistent=persistent)
+
+ def _get_positional_embeddings(
+ self, sample_height: int, sample_width: int, sample_frames: int, device: Optional[torch.device] = None
+ ) -> torch.Tensor:
+ post_patch_height = sample_height // self.patch_size
+ post_patch_width = sample_width // self.patch_size
+ post_time_compression_frames = (sample_frames - 1) // self.temporal_compression_ratio + 1
+ num_patches = post_patch_height * post_patch_width * post_time_compression_frames
+
+ pos_embedding = get_3d_sincos_pos_embed(
+ self.embed_dim,
+ (post_patch_width, post_patch_height),
+ post_time_compression_frames,
+ self.spatial_interpolation_scale,
+ self.temporal_interpolation_scale,
+ device=device,
+ output_type="pt",
+ )
+ pos_embedding = pos_embedding.flatten(0, 1)
+ joint_pos_embedding = pos_embedding.new_zeros(
+ 1, self.max_text_seq_length + num_patches, self.embed_dim, requires_grad=False
+ )
+ joint_pos_embedding.data[:, self.max_text_seq_length :].copy_(pos_embedding)
+
+ return joint_pos_embedding
+
+ def forward(self, text_embeds: torch.Tensor, image_embeds: torch.Tensor):
+ r"""
+ Args:
+ text_embeds (`torch.Tensor`):
+ Input text embeddings. Expected shape: (batch_size, seq_length, embedding_dim).
+ image_embeds (`torch.Tensor`):
+ Input image embeddings. Expected shape: (batch_size, num_frames, channels, height, width).
+ """
+ text_embeds = self.text_proj(text_embeds)
+
+ batch_size, num_frames, channels, height, width = image_embeds.shape
+
+ if self.patch_size_t is None:
+ image_embeds = image_embeds.reshape(-1, channels, height, width)
+ image_embeds = self.proj(image_embeds)
+ image_embeds = image_embeds.view(batch_size, num_frames, *image_embeds.shape[1:])
+ image_embeds = image_embeds.flatten(3).transpose(2, 3) # [batch, num_frames, height x width, channels]
+ image_embeds = image_embeds.flatten(1, 2) # [batch, num_frames x height x width, channels]
+ else:
+ p = self.patch_size
+ p_t = self.patch_size_t
+
+ image_embeds = image_embeds.permute(0, 1, 3, 4, 2)
+ image_embeds = image_embeds.reshape(
+ batch_size, num_frames // p_t, p_t, height // p, p, width // p, p, channels
+ )
+ image_embeds = image_embeds.permute(0, 1, 3, 5, 7, 2, 4, 6).flatten(4, 7).flatten(1, 3)
+ image_embeds = self.proj(image_embeds)
+
+ embeds = torch.cat(
+ [text_embeds, image_embeds], dim=1
+ ).contiguous() # [batch, seq_length + num_frames x height x width, channels]
+
+ if self.use_positional_embeddings or self.use_learned_positional_embeddings:
+ if self.use_learned_positional_embeddings and (self.sample_width != width or self.sample_height != height):
+ raise ValueError(
+ "It is currently not possible to generate videos at a different resolution that the defaults. This should only be the case with 'THUDM/CogVideoX-5b-I2V'."
+ "If you think this is incorrect, please open an issue at https://github.com/huggingface/diffusers/issues."
+ )
+
+ pre_time_compression_frames = (num_frames - 1) * self.temporal_compression_ratio + 1
+
+ if (
+ self.sample_height != height
+ or self.sample_width != width
+ or self.sample_frames != pre_time_compression_frames
+ ):
+ pos_embedding = self._get_positional_embeddings(
+ height, width, pre_time_compression_frames, device=embeds.device
+ )
+ else:
+ pos_embedding = self.pos_embedding
+
+ pos_embedding = pos_embedding.to(dtype=embeds.dtype)
+ embeds = embeds + pos_embedding
+
+ return embeds
+
+
+class CogView3PlusPatchEmbed(nn.Module):
+ def __init__(
+ self,
+ in_channels: int = 16,
+ hidden_size: int = 2560,
+ patch_size: int = 2,
+ text_hidden_size: int = 4096,
+ pos_embed_max_size: int = 128,
+ ):
+ super().__init__()
+ self.in_channels = in_channels
+ self.hidden_size = hidden_size
+ self.patch_size = patch_size
+ self.text_hidden_size = text_hidden_size
+ self.pos_embed_max_size = pos_embed_max_size
+ # Linear projection for image patches
+ self.proj = nn.Linear(in_channels * patch_size**2, hidden_size)
+
+ # Linear projection for text embeddings
+ self.text_proj = nn.Linear(text_hidden_size, hidden_size)
+
+ pos_embed = get_2d_sincos_pos_embed(
+ hidden_size, pos_embed_max_size, base_size=pos_embed_max_size, output_type="pt"
+ )
+ pos_embed = pos_embed.reshape(pos_embed_max_size, pos_embed_max_size, hidden_size)
+ self.register_buffer("pos_embed", pos_embed.float(), persistent=False)
+
+ def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, channel, height, width = hidden_states.shape
+
+ if height % self.patch_size != 0 or width % self.patch_size != 0:
+ raise ValueError("Height and width must be divisible by patch size")
+
+ height = height // self.patch_size
+ width = width // self.patch_size
+ hidden_states = hidden_states.view(batch_size, channel, height, self.patch_size, width, self.patch_size)
+ hidden_states = hidden_states.permute(0, 2, 4, 1, 3, 5).contiguous()
+ hidden_states = hidden_states.view(batch_size, height * width, channel * self.patch_size * self.patch_size)
+
+ # Project the patches
+ hidden_states = self.proj(hidden_states)
+ encoder_hidden_states = self.text_proj(encoder_hidden_states)
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
+
+ # Calculate text_length
+ text_length = encoder_hidden_states.shape[1]
+
+ image_pos_embed = self.pos_embed[:height, :width].reshape(height * width, -1)
+ text_pos_embed = torch.zeros(
+ (text_length, self.hidden_size), dtype=image_pos_embed.dtype, device=image_pos_embed.device
+ )
+ pos_embed = torch.cat([text_pos_embed, image_pos_embed], dim=0)[None, ...]
+
+ return (hidden_states + pos_embed).to(hidden_states.dtype)
+
+
+def get_3d_rotary_pos_embed(
+ embed_dim,
+ crops_coords,
+ grid_size,
+ temporal_size,
+ theta: int = 10000,
+ use_real: bool = True,
+ grid_type: str = "linspace",
+ max_size: Optional[Tuple[int, int]] = None,
+ device: Optional[torch.device] = None,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ """
+ RoPE for video tokens with 3D structure.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size, corresponding to hidden_size_head.
+ crops_coords (`Tuple[int]`):
+ The top-left and bottom-right coordinates of the crop.
+ grid_size (`Tuple[int]`):
+ The grid size of the spatial positional embedding (height, width).
+ temporal_size (`int`):
+ The size of the temporal dimension.
+ theta (`float`):
+ Scaling factor for frequency computation.
+ grid_type (`str`):
+ Whether to use "linspace" or "slice" to compute grids.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `(temporal_size * grid_size[0] * grid_size[1], embed_dim/2)`.
+ """
+ if use_real is not True:
+ raise ValueError(" `use_real = False` is not currently supported for get_3d_rotary_pos_embed")
+
+ if grid_type == "linspace":
+ start, stop = crops_coords
+ grid_size_h, grid_size_w = grid_size
+ grid_h = torch.linspace(
+ start[0], stop[0] * (grid_size_h - 1) / grid_size_h, grid_size_h, device=device, dtype=torch.float32
+ )
+ grid_w = torch.linspace(
+ start[1], stop[1] * (grid_size_w - 1) / grid_size_w, grid_size_w, device=device, dtype=torch.float32
+ )
+ grid_t = torch.arange(temporal_size, device=device, dtype=torch.float32)
+ grid_t = torch.linspace(
+ 0, temporal_size * (temporal_size - 1) / temporal_size, temporal_size, device=device, dtype=torch.float32
+ )
+ elif grid_type == "slice":
+ max_h, max_w = max_size
+ grid_size_h, grid_size_w = grid_size
+ grid_h = torch.arange(max_h, device=device, dtype=torch.float32)
+ grid_w = torch.arange(max_w, device=device, dtype=torch.float32)
+ grid_t = torch.arange(temporal_size, device=device, dtype=torch.float32)
+ else:
+ raise ValueError("Invalid value passed for `grid_type`.")
+
+ # Compute dimensions for each axis
+ dim_t = embed_dim // 4
+ dim_h = embed_dim // 8 * 3
+ dim_w = embed_dim // 8 * 3
+
+ # Temporal frequencies
+ freqs_t = get_1d_rotary_pos_embed(dim_t, grid_t, theta=theta, use_real=True)
+ # Spatial frequencies for height and width
+ freqs_h = get_1d_rotary_pos_embed(dim_h, grid_h, theta=theta, use_real=True)
+ freqs_w = get_1d_rotary_pos_embed(dim_w, grid_w, theta=theta, use_real=True)
+
+ # BroadCast and concatenate temporal and spaial frequencie (height and width) into a 3d tensor
+ def combine_time_height_width(freqs_t, freqs_h, freqs_w):
+ freqs_t = freqs_t[:, None, None, :].expand(
+ -1, grid_size_h, grid_size_w, -1
+ ) # temporal_size, grid_size_h, grid_size_w, dim_t
+ freqs_h = freqs_h[None, :, None, :].expand(
+ temporal_size, -1, grid_size_w, -1
+ ) # temporal_size, grid_size_h, grid_size_2, dim_h
+ freqs_w = freqs_w[None, None, :, :].expand(
+ temporal_size, grid_size_h, -1, -1
+ ) # temporal_size, grid_size_h, grid_size_2, dim_w
+
+ freqs = torch.cat(
+ [freqs_t, freqs_h, freqs_w], dim=-1
+ ) # temporal_size, grid_size_h, grid_size_w, (dim_t + dim_h + dim_w)
+ freqs = freqs.view(
+ temporal_size * grid_size_h * grid_size_w, -1
+ ) # (temporal_size * grid_size_h * grid_size_w), (dim_t + dim_h + dim_w)
+ return freqs
+
+ t_cos, t_sin = freqs_t # both t_cos and t_sin has shape: temporal_size, dim_t
+ h_cos, h_sin = freqs_h # both h_cos and h_sin has shape: grid_size_h, dim_h
+ w_cos, w_sin = freqs_w # both w_cos and w_sin has shape: grid_size_w, dim_w
+
+ if grid_type == "slice":
+ t_cos, t_sin = t_cos[:temporal_size], t_sin[:temporal_size]
+ h_cos, h_sin = h_cos[:grid_size_h], h_sin[:grid_size_h]
+ w_cos, w_sin = w_cos[:grid_size_w], w_sin[:grid_size_w]
+
+ cos = combine_time_height_width(t_cos, h_cos, w_cos)
+ sin = combine_time_height_width(t_sin, h_sin, w_sin)
+ return cos, sin
+
+
+def get_3d_rotary_pos_embed_allegro(
+ embed_dim,
+ crops_coords,
+ grid_size,
+ temporal_size,
+ interpolation_scale: Tuple[float, float, float] = (1.0, 1.0, 1.0),
+ theta: int = 10000,
+ device: Optional[torch.device] = None,
+) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ # TODO(aryan): docs
+ start, stop = crops_coords
+ grid_size_h, grid_size_w = grid_size
+ interpolation_scale_t, interpolation_scale_h, interpolation_scale_w = interpolation_scale
+ grid_t = torch.linspace(
+ 0, temporal_size * (temporal_size - 1) / temporal_size, temporal_size, device=device, dtype=torch.float32
+ )
+ grid_h = torch.linspace(
+ start[0], stop[0] * (grid_size_h - 1) / grid_size_h, grid_size_h, device=device, dtype=torch.float32
+ )
+ grid_w = torch.linspace(
+ start[1], stop[1] * (grid_size_w - 1) / grid_size_w, grid_size_w, device=device, dtype=torch.float32
+ )
+
+ # Compute dimensions for each axis
+ dim_t = embed_dim // 3
+ dim_h = embed_dim // 3
+ dim_w = embed_dim // 3
+
+ # Temporal frequencies
+ freqs_t = get_1d_rotary_pos_embed(
+ dim_t, grid_t / interpolation_scale_t, theta=theta, use_real=True, repeat_interleave_real=False
+ )
+ # Spatial frequencies for height and width
+ freqs_h = get_1d_rotary_pos_embed(
+ dim_h, grid_h / interpolation_scale_h, theta=theta, use_real=True, repeat_interleave_real=False
+ )
+ freqs_w = get_1d_rotary_pos_embed(
+ dim_w, grid_w / interpolation_scale_w, theta=theta, use_real=True, repeat_interleave_real=False
+ )
+
+ return freqs_t, freqs_h, freqs_w, grid_t, grid_h, grid_w
+
+
+def get_2d_rotary_pos_embed(
+ embed_dim, crops_coords, grid_size, use_real=True, device: Optional[torch.device] = None, output_type: str = "np"
+):
+ """
+ RoPE for image tokens with 2d structure.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size
+ crops_coords (`Tuple[int]`)
+ The top-left and bottom-right coordinates of the crop.
+ grid_size (`Tuple[int]`):
+ The grid size of the positional embedding.
+ use_real (`bool`):
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+ device: (`torch.device`, **optional**):
+ The device used to create tensors.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+ """
+ if output_type == "np":
+ deprecation_message = (
+ "`get_2d_sincos_pos_embed` uses `torch` and supports `device`."
+ " `from_numpy` is no longer required."
+ " Pass `output_type='pt' to use the new version now."
+ )
+ deprecate("output_type=='np'", "0.33.0", deprecation_message, standard_warn=False)
+ return _get_2d_rotary_pos_embed_np(
+ embed_dim=embed_dim,
+ crops_coords=crops_coords,
+ grid_size=grid_size,
+ use_real=use_real,
+ )
+ start, stop = crops_coords
+ # scale end by (steps−1)/steps matches np.linspace(..., endpoint=False)
+ grid_h = torch.linspace(
+ start[0], stop[0] * (grid_size[0] - 1) / grid_size[0], grid_size[0], device=device, dtype=torch.float32
+ )
+ grid_w = torch.linspace(
+ start[1], stop[1] * (grid_size[1] - 1) / grid_size[1], grid_size[1], device=device, dtype=torch.float32
+ )
+ grid = torch.meshgrid(grid_w, grid_h, indexing="xy")
+ grid = torch.stack(grid, dim=0) # [2, W, H]
+
+ grid = grid.reshape([2, 1, *grid.shape[1:]])
+ pos_embed = get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real)
+ return pos_embed
+
+
+def _get_2d_rotary_pos_embed_np(embed_dim, crops_coords, grid_size, use_real=True):
+ """
+ RoPE for image tokens with 2d structure.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size
+ crops_coords (`Tuple[int]`)
+ The top-left and bottom-right coordinates of the crop.
+ grid_size (`Tuple[int]`):
+ The grid size of the positional embedding.
+ use_real (`bool`):
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+ """
+ start, stop = crops_coords
+ grid_h = np.linspace(start[0], stop[0], grid_size[0], endpoint=False, dtype=np.float32)
+ grid_w = np.linspace(start[1], stop[1], grid_size[1], endpoint=False, dtype=np.float32)
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0) # [2, W, H]
+
+ grid = grid.reshape([2, 1, *grid.shape[1:]])
+ pos_embed = get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=use_real)
+ return pos_embed
+
+
+def get_2d_rotary_pos_embed_from_grid(embed_dim, grid, use_real=False):
+ """
+ Get 2D RoPE from grid.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size, corresponding to hidden_size_head.
+ grid (`np.ndarray`):
+ The grid of the positional embedding.
+ use_real (`bool`):
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+ """
+ assert embed_dim % 4 == 0
+
+ # use half of dimensions to encode grid_h
+ emb_h = get_1d_rotary_pos_embed(
+ embed_dim // 2, grid[0].reshape(-1), use_real=use_real
+ ) # (H*W, D/2) if use_real else (H*W, D/4)
+ emb_w = get_1d_rotary_pos_embed(
+ embed_dim // 2, grid[1].reshape(-1), use_real=use_real
+ ) # (H*W, D/2) if use_real else (H*W, D/4)
+
+ if use_real:
+ cos = torch.cat([emb_h[0], emb_w[0]], dim=1) # (H*W, D)
+ sin = torch.cat([emb_h[1], emb_w[1]], dim=1) # (H*W, D)
+ return cos, sin
+ else:
+ emb = torch.cat([emb_h, emb_w], dim=1) # (H*W, D/2)
+ return emb
+
+
+def get_2d_rotary_pos_embed_lumina(embed_dim, len_h, len_w, linear_factor=1.0, ntk_factor=1.0):
+ """
+ Get 2D RoPE from grid.
+
+ Args:
+ embed_dim: (`int`):
+ The embedding dimension size, corresponding to hidden_size_head.
+ grid (`np.ndarray`):
+ The grid of the positional embedding.
+ linear_factor (`float`):
+ The linear factor of the positional embedding, which is used to scale the positional embedding in the linear
+ layer.
+ ntk_factor (`float`):
+ The ntk factor of the positional embedding, which is used to scale the positional embedding in the ntk layer.
+
+ Returns:
+ `torch.Tensor`: positional embedding with shape `( grid_size * grid_size, embed_dim/2)`.
+ """
+ assert embed_dim % 4 == 0
+
+ emb_h = get_1d_rotary_pos_embed(
+ embed_dim // 2, len_h, linear_factor=linear_factor, ntk_factor=ntk_factor
+ ) # (H, D/4)
+ emb_w = get_1d_rotary_pos_embed(
+ embed_dim // 2, len_w, linear_factor=linear_factor, ntk_factor=ntk_factor
+ ) # (W, D/4)
+ emb_h = emb_h.view(len_h, 1, embed_dim // 4, 1).repeat(1, len_w, 1, 1) # (H, W, D/4, 1)
+ emb_w = emb_w.view(1, len_w, embed_dim // 4, 1).repeat(len_h, 1, 1, 1) # (H, W, D/4, 1)
+
+ emb = torch.cat([emb_h, emb_w], dim=-1).flatten(2) # (H, W, D/2)
+ return emb
+
+
+def get_1d_rotary_pos_embed(
+ dim: int,
+ pos: Union[np.ndarray, int],
+ theta: float = 10000.0,
+ use_real=False,
+ linear_factor=1.0,
+ ntk_factor=1.0,
+ repeat_interleave_real=True,
+ freqs_dtype=torch.float32, # torch.float32, torch.float64 (flux)
+):
+ """
+ Precompute the frequency tensor for complex exponentials (cis) with given dimensions.
+
+ This function calculates a frequency tensor with complex exponentials using the given dimension 'dim' and the end
+ index 'end'. The 'theta' parameter scales the frequencies. The returned tensor contains complex values in complex64
+ data type.
+
+ Args:
+ dim (`int`): Dimension of the frequency tensor.
+ pos (`np.ndarray` or `int`): Position indices for the frequency tensor. [S] or scalar
+ theta (`float`, *optional*, defaults to 10000.0):
+ Scaling factor for frequency computation. Defaults to 10000.0.
+ use_real (`bool`, *optional*):
+ If True, return real part and imaginary part separately. Otherwise, return complex numbers.
+ linear_factor (`float`, *optional*, defaults to 1.0):
+ Scaling factor for the context extrapolation. Defaults to 1.0.
+ ntk_factor (`float`, *optional*, defaults to 1.0):
+ Scaling factor for the NTK-Aware RoPE. Defaults to 1.0.
+ repeat_interleave_real (`bool`, *optional*, defaults to `True`):
+ If `True` and `use_real`, real part and imaginary part are each interleaved with themselves to reach `dim`.
+ Otherwise, they are concateanted with themselves.
+ freqs_dtype (`torch.float32` or `torch.float64`, *optional*, defaults to `torch.float32`):
+ the dtype of the frequency tensor.
+ Returns:
+ `torch.Tensor`: Precomputed frequency tensor with complex exponentials. [S, D/2]
+ """
+ assert dim % 2 == 0
+
+ if isinstance(pos, int):
+ pos = torch.arange(pos)
+ if isinstance(pos, np.ndarray):
+ pos = torch.from_numpy(pos) # type: ignore # [S]
+
+ theta = theta * ntk_factor
+ freqs = (
+ 1.0
+ / (theta ** (torch.arange(0, dim, 2, dtype=freqs_dtype, device=pos.device)[: (dim // 2)] / dim))
+ / linear_factor
+ ) # [D/2]
+ freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
+ is_npu = freqs.device.type == "npu"
+ if is_npu:
+ freqs = freqs.float()
+ if use_real and repeat_interleave_real:
+ # flux, hunyuan-dit, cogvideox
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float() # [S, D]
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1, output_size=freqs.shape[1] * 2).float() # [S, D]
+ return freqs_cos, freqs_sin
+ elif use_real:
+ # stable audio, allegro
+ freqs_cos = torch.cat([freqs.cos(), freqs.cos()], dim=-1).float() # [S, D]
+ freqs_sin = torch.cat([freqs.sin(), freqs.sin()], dim=-1).float() # [S, D]
+ return freqs_cos, freqs_sin
+ else:
+ # lumina
+ freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64 # [S, D/2]
+ return freqs_cis
+
+
+def apply_rotary_emb(
+ x: torch.Tensor,
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]],
+ use_real: bool = True,
+ use_real_unbind_dim: int = -1,
+) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Apply rotary embeddings to input tensors using the given frequency tensor. This function applies rotary embeddings
+ to the given query or key 'x' tensors using the provided frequency tensor 'freqs_cis'. The input tensors are
+ reshaped as complex numbers, and the frequency tensor is reshaped for broadcasting compatibility. The resulting
+ tensors contain rotary embeddings and are returned as real tensors.
+
+ Args:
+ x (`torch.Tensor`):
+ Query or key tensor to apply rotary embeddings. [B, H, S, D] xk (torch.Tensor): Key tensor to apply
+ freqs_cis (`Tuple[torch.Tensor]`): Precomputed frequency tensor for complex exponentials. ([S, D], [S, D],)
+
+ Returns:
+ Tuple[torch.Tensor, torch.Tensor]: Tuple of modified query tensor and key tensor with rotary embeddings.
+ """
+ if use_real:
+ cos, sin = freqs_cis # [S, D]
+ cos = cos[None, None]
+ sin = sin[None, None]
+ cos, sin = cos.to(x.device), sin.to(x.device)
+
+ if use_real_unbind_dim == -1:
+ # Used for flux, cogvideox, hunyuan-dit
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
+ elif use_real_unbind_dim == -2:
+ # Used for Stable Audio, OmniGen and CogView4
+ x_real, x_imag = x.reshape(*x.shape[:-1], 2, -1).unbind(-2) # [B, S, H, D//2]
+ x_rotated = torch.cat([-x_imag, x_real], dim=-1)
+ else:
+ raise ValueError(f"`use_real_unbind_dim={use_real_unbind_dim}` but should be -1 or -2.")
+
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
+
+ return out
+ else:
+ # used for lumina
+ x_rotated = torch.view_as_complex(x.float().reshape(*x.shape[:-1], -1, 2))
+ freqs_cis = freqs_cis.unsqueeze(2)
+ x_out = torch.view_as_real(x_rotated * freqs_cis).flatten(3)
+
+ return x_out.type_as(x)
+
+
+def apply_rotary_emb_allegro(x: torch.Tensor, freqs_cis, positions):
+ # TODO(aryan): rewrite
+ def apply_1d_rope(tokens, pos, cos, sin):
+ cos = F.embedding(pos, cos)[:, None, :, :]
+ sin = F.embedding(pos, sin)[:, None, :, :]
+ x1, x2 = tokens[..., : tokens.shape[-1] // 2], tokens[..., tokens.shape[-1] // 2 :]
+ tokens_rotated = torch.cat((-x2, x1), dim=-1)
+ return (tokens.float() * cos + tokens_rotated.float() * sin).to(tokens.dtype)
+
+ (t_cos, t_sin), (h_cos, h_sin), (w_cos, w_sin) = freqs_cis
+ t, h, w = x.chunk(3, dim=-1)
+ t = apply_1d_rope(t, positions[0], t_cos, t_sin)
+ h = apply_1d_rope(h, positions[1], h_cos, h_sin)
+ w = apply_1d_rope(w, positions[2], w_cos, w_sin)
+ x = torch.cat([t, h, w], dim=-1)
+ return x
+
+
+class FluxPosEmbed(nn.Module):
+ # modified from https://github.com/black-forest-labs/flux/blob/c00d7c60b085fce8058b9df845e036090873f2ce/src/flux/modules/layers.py#L11
+ def __init__(self, theta: int, axes_dim: List[int]):
+ super().__init__()
+ self.theta = theta
+ self.axes_dim = axes_dim
+
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
+ n_axes = ids.shape[-1]
+ cos_out = []
+ sin_out = []
+ pos = ids.float()
+ is_mps = ids.device.type == "mps"
+ is_npu = ids.device.type == "npu"
+ freqs_dtype = torch.float32 if (is_mps or is_npu) else torch.float64
+ for i in range(n_axes):
+ cos, sin = get_1d_rotary_pos_embed(
+ self.axes_dim[i],
+ pos[:, i],
+ theta=self.theta,
+ repeat_interleave_real=True,
+ use_real=True,
+ freqs_dtype=freqs_dtype,
+ )
+ cos_out.append(cos)
+ sin_out.append(sin)
+ freqs_cos = torch.cat(cos_out, dim=-1).to(ids.device)
+ freqs_sin = torch.cat(sin_out, dim=-1).to(ids.device)
+ return freqs_cos, freqs_sin
+
+
+class TimestepEmbedding(nn.Module):
+ def __init__(
+ self,
+ in_channels: int,
+ time_embed_dim: int,
+ act_fn: str = "silu",
+ out_dim: int = None,
+ post_act_fn: Optional[str] = None,
+ cond_proj_dim=None,
+ sample_proj_bias=True,
+ ):
+ super().__init__()
+
+ self.linear_1 = nn.Linear(in_channels, time_embed_dim, sample_proj_bias)
+
+ if cond_proj_dim is not None:
+ self.cond_proj = nn.Linear(cond_proj_dim, in_channels, bias=False)
+ else:
+ self.cond_proj = None
+
+ self.act = get_activation(act_fn)
+
+ if out_dim is not None:
+ time_embed_dim_out = out_dim
+ else:
+ time_embed_dim_out = time_embed_dim
+ self.linear_2 = nn.Linear(time_embed_dim, time_embed_dim_out, sample_proj_bias)
+
+ if post_act_fn is None:
+ self.post_act = None
+ else:
+ self.post_act = get_activation(post_act_fn)
+
+ def forward(self, sample, condition=None):
+ if condition is not None:
+ sample = sample + self.cond_proj(condition)
+ sample = self.linear_1(sample)
+
+ if self.act is not None:
+ sample = self.act(sample)
+
+ sample = self.linear_2(sample)
+
+ if self.post_act is not None:
+ sample = self.post_act(sample)
+ return sample
+
+
+class Timesteps(nn.Module):
+ def __init__(self, num_channels: int, flip_sin_to_cos: bool, downscale_freq_shift: float, scale: int = 1):
+ super().__init__()
+ self.num_channels = num_channels
+ self.flip_sin_to_cos = flip_sin_to_cos
+ self.downscale_freq_shift = downscale_freq_shift
+ self.scale = scale
+
+ def forward(self, timesteps):
+ t_emb = get_timestep_embedding(
+ timesteps,
+ self.num_channels,
+ flip_sin_to_cos=self.flip_sin_to_cos,
+ downscale_freq_shift=self.downscale_freq_shift,
+ scale=self.scale,
+ )
+ return t_emb
+
+
+class GaussianFourierProjection(nn.Module):
+ """Gaussian Fourier embeddings for noise levels."""
+
+ def __init__(
+ self, embedding_size: int = 256, scale: float = 1.0, set_W_to_weight=True, log=True, flip_sin_to_cos=False
+ ):
+ super().__init__()
+ self.weight = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
+ self.log = log
+ self.flip_sin_to_cos = flip_sin_to_cos
+
+ if set_W_to_weight:
+ # to delete later
+ del self.weight
+ self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
+ self.weight = self.W
+ del self.W
+
+ def forward(self, x):
+ if self.log:
+ x = torch.log(x)
+
+ x_proj = x[:, None] * self.weight[None, :] * 2 * np.pi
+
+ if self.flip_sin_to_cos:
+ out = torch.cat([torch.cos(x_proj), torch.sin(x_proj)], dim=-1)
+ else:
+ out = torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
+ return out
+
+
+class SinusoidalPositionalEmbedding(nn.Module):
+ """Apply positional information to a sequence of embeddings.
+
+ Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to
+ them
+
+ Args:
+ embed_dim: (int): Dimension of the positional embedding.
+ max_seq_length: Maximum sequence length to apply positional embeddings
+
+ """
+
+ def __init__(self, embed_dim: int, max_seq_length: int = 32):
+ super().__init__()
+ position = torch.arange(max_seq_length).unsqueeze(1)
+ div_term = torch.exp(torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim))
+ pe = torch.zeros(1, max_seq_length, embed_dim)
+ pe[0, :, 0::2] = torch.sin(position * div_term)
+ pe[0, :, 1::2] = torch.cos(position * div_term)
+ self.register_buffer("pe", pe)
+
+ def forward(self, x):
+ _, seq_length, _ = x.shape
+ x = x + self.pe[:, :seq_length]
+ return x
+
+
+class ImagePositionalEmbeddings(nn.Module):
+ """
+ Converts latent image classes into vector embeddings. Sums the vector embeddings with positional embeddings for the
+ height and width of the latent space.
+
+ For more details, see figure 10 of the dall-e paper: https://arxiv.org/abs/2102.12092
+
+ For VQ-diffusion:
+
+ Output vector embeddings are used as input for the transformer.
+
+ Note that the vector embeddings for the transformer are different than the vector embeddings from the VQVAE.
+
+ Args:
+ num_embed (`int`):
+ Number of embeddings for the latent pixels embeddings.
+ height (`int`):
+ Height of the latent image i.e. the number of height embeddings.
+ width (`int`):
+ Width of the latent image i.e. the number of width embeddings.
+ embed_dim (`int`):
+ Dimension of the produced vector embeddings. Used for the latent pixel, height, and width embeddings.
+ """
+
+ def __init__(
+ self,
+ num_embed: int,
+ height: int,
+ width: int,
+ embed_dim: int,
+ ):
+ super().__init__()
+
+ self.height = height
+ self.width = width
+ self.num_embed = num_embed
+ self.embed_dim = embed_dim
+
+ self.emb = nn.Embedding(self.num_embed, embed_dim)
+ self.height_emb = nn.Embedding(self.height, embed_dim)
+ self.width_emb = nn.Embedding(self.width, embed_dim)
+
+ def forward(self, index):
+ emb = self.emb(index)
+
+ height_emb = self.height_emb(torch.arange(self.height, device=index.device).view(1, self.height))
+
+ # 1 x H x D -> 1 x H x 1 x D
+ height_emb = height_emb.unsqueeze(2)
+
+ width_emb = self.width_emb(torch.arange(self.width, device=index.device).view(1, self.width))
+
+ # 1 x W x D -> 1 x 1 x W x D
+ width_emb = width_emb.unsqueeze(1)
+
+ pos_emb = height_emb + width_emb
+
+ # 1 x H x W x D -> 1 x L xD
+ pos_emb = pos_emb.view(1, self.height * self.width, -1)
+
+ emb = emb + pos_emb[:, : emb.shape[1], :]
+
+ return emb
+
+
+class LabelEmbedding(nn.Module):
+ """
+ Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.
+
+ Args:
+ num_classes (`int`): The number of classes.
+ hidden_size (`int`): The size of the vector embeddings.
+ dropout_prob (`float`): The probability of dropping a label.
+ """
+
+ def __init__(self, num_classes, hidden_size, dropout_prob):
+ super().__init__()
+ use_cfg_embedding = dropout_prob > 0
+ self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)
+ self.num_classes = num_classes
+ self.dropout_prob = dropout_prob
+
+ def token_drop(self, labels, force_drop_ids=None):
+ """
+ Drops labels to enable classifier-free guidance.
+ """
+ if force_drop_ids is None:
+ drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob
+ else:
+ drop_ids = torch.tensor(force_drop_ids == 1)
+ labels = torch.where(drop_ids, self.num_classes, labels)
+ return labels
+
+ def forward(self, labels: torch.LongTensor, force_drop_ids=None):
+ use_dropout = self.dropout_prob > 0
+ if (self.training and use_dropout) or (force_drop_ids is not None):
+ labels = self.token_drop(labels, force_drop_ids)
+ embeddings = self.embedding_table(labels)
+ return embeddings
+
+
+class TextImageProjection(nn.Module):
+ def __init__(
+ self,
+ text_embed_dim: int = 1024,
+ image_embed_dim: int = 768,
+ cross_attention_dim: int = 768,
+ num_image_text_embeds: int = 10,
+ ):
+ super().__init__()
+
+ self.num_image_text_embeds = num_image_text_embeds
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
+ self.text_proj = nn.Linear(text_embed_dim, cross_attention_dim)
+
+ def forward(self, text_embeds: torch.Tensor, image_embeds: torch.Tensor):
+ batch_size = text_embeds.shape[0]
+
+ # image
+ image_text_embeds = self.image_embeds(image_embeds)
+ image_text_embeds = image_text_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
+
+ # text
+ text_embeds = self.text_proj(text_embeds)
+
+ return torch.cat([image_text_embeds, text_embeds], dim=1)
+
+
+class ImageProjection(nn.Module):
+ def __init__(
+ self,
+ image_embed_dim: int = 768,
+ cross_attention_dim: int = 768,
+ num_image_text_embeds: int = 32,
+ ):
+ super().__init__()
+
+ self.num_image_text_embeds = num_image_text_embeds
+ self.image_embeds = nn.Linear(image_embed_dim, self.num_image_text_embeds * cross_attention_dim)
+ self.norm = nn.LayerNorm(cross_attention_dim)
+
+ def forward(self, image_embeds: torch.Tensor):
+ batch_size = image_embeds.shape[0]
+
+ # image
+ image_embeds = self.image_embeds(image_embeds.to(self.image_embeds.weight.dtype))
+ image_embeds = image_embeds.reshape(batch_size, self.num_image_text_embeds, -1)
+ image_embeds = self.norm(image_embeds)
+ return image_embeds
+
+
+class IPAdapterFullImageProjection(nn.Module):
+ def __init__(self, image_embed_dim=1024, cross_attention_dim=1024):
+ super().__init__()
+ from .attention import FeedForward
+
+ self.ff = FeedForward(image_embed_dim, cross_attention_dim, mult=1, activation_fn="gelu")
+ self.norm = nn.LayerNorm(cross_attention_dim)
+
+ def forward(self, image_embeds: torch.Tensor):
+ return self.norm(self.ff(image_embeds))
+
+
+class IPAdapterFaceIDImageProjection(nn.Module):
+ def __init__(self, image_embed_dim=1024, cross_attention_dim=1024, mult=1, num_tokens=1):
+ super().__init__()
+ from .attention import FeedForward
+
+ self.num_tokens = num_tokens
+ self.cross_attention_dim = cross_attention_dim
+ self.ff = FeedForward(image_embed_dim, cross_attention_dim * num_tokens, mult=mult, activation_fn="gelu")
+ self.norm = nn.LayerNorm(cross_attention_dim)
+
+ def forward(self, image_embeds: torch.Tensor):
+ x = self.ff(image_embeds)
+ x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
+ return self.norm(x)
+
+
+class CombinedTimestepLabelEmbeddings(nn.Module):
+ def __init__(self, num_classes, embedding_dim, class_dropout_prob=0.1):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=1)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.class_embedder = LabelEmbedding(num_classes, embedding_dim, class_dropout_prob)
+
+ def forward(self, timestep, class_labels, hidden_dtype=None):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
+
+ class_labels = self.class_embedder(class_labels) # (N, D)
+
+ conditioning = timesteps_emb + class_labels # (N, D)
+
+ return conditioning
+
+
+class CombinedTimestepTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ pooled_projections = self.text_embedder(pooled_projection)
+
+ conditioning = timesteps_emb + pooled_projections
+
+ return conditioning
+
+
+class CombinedTimestepGuidanceTextProjEmbeddings(nn.Module):
+ def __init__(self, embedding_dim, pooled_projection_dim):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(self, timestep, guidance, pooled_projection):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ guidance_proj = self.time_proj(guidance)
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype)) # (N, D)
+
+ time_guidance_emb = timesteps_emb + guidance_emb
+
+ pooled_projections = self.text_embedder(pooled_projection)
+ conditioning = time_guidance_emb + pooled_projections
+
+ return conditioning
+
+
+class CogView3CombinedTimestepSizeEmbeddings(nn.Module):
+ def __init__(self, embedding_dim: int, condition_dim: int, pooled_projection_dim: int, timesteps_dim: int = 256):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=timesteps_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.condition_proj = Timesteps(num_channels=condition_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=timesteps_dim, time_embed_dim=embedding_dim)
+ self.condition_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ original_size: torch.Tensor,
+ target_size: torch.Tensor,
+ crop_coords: torch.Tensor,
+ hidden_dtype: torch.dtype,
+ ) -> torch.Tensor:
+ timesteps_proj = self.time_proj(timestep)
+
+ original_size_proj = self.condition_proj(original_size.flatten()).view(original_size.size(0), -1)
+ crop_coords_proj = self.condition_proj(crop_coords.flatten()).view(crop_coords.size(0), -1)
+ target_size_proj = self.condition_proj(target_size.flatten()).view(target_size.size(0), -1)
+
+ # (B, 3 * condition_dim)
+ condition_proj = torch.cat([original_size_proj, crop_coords_proj, target_size_proj], dim=1)
+
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (B, embedding_dim)
+ condition_emb = self.condition_embedder(condition_proj.to(dtype=hidden_dtype)) # (B, embedding_dim)
+
+ conditioning = timesteps_emb + condition_emb
+ return conditioning
+
+
+class HunyuanDiTAttentionPool(nn.Module):
+ # Copied from https://github.com/Tencent/HunyuanDiT/blob/cb709308d92e6c7e8d59d0dff41b74d35088db6a/hydit/modules/poolers.py#L6
+
+ def __init__(self, spacial_dim: int, embed_dim: int, num_heads: int, output_dim: int = None):
+ super().__init__()
+ self.positional_embedding = nn.Parameter(torch.randn(spacial_dim + 1, embed_dim) / embed_dim**0.5)
+ self.k_proj = nn.Linear(embed_dim, embed_dim)
+ self.q_proj = nn.Linear(embed_dim, embed_dim)
+ self.v_proj = nn.Linear(embed_dim, embed_dim)
+ self.c_proj = nn.Linear(embed_dim, output_dim or embed_dim)
+ self.num_heads = num_heads
+
+ def forward(self, x):
+ x = x.permute(1, 0, 2) # NLC -> LNC
+ x = torch.cat([x.mean(dim=0, keepdim=True), x], dim=0) # (L+1)NC
+ x = x + self.positional_embedding[:, None, :].to(x.dtype) # (L+1)NC
+ x, _ = F.multi_head_attention_forward(
+ query=x[:1],
+ key=x,
+ value=x,
+ embed_dim_to_check=x.shape[-1],
+ num_heads=self.num_heads,
+ q_proj_weight=self.q_proj.weight,
+ k_proj_weight=self.k_proj.weight,
+ v_proj_weight=self.v_proj.weight,
+ in_proj_weight=None,
+ in_proj_bias=torch.cat([self.q_proj.bias, self.k_proj.bias, self.v_proj.bias]),
+ bias_k=None,
+ bias_v=None,
+ add_zero_attn=False,
+ dropout_p=0,
+ out_proj_weight=self.c_proj.weight,
+ out_proj_bias=self.c_proj.bias,
+ use_separate_proj_weight=True,
+ training=self.training,
+ need_weights=False,
+ )
+ return x.squeeze(0)
+
+
+class HunyuanCombinedTimestepTextSizeStyleEmbedding(nn.Module):
+ def __init__(
+ self,
+ embedding_dim,
+ pooled_projection_dim=1024,
+ seq_len=256,
+ cross_attention_dim=2048,
+ use_style_cond_and_image_meta_size=True,
+ ):
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+
+ self.size_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+
+ self.pooler = HunyuanDiTAttentionPool(
+ seq_len, cross_attention_dim, num_heads=8, output_dim=pooled_projection_dim
+ )
+
+ # Here we use a default learned embedder layer for future extension.
+ self.use_style_cond_and_image_meta_size = use_style_cond_and_image_meta_size
+ if use_style_cond_and_image_meta_size:
+ self.style_embedder = nn.Embedding(1, embedding_dim)
+ extra_in_dim = 256 * 6 + embedding_dim + pooled_projection_dim
+ else:
+ extra_in_dim = pooled_projection_dim
+
+ self.extra_embedder = PixArtAlphaTextProjection(
+ in_features=extra_in_dim,
+ hidden_size=embedding_dim * 4,
+ out_features=embedding_dim,
+ act_fn="silu_fp32",
+ )
+
+ def forward(self, timestep, encoder_hidden_states, image_meta_size, style, hidden_dtype=None):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, 256)
+
+ # extra condition1: text
+ pooled_projections = self.pooler(encoder_hidden_states) # (N, 1024)
+
+ if self.use_style_cond_and_image_meta_size:
+ # extra condition2: image meta size embedding
+ image_meta_size = self.size_proj(image_meta_size.view(-1))
+ image_meta_size = image_meta_size.to(dtype=hidden_dtype)
+ image_meta_size = image_meta_size.view(-1, 6 * 256) # (N, 1536)
+
+ # extra condition3: style embedding
+ style_embedding = self.style_embedder(style) # (N, embedding_dim)
+
+ # Concatenate all extra vectors
+ extra_cond = torch.cat([pooled_projections, image_meta_size, style_embedding], dim=1)
+ else:
+ extra_cond = torch.cat([pooled_projections], dim=1)
+
+ conditioning = timesteps_emb + self.extra_embedder(extra_cond) # [B, D]
+
+ return conditioning
+
+
+class LuminaCombinedTimestepCaptionEmbedding(nn.Module):
+ def __init__(self, hidden_size=4096, cross_attention_dim=2048, frequency_embedding_size=256):
+ super().__init__()
+ self.time_proj = Timesteps(
+ num_channels=frequency_embedding_size, flip_sin_to_cos=True, downscale_freq_shift=0.0
+ )
+
+ self.timestep_embedder = TimestepEmbedding(in_channels=frequency_embedding_size, time_embed_dim=hidden_size)
+
+ self.caption_embedder = nn.Sequential(
+ nn.LayerNorm(cross_attention_dim),
+ nn.Linear(
+ cross_attention_dim,
+ hidden_size,
+ bias=True,
+ ),
+ )
+
+ def forward(self, timestep, caption_feat, caption_mask):
+ # timestep embedding:
+ time_freq = self.time_proj(timestep)
+ time_embed = self.timestep_embedder(time_freq.to(dtype=caption_feat.dtype))
+
+ # caption condition embedding:
+ caption_mask_float = caption_mask.float().unsqueeze(-1)
+ caption_feats_pool = (caption_feat * caption_mask_float).sum(dim=1) / caption_mask_float.sum(dim=1)
+ caption_feats_pool = caption_feats_pool.to(caption_feat)
+ caption_embed = self.caption_embedder(caption_feats_pool)
+
+ conditioning = time_embed + caption_embed
+
+ return conditioning
+
+
+class MochiCombinedTimestepCaptionEmbedding(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ pooled_projection_dim: int,
+ text_embed_dim: int,
+ time_embed_dim: int = 256,
+ num_attention_heads: int = 8,
+ ) -> None:
+ super().__init__()
+
+ self.time_proj = Timesteps(num_channels=time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0.0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=time_embed_dim, time_embed_dim=embedding_dim)
+ self.pooler = MochiAttentionPool(
+ num_attention_heads=num_attention_heads, embed_dim=text_embed_dim, output_dim=embedding_dim
+ )
+ self.caption_proj = nn.Linear(text_embed_dim, pooled_projection_dim)
+
+ def forward(
+ self,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_attention_mask: torch.Tensor,
+ hidden_dtype: Optional[torch.dtype] = None,
+ ):
+ time_proj = self.time_proj(timestep)
+ time_emb = self.timestep_embedder(time_proj.to(dtype=hidden_dtype))
+
+ pooled_projections = self.pooler(encoder_hidden_states, encoder_attention_mask)
+ caption_proj = self.caption_proj(encoder_hidden_states)
+
+ conditioning = time_emb + pooled_projections
+ return conditioning, caption_proj
+
+
+class TextTimeEmbedding(nn.Module):
+ def __init__(self, encoder_dim: int, time_embed_dim: int, num_heads: int = 64):
+ super().__init__()
+ self.norm1 = nn.LayerNorm(encoder_dim)
+ self.pool = AttentionPooling(num_heads, encoder_dim)
+ self.proj = nn.Linear(encoder_dim, time_embed_dim)
+ self.norm2 = nn.LayerNorm(time_embed_dim)
+
+ def forward(self, hidden_states):
+ hidden_states = self.norm1(hidden_states)
+ hidden_states = self.pool(hidden_states)
+ hidden_states = self.proj(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class TextImageTimeEmbedding(nn.Module):
+ def __init__(self, text_embed_dim: int = 768, image_embed_dim: int = 768, time_embed_dim: int = 1536):
+ super().__init__()
+ self.text_proj = nn.Linear(text_embed_dim, time_embed_dim)
+ self.text_norm = nn.LayerNorm(time_embed_dim)
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
+
+ def forward(self, text_embeds: torch.Tensor, image_embeds: torch.Tensor):
+ # text
+ time_text_embeds = self.text_proj(text_embeds)
+ time_text_embeds = self.text_norm(time_text_embeds)
+
+ # image
+ time_image_embeds = self.image_proj(image_embeds)
+
+ return time_image_embeds + time_text_embeds
+
+
+class ImageTimeEmbedding(nn.Module):
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
+ super().__init__()
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
+ self.image_norm = nn.LayerNorm(time_embed_dim)
+
+ def forward(self, image_embeds: torch.Tensor):
+ # image
+ time_image_embeds = self.image_proj(image_embeds)
+ time_image_embeds = self.image_norm(time_image_embeds)
+ return time_image_embeds
+
+
+class ImageHintTimeEmbedding(nn.Module):
+ def __init__(self, image_embed_dim: int = 768, time_embed_dim: int = 1536):
+ super().__init__()
+ self.image_proj = nn.Linear(image_embed_dim, time_embed_dim)
+ self.image_norm = nn.LayerNorm(time_embed_dim)
+ self.input_hint_block = nn.Sequential(
+ nn.Conv2d(3, 16, 3, padding=1),
+ nn.SiLU(),
+ nn.Conv2d(16, 16, 3, padding=1),
+ nn.SiLU(),
+ nn.Conv2d(16, 32, 3, padding=1, stride=2),
+ nn.SiLU(),
+ nn.Conv2d(32, 32, 3, padding=1),
+ nn.SiLU(),
+ nn.Conv2d(32, 96, 3, padding=1, stride=2),
+ nn.SiLU(),
+ nn.Conv2d(96, 96, 3, padding=1),
+ nn.SiLU(),
+ nn.Conv2d(96, 256, 3, padding=1, stride=2),
+ nn.SiLU(),
+ nn.Conv2d(256, 4, 3, padding=1),
+ )
+
+ def forward(self, image_embeds: torch.Tensor, hint: torch.Tensor):
+ # image
+ time_image_embeds = self.image_proj(image_embeds)
+ time_image_embeds = self.image_norm(time_image_embeds)
+ hint = self.input_hint_block(hint)
+ return time_image_embeds, hint
+
+
+class AttentionPooling(nn.Module):
+ # Copied from https://github.com/deep-floyd/IF/blob/2f91391f27dd3c468bf174be5805b4cc92980c0b/deepfloyd_if/model/nn.py#L54
+
+ def __init__(self, num_heads, embed_dim, dtype=None):
+ super().__init__()
+ self.dtype = dtype
+ self.positional_embedding = nn.Parameter(torch.randn(1, embed_dim) / embed_dim**0.5)
+ self.k_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
+ self.q_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
+ self.v_proj = nn.Linear(embed_dim, embed_dim, dtype=self.dtype)
+ self.num_heads = num_heads
+ self.dim_per_head = embed_dim // self.num_heads
+
+ def forward(self, x):
+ bs, length, width = x.size()
+
+ def shape(x):
+ # (bs, length, width) --> (bs, length, n_heads, dim_per_head)
+ x = x.view(bs, -1, self.num_heads, self.dim_per_head)
+ # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
+ x = x.transpose(1, 2)
+ # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
+ x = x.reshape(bs * self.num_heads, -1, self.dim_per_head)
+ # (bs*n_heads, length, dim_per_head) --> (bs*n_heads, dim_per_head, length)
+ x = x.transpose(1, 2)
+ return x
+
+ class_token = x.mean(dim=1, keepdim=True) + self.positional_embedding.to(x.dtype)
+ x = torch.cat([class_token, x], dim=1) # (bs, length+1, width)
+
+ # (bs*n_heads, class_token_length, dim_per_head)
+ q = shape(self.q_proj(class_token))
+ # (bs*n_heads, length+class_token_length, dim_per_head)
+ k = shape(self.k_proj(x))
+ v = shape(self.v_proj(x))
+
+ # (bs*n_heads, class_token_length, length+class_token_length):
+ scale = 1 / math.sqrt(math.sqrt(self.dim_per_head))
+ weight = torch.einsum("bct,bcs->bts", q * scale, k * scale) # More stable with f16 than dividing afterwards
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
+
+ # (bs*n_heads, dim_per_head, class_token_length)
+ a = torch.einsum("bts,bcs->bct", weight, v)
+
+ # (bs, length+1, width)
+ a = a.reshape(bs, -1, 1).transpose(1, 2)
+
+ return a[:, 0, :] # cls_token
+
+
+class MochiAttentionPool(nn.Module):
+ def __init__(
+ self,
+ num_attention_heads: int,
+ embed_dim: int,
+ output_dim: Optional[int] = None,
+ ) -> None:
+ super().__init__()
+
+ self.output_dim = output_dim or embed_dim
+ self.num_attention_heads = num_attention_heads
+
+ self.to_kv = nn.Linear(embed_dim, 2 * embed_dim)
+ self.to_q = nn.Linear(embed_dim, embed_dim)
+ self.to_out = nn.Linear(embed_dim, self.output_dim)
+
+ @staticmethod
+ def pool_tokens(x: torch.Tensor, mask: torch.Tensor, *, keepdim=False) -> torch.Tensor:
+ """
+ Pool tokens in x using mask.
+
+ NOTE: We assume x does not require gradients.
+
+ Args:
+ x: (B, L, D) tensor of tokens.
+ mask: (B, L) boolean tensor indicating which tokens are not padding.
+
+ Returns:
+ pooled: (B, D) tensor of pooled tokens.
+ """
+ assert x.size(1) == mask.size(1) # Expected mask to have same length as tokens.
+ assert x.size(0) == mask.size(0) # Expected mask to have same batch size as tokens.
+ mask = mask[:, :, None].to(dtype=x.dtype)
+ mask = mask / mask.sum(dim=1, keepdim=True).clamp(min=1)
+ pooled = (x * mask).sum(dim=1, keepdim=keepdim)
+ return pooled
+
+ def forward(self, x: torch.Tensor, mask: torch.BoolTensor) -> torch.Tensor:
+ r"""
+ Args:
+ x (`torch.Tensor`):
+ Tensor of shape `(B, S, D)` of input tokens.
+ mask (`torch.Tensor`):
+ Boolean ensor of shape `(B, S)` indicating which tokens are not padding.
+
+ Returns:
+ `torch.Tensor`:
+ `(B, D)` tensor of pooled tokens.
+ """
+ D = x.size(2)
+
+ # Construct attention mask, shape: (B, 1, num_queries=1, num_keys=1+L).
+ attn_mask = mask[:, None, None, :].bool() # (B, 1, 1, L).
+ attn_mask = F.pad(attn_mask, (1, 0), value=True) # (B, 1, 1, 1+L).
+
+ # Average non-padding token features. These will be used as the query.
+ x_pool = self.pool_tokens(x, mask, keepdim=True) # (B, 1, D)
+
+ # Concat pooled features to input sequence.
+ x = torch.cat([x_pool, x], dim=1) # (B, L+1, D)
+
+ # Compute queries, keys, values. Only the mean token is used to create a query.
+ kv = self.to_kv(x) # (B, L+1, 2 * D)
+ q = self.to_q(x[:, 0]) # (B, D)
+
+ # Extract heads.
+ head_dim = D // self.num_attention_heads
+ kv = kv.unflatten(2, (2, self.num_attention_heads, head_dim)) # (B, 1+L, 2, H, head_dim)
+ kv = kv.transpose(1, 3) # (B, H, 2, 1+L, head_dim)
+ k, v = kv.unbind(2) # (B, H, 1+L, head_dim)
+ q = q.unflatten(1, (self.num_attention_heads, head_dim)) # (B, H, head_dim)
+ q = q.unsqueeze(2) # (B, H, 1, head_dim)
+
+ # Compute attention.
+ x = F.scaled_dot_product_attention(q, k, v, attn_mask=attn_mask, dropout_p=0.0) # (B, H, 1, head_dim)
+
+ # Concatenate heads and run output.
+ x = x.squeeze(2).flatten(1, 2) # (B, D = H * head_dim)
+ x = self.to_out(x)
+ return x
+
+
+def get_fourier_embeds_from_boundingbox(embed_dim, box):
+ """
+ Args:
+ embed_dim: int
+ box: a 3-D tensor [B x N x 4] representing the bounding boxes for GLIGEN pipeline
+ Returns:
+ [B x N x embed_dim] tensor of positional embeddings
+ """
+
+ batch_size, num_boxes = box.shape[:2]
+
+ emb = 100 ** (torch.arange(embed_dim) / embed_dim)
+ emb = emb[None, None, None].to(device=box.device, dtype=box.dtype)
+ emb = emb * box.unsqueeze(-1)
+
+ emb = torch.stack((emb.sin(), emb.cos()), dim=-1)
+ emb = emb.permute(0, 1, 3, 4, 2).reshape(batch_size, num_boxes, embed_dim * 2 * 4)
+
+ return emb
+
+
+class GLIGENTextBoundingboxProjection(nn.Module):
+ def __init__(self, positive_len, out_dim, feature_type="text-only", fourier_freqs=8):
+ super().__init__()
+ self.positive_len = positive_len
+ self.out_dim = out_dim
+
+ self.fourier_embedder_dim = fourier_freqs
+ self.position_dim = fourier_freqs * 2 * 4 # 2: sin/cos, 4: xyxy
+
+ if isinstance(out_dim, tuple):
+ out_dim = out_dim[0]
+
+ if feature_type == "text-only":
+ self.linears = nn.Sequential(
+ nn.Linear(self.positive_len + self.position_dim, 512),
+ nn.SiLU(),
+ nn.Linear(512, 512),
+ nn.SiLU(),
+ nn.Linear(512, out_dim),
+ )
+ self.null_positive_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
+
+ elif feature_type == "text-image":
+ self.linears_text = nn.Sequential(
+ nn.Linear(self.positive_len + self.position_dim, 512),
+ nn.SiLU(),
+ nn.Linear(512, 512),
+ nn.SiLU(),
+ nn.Linear(512, out_dim),
+ )
+ self.linears_image = nn.Sequential(
+ nn.Linear(self.positive_len + self.position_dim, 512),
+ nn.SiLU(),
+ nn.Linear(512, 512),
+ nn.SiLU(),
+ nn.Linear(512, out_dim),
+ )
+ self.null_text_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
+ self.null_image_feature = torch.nn.Parameter(torch.zeros([self.positive_len]))
+
+ self.null_position_feature = torch.nn.Parameter(torch.zeros([self.position_dim]))
+
+ def forward(
+ self,
+ boxes,
+ masks,
+ positive_embeddings=None,
+ phrases_masks=None,
+ image_masks=None,
+ phrases_embeddings=None,
+ image_embeddings=None,
+ ):
+ masks = masks.unsqueeze(-1)
+
+ # embedding position (it may includes padding as placeholder)
+ xyxy_embedding = get_fourier_embeds_from_boundingbox(self.fourier_embedder_dim, boxes) # B*N*4 -> B*N*C
+
+ # learnable null embedding
+ xyxy_null = self.null_position_feature.view(1, 1, -1)
+
+ # replace padding with learnable null embedding
+ xyxy_embedding = xyxy_embedding * masks + (1 - masks) * xyxy_null
+
+ # positionet with text only information
+ if positive_embeddings is not None:
+ # learnable null embedding
+ positive_null = self.null_positive_feature.view(1, 1, -1)
+
+ # replace padding with learnable null embedding
+ positive_embeddings = positive_embeddings * masks + (1 - masks) * positive_null
+
+ objs = self.linears(torch.cat([positive_embeddings, xyxy_embedding], dim=-1))
+
+ # positionet with text and image information
+ else:
+ phrases_masks = phrases_masks.unsqueeze(-1)
+ image_masks = image_masks.unsqueeze(-1)
+
+ # learnable null embedding
+ text_null = self.null_text_feature.view(1, 1, -1)
+ image_null = self.null_image_feature.view(1, 1, -1)
+
+ # replace padding with learnable null embedding
+ phrases_embeddings = phrases_embeddings * phrases_masks + (1 - phrases_masks) * text_null
+ image_embeddings = image_embeddings * image_masks + (1 - image_masks) * image_null
+
+ objs_text = self.linears_text(torch.cat([phrases_embeddings, xyxy_embedding], dim=-1))
+ objs_image = self.linears_image(torch.cat([image_embeddings, xyxy_embedding], dim=-1))
+ objs = torch.cat([objs_text, objs_image], dim=1)
+
+ return objs
+
+
+class PixArtAlphaCombinedTimestepSizeEmbeddings(nn.Module):
+ """
+ For PixArt-Alpha.
+
+ Reference:
+ https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L164C9-L168C29
+ """
+
+ def __init__(self, embedding_dim, size_emb_dim, use_additional_conditions: bool = False):
+ super().__init__()
+
+ self.outdim = size_emb_dim
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
+
+ self.use_additional_conditions = use_additional_conditions
+ if use_additional_conditions:
+ self.additional_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.resolution_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
+ self.aspect_ratio_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=size_emb_dim)
+
+ def forward(self, timestep, resolution, aspect_ratio, batch_size, hidden_dtype):
+ timesteps_proj = self.time_proj(timestep)
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
+
+ if self.use_additional_conditions:
+ resolution_emb = self.additional_condition_proj(resolution.flatten()).to(hidden_dtype)
+ resolution_emb = self.resolution_embedder(resolution_emb).reshape(batch_size, -1)
+ aspect_ratio_emb = self.additional_condition_proj(aspect_ratio.flatten()).to(hidden_dtype)
+ aspect_ratio_emb = self.aspect_ratio_embedder(aspect_ratio_emb).reshape(batch_size, -1)
+ conditioning = timesteps_emb + torch.cat([resolution_emb, aspect_ratio_emb], dim=1)
+ else:
+ conditioning = timesteps_emb
+
+ return conditioning
+
+
+class PixArtAlphaTextProjection(nn.Module):
+ """
+ Projects caption embeddings. Also handles dropout for classifier-free guidance.
+
+ Adapted from https://github.com/PixArt-alpha/PixArt-alpha/blob/master/diffusion/model/nets/PixArt_blocks.py
+ """
+
+ def __init__(self, in_features, hidden_size, out_features=None, act_fn="gelu_tanh"):
+ super().__init__()
+ if out_features is None:
+ out_features = hidden_size
+ self.linear_1 = nn.Linear(in_features=in_features, out_features=hidden_size, bias=True)
+ if act_fn == "gelu_tanh":
+ self.act_1 = nn.GELU(approximate="tanh")
+ elif act_fn == "silu":
+ self.act_1 = nn.SiLU()
+ elif act_fn == "silu_fp32":
+ self.act_1 = FP32SiLU()
+ else:
+ raise ValueError(f"Unknown activation function: {act_fn}")
+ self.linear_2 = nn.Linear(in_features=hidden_size, out_features=out_features, bias=True)
+
+ def forward(self, caption):
+ hidden_states = self.linear_1(caption)
+ hidden_states = self.act_1(hidden_states)
+ hidden_states = self.linear_2(hidden_states)
+ return hidden_states
+
+
+class IPAdapterPlusImageProjectionBlock(nn.Module):
+ def __init__(
+ self,
+ embed_dims: int = 768,
+ dim_head: int = 64,
+ heads: int = 16,
+ ffn_ratio: float = 4,
+ ) -> None:
+ super().__init__()
+ from .attention import FeedForward
+
+ self.ln0 = nn.LayerNorm(embed_dims)
+ self.ln1 = nn.LayerNorm(embed_dims)
+ self.attn = Attention(
+ query_dim=embed_dims,
+ dim_head=dim_head,
+ heads=heads,
+ out_bias=False,
+ )
+ self.ff = nn.Sequential(
+ nn.LayerNorm(embed_dims),
+ FeedForward(embed_dims, embed_dims, activation_fn="gelu", mult=ffn_ratio, bias=False),
+ )
+
+ def forward(self, x, latents, residual):
+ encoder_hidden_states = self.ln0(x)
+ latents = self.ln1(latents)
+ encoder_hidden_states = torch.cat([encoder_hidden_states, latents], dim=-2)
+ latents = self.attn(latents, encoder_hidden_states) + residual
+ latents = self.ff(latents) + latents
+ return latents
+
+
+class IPAdapterPlusImageProjection(nn.Module):
+ """Resampler of IP-Adapter Plus.
+
+ Args:
+ embed_dims (int): The feature dimension. Defaults to 768. output_dims (int): The number of output channels,
+ that is the same
+ number of the channels in the `unet.config.cross_attention_dim`. Defaults to 1024.
+ hidden_dims (int):
+ The number of hidden channels. Defaults to 1280. depth (int): The number of blocks. Defaults
+ to 8. dim_head (int): The number of head channels. Defaults to 64. heads (int): Parallel attention heads.
+ Defaults to 16. num_queries (int):
+ The number of queries. Defaults to 8. ffn_ratio (float): The expansion ratio
+ of feedforward network hidden
+ layer channels. Defaults to 4.
+ """
+
+ def __init__(
+ self,
+ embed_dims: int = 768,
+ output_dims: int = 1024,
+ hidden_dims: int = 1280,
+ depth: int = 4,
+ dim_head: int = 64,
+ heads: int = 16,
+ num_queries: int = 8,
+ ffn_ratio: float = 4,
+ ) -> None:
+ super().__init__()
+ self.latents = nn.Parameter(torch.randn(1, num_queries, hidden_dims) / hidden_dims**0.5)
+
+ self.proj_in = nn.Linear(embed_dims, hidden_dims)
+
+ self.proj_out = nn.Linear(hidden_dims, output_dims)
+ self.norm_out = nn.LayerNorm(output_dims)
+
+ self.layers = nn.ModuleList(
+ [IPAdapterPlusImageProjectionBlock(hidden_dims, dim_head, heads, ffn_ratio) for _ in range(depth)]
+ )
+
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ x (torch.Tensor): Input Tensor.
+ Returns:
+ torch.Tensor: Output Tensor.
+ """
+ latents = self.latents.repeat(x.size(0), 1, 1)
+
+ x = self.proj_in(x)
+
+ for block in self.layers:
+ residual = latents
+ latents = block(x, latents, residual)
+
+ latents = self.proj_out(latents)
+ return self.norm_out(latents)
+
+
+class IPAdapterFaceIDPlusImageProjection(nn.Module):
+ """FacePerceiverResampler of IP-Adapter Plus.
+
+ Args:
+ embed_dims (int): The feature dimension. Defaults to 768. output_dims (int): The number of output channels,
+ that is the same
+ number of the channels in the `unet.config.cross_attention_dim`. Defaults to 1024.
+ hidden_dims (int):
+ The number of hidden channels. Defaults to 1280. depth (int): The number of blocks. Defaults
+ to 8. dim_head (int): The number of head channels. Defaults to 64. heads (int): Parallel attention heads.
+ Defaults to 16. num_tokens (int): Number of tokens num_queries (int): The number of queries. Defaults to 8.
+ ffn_ratio (float): The expansion ratio of feedforward network hidden
+ layer channels. Defaults to 4.
+ ffproj_ratio (float): The expansion ratio of feedforward network hidden
+ layer channels (for ID embeddings). Defaults to 4.
+ """
+
+ def __init__(
+ self,
+ embed_dims: int = 768,
+ output_dims: int = 768,
+ hidden_dims: int = 1280,
+ id_embeddings_dim: int = 512,
+ depth: int = 4,
+ dim_head: int = 64,
+ heads: int = 16,
+ num_tokens: int = 4,
+ num_queries: int = 8,
+ ffn_ratio: float = 4,
+ ffproj_ratio: int = 2,
+ ) -> None:
+ super().__init__()
+ from .attention import FeedForward
+
+ self.num_tokens = num_tokens
+ self.embed_dim = embed_dims
+ self.clip_embeds = None
+ self.shortcut = False
+ self.shortcut_scale = 1.0
+
+ self.proj = FeedForward(id_embeddings_dim, embed_dims * num_tokens, activation_fn="gelu", mult=ffproj_ratio)
+ self.norm = nn.LayerNorm(embed_dims)
+
+ self.proj_in = nn.Linear(hidden_dims, embed_dims)
+
+ self.proj_out = nn.Linear(embed_dims, output_dims)
+ self.norm_out = nn.LayerNorm(output_dims)
+
+ self.layers = nn.ModuleList(
+ [IPAdapterPlusImageProjectionBlock(embed_dims, dim_head, heads, ffn_ratio) for _ in range(depth)]
+ )
+
+ def forward(self, id_embeds: torch.Tensor) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ id_embeds (torch.Tensor): Input Tensor (ID embeds).
+ Returns:
+ torch.Tensor: Output Tensor.
+ """
+ id_embeds = id_embeds.to(self.clip_embeds.dtype)
+ id_embeds = self.proj(id_embeds)
+ id_embeds = id_embeds.reshape(-1, self.num_tokens, self.embed_dim)
+ id_embeds = self.norm(id_embeds)
+ latents = id_embeds
+
+ clip_embeds = self.proj_in(self.clip_embeds)
+ x = clip_embeds.reshape(-1, clip_embeds.shape[2], clip_embeds.shape[3])
+
+ for block in self.layers:
+ residual = latents
+ latents = block(x, latents, residual)
+
+ latents = self.proj_out(latents)
+ out = self.norm_out(latents)
+ if self.shortcut:
+ out = id_embeds + self.shortcut_scale * out
+ return out
+
+
+class IPAdapterTimeImageProjectionBlock(nn.Module):
+ """Block for IPAdapterTimeImageProjection.
+
+ Args:
+ hidden_dim (`int`, defaults to 1280):
+ The number of hidden channels.
+ dim_head (`int`, defaults to 64):
+ The number of head channels.
+ heads (`int`, defaults to 20):
+ Parallel attention heads.
+ ffn_ratio (`int`, defaults to 4):
+ The expansion ratio of feedforward network hidden layer channels.
+ """
+
+ def __init__(
+ self,
+ hidden_dim: int = 1280,
+ dim_head: int = 64,
+ heads: int = 20,
+ ffn_ratio: int = 4,
+ ) -> None:
+ super().__init__()
+ from .attention import FeedForward
+
+ self.ln0 = nn.LayerNorm(hidden_dim)
+ self.ln1 = nn.LayerNorm(hidden_dim)
+ self.attn = Attention(
+ query_dim=hidden_dim,
+ cross_attention_dim=hidden_dim,
+ dim_head=dim_head,
+ heads=heads,
+ bias=False,
+ out_bias=False,
+ )
+ self.ff = FeedForward(hidden_dim, hidden_dim, activation_fn="gelu", mult=ffn_ratio, bias=False)
+
+ # AdaLayerNorm
+ self.adaln_silu = nn.SiLU()
+ self.adaln_proj = nn.Linear(hidden_dim, 4 * hidden_dim)
+ self.adaln_norm = nn.LayerNorm(hidden_dim)
+
+ # Set attention scale and fuse KV
+ self.attn.scale = 1 / math.sqrt(math.sqrt(dim_head))
+ self.attn.fuse_projections()
+ self.attn.to_k = None
+ self.attn.to_v = None
+
+ def forward(self, x: torch.Tensor, latents: torch.Tensor, timestep_emb: torch.Tensor) -> torch.Tensor:
+ """Forward pass.
+
+ Args:
+ x (`torch.Tensor`):
+ Image features.
+ latents (`torch.Tensor`):
+ Latent features.
+ timestep_emb (`torch.Tensor`):
+ Timestep embedding.
+
+ Returns:
+ `torch.Tensor`: Output latent features.
+ """
+
+ # Shift and scale for AdaLayerNorm
+ emb = self.adaln_proj(self.adaln_silu(timestep_emb))
+ shift_msa, scale_msa, shift_mlp, scale_mlp = emb.chunk(4, dim=1)
+
+ # Fused Attention
+ residual = latents
+ x = self.ln0(x)
+ latents = self.ln1(latents) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+
+ batch_size = latents.shape[0]
+
+ query = self.attn.to_q(latents)
+ kv_input = torch.cat((x, latents), dim=-2)
+ key, value = self.attn.to_kv(kv_input).chunk(2, dim=-1)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // self.attn.heads
+
+ query = query.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
+ key = key.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
+ value = value.view(batch_size, -1, self.attn.heads, head_dim).transpose(1, 2)
+
+ weight = (query * self.attn.scale) @ (key * self.attn.scale).transpose(-2, -1)
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
+ latents = weight @ value
+
+ latents = latents.transpose(1, 2).reshape(batch_size, -1, self.attn.heads * head_dim)
+ latents = self.attn.to_out[0](latents)
+ latents = self.attn.to_out[1](latents)
+ latents = latents + residual
+
+ ## FeedForward
+ residual = latents
+ latents = self.adaln_norm(latents) * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+ return self.ff(latents) + residual
+
+
+# Modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
+class IPAdapterTimeImageProjection(nn.Module):
+ """Resampler of SD3 IP-Adapter with timestep embedding.
+
+ Args:
+ embed_dim (`int`, defaults to 1152):
+ The feature dimension.
+ output_dim (`int`, defaults to 2432):
+ The number of output channels.
+ hidden_dim (`int`, defaults to 1280):
+ The number of hidden channels.
+ depth (`int`, defaults to 4):
+ The number of blocks.
+ dim_head (`int`, defaults to 64):
+ The number of head channels.
+ heads (`int`, defaults to 20):
+ Parallel attention heads.
+ num_queries (`int`, defaults to 64):
+ The number of queries.
+ ffn_ratio (`int`, defaults to 4):
+ The expansion ratio of feedforward network hidden layer channels.
+ timestep_in_dim (`int`, defaults to 320):
+ The number of input channels for timestep embedding.
+ timestep_flip_sin_to_cos (`bool`, defaults to True):
+ Flip the timestep embedding order to `cos, sin` (if True) or `sin, cos` (if False).
+ timestep_freq_shift (`int`, defaults to 0):
+ Controls the timestep delta between frequencies between dimensions.
+ """
+
+ def __init__(
+ self,
+ embed_dim: int = 1152,
+ output_dim: int = 2432,
+ hidden_dim: int = 1280,
+ depth: int = 4,
+ dim_head: int = 64,
+ heads: int = 20,
+ num_queries: int = 64,
+ ffn_ratio: int = 4,
+ timestep_in_dim: int = 320,
+ timestep_flip_sin_to_cos: bool = True,
+ timestep_freq_shift: int = 0,
+ ) -> None:
+ super().__init__()
+ self.latents = nn.Parameter(torch.randn(1, num_queries, hidden_dim) / hidden_dim**0.5)
+ self.proj_in = nn.Linear(embed_dim, hidden_dim)
+ self.proj_out = nn.Linear(hidden_dim, output_dim)
+ self.norm_out = nn.LayerNorm(output_dim)
+ self.layers = nn.ModuleList(
+ [IPAdapterTimeImageProjectionBlock(hidden_dim, dim_head, heads, ffn_ratio) for _ in range(depth)]
+ )
+ self.time_proj = Timesteps(timestep_in_dim, timestep_flip_sin_to_cos, timestep_freq_shift)
+ self.time_embedding = TimestepEmbedding(timestep_in_dim, hidden_dim, act_fn="silu")
+
+ def forward(self, x: torch.Tensor, timestep: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """Forward pass.
+
+ Args:
+ x (`torch.Tensor`):
+ Image features.
+ timestep (`torch.Tensor`):
+ Timestep in denoising process.
+ Returns:
+ `Tuple`[`torch.Tensor`, `torch.Tensor`]: The pair (latents, timestep_emb).
+ """
+ timestep_emb = self.time_proj(timestep).to(dtype=x.dtype)
+ timestep_emb = self.time_embedding(timestep_emb)
+
+ latents = self.latents.repeat(x.size(0), 1, 1)
+
+ x = self.proj_in(x)
+ x = x + timestep_emb[:, None]
+
+ for block in self.layers:
+ latents = block(x, latents, timestep_emb)
+
+ latents = self.proj_out(latents)
+ latents = self.norm_out(latents)
+
+ return latents, timestep_emb
+
+
+class MultiIPAdapterImageProjection(nn.Module):
+ def __init__(self, IPAdapterImageProjectionLayers: Union[List[nn.Module], Tuple[nn.Module]]):
+ super().__init__()
+ self.image_projection_layers = nn.ModuleList(IPAdapterImageProjectionLayers)
+
+ @property
+ def num_ip_adapters(self) -> int:
+ """Number of IP-Adapters loaded."""
+ return len(self.image_projection_layers)
+
+ def forward(self, image_embeds: List[torch.Tensor]):
+ projected_image_embeds = []
+
+ # currently, we accept `image_embeds` as
+ # 1. a tensor (deprecated) with shape [batch_size, embed_dim] or [batch_size, sequence_length, embed_dim]
+ # 2. list of `n` tensors where `n` is number of ip-adapters, each tensor can hae shape [batch_size, num_images, embed_dim] or [batch_size, num_images, sequence_length, embed_dim]
+ if not isinstance(image_embeds, list):
+ deprecation_message = (
+ "You have passed a tensor as `image_embeds`.This is deprecated and will be removed in a future release."
+ " Please make sure to update your script to pass `image_embeds` as a list of tensors to suppress this warning."
+ )
+ deprecate("image_embeds not a list", "1.0.0", deprecation_message, standard_warn=False)
+ image_embeds = [image_embeds.unsqueeze(1)]
+
+ if len(image_embeds) != len(self.image_projection_layers):
+ raise ValueError(
+ f"image_embeds must have the same length as image_projection_layers, got {len(image_embeds)} and {len(self.image_projection_layers)}"
+ )
+
+ for image_embed, image_projection_layer in zip(image_embeds, self.image_projection_layers):
+ batch_size, num_images = image_embed.shape[0], image_embed.shape[1]
+ image_embed = image_embed.reshape((batch_size * num_images,) + image_embed.shape[2:])
+ image_embed = image_projection_layer(image_embed)
+ image_embed = image_embed.reshape((batch_size, num_images) + image_embed.shape[1:])
+
+ projected_image_embeds.append(image_embed)
+
+ return projected_image_embeds
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/normalization.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/normalization.py
new file mode 100644
index 0000000000000000000000000000000000000000..f492190f50748a0fc17e5b613e304c12eeb9ac3e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/normalization.py
@@ -0,0 +1,652 @@
+# coding=utf-8
+# Copyright 2024 HuggingFace Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import numbers
+from typing import Dict, Optional, Tuple
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+import numbers
+from typing import Dict, Optional, Tuple
+
+
+from diffusers.utils import is_torch_npu_available, is_torch_version
+from .activations import get_activation
+from .embeddings import CombinedTimestepLabelEmbeddings, PixArtAlphaCombinedTimestepSizeEmbeddings
+
+class AdaLayerNorm(nn.Module):
+ r"""
+ Norm layer modified to incorporate timestep embeddings.
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`, *optional*): The size of the embeddings dictionary.
+ output_dim (`int`, *optional*):
+ norm_elementwise_affine (`bool`, defaults to `False):
+ norm_eps (`bool`, defaults to `False`):
+ chunk_dim (`int`, defaults to `0`):
+ """
+
+ def __init__(
+ self,
+ embedding_dim: int,
+ num_embeddings: Optional[int] = None,
+ output_dim: Optional[int] = None,
+ norm_elementwise_affine: bool = False,
+ norm_eps: float = 1e-5,
+ chunk_dim: int = 0,
+ ):
+ super().__init__()
+
+ self.chunk_dim = chunk_dim
+ output_dim = output_dim or embedding_dim * 2
+
+ if num_embeddings is not None:
+ self.emb = nn.Embedding(num_embeddings, embedding_dim)
+ else:
+ self.emb = None
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, output_dim)
+ self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine)
+
+ def forward(
+ self, x: torch.Tensor, timestep: Optional[torch.Tensor] = None, temb: Optional[torch.Tensor] = None
+ ) -> torch.Tensor:
+ if self.emb is not None:
+ temb = self.emb(timestep)
+
+ temb = self.linear(self.silu(temb))
+
+ if self.chunk_dim == 1:
+ # This is a bit weird why we have the order of "shift, scale" here and "scale, shift" in the
+ # other if-branch. This branch is specific to CogVideoX and OmniGen for now.
+ shift, scale = temb.chunk(2, dim=1)
+ shift = shift[:, None, :]
+ scale = scale[:, None, :]
+ else:
+ scale, shift = temb.chunk(2, dim=0)
+
+ x = self.norm(x) * (1 + scale) + shift
+ return x
+
+
+class FP32LayerNorm(nn.LayerNorm):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ origin_dtype = inputs.dtype
+ return F.layer_norm(
+ inputs.float(),
+ self.normalized_shape,
+ self.weight.float() if self.weight is not None else None,
+ self.bias.float() if self.bias is not None else None,
+ self.eps,
+ ).to(origin_dtype)
+
+
+class SD35AdaLayerNormZeroX(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (AdaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True) -> None:
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 9 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ raise ValueError(f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm'.")
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, ...]:
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp, shift_msa2, scale_msa2, gate_msa2 = emb.chunk(
+ 9, dim=1
+ )
+ norm_hidden_states = self.norm(hidden_states)
+ hidden_states = norm_hidden_states * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ norm_hidden_states2 = norm_hidden_states * (1 + scale_msa2[:, None]) + shift_msa2[:, None]
+ return hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp, norm_hidden_states2, gate_msa2
+
+
+class AdaLayerNormZero(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None, norm_type="layer_norm", bias=True):
+ super().__init__()
+ if num_embeddings is not None:
+ self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
+ else:
+ self.emb = None
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ elif norm_type == "fp32_layer_norm":
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
+ else:
+ raise ValueError(
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ timestep: Optional[torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ hidden_dtype: Optional[torch.dtype] = None,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ if self.emb is not None:
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
+
+
+class AdaLayerNormZeroSingle(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ raise ValueError(
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
+ )
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ emb = self.linear(self.silu(emb))
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ return x, gate_msa
+
+
+class LuminaRMSNormZero(nn.Module):
+ """
+ Norm layer adaptive RMS normalization zero.
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ """
+
+ def __init__(self, embedding_dim: int, norm_eps: float, norm_elementwise_affine: bool):
+ super().__init__()
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(
+ min(embedding_dim, 1024),
+ 4 * embedding_dim,
+ bias=True,
+ )
+ self.norm = RMSNorm(embedding_dim, eps=norm_eps)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ emb = self.linear(self.silu(emb))
+ scale_msa, gate_msa, scale_mlp, gate_mlp = emb.chunk(4, dim=1)
+ x = self.norm(x) * (1 + scale_msa[:, None])
+
+ return x, gate_msa, scale_mlp, gate_mlp
+
+
+class AdaLayerNormSingle(nn.Module):
+ r"""
+ Norm layer adaptive layer norm single (adaLN-single).
+
+ As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ use_additional_conditions (`bool`): To use additional conditions for normalization or not.
+ """
+
+ def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
+ super().__init__()
+
+ self.emb = PixArtAlphaCombinedTimestepSizeEmbeddings(
+ embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
+ )
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ batch_size: Optional[int] = None,
+ hidden_dtype: Optional[torch.dtype] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ # No modulation happening here.
+ added_cond_kwargs = added_cond_kwargs or {"resolution": None, "aspect_ratio": None}
+ embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype)
+ return self.linear(self.silu(embedded_timestep)), embedded_timestep
+
+
+class AdaGroupNorm(nn.Module):
+ r"""
+ GroupNorm layer modified to incorporate timestep embeddings.
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ num_groups (`int`): The number of groups to separate the channels into.
+ act_fn (`str`, *optional*, defaults to `None`): The activation function to use.
+ eps (`float`, *optional*, defaults to `1e-5`): The epsilon value to use for numerical stability.
+ """
+
+ def __init__(
+ self, embedding_dim: int, out_dim: int, num_groups: int, act_fn: Optional[str] = None, eps: float = 1e-5
+ ):
+ super().__init__()
+ self.num_groups = num_groups
+ self.eps = eps
+
+ if act_fn is None:
+ self.act = None
+ else:
+ self.act = get_activation(act_fn)
+
+ self.linear = nn.Linear(embedding_dim, out_dim * 2)
+
+ def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
+ if self.act:
+ emb = self.act(emb)
+ emb = self.linear(emb)
+ emb = emb[:, :, None, None]
+ scale, shift = emb.chunk(2, dim=1)
+
+ x = F.group_norm(x, self.num_groups, eps=self.eps)
+ x = x * (1 + scale) + shift
+ return x
+
+
+class AdaLayerNormContinuous(nn.Module):
+ r"""
+ Adaptive normalization layer with a norm layer (layer_norm or rms_norm).
+
+ Args:
+ embedding_dim (`int`): Embedding dimension to use during projection.
+ conditioning_embedding_dim (`int`): Dimension of the input condition.
+ elementwise_affine (`bool`, defaults to `True`):
+ Boolean flag to denote if affine transformation should be applied.
+ eps (`float`, defaults to 1e-5): Epsilon factor.
+ bias (`bias`, defaults to `True`): Boolean flag to denote if bias should be use.
+ norm_type (`str`, defaults to `"layer_norm"`):
+ Normalization layer to use. Values supported: "layer_norm", "rms_norm".
+ """
+
+ def __init__(
+ self,
+ embedding_dim: int,
+ conditioning_embedding_dim: int,
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
+ # However, this is how it was implemented in the original code, and it's rather likely you should
+ # set `elementwise_affine` to False.
+ elementwise_affine=True,
+ eps=1e-5,
+ bias=True,
+ norm_type="layer_norm",
+ ):
+ super().__init__()
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
+ if norm_type == "layer_norm":
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
+ elif norm_type == "rms_norm":
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
+ else:
+ raise ValueError(f"unknown norm_type {norm_type}")
+
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
+ scale, shift = torch.chunk(emb, 2, dim=1)
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
+ return x
+
+
+class LuminaLayerNormContinuous(nn.Module):
+ def __init__(
+ self,
+ embedding_dim: int,
+ conditioning_embedding_dim: int,
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
+ # However, this is how it was implemented in the original code, and it's rather likely you should
+ # set `elementwise_affine` to False.
+ elementwise_affine=True,
+ eps=1e-5,
+ bias=True,
+ norm_type="layer_norm",
+ out_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # AdaLN
+ self.silu = nn.SiLU()
+ self.linear_1 = nn.Linear(conditioning_embedding_dim, embedding_dim, bias=bias)
+
+ if norm_type == "layer_norm":
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
+ elif norm_type == "rms_norm":
+ self.norm = RMSNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
+ else:
+ raise ValueError(f"unknown norm_type {norm_type}")
+
+ self.linear_2 = None
+ if out_dim is not None:
+ self.linear_2 = nn.Linear(embedding_dim, out_dim, bias=bias)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ conditioning_embedding: torch.Tensor,
+ ) -> torch.Tensor:
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
+ emb = self.linear_1(self.silu(conditioning_embedding).to(x.dtype))
+ scale = emb
+ x = self.norm(x) * (1 + scale)[:, None, :]
+
+ if self.linear_2 is not None:
+ x = self.linear_2(x)
+
+ return x
+
+
+class CogView3PlusAdaLayerNormZeroTextImage(nn.Module):
+ r"""
+ Norm layer adaptive layer norm zero (adaLN-Zero).
+
+ Parameters:
+ embedding_dim (`int`): The size of each embedding vector.
+ num_embeddings (`int`): The size of the embeddings dictionary.
+ """
+
+ def __init__(self, embedding_dim: int, dim: int):
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(embedding_dim, 12 * dim, bias=True)
+ self.norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
+ self.norm_c = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
+
+ def forward(
+ self,
+ x: torch.Tensor,
+ context: torch.Tensor,
+ emb: Optional[torch.Tensor] = None,
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ emb = self.linear(self.silu(emb))
+ (
+ shift_msa,
+ scale_msa,
+ gate_msa,
+ shift_mlp,
+ scale_mlp,
+ gate_mlp,
+ c_shift_msa,
+ c_scale_msa,
+ c_gate_msa,
+ c_shift_mlp,
+ c_scale_mlp,
+ c_gate_mlp,
+ ) = emb.chunk(12, dim=1)
+ normed_x = self.norm_x(x)
+ normed_context = self.norm_c(context)
+ x = normed_x * (1 + scale_msa[:, None]) + shift_msa[:, None]
+ context = normed_context * (1 + c_scale_msa[:, None]) + c_shift_msa[:, None]
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp, context, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp
+
+
+class CogVideoXLayerNormZero(nn.Module):
+ def __init__(
+ self,
+ conditioning_dim: int,
+ embedding_dim: int,
+ elementwise_affine: bool = True,
+ eps: float = 1e-5,
+ bias: bool = True,
+ ) -> None:
+ super().__init__()
+
+ self.silu = nn.SiLU()
+ self.linear = nn.Linear(conditioning_dim, 6 * embedding_dim, bias=bias)
+ self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
+
+ def forward(
+ self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
+ shift, scale, gate, enc_shift, enc_scale, enc_gate = self.linear(self.silu(temb)).chunk(6, dim=1)
+ hidden_states = self.norm(hidden_states) * (1 + scale)[:, None, :] + shift[:, None, :]
+ encoder_hidden_states = self.norm(encoder_hidden_states) * (1 + enc_scale)[:, None, :] + enc_shift[:, None, :]
+ return hidden_states, encoder_hidden_states, gate[:, None, :], enc_gate[:, None, :]
+
+
+if is_torch_version(">=", "2.1.0"):
+ LayerNorm = nn.LayerNorm
+else:
+ # Has optional bias parameter compared to torch layer norm
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
+ class LayerNorm(nn.Module):
+ r"""
+ LayerNorm with the bias parameter.
+
+ Args:
+ dim (`int`): Dimensionality to use for the parameters.
+ eps (`float`, defaults to 1e-5): Epsilon factor.
+ elementwise_affine (`bool`, defaults to `True`):
+ Boolean flag to denote if affine transformation should be applied.
+ bias (`bias`, defaults to `True`): Boolean flag to denote if bias should be use.
+ """
+
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
+ else:
+ self.weight = None
+ self.bias = None
+
+ def forward(self, input):
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
+
+
+class RMSNorm(nn.Module):
+ r"""
+ RMS Norm as introduced in https://arxiv.org/abs/1910.07467 by Zhang et al.
+
+ Args:
+ dim (`int`): Number of dimensions to use for `weights`. Only effective when `elementwise_affine` is True.
+ eps (`float`): Small value to use when calculating the reciprocal of the square-root.
+ elementwise_affine (`bool`, defaults to `True`):
+ Boolean flag to denote if affine transformation should be applied.
+ bias (`bool`, defaults to False): If also training the `bias` param.
+ """
+
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True, bias: bool = False):
+ super().__init__()
+
+ self.eps = eps
+ self.elementwise_affine = elementwise_affine
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ self.weight = None
+ self.bias = None
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ if bias:
+ self.bias = nn.Parameter(torch.zeros(dim))
+
+ def forward(self, hidden_states):
+ if is_torch_npu_available():
+ import torch_npu
+
+ if self.weight is not None:
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+ hidden_states = torch_npu.npu_rms_norm(hidden_states, self.weight, epsilon=self.eps)[0]
+ if self.bias is not None:
+ hidden_states = hidden_states + self.bias
+ else:
+ input_dtype = hidden_states.dtype
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
+
+ if self.weight is not None:
+ # convert into half-precision if necessary
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
+ hidden_states = hidden_states.to(self.weight.dtype)
+ hidden_states = hidden_states * self.weight
+ if self.bias is not None:
+ hidden_states = hidden_states + self.bias
+ else:
+ hidden_states = hidden_states.to(input_dtype)
+
+ return hidden_states
+
+
+# TODO: (Dhruv) This can be replaced with regular RMSNorm in Mochi once `_keep_in_fp32_modules` is supported
+# for sharded checkpoints, see: https://github.com/huggingface/diffusers/issues/10013
+class MochiRMSNorm(nn.Module):
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
+ super().__init__()
+
+ self.eps = eps
+
+ if isinstance(dim, numbers.Integral):
+ dim = (dim,)
+
+ self.dim = torch.Size(dim)
+
+ if elementwise_affine:
+ self.weight = nn.Parameter(torch.ones(dim))
+ else:
+ self.weight = None
+
+ def forward(self, hidden_states):
+ input_dtype = hidden_states.dtype
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
+
+ if self.weight is not None:
+ hidden_states = hidden_states * self.weight
+ hidden_states = hidden_states.to(input_dtype)
+
+ return hidden_states
+
+
+class GlobalResponseNorm(nn.Module):
+ r"""
+ Global response normalization as introduced in ConvNeXt-v2 (https://arxiv.org/abs/2301.00808).
+
+ Args:
+ dim (`int`): Number of dimensions to use for the `gamma` and `beta`.
+ """
+
+ # Taken from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105
+ def __init__(self, dim):
+ super().__init__()
+ self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
+ self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
+
+ def forward(self, x):
+ gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
+ nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
+ return self.gamma * (x * nx) + self.beta + x
+
+
+class LpNorm(nn.Module):
+ def __init__(self, p: int = 2, dim: int = -1, eps: float = 1e-12):
+ super().__init__()
+
+ self.p = p
+ self.dim = dim
+ self.eps = eps
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ return F.normalize(hidden_states, p=self.p, dim=self.dim, eps=self.eps)
+
+
+def get_normalization(
+ norm_type: str = "batch_norm",
+ num_features: Optional[int] = None,
+ eps: float = 1e-5,
+ elementwise_affine: bool = True,
+ bias: bool = True,
+) -> nn.Module:
+ if norm_type == "rms_norm":
+ norm = RMSNorm(num_features, eps=eps, elementwise_affine=elementwise_affine, bias=bias)
+ elif norm_type == "layer_norm":
+ norm = nn.LayerNorm(num_features, eps=eps, elementwise_affine=elementwise_affine, bias=bias)
+ elif norm_type == "batch_norm":
+ norm = nn.BatchNorm2d(num_features, eps=eps, affine=elementwise_affine)
+ else:
+ raise ValueError(f"{norm_type=} is not supported.")
+ return norm
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..8960e7bde7f9f9b27f51deb00fb575f4c342d91a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor.py
@@ -0,0 +1,553 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+ # B L D --> B L H D -> B H L D
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = self.attn_fn(
+ query, key_img, value_img, None
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ # self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ hidden_states: torch.Tensor,
+ # encoder_hidden_states: torch.Tensor,
+ # encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ # encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ # if encoder_hidden_states_image is not None:
+ # encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+ # print(t_dim, h_dim, w_dim)
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+
+class WanRotary2DPosEmbed(nn.Module):
+ def __init__(self, attention_head_dim: int, patch_size_2d: Tuple[int, int], max_seq_len: int, theta: float = 10000.0):
+ super().__init__()
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size_2d # (H, W)
+ self.max_seq_len = max_seq_len
+
+ h_dim = attention_head_dim // 2
+ w_dim = attention_head_dim - h_dim
+
+ freq_h = get_1d_rotary_pos_embed(h_dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64)
+ freq_w = get_1d_rotary_pos_embed(w_dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64)
+
+ self.freqs_h = freq_h
+ self.freqs_w = freq_w
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ _, _, _, height, width = hidden_states.shape
+ p_h, p_w = self.patch_size
+ pph, ppw = height // p_h, width // p_w
+
+ self.freqs_h = self.freqs_h.to(hidden_states.device)
+ self.freqs_w = self.freqs_w.to(hidden_states.device)
+
+ freqs_h = self.freqs_h[:pph].view(1, pph, 1, -1).expand(1, pph, ppw, -1)
+ freqs_w = self.freqs_w[:ppw].view(1, 1, ppw, -1).expand(1, pph, ppw, -1)
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1).reshape(1, 1, pph * ppw, -1)
+ return freqs
+
+# Text Free
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ # self.attn2 = Attention(
+ # query_dim=dim,
+ # heads=num_heads,
+ # kv_heads=num_heads,
+ # dim_head=dim // num_heads,
+ # qk_norm=qk_norm,
+ # eps=eps,
+ # bias=True,
+ # cross_attention_dim=None,
+ # out_bias=True,
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ # processor=WanAttnProcessor2_0(),
+ # )
+ # self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ # encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+ # text free
+ # 2. Cross-attention
+ # norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ # attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ # hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanRefextractor(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.rope_2d = WanRotary2DPosEmbed(attention_head_dim, patch_size[1:], rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ self.ref_blocks = nn.ModuleList([])
+
+ for _ in range(len(self.blocks)+1):
+ self.ref_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+ # 4. Output norm & projection
+ # self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ # self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ # self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ # encoder_hidden_states: torch.Tensor,
+ # encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = False,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+ if num_frames == 1:
+ rotary_emb = self.rope_2d(hidden_states)
+ else:
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ # timestep, encoder_hidden_states, encoder_hidden_states_image
+ # )
+ # use hidden_states for type
+ temb, timestep_proj = self.condition_embedder(timestep,hidden_states)
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ # if encoder_hidden_states_image is not None:
+ # encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for block in self.blocks:
+ block_samples = block_samples + (hidden_states, )
+ # direct
+ # if torch.is_grad_enabled() and self.gradient_checkpointing:
+ # hidden_states = self._gradient_checkpointing_func(
+ # block, hidden_states, timestep_proj, rotary_emb
+ # )
+ # else:
+ hidden_states = block(hidden_states, timestep_proj, rotary_emb)
+ block_samples = block_samples + (hidden_states, )
+
+
+ ref_block_samples = ()
+ assert len(block_samples) == len(self.ref_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, ref_blocks has length {len(self.ref_blocks)}"
+
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ return ref_block_samples, rotary_emb
+ # # 5. Output norm, projection & unpatchify
+ # shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # # Move the shift and scale tensors to the same device as hidden_states.
+ # # When using multi-GPU inference via accelerate these will be on the
+ # # first device rather than the last device, which hidden_states ends up
+ # # on.
+ # shift = shift.to(hidden_states.device)
+ # scale = scale.to(hidden_states.device)
+
+ # hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ # hidden_states = self.proj_out(hidden_states)
+
+ # hidden_states = hidden_states.reshape(
+ # batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ # )
+ # hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ # output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ # if USE_PEFT_BACKEND:
+ # # remove `lora_scale` from each PEFT layer
+ # unscale_lora_layers(self, lora_scale)
+
+ # if not return_dict:
+ # return (output,)
+
+ # return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor_2d.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..ad9b5d98b533e67dc93d33293f027201c60f46bc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/refextractor_2d.py
@@ -0,0 +1,556 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+import re
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module
+from diffusers.utils import is_torch_version
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+def get_torch_cuda_version():
+ if not torch.version.cuda:
+ return (0, 0)
+ match = re.match(r"(\d+)\.(\d+)", torch.version.cuda)
+ if match:
+ return tuple(map(int, match.groups()))
+ return (0, 0)
+
+
+def apply_rotary_emb_split(hidden_states, freqs, t_dim):
+ t_part, hw_part = torch.split(hidden_states, [t_dim, hidden_states.shape[-1] - t_dim], dim=-1)
+ hw_freqs = freqs[..., t_dim//2:]
+
+ x_hw = torch.view_as_complex(hw_part.to(torch.float64).unflatten(-1, (-1, 2)))
+ out_hw = torch.view_as_real(x_hw * hw_freqs).flatten(-2, -1)
+ return torch.cat([t_part, out_hw.type_as(hidden_states)], dim=-1)
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+ # B L D --> B L H D -> B H L D
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+ # t_dim不做rope!!
+ query = apply_rotary_emb_split(query, rotary_emb, t_dim)
+ key = apply_rotary_emb_split(key, rotary_emb,t_dim)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = self.attn_fn(
+ query, key_img, value_img, None
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ # self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ hidden_states: torch.Tensor,
+ # encoder_hidden_states: torch.Tensor,
+ # encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ # encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ # if encoder_hidden_states_image is not None:
+ # encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+ # print(t_dim, h_dim, w_dim)
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+# Text Free
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ # self.attn2 = Attention(
+ # query_dim=dim,
+ # heads=num_heads,
+ # kv_heads=num_heads,
+ # dim_head=dim // num_heads,
+ # qk_norm=qk_norm,
+ # eps=eps,
+ # bias=True,
+ # cross_attention_dim=None,
+ # out_bias=True,
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ # processor=WanAttnProcessor2_0(),
+ # )
+ # self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ # encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+ # text free
+ # 2. Cross-attention
+ # norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ # attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ # hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanRefextractor(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ self.ref_blocks = nn.ModuleList([])
+
+ for _ in range(len(self.blocks)+1):
+ self.ref_blocks.append(zero_module(nn.Linear(inner_dim, inner_dim)))
+
+ # 4. Output norm & projection
+ # self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ # self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ # self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ major, minor = get_torch_cuda_version()
+ ckpt_kwargs = {"use_reentrant": (major > 12) or (major == 12 and minor >= 2)}
+ def _gradient_checkpointing_func(module, *args):
+
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+ print(f"Set gradient checkpointing: ckpt_kwargs={ckpt_kwargs} (CUDA {major}.{minor})")
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ # encoder_hidden_states: torch.Tensor,
+ # encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = False,
+ ref_pose_cond = None,
+ add_pose = False,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ assert num_frames == 1
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # if ref_pose_cond is not None and add_pose:
+ # hidden_states = hidden_states + ref_pose_cond
+
+ # temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ # timestep, encoder_hidden_states, encoder_hidden_states_image
+ # )
+ # use hidden_states for type
+ temb, timestep_proj = self.condition_embedder(timestep,hidden_states)
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ # if encoder_hidden_states_image is not None:
+ # encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ block_samples = ()
+ for block in self.blocks:
+ block_samples = block_samples + (hidden_states, )
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, timestep_proj, rotary_emb)
+ block_samples = block_samples + (hidden_states, )
+
+
+ ref_block_samples = ()
+ assert len(block_samples) == len(self.ref_blocks), \
+ f"Length mismatch: block_samples has length {len(block_samples)}, ref_blocks has length {len(self.ref_blocks)}"
+
+ for block_sample, ref_block in zip(block_samples, self.ref_blocks):
+ block_sample = ref_block(block_sample)
+ ref_block_samples = ref_block_samples + (block_sample, )
+
+ return ref_block_samples, rotary_emb
+ # # 5. Output norm, projection & unpatchify
+ # shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # # Move the shift and scale tensors to the same device as hidden_states.
+ # # When using multi-GPU inference via accelerate these will be on the
+ # # first device rather than the last device, which hidden_states ends up
+ # # on.
+ # shift = shift.to(hidden_states.device)
+ # scale = scale.to(hidden_states.device)
+
+ # hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ # hidden_states = self.proj_out(hidden_states)
+
+ # hidden_states = hidden_states.reshape(
+ # batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ # )
+ # hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ # output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ # if USE_PEFT_BACKEND:
+ # # remove `lora_scale` from each PEFT layer
+ # unscale_lora_layers(self, lora_scale)
+
+ # if not return_dict:
+ # return (output,)
+
+ # return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan.py
new file mode 100644
index 0000000000000000000000000000000000000000..08817f5116feb5597b09aaabd21fb382f6862ae4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan.py
@@ -0,0 +1,483 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("WanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = F.scaled_dot_product_attention(
+ query, key_img, value_img, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ controlnet_cond=None,
+ conditioning_scale = 0,
+ controlnet_blocks_repeat = False,
+ token_replace = False,
+ image_pose = None,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ for block in self.blocks:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ for block in self.blocks:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_controlnet.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..154c26be735c8a29c84179f54196c51a63f6438a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_controlnet.py
@@ -0,0 +1,503 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("WanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = F.scaled_dot_product_attention(
+ query, key_img, value_img, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import WanControlNet
+ self.controlnet = WanControlNet.from_config(controlnet_config).to(weight_dtype)
+
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ controlnet_block_samples = None
+ if conditioning_scale > 0:
+ controlnet_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ controlnet_cond = controlnet_cond,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_hidden_states_image = encoder_hidden_states_image,
+ return_dict = False,
+ attention_kwargs = attention_kwargs,
+ )
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ interval_control = len(self.blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+
+ for index_block, block in enumerate(self.blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ if controlnet_block_samples is not None:
+ if controlnet_blocks_repeat:
+ # 12345 12345 12345 12345 ....
+ hidden_states = (
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ # 00000 11111 22222 33333 ....
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
+
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_pose.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_pose.py
new file mode 100644
index 0000000000000000000000000000000000000000..15e4a09dcc97187c4a46f4247fb44b7fce35ca71
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_pose.py
@@ -0,0 +1,556 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from .utils import ckpt_kwargs
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class WanAttnProcessor2_0:
+
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(
+ q, k, v, flash_attn3_func
+ )
+ print("[INFO] Wan: Using FlashAttention-3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import (
+ flash_attn_func as flash_attn2_func,
+ )
+
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(
+ q, k, v, flash_attn2_func
+ )
+ print("[INFO] Wan: Using FlashAttention-2")
+ except ImportError:
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError(
+ "Requires PyTorch≥2.0 or Flash-Attention. Please upgrade."
+ )
+ self.attn_backend = "torch"
+ self.attn_fn = (
+ lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q,
+ k,
+ v,
+ attn_mask=mask,
+ dropout_p=0.0,
+ is_causal=False,
+ )
+ )
+ print("[INFO] Wan: Using torch.scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Flash-Attention shape:[B,H,L,D] ↔ [B,L,H,D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False)
+ if isinstance(out, tuple): # flash-attn-3 returns (attn, logsumexp)
+ out = out[0]
+ return out.transpose(1, 2)
+
+ # ---------------------------------------------------------------------
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ # [B, L, D] -> [B, H, L, Dh]
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # Optional image (I2V)
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = self.attn_fn(query, key_img, value_img, None)
+ hidden_states_img = (
+ hidden_states_img.transpose(1, 2).flatten(2, 3).type_as(query)
+ )
+
+ hidden_states = self.attn_fn(query, key, value, attention_mask)
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3).type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ # Output proj + dropout
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.inner_dim = inner_dim
+ self.in_channels = in_channels
+
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+ self.add_pose = False
+
+ def set_up_pose(self, weight_dtype):
+ self.add_pose = True
+ print("============set_up_pose============")
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = self.inner_dim, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block = 1,
+ spatial_compression_ratio=16
+ )
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ if conditioning_scale == 0:
+ # zero3 train bug
+ controlnet_cond = self.input_hint_block(controlnet_cond)*0
+ else:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ hidden_states = hidden_states + controlnet_cond
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ for block in self.blocks:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ for block in self.blocks:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor.py
new file mode 100644
index 0000000000000000000000000000000000000000..403ba487239f480a204b0572de411cc5aa60225a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor.py
@@ -0,0 +1,557 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("FusedWanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d 情况
+ if hidden_states.shape[1] != ref_latent.shape[1]:
+ L_ref = ref_latent.shape[1]
+ t = hidden_states.shape[1] // ref_latent.shape[1] # Time multiplier
+ B, H, _, D = query.shape # Original query shape: [B, H, t*h*w, D//H]
+ query_ref = rearrange(query, 'B H (t L_ref) D -> (B t) H L_ref D', t=t, L_ref=L_ref)
+ # query_ref = query.reshape(B, H, t, -1, D).transpose(1, 2)
+ # query_ref = query_ref.reshape(B * t, H, -1, D)
+ key_ref = key_ref.unsqueeze(1).repeat(1, t, 1, 1, 1).view(B * t, H, -1, D)
+ value_ref = value_ref.unsqueeze(1).repeat(1, t, 1, 1, 1).view(B * t, H, -1, D)
+ else:
+ query_ref = query
+
+ query_ref = apply_rotary_emb(query_ref, ref_rotary_emb)
+ key_ref = apply_rotary_emb(key_ref, ref_rotary_emb)
+
+ ref_hidden_states = F.scaled_dot_product_attention(
+ query_ref, key_ref, value_ref, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+ if hidden_states.shape[1] != ref_latent.shape[1]:
+ ref_hidden_states = ref_hidden_states.reshape(B, t, H, -1, D).transpose(2, 3) # [B, t, h*w, H, D//H]
+ ref_hidden_states = ref_hidden_states.reshape(B, t * ref_latent.shape[1], H * D) #
+ else:
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query_3d, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+ from .refextractor import WanRefextractor
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ #向上取整
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..47a5de8580162028c89bc0cd75b9b2229aebdc5c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d.py
@@ -0,0 +1,588 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+
+ query_ref = apply_rotary_emb_split(query, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=False,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ image_pose = None,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_controlnet_last_prefix.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_controlnet_last_prefix.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f2e9e711e9e46fcf46fbc9a648a4b6729414d17
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_controlnet_last_prefix.py
@@ -0,0 +1,783 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder, MiniEncoder2D
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+def apply_mod(x, scale, shift):
+ return x * (1 + scale) + shift
+
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+
+ query_ref = apply_rotary_emb_split(query, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ t_token_replace = None
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ if t_token_replace is not None:
+ t_token_replace = self.timesteps_proj(t_token_replace).to(dtype=timestep.dtype)
+ temb_token_replace = self.time_embedder(t_token_replace).type_as(encoder_hidden_states)
+ timestep_proj_token_replace = self.time_proj(self.act_fn(temb_token_replace))
+ else:
+ temb_token_replace = None
+ timestep_proj_token_replace = None
+
+
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ drop_cross_attn = False
+ ):
+ super().__init__()
+ self.drop_cross_attn = drop_cross_attn
+
+ # 1. Self-attention
+
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=False,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ if not drop_cross_attn:
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ timestep_proj_token_replace = None,
+ replace_token_num = None,
+ token_replace_start =None,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ if timestep_proj_token_replace is not None and replace_token_num is not None:
+ tr_shift_msa, tr_scale_msa, tr_gate_msa, \
+ tr_c_shift_msa, tr_c_scale_msa, tr_c_gate_msa = (
+ self.scale_shift_table + timestep_proj_token_replace.float()
+ ).chunk(6, dim=1) # 同样 (B, 1, D)
+ use_token_replace = True
+ else:
+ use_token_replace = False
+
+ # L0 = replace_token_num or 0
+ start = token_replace_start or 0
+ end = start + (replace_token_num or 0)
+
+ # 1. Self-attention
+ norm_h = self.norm1(hidden_states.float()) # (B, L, D)
+ if use_token_replace:
+ norm_hidden_states = torch.cat([
+ apply_mod(norm_h[:, :start], scale_msa, shift_msa), # cond/前段 → T
+ apply_mod(norm_h[:, start:end], tr_scale_msa, tr_shift_msa), # replace段 → t=0
+ apply_mod(norm_h[:, end:], scale_msa, shift_msa) # 剩余 → T
+ ], dim=1).type_as(hidden_states)
+ else:
+ norm_hidden_states = apply_mod(norm_h, scale_msa, shift_msa).type_as(hidden_states)
+
+
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ if use_token_replace:
+ hidden_states = torch.cat([
+ hidden_states.float()[:, :start] + attn_output[:, :start] * gate_msa,
+ hidden_states.float()[:, start:end] + attn_output[:, start:end] * tr_gate_msa,
+ hidden_states.float()[:, end:] + attn_output[:, end:] * gate_msa
+ ], dim=1).type_as(hidden_states)
+ else:
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+ # hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ if not self.drop_cross_attn:
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_h = self.norm3(hidden_states.float()) # (B, L, D)
+ if use_token_replace:
+ norm_hidden_states = torch.cat([
+ apply_mod(norm_h[:, :start], c_scale_msa, c_shift_msa),
+ apply_mod(norm_h[:, start:end], tr_c_scale_msa, tr_c_shift_msa),
+ apply_mod(norm_h[:, end:], c_scale_msa, c_shift_msa)
+ ], dim=1).type_as(hidden_states)
+ else:
+ norm_hidden_states = apply_mod(norm_h, c_scale_msa, c_shift_msa).type_as(hidden_states)
+
+ ff_output = self.ffn(norm_hidden_states)
+ if use_token_replace:
+
+ hidden_states = torch.cat([
+ hidden_states.float()[:, :start] + ff_output[:, :start] * c_gate_msa,
+ hidden_states.float()[:, start:end] + ff_output[:, start:end] * tr_c_gate_msa,
+ hidden_states.float()[:, end:] + ff_output[:, end:] * c_gate_msa
+ ], dim=1).type_as(hidden_states)
+
+ else:
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.inner_dim = inner_dim
+ self.in_channels = in_channels
+
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+ self.add_pose = False
+
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ # pose resnet + self attention block
+ import json
+ with open(controlnet_config, "r") as f:
+ cfg = json.load(f)
+
+ inner_dim = cfg.get("inner_dim", self.inner_dim)
+ ffn_dim = cfg.get("ffn_dim", 13824)
+ num_attention_heads = cfg.get("num_attention_heads", 40)
+ qk_norm = cfg.get("qk_norm", "rms_norm_across_heads")
+ cross_attn_norm = cfg.get("cross_attn_norm", True)
+ eps = cfg.get("eps", 1e-6)
+ num_layers = cfg.get("num_layers", 4)
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels=3,
+ out_channels=self.inner_dim,
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups=4,
+ layers_per_block=1,
+ spatial_compression_ratio=16
+ )
+
+ self.controlnet = nn.Module()
+ self.controlnet.blocks = nn.ModuleList([
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim=None, drop_cross_attn=True
+ ) for _ in range(num_layers)
+ ])
+ self.controlnet_zero = nn.ModuleList([
+ zero_module(nn.Linear(inner_dim, inner_dim))
+ for _ in range(num_layers)
+ ])
+ self.add_pose = True
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.image_to_cond = MiniEncoder2D(
+ in_channels = config["in_channels"],
+ out_channels = self.in_channels,
+ down_block_types= ("DownEncoderBlockInflated","DownEncoderBlockInflated","DownEncoderBlockInflated"),
+ block_out_channels=(16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block = 1,
+ spatial_compression_ratio=1
+ )
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ image_pose = None,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+ image_prefix = self.image_to_cond(image_latents)[0]
+ hidden_states = torch.concat([image_prefix,hidden_states],dim=2)
+
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False,
+ # ref_pose_cond = ref_pose_cond
+ # 目前不会用到的txt部分
+ )
+
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ if controlnet_cond is not None and self.add_pose:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ controlnet_cond_prefix = self.input_hint_block(image_pose)
+ controlnet_cond = torch.concat([controlnet_cond_prefix,controlnet_cond],dim=2)
+
+ controlnet_tokens = controlnet_cond.flatten(2).transpose(1, 2)
+
+
+ if token_replace:
+ t_token_replace = torch.zeros_like(timestep)
+ # 5 frames -> VAE -> 2 frames
+ # start: 1 frame
+ token_replace_start = post_patch_height * post_patch_width
+ replace_token_num = 2 * post_patch_height * post_patch_width
+ else:
+ token_replace_start = None
+ t_token_replace = None
+ replace_token_num = None
+
+
+ temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image, t_token_replace
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+ if timestep_proj_token_replace is not None:
+ timestep_proj_token_replace = timestep_proj_token_replace.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ control_inject_layers = len(self.controlnet.blocks) if self.add_pose else 0
+ num_main_blocks = len(self.blocks)
+ prev_main = None
+ prev_control = None
+
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ # ===== Main Branch =====
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda( block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num, token_replace_start)
+ else:
+ hidden_states = block( hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num, token_replace_start)
+ # ===== ControlNet Branch=====
+ if self.add_pose and prev_main is not None and (index_block - 1) < control_inject_layers:
+ if index_block == 1:
+ ctrl_in = prev_main + controlnet_tokens
+
+ elif prev_control is not None:
+ ctrl_in = prev_control
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ control_out = self._gradient_checkpointing_func_cuda(self.controlnet.blocks[index_block - 1], ctrl_in, encoder_hidden_states, timestep_proj, rotary_emb, None, None, timestep_proj_token_replace, replace_token_num, token_replace_start)
+ else:
+ control_out = self.controlnet.blocks[index_block - 1](
+ ctrl_in, encoder_hidden_states, timestep_proj, rotary_emb,
+ None, None,
+ timestep_proj_token_replace, replace_token_num,token_replace_start
+ )
+ prev_control = control_out
+
+ control_out_proj = self.controlnet_zero[index_block - 1](control_out)
+ hidden_states = hidden_states + control_out_proj * conditioning_scale
+
+ prev_main = hidden_states
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ if temb_token_replace is not None and replace_token_num is not None:
+ shift_tr, scale_tr = (
+ self.scale_shift_table + temb_token_replace.unsqueeze(1)
+ ).chunk(2, dim=1)
+ shift_tr = shift_tr.to(hidden_states.device)
+ scale_tr = scale_tr.to(hidden_states.device)
+ use_token_replace = True
+ else:
+ use_token_replace = False
+
+ normed = self.norm_out(hidden_states.float())
+ if use_token_replace:
+ start = token_replace_start
+ end = start + replace_token_num
+ normed = torch.cat([
+ apply_mod(normed[:, :start], scale, shift),
+ apply_mod(normed[:, start:end], scale_tr, shift_tr),
+ apply_mod(normed[:, end:], scale, shift)
+ ], dim=1)
+ else:
+ normed = normed * (1 + scale) + shift
+ # hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(normed.type_as(hidden_states))
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+ output = output[:, :, 1:, :, :]
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose.py
new file mode 100644
index 0000000000000000000000000000000000000000..c27fde32c5522cf7b672ab7786be031cc4c93a94
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose.py
@@ -0,0 +1,623 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+
+ query_ref = apply_rotary_emb_split(query, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=False,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.inner_dim = inner_dim
+ self.in_channels = in_channels
+
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+ self.add_pose = False
+
+
+ def set_up_pose(self, weight_dtype):
+ self.add_pose = True
+ print("============set_up_pose============")
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = self.inner_dim, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block = 1,
+ spatial_compression_ratio=16
+ )
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ # import pdb; pdb.set_trace()
+ # assert conditioning_scale == 1
+ if conditioning_scale == 0:
+ # zero3 train bug
+ controlnet_cond = self.input_hint_block(controlnet_cond)*0
+ else:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ hidden_states = hidden_states + controlnet_cond
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # ============== add control here ===============
+
+
+ # else: #self.add_pose == False
+ # pass
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ #向上取整
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose_last.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose_last.py
new file mode 100644
index 0000000000000000000000000000000000000000..73e691fdff4de07dc67fbb9f89ddcd5b57856946
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_pose_last.py
@@ -0,0 +1,709 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+
+ query_ref = apply_rotary_emb_split(query, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ t_token_replace = None
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ if t_token_replace is not None:
+ t_token_replace = self.timesteps_proj(t_token_replace).to(dtype=timestep.dtype)
+ temb_token_replace = self.time_embedder(t_token_replace).type_as(encoder_hidden_states)
+ timestep_proj_token_replace = self.time_proj(self.act_fn(temb_token_replace))
+ else:
+ temb_token_replace = None
+ timestep_proj_token_replace = None
+
+
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=False,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ timestep_proj_token_replace = None,
+ replace_token_num = None,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ if timestep_proj_token_replace is not None and replace_token_num is not None:
+ tr_shift_msa, tr_scale_msa, tr_gate_msa, \
+ tr_c_shift_msa, tr_c_scale_msa, tr_c_gate_msa = (
+ self.scale_shift_table + timestep_proj_token_replace.float()
+ ).chunk(6, dim=1) # 同样 (B, 1, D)
+ use_token_replace = True
+ else:
+ use_token_replace = False
+
+ L0 = replace_token_num or 0
+
+ # 1. Self-attention
+ norm_h = self.norm1(hidden_states.float()) # (B, L, D)
+ if use_token_replace:
+ h_zero = norm_h[:, :L0] * (1 + tr_scale_msa) + tr_shift_msa
+ h_other = norm_h[:, L0:] * (1 + scale_msa) + shift_msa
+ norm_hidden_states = torch.cat([h_zero, h_other], dim=1).type_as(hidden_states)
+ else:
+ norm_hidden_states = (norm_h * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ # norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ if use_token_replace:
+ h_zero = hidden_states.float()[:, :L0] + attn_output[:, :L0] * tr_gate_msa
+ h_other = hidden_states.float()[:, L0:] + attn_output[:, L0:] * gate_msa
+ hidden_states = torch.cat([h_zero, h_other], dim=1).type_as(hidden_states)
+ else:
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+ # hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_h = self.norm3(hidden_states.float()) # (B, L, D)
+ if use_token_replace:
+ h_zero = norm_h[:, :L0] * (1 + tr_c_scale_msa) + tr_c_shift_msa
+ h_other = norm_h[:, L0:] * (1 + c_scale_msa) + c_shift_msa
+ norm_hidden_states = torch.cat([h_zero, h_other], dim=1).type_as(hidden_states)
+ else:
+ norm_hidden_states = (norm_h * (1 + c_scale_msa) + c_shift_msa).type_as(hidden_states)
+ # norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ # hidden_states
+ # )
+ ff_output = self.ffn(norm_hidden_states)
+ if use_token_replace:
+ h_zero = hidden_states.float()[:, :L0] + ff_output[:, :L0] * tr_c_gate_msa
+ h_other = hidden_states.float()[:, L0:] + ff_output[:, L0:] * c_gate_msa
+ hidden_states = torch.cat([h_zero, h_other], dim=1).type_as(hidden_states)
+ else:
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+ # hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.inner_dim = inner_dim
+ self.in_channels = in_channels
+
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+ self.add_pose = False
+
+
+ def set_up_pose(self, weight_dtype):
+ self.add_pose = True
+ print("============set_up_pose============")
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = self.inner_dim, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block = 1,
+ spatial_compression_ratio=16
+ )
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ image_pose = None,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ token_replace = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ # if image_pose is not None:
+ # ref_pose_cond = self.input_hint_block(image_pose)
+ # else:
+ # ref_pose_cond = None
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False,
+ # ref_pose_cond = ref_pose_cond
+ # 目前不会用到的txt部分
+ )
+
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+
+ # import pdb; pdb.set_trace()
+ # assert conditioning_scale == 1
+ if self.add_pose:
+ if conditioning_scale == 0:
+ # zero3 train bug, must use input_hint_block
+ controlnet_cond = self.input_hint_block(controlnet_cond)*0
+ else:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ hidden_states = hidden_states + controlnet_cond
+
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ # ============== add control here ===============
+
+
+ # else: #self.add_pose == False
+ # pass
+
+ if token_replace:
+ t_token_replace = torch.zeros_like(timestep)
+ # 5 frames -> VAE -> 2 frames
+ replace_token_num = 2 * post_patch_height * post_patch_width
+ else:
+ t_token_replace = None
+ replace_token_num = None
+
+
+ temb, timestep_proj, temb_token_replace, timestep_proj_token_replace, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image, t_token_replace
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+ if timestep_proj_token_replace is not None:
+ timestep_proj_token_replace = timestep_proj_token_replace.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ #向上取整
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb, timestep_proj_token_replace, replace_token_num)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ if temb_token_replace is not None and replace_token_num is not None:
+ shift_tr, scale_tr = (
+ self.scale_shift_table + temb_token_replace.unsqueeze(1)
+ ).chunk(2, dim=1)
+ shift_tr = shift_tr.to(hidden_states.device)
+ scale_tr = scale_tr.to(hidden_states.device)
+ use_token_replace = True
+ else:
+ use_token_replace = False
+ L0 = replace_token_num or 0
+
+ normed = self.norm_out(hidden_states.float())
+ if use_token_replace:
+ out_zero = normed[:, :L0] * (1 + scale_tr) + shift_tr
+ # 其余 token 用当前 t 的调制
+ out_other = normed[:, L0:] * (1 + scale) + shift
+ normed = torch.cat([out_zero, out_other], dim=1)
+ else:
+ normed = normed * (1 + scale) + shift
+ # hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(normed.type_as(hidden_states))
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f0ebe049ac67803642d84662f08f4900f8dcd41
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q.py
@@ -0,0 +1,662 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from diffusers.utils import is_torch_version
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ # query是rotary_emb
+ # update query_ref
+ query_ref = attn.fuser_q(hidden_states)
+ query_ref = attn.fuser_norm_q(query_ref)
+ query_ref = query_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ query_ref = apply_rotary_emb_split(query_ref, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def _gradient_checkpointing_func(module, *args):
+
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import WanControlNet
+ self.controlnet = WanControlNet.from_config(controlnet_config).to(weight_dtype)
+
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def load_state_dict(self, state_dict, strict=True):
+ # 直接加载
+
+ if any("fuser_q" in key for key in state_dict.keys()):
+ super().load_state_dict(state_dict, strict=strict)
+ return
+ # 加载原来的ckpt
+ new_state_dict = dict() # 获取当前模型的状态字典
+ for key in state_dict.keys():
+ new_state_dict[key] = state_dict[key]
+
+ if "to_q" in key:
+ # init : to_q -> fuser_q
+ init_key = key.replace("to_q", "fuser_q")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+
+ elif "norm_q" in key:
+ init_key = key.replace("norm_q", "fuser_norm_q")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+
+ return super().load_state_dict(new_state_dict, strict=strict)
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+ if conditioning_scale == 0:
+ if torch.is_grad_enabled():
+ controlnet_block_samples = self.controlnet(
+ hidden_states=hidden_states,
+ controlnet_cond=controlnet_cond,
+ timestep=timestep,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_hidden_states_image=encoder_hidden_states_image,
+ return_dict=False,
+ attention_kwargs=attention_kwargs,
+ )
+ controlnet_block_samples = [x * 0 for x in controlnet_block_samples]
+ else:
+ controlnet_block_samples = None
+ else:
+ controlnet_block_samples = self.controlnet(
+ hidden_states=hidden_states,
+ controlnet_cond=controlnet_cond,
+ timestep=timestep,
+ encoder_hidden_states=encoder_hidden_states,
+ encoder_hidden_states_image=encoder_hidden_states_image,
+ return_dict=False,
+ attention_kwargs=attention_kwargs,
+ )
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ #向上取整
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb)
+
+ if controlnet_block_samples is not None:
+ interval_control = len(self.blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+ if controlnet_blocks_repeat:
+ # 12345 12345 12345 12345 ....
+ hidden_states = (
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ # 00000 11111 22222 33333 ....
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
+
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q_pose.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q_pose.py
new file mode 100644
index 0000000000000000000000000000000000000000..e04c2e0f690728165ff163e809217d8fe3632fcc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_2d_split_q_pose.py
@@ -0,0 +1,682 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+import re
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+from einops import rearrange
+from .refextractor_2d import WanRefextractor, apply_rotary_emb_split
+from opensora.controlnet_modules.controlnet import zero_module, MiniHunyuanEncoder
+from .utils import ckpt_kwargs
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+
+
+class FusedWanAttnProcessor2_0:
+ def __init__(self):
+ self.attn_fn = None
+ try:
+ from flash_attn_interface import flash_attn_func as flash_attn3_func
+ self.attn_backend = "flash-attn-3"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn3_func)
+ print("[INFO] Using FlashAttention 3")
+ except ImportError:
+ try:
+ from flash_attn.flash_attn_interface import flash_attn_func as flash_attn2_func
+ self.attn_backend = "flash-attn-2"
+ self.attn_fn = lambda q, k, v, mask: self._flash_attn_wrapper(q, k, v, flash_attn2_func)
+ print("[INFO] Using FlashAttention 2")
+ except ImportError:
+ import torch.nn.functional as F
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("Requires PyTorch 2.0 or FlashAttention.")
+ self.attn_backend = "torch"
+ self.attn_fn = lambda q, k, v, mask: F.scaled_dot_product_attention(
+ q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False
+ )
+ print("[INFO] Using PyTorch scaled_dot_product_attention")
+
+ def _flash_attn_wrapper(self, q, k, v, flash_func):
+ # Input: [B, H, L, D] → [B, L, H, D]
+ q, k, v = q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2)
+ out = flash_func(
+ q, k, v, softmax_scale=q.shape[-1] ** -0.5, causal=False
+ )
+ # FlashAttention-3 returns (attn, logsumexp), FlashAttention-2 returns attn
+ if isinstance(out, tuple):
+ out = out[0]
+ return out.transpose(1, 2) # Return to [B, H, L, D]
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ref_latent: Optional[torch.Tensor] = None,
+ ref_rotary_emb = None,
+ ) -> torch.Tensor:
+ # encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ assert ref_latent is not None, "use add_k_proj, so ref_latent can't be None"
+ # encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ # encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query_3d = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+ else:
+ query_3d = query
+
+ # ref
+ ref_hidden_states = None
+ if ref_latent is not None:
+ key_ref = attn.add_k_proj(ref_latent)
+ key_ref = attn.norm_added_k(key_ref)
+ value_ref = attn.add_v_proj(ref_latent)
+
+ key_ref = key_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_ref = value_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ # 2d
+ attention_head_dim = 128
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ # query是rotary_emb
+ # update query_ref
+ query_ref = attn.fuser_q(hidden_states)
+ query_ref = attn.fuser_norm_q(query_ref)
+ query_ref = query_ref.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ query_ref = apply_rotary_emb_split(query_ref, rotary_emb, t_dim)
+ key_ref = apply_rotary_emb_split(key_ref, ref_rotary_emb,t_dim)
+
+ ref_hidden_states = self.attn_fn(
+ query_ref, key_ref, value_ref, None
+ )
+
+ ref_hidden_states = ref_hidden_states.transpose(1, 2).flatten(2, 3)
+ ref_hidden_states = ref_hidden_states.type_as(query)
+
+ hidden_states = self.attn_fn(
+ query_3d, key, value, attention_mask
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if ref_hidden_states is not None:
+ hidden_states = hidden_states + ref_hidden_states
+
+ # linear projection
+ hidden_states = attn.to_out[0](hidden_states)
+ # drop out
+ hidden_states = attn.to_out[1](hidden_states)
+
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ add_fuser_q=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ # remove image part
+ # added_kv_proj_dim=added_kv_proj_dim,
+ # added_proj_bias=True,
+ processor=FusedWanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ref_latent: torch.Tensor,
+ ref_rotary_emb,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb, ref_latent=ref_latent, ref_rotary_emb=ref_rotary_emb)
+
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ self.inner_dim = inner_dim
+ self.in_channels = in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, inner_dim # 这里本来是added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+ self.add_pose = False
+
+ def _gradient_checkpointing_func(module, *args):
+
+ return torch.utils.checkpoint.checkpoint(
+ module.__call__,
+ *args,
+ **ckpt_kwargs,
+ )
+
+ self._gradient_checkpointing_func_cuda = _gradient_checkpointing_func
+
+
+
+
+ def set_up_pose(self, weight_dtype):
+ self.add_pose = True
+
+ self.input_hint_block = MiniHunyuanEncoder(
+ in_channels = 3, #一般肯定是3
+ out_channels = self.in_channels // 2, #一般情况下,和self.out_channels一致,这里主要是考虑可能用不同的patch_embedding方案
+ block_out_channels=(16, 16, 16, 16),
+ norm_num_groups = 4,
+ layers_per_block=1
+ )
+ self.controlnet_x_embedder = zero_module(torch.nn.Linear(self.in_channels * 2, self.inner_dim))
+
+
+
+
+ def set_up_refextractor(self, refextractor_config, weight_dtype):
+
+ self.refextractor = WanRefextractor.from_config(refextractor_config).to(weight_dtype)
+ import json
+ with open(refextractor_config, "r") as f:
+ config = json.load(f)
+ self.ref_repeat = config.get("ref_repeat", True)
+ print("self.ref_repeat",self.ref_repeat)
+
+ # use added_kv_proj_dim and added_kv_proj_dim==inner_dim
+
+
+ def load_state_dict(self, state_dict, strict=True):
+ # 直接加载
+
+ if "fuser_q" in state_dict.keys():
+ print("fuser_q in state_dict.keys()")
+ return super().load_state_dict(state_dict, strict=strict)
+
+ # 加载原来的ckpt
+ new_state_dict = dict() # 获取当前模型的状态字典
+ for key in state_dict.keys():
+ new_state_dict[key] = state_dict[key]
+
+ if "to_q" in key:
+ # init : to_q -> fuser_q
+ init_key = key.replace("to_q", "fuser_q")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+ elif "norm_q" in key:
+ init_key = key.replace("norm_q", "fuser_norm_q")
+ if init_key in self.state_dict().keys():
+ new_state_dict[init_key] = state_dict[key]
+
+
+ return super().load_state_dict(new_state_dict, strict=strict)
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ image_latents = None,# ref -> VAE
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ controlnet_cond=None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+
+ # encoder_hidden_states_image must be None
+ assert encoder_hidden_states_image is None
+
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ # repeat image_latents
+
+ if self.ref_repeat:
+ if image_latents.shape[2] == 1:
+ image_latents = image_latents.repeat(1, 1, num_frames, 1, 1)
+ elif image_latents.shape[2] == num_frames:
+ pass
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+ else:
+ if image_latents.shape[2] == 1:
+ pass
+ elif image_latents.shape[2] == num_frames:
+ image_latents = image_latents[:, :, :1,]
+ else:
+ raise ValueError("image_latents.shape[2] must be 1 or ot")
+
+ # get ref_block_samples
+ ref_block_samples, ref_rotary_emb = self.refextractor(
+ hidden_states = image_latents,
+ timestep = timestep,
+ return_dict = False
+ # 目前不会用到的txt部分
+ )
+
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ assert not (conditioning_scale == 1 and self.add_pose is False), \
+ "Invalid configuration: conditioning_scale == 1 requires self.add_pose == True"
+
+ if conditioning_scale == 0 and self.add_pose:
+ if torch.is_grad_enabled():
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ batch_size_c, channels_c, num_frames_c, height_c, width_c = controlnet_cond.shape
+ height_c = height_c // p_h
+ width_c = width_c // p_w
+ num_frames_c = num_frames_c // p_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels_c, num_frames_c, p_t, height_c, p_h, width_c, p_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, num_frames_c * height_c * width_c, -1)
+
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond) * 0
+ else:
+ pass
+ elif conditioning_scale == 1 and self.add_pose:
+ controlnet_cond = self.input_hint_block(controlnet_cond)
+ batch_size_c, channels_c, num_frames_c, height_c, width_c = controlnet_cond.shape
+ height_c = height_c // p_h
+ width_c = width_c // p_w
+ num_frames_c = num_frames_c // p_t
+ controlnet_cond = controlnet_cond.reshape(
+ batch_size, channels_c, num_frames_c, p_t, height_c, p_h, width_c, p_w
+ )
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 6, 1, 3, 5, 7)
+ controlnet_cond = controlnet_cond.reshape(batch_size, num_frames_c * height_c * width_c, -1)
+ # ============== add control here ===============
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
+
+ else: #self.add_pose == False
+ pass
+
+
+
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+
+ for index_block, block in enumerate(self.blocks):
+ ref_latent = None
+ if ref_block_samples is not None:
+ interval_ref = len(self.blocks) / len(ref_block_samples)
+ #向上取整
+ interval_ref = int(np.ceil(interval_ref))
+ ref_latent = ref_block_samples[index_block // interval_ref]
+
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func_cuda(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb, ref_latent, ref_rotary_emb)
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_controlnet.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_controlnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..154c26be735c8a29c84179f54196c51a63f6438a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/transformer_wan_refextractor_controlnet.py
@@ -0,0 +1,503 @@
+# Copyright 2025 The Wan Team and The HuggingFace Team. All rights reserved.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import math
+from typing import Any, Dict, Optional, Tuple, Union
+import numpy as np
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from diffusers import ModelMixin
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.loaders import FromOriginalModelMixin, PeftAdapterMixin
+from diffusers.utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
+
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from .attention_processor import Attention
+from .normalization import FP32LayerNorm
+from .attention import FeedForward
+from .embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
+
+logger = logging.get_logger(__name__) # pylint: disable=invalid-name
+
+
+class WanAttnProcessor2_0:
+ def __init__(self):
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("WanAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ rotary_emb: Optional[torch.Tensor] = None,
+ ) -> torch.Tensor:
+ encoder_hidden_states_img = None
+ if attn.add_k_proj is not None:
+ encoder_hidden_states_img = encoder_hidden_states[:, :257]
+ encoder_hidden_states = encoder_hidden_states[:, 257:]
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+
+ query = attn.to_q(hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ if attn.norm_q is not None:
+ query = attn.norm_q(query)
+ if attn.norm_k is not None:
+ key = attn.norm_k(key)
+
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ if rotary_emb is not None:
+
+ def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
+ x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
+ x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
+ return x_out.type_as(hidden_states)
+
+ query = apply_rotary_emb(query, rotary_emb)
+ key = apply_rotary_emb(key, rotary_emb)
+
+ # I2V task
+ hidden_states_img = None
+ if encoder_hidden_states_img is not None:
+ key_img = attn.add_k_proj(encoder_hidden_states_img)
+ key_img = attn.norm_added_k(key_img)
+ value_img = attn.add_v_proj(encoder_hidden_states_img)
+
+ key_img = key_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+ value_img = value_img.unflatten(2, (attn.heads, -1)).transpose(1, 2)
+
+ hidden_states_img = F.scaled_dot_product_attention(
+ query, key_img, value_img, attn_mask=None, dropout_p=0.0, is_causal=False
+ )
+ hidden_states_img = hidden_states_img.transpose(1, 2).flatten(2, 3)
+ hidden_states_img = hidden_states_img.type_as(query)
+
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
+ hidden_states = hidden_states.type_as(query)
+
+ if hidden_states_img is not None:
+ hidden_states = hidden_states + hidden_states_img
+
+ hidden_states = attn.to_out[0](hidden_states)
+ hidden_states = attn.to_out[1](hidden_states)
+ return hidden_states
+
+
+class WanImageEmbedding(torch.nn.Module):
+ def __init__(self, in_features: int, out_features: int):
+ super().__init__()
+
+ self.norm1 = FP32LayerNorm(in_features)
+ self.ff = FeedForward(in_features, out_features, mult=1, activation_fn="gelu")
+ self.norm2 = FP32LayerNorm(out_features)
+
+ def forward(self, encoder_hidden_states_image: torch.Tensor) -> torch.Tensor:
+ hidden_states = self.norm1(encoder_hidden_states_image)
+ hidden_states = self.ff(hidden_states)
+ hidden_states = self.norm2(hidden_states)
+ return hidden_states
+
+
+class WanTimeTextImageEmbedding(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ time_freq_dim: int,
+ time_proj_dim: int,
+ text_embed_dim: int,
+ image_embed_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
+ self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
+ self.act_fn = nn.SiLU()
+ self.time_proj = nn.Linear(dim, time_proj_dim)
+ self.text_embedder = PixArtAlphaTextProjection(text_embed_dim, dim, act_fn="gelu_tanh")
+
+ self.image_embedder = None
+ if image_embed_dim is not None:
+ self.image_embedder = WanImageEmbedding(image_embed_dim, dim)
+
+ def forward(
+ self,
+ timestep: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ ):
+ timestep = self.timesteps_proj(timestep)
+
+ time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
+ if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
+ timestep = timestep.to(time_embedder_dtype)
+ temb = self.time_embedder(timestep).type_as(encoder_hidden_states)
+ timestep_proj = self.time_proj(self.act_fn(temb))
+
+ encoder_hidden_states = self.text_embedder(encoder_hidden_states)
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states_image = self.image_embedder(encoder_hidden_states_image)
+
+ return temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image
+
+
+class WanRotaryPosEmbed(nn.Module):
+ def __init__(
+ self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
+ ):
+ super().__init__()
+
+ self.attention_head_dim = attention_head_dim
+ self.patch_size = patch_size
+ self.max_seq_len = max_seq_len
+
+ h_dim = w_dim = 2 * (attention_head_dim // 6)
+ t_dim = attention_head_dim - h_dim - w_dim
+
+ freqs = []
+ for dim in [t_dim, h_dim, w_dim]:
+ freq = get_1d_rotary_pos_embed(
+ dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
+ )
+ freqs.append(freq)
+ self.freqs = torch.cat(freqs, dim=1)
+
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.patch_size
+ ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
+
+ self.freqs = self.freqs.to(hidden_states.device)
+ freqs = self.freqs.split_with_sizes(
+ [
+ self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
+ self.attention_head_dim // 6,
+ self.attention_head_dim // 6,
+ ],
+ dim=1,
+ )
+
+ freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
+ freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
+ freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
+ return freqs
+
+
+class WanTransformerBlock(nn.Module):
+ def __init__(
+ self,
+ dim: int,
+ ffn_dim: int,
+ num_heads: int,
+ qk_norm: str = "rms_norm_across_heads",
+ cross_attn_norm: bool = False,
+ eps: float = 1e-6,
+ added_kv_proj_dim: Optional[int] = None,
+ ):
+ super().__init__()
+
+ # 1. Self-attention
+ self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+
+ # 2. Cross-attention
+ self.attn2 = Attention(
+ query_dim=dim,
+ heads=num_heads,
+ kv_heads=num_heads,
+ dim_head=dim // num_heads,
+ qk_norm=qk_norm,
+ eps=eps,
+ bias=True,
+ cross_attention_dim=None,
+ out_bias=True,
+ added_kv_proj_dim=added_kv_proj_dim,
+ added_proj_bias=True,
+ processor=WanAttnProcessor2_0(),
+ )
+ self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=True) if cross_attn_norm else nn.Identity()
+
+ # 3. Feed-forward
+ self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
+ self.norm3 = FP32LayerNorm(dim, eps, elementwise_affine=False)
+
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ encoder_hidden_states: torch.Tensor,
+ temb: torch.Tensor,
+ rotary_emb: torch.Tensor,
+ ) -> torch.Tensor:
+ shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
+ self.scale_shift_table + temb.float()
+ ).chunk(6, dim=1)
+
+ # 1. Self-attention
+ norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
+ attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
+ hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
+
+ # 2. Cross-attention
+ norm_hidden_states = self.norm2(hidden_states.float()).type_as(hidden_states)
+ attn_output = self.attn2(hidden_states=norm_hidden_states, encoder_hidden_states=encoder_hidden_states)
+ hidden_states = hidden_states + attn_output
+
+ # 3. Feed-forward
+ norm_hidden_states = (self.norm3(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
+ hidden_states
+ )
+ ff_output = self.ffn(norm_hidden_states)
+ hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
+
+ return hidden_states
+
+
+class WanTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
+ r"""
+ A Transformer model for video-like data used in the Wan model.
+
+ Args:
+ patch_size (`Tuple[int]`, defaults to `(1, 2, 2)`):
+ 3D patch dimensions for video embedding (t_patch, h_patch, w_patch).
+ num_attention_heads (`int`, defaults to `40`):
+ Fixed length for text embeddings.
+ attention_head_dim (`int`, defaults to `128`):
+ The number of channels in each head.
+ in_channels (`int`, defaults to `16`):
+ The number of channels in the input.
+ out_channels (`int`, defaults to `16`):
+ The number of channels in the output.
+ text_dim (`int`, defaults to `512`):
+ Input dimension for text embeddings.
+ freq_dim (`int`, defaults to `256`):
+ Dimension for sinusoidal time embeddings.
+ ffn_dim (`int`, defaults to `13824`):
+ Intermediate dimension in feed-forward network.
+ num_layers (`int`, defaults to `40`):
+ The number of layers of transformer blocks to use.
+ window_size (`Tuple[int]`, defaults to `(-1, -1)`):
+ Window size for local attention (-1 indicates global attention).
+ cross_attn_norm (`bool`, defaults to `True`):
+ Enable cross-attention normalization.
+ qk_norm (`bool`, defaults to `True`):
+ Enable query/key normalization.
+ eps (`float`, defaults to `1e-6`):
+ Epsilon value for normalization layers.
+ add_img_emb (`bool`, defaults to `False`):
+ Whether to use img_emb.
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
+ """
+
+ _supports_gradient_checkpointing = True
+ _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
+ _no_split_modules = ["WanTransformerBlock"]
+ _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2", "norm3"]
+ _keys_to_ignore_on_load_unexpected = ["norm_added_q"]
+
+ @register_to_config
+ def __init__(
+ self,
+ patch_size: Tuple[int] = (1, 2, 2),
+ num_attention_heads: int = 40,
+ attention_head_dim: int = 128,
+ in_channels: int = 16,
+ out_channels: int = 16,
+ text_dim: int = 4096,
+ freq_dim: int = 256,
+ ffn_dim: int = 13824,
+ num_layers: int = 40,
+ cross_attn_norm: bool = True,
+ qk_norm: Optional[str] = "rms_norm_across_heads",
+ eps: float = 1e-6,
+ image_dim: Optional[int] = None,
+ added_kv_proj_dim: Optional[int] = None,
+ rope_max_seq_len: int = 1024,
+ ) -> None:
+ super().__init__()
+
+ inner_dim = num_attention_heads * attention_head_dim
+ out_channels = out_channels or in_channels
+
+ # 1. Patch & position embedding
+ self.rope = WanRotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
+ self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
+
+ # 2. Condition embeddings
+ # image_embedding_dim=1280 for I2V model
+ self.condition_embedder = WanTimeTextImageEmbedding(
+ dim=inner_dim,
+ time_freq_dim=freq_dim,
+ time_proj_dim=inner_dim * 6,
+ text_embed_dim=text_dim,
+ image_embed_dim=image_dim,
+ )
+
+ # 3. Transformer blocks
+ self.blocks = nn.ModuleList(
+ [
+ WanTransformerBlock(
+ inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
+ )
+ for _ in range(num_layers)
+ ]
+ )
+
+ # 4. Output norm & projection
+ self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
+ self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
+ self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
+
+ self.gradient_checkpointing = False
+
+ def set_up_controlnet(self, controlnet_config, weight_dtype):
+ from .controlnet import WanControlNet
+ self.controlnet = WanControlNet.from_config(controlnet_config).to(weight_dtype)
+
+
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ controlnet_cond: torch.Tensor,
+ timestep: torch.LongTensor,
+ encoder_hidden_states: torch.Tensor,
+ encoder_hidden_states_image: Optional[torch.Tensor] = None,
+ return_dict: bool = True,
+ attention_kwargs: Optional[Dict[str, Any]] = None,
+ image_latents = None,
+ conditioning_scale = 1,
+ controlnet_blocks_repeat = False,
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
+ if attention_kwargs is not None:
+ attention_kwargs = attention_kwargs.copy()
+ lora_scale = attention_kwargs.pop("scale", 1.0)
+ else:
+ lora_scale = 1.0
+
+ controlnet_block_samples = None
+ if conditioning_scale > 0:
+ controlnet_block_samples = self.controlnet(
+ hidden_states = hidden_states,
+ controlnet_cond = controlnet_cond,
+ timestep = timestep,
+ encoder_hidden_states = encoder_hidden_states,
+ encoder_hidden_states_image = encoder_hidden_states_image,
+ return_dict = False,
+ attention_kwargs = attention_kwargs,
+ )
+
+ if USE_PEFT_BACKEND:
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
+ scale_lora_layers(self, lora_scale)
+ else:
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
+ logger.warning(
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
+ )
+
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
+ p_t, p_h, p_w = self.config.patch_size
+ post_patch_num_frames = num_frames // p_t
+ post_patch_height = height // p_h
+ post_patch_width = width // p_w
+
+ rotary_emb = self.rope(hidden_states)
+
+ hidden_states = self.patch_embedding(hidden_states)
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
+
+ temb, timestep_proj, encoder_hidden_states, encoder_hidden_states_image = self.condition_embedder(
+ timestep, encoder_hidden_states, encoder_hidden_states_image
+ )
+ timestep_proj = timestep_proj.unflatten(1, (6, -1))
+
+ if encoder_hidden_states_image is not None:
+ encoder_hidden_states = torch.concat([encoder_hidden_states_image, encoder_hidden_states], dim=1)
+
+ # 4. Transformer blocks
+ interval_control = len(self.blocks) / len(controlnet_block_samples)
+ interval_control = int(np.ceil(interval_control))
+
+ for index_block, block in enumerate(self.blocks):
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
+ hidden_states = self._gradient_checkpointing_func(
+ block, hidden_states, encoder_hidden_states, timestep_proj, rotary_emb
+ )
+ else:
+ hidden_states = block(hidden_states, encoder_hidden_states, timestep_proj, rotary_emb)
+
+ if controlnet_block_samples is not None:
+ if controlnet_blocks_repeat:
+ # 12345 12345 12345 12345 ....
+ hidden_states = (
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
+ )
+ else:
+ # 00000 11111 22222 33333 ....
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
+
+
+ # 5. Output norm, projection & unpatchify
+ shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
+
+ # Move the shift and scale tensors to the same device as hidden_states.
+ # When using multi-GPU inference via accelerate these will be on the
+ # first device rather than the last device, which hidden_states ends up
+ # on.
+ shift = shift.to(hidden_states.device)
+ scale = scale.to(hidden_states.device)
+
+ hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
+ hidden_states = self.proj_out(hidden_states)
+
+ hidden_states = hidden_states.reshape(
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
+ )
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
+ output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
+
+ if USE_PEFT_BACKEND:
+ # remove `lora_scale` from each PEFT layer
+ unscale_lora_layers(self, lora_scale)
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
diff --git a/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/utils.py b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..7f44c1618070b25281707086c4dd3d1a74d924c9
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/model_variants/wanx_diffusers_src/utils.py
@@ -0,0 +1,14 @@
+import torch
+import re
+
+def get_torch_cuda_version():
+ if not torch.version.cuda:
+ return (0, 0)
+ match = re.match(r"(\d+)\.(\d+)", torch.version.cuda)
+ if match:
+ return tuple(map(int, match.groups()))
+ return (0, 0)
+
+major, minor = get_torch_cuda_version()
+ckpt_kwargs = {"use_reentrant": (major > 12) or (major == 12 and minor >= 2)}
+print(f"Set gradient checkpointing: ckpt_kwargs={ckpt_kwargs} (CUDA {major}.{minor})")
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/__init__.py b/One-to-All-Animation/video-generation/opensora/models/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..3eca32c739ed7eaf060421489d9dac7568dffe67
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/__init__.py
@@ -0,0 +1 @@
+from .causalvideovae.model import CausalVAEModelWrapper
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..bc1357393ee13227aa72acb9111811ee3533826a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/__init__.py
@@ -0,0 +1,32 @@
+from torchvision.transforms import Lambda
+from .model.causal_vae import CausalVAEModelWrapper
+
+ae_stride_config = {
+ 'CausalVAEModel_D4_2x8x8': [2, 8, 8],
+ 'CausalVAEModel_D8_2x8x8': [2, 8, 8],
+ 'CausalVAEModel_D4_4x8x8': [4, 8, 8],
+ 'CausalVAEModel_D8_4x8x8': [4, 8, 8],
+}
+
+
+ae_channel_config = {
+ 'CausalVAEModel_D4_2x8x8': 4,
+ 'CausalVAEModel_D8_2x8x8': 8,
+ 'CausalVAEModel_D4_4x8x8': 4,
+ 'CausalVAEModel_D8_4x8x8': 8,
+}
+
+
+ae_denorm = {
+ 'CausalVAEModel_D4_2x8x8': lambda x: (x + 1.) / 2.,
+ 'CausalVAEModel_D8_2x8x8': lambda x: (x + 1.) / 2.,
+ 'CausalVAEModel_D4_4x8x8': lambda x: (x + 1.) / 2.,
+ 'CausalVAEModel_D8_4x8x8': lambda x: (x + 1.) / 2.,
+}
+
+ae_norm = {
+ 'CausalVAEModel_D4_2x8x8': Lambda(lambda x: 2. * x - 1.),
+ 'CausalVAEModel_D8_2x8x8': Lambda(lambda x: 2. * x - 1.),
+ 'CausalVAEModel_D4_4x8x8': Lambda(lambda x: 2. * x - 1.),
+ 'CausalVAEModel_D8_4x8x8': Lambda(lambda x: 2. * x - 1.),
+}
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb0d0f041a8b74aa34778b4fb26e0208d07c980c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/__init__.py
@@ -0,0 +1,65 @@
+from torchvision.transforms import Compose
+from transformers import AutoTokenizer
+
+from .feature_datasets import T2V_Feature_dataset, T2V_T5_Feature_dataset
+from torchvision import transforms
+from torchvision.transforms import Lambda
+
+from .t2v_datasets import T2V_dataset
+from .transform import ToTensorVideo, TemporalRandomCrop, RandomHorizontalFlipVideo, CenterCropResizeVideo, LongSideResizeVideo, SpatialStrideCropVideo
+
+
+ae_norm = {
+ 'CausalVAEModel_4x8x8': Lambda(lambda x: 2. * x - 1.),
+ 'CausalVQVAEModel_4x4x4': Lambda(lambda x: x - 0.5),
+ 'CausalVQVAEModel_4x8x8': Lambda(lambda x: x - 0.5),
+ 'VQVAEModel_4x4x4': Lambda(lambda x: x - 0.5),
+ 'VQVAEModel_4x8x8': Lambda(lambda x: x - 0.5),
+ "bair_stride4x2x2": Lambda(lambda x: x - 0.5),
+ "ucf101_stride4x4x4": Lambda(lambda x: x - 0.5),
+ "kinetics_stride4x4x4": Lambda(lambda x: x - 0.5),
+ "kinetics_stride2x4x4": Lambda(lambda x: x - 0.5),
+ 'stabilityai/sd-vae-ft-mse': transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
+ 'stabilityai/sd-vae-ft-ema': transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
+ 'vqgan_imagenet_f16_1024': Lambda(lambda x: 2. * x - 1.),
+ 'vqgan_imagenet_f16_16384': Lambda(lambda x: 2. * x - 1.),
+ 'vqgan_gumbel_f8': Lambda(lambda x: 2. * x - 1.),
+
+}
+ae_denorm = {
+ 'CausalVAEModel_4x8x8': lambda x: (x + 1.) / 2.,
+ 'CausalVQVAEModel_4x4x4': lambda x: x + 0.5,
+ 'CausalVQVAEModel_4x8x8': lambda x: x + 0.5,
+ 'VQVAEModel_4x4x4': lambda x: x + 0.5,
+ 'VQVAEModel_4x8x8': lambda x: x + 0.5,
+ "bair_stride4x2x2": lambda x: x + 0.5,
+ "ucf101_stride4x4x4": lambda x: x + 0.5,
+ "kinetics_stride4x4x4": lambda x: x + 0.5,
+ "kinetics_stride2x4x4": lambda x: x + 0.5,
+ 'stabilityai/sd-vae-ft-mse': lambda x: 0.5 * x + 0.5,
+ 'stabilityai/sd-vae-ft-ema': lambda x: 0.5 * x + 0.5,
+ 'vqgan_imagenet_f16_1024': lambda x: (x + 1.) / 2.,
+ 'vqgan_imagenet_f16_16384': lambda x: (x + 1.) / 2.,
+ 'vqgan_gumbel_f8': lambda x: (x + 1.) / 2.,
+}
+
+def getdataset(args):
+ temporal_sample = TemporalRandomCrop(args.num_frames * args.sample_rate) # 16 x
+ norm_fun = ae_norm[args.ae]
+ if args.dataset == 't2v':
+ if args.multi_scale:
+ resize = [
+ LongSideResizeVideo(args.max_image_size, skip_low_resolution=True),
+ SpatialStrideCropVideo(args.stride)
+ ]
+ else:
+ resize = [CenterCropResizeVideo(args.max_image_size), ]
+ transform = transforms.Compose([
+ ToTensorVideo(),
+ *resize,
+ # RandomHorizontalFlipVideo(p=0.5), # in case their caption have position decription
+ norm_fun
+ ])
+ tokenizer = AutoTokenizer.from_pretrained(args.text_encoder_name, cache_dir=args.cache_dir)
+ return T2V_dataset(args, transform=transform, temporal_sample=temporal_sample, tokenizer=tokenizer)
+ raise NotImplementedError(args.dataset)
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/feature_datasets.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/feature_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..e8f85f2c1f70e8a5eea4dcb8bb9f4ec0474cf6d6
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/feature_datasets.py
@@ -0,0 +1,213 @@
+import json
+import os
+import torch
+import random
+import torch.utils.data as data
+
+import numpy as np
+from glob import glob
+from PIL import Image
+from torch.utils.data import Dataset
+from tqdm import tqdm
+
+from .transform import center_crop, RandomCropVideo
+from ..utils.dataset_utils import DecordInit
+
+
+class T2V_Feature_dataset(Dataset):
+ def __init__(self, args, temporal_sample):
+
+ self.video_folder = args.video_folder
+ self.num_frames = args.video_length
+ self.temporal_sample = temporal_sample
+
+ print('Building dataset...')
+ if os.path.exists('samples_430k.json'):
+ with open('samples_430k.json', 'r') as f:
+ self.samples = json.load(f)
+ else:
+ self.samples = self._make_dataset()
+ with open('samples_430k.json', 'w') as f:
+ json.dump(self.samples, f, indent=2)
+
+ self.use_image_num = args.use_image_num
+ self.use_img_from_vid = args.use_img_from_vid
+ if self.use_image_num != 0 and not self.use_img_from_vid:
+ self.img_cap_list = self.get_img_cap_list()
+
+ def _make_dataset(self):
+ all_mp4 = list(glob(os.path.join(self.video_folder, '**', '*.mp4'), recursive=True))
+ # all_mp4 = all_mp4[:1000]
+ samples = []
+ for i in tqdm(all_mp4):
+ video_id = os.path.basename(i).split('.')[0]
+ ae = os.path.split(i)[0].replace('data_split_tt', 'lb_causalvideovae444_feature')
+ ae = os.path.join(ae, f'{video_id}_causalvideovae444.npy')
+ if not os.path.exists(ae):
+ continue
+
+ t5 = os.path.split(i)[0].replace('data_split_tt', 'lb_t5_feature')
+ cond_list = []
+ cond_llava = os.path.join(t5, f'{video_id}_t5_llava_fea.npy')
+ mask_llava = os.path.join(t5, f'{video_id}_t5_llava_mask.npy')
+ if os.path.exists(cond_llava) and os.path.exists(mask_llava):
+ llava = dict(cond=cond_llava, mask=mask_llava)
+ cond_list.append(llava)
+ cond_sharegpt4v = os.path.join(t5, f'{video_id}_t5_sharegpt4v_fea.npy')
+ mask_sharegpt4v = os.path.join(t5, f'{video_id}_t5_sharegpt4v_mask.npy')
+ if os.path.exists(cond_sharegpt4v) and os.path.exists(mask_sharegpt4v):
+ sharegpt4v = dict(cond=cond_sharegpt4v, mask=mask_sharegpt4v)
+ cond_list.append(sharegpt4v)
+ if len(cond_list) > 0:
+ sample = dict(ae=ae, t5=cond_list)
+ samples.append(sample)
+ return samples
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, idx):
+ # try:
+ sample = self.samples[idx]
+ ae, t5 = sample['ae'], sample['t5']
+ t5 = random.choice(t5)
+ video_origin = np.load(ae)[0] # C T H W
+ _, total_frames, _, _ = video_origin.shape
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ assert end_frame_ind - start_frame_ind >= self.num_frames
+ select_video_idx = np.linspace(start_frame_ind, end_frame_ind - 1, num=self.num_frames, dtype=int) # start, stop, num=50
+ # print('select_video_idx', total_frames, select_video_idx)
+ video = video_origin[:, select_video_idx] # C num_frames H W
+ video = torch.from_numpy(video)
+
+ cond = torch.from_numpy(np.load(t5['cond']))[0] # L
+ cond_mask = torch.from_numpy(np.load(t5['mask']))[0] # L D
+
+ if self.use_image_num != 0 and self.use_img_from_vid:
+ select_image_idx = np.random.randint(0, total_frames, self.use_image_num)
+ # print('select_image_idx', total_frames, self.use_image_num, select_image_idx)
+ images = video_origin[:, select_image_idx] # c, num_img, h, w
+ images = torch.from_numpy(images)
+ video = torch.cat([video, images], dim=1) # c, num_frame+num_img, h, w
+ cond = torch.stack([cond] * (1+self.use_image_num)) # 1+self.use_image_num, l
+ cond_mask = torch.stack([cond_mask] * (1+self.use_image_num)) # 1+self.use_image_num, l
+ elif self.use_image_num != 0 and not self.use_img_from_vid:
+ images, captions = self.img_cap_list[idx]
+ raise NotImplementedError
+ else:
+ pass
+
+ return video, cond, cond_mask
+ # except Exception as e:
+ # print(f'Error with {e}, {sample}')
+ # return self.__getitem__(random.randint(0, self.__len__() - 1))
+
+ def get_img_cap_list(self):
+ raise NotImplementedError
+
+
+
+
+class T2V_T5_Feature_dataset(Dataset):
+ def __init__(self, args, transform, temporal_sample):
+
+ self.video_folder = args.video_folder
+ self.num_frames = args.num_frames
+ self.transform = transform
+ self.temporal_sample = temporal_sample
+ self.v_decoder = DecordInit()
+
+ print('Building dataset...')
+ if os.path.exists('samples_430k.json'):
+ with open('samples_430k.json', 'r') as f:
+ self.samples = json.load(f)
+ self.samples = [dict(ae=i['ae'].replace('lb_causalvideovae444_feature', 'data_split_1024').replace('_causalvideovae444.npy', '.mp4'), t5=i['t5']) for i in self.samples]
+ else:
+ self.samples = self._make_dataset()
+ with open('samples_430k.json', 'w') as f:
+ json.dump(self.samples, f, indent=2)
+
+ self.use_image_num = args.use_image_num
+ self.use_img_from_vid = args.use_img_from_vid
+ if self.use_image_num != 0 and not self.use_img_from_vid:
+ self.img_cap_list = self.get_img_cap_list()
+
+ def _make_dataset(self):
+ all_mp4 = list(glob(os.path.join(self.video_folder, '**', '*.mp4'), recursive=True))
+ # all_mp4 = all_mp4[:1000]
+ samples = []
+ for i in tqdm(all_mp4):
+ video_id = os.path.basename(i).split('.')[0]
+ # ae = os.path.split(i)[0].replace('data_split', 'lb_causalvideovae444_feature')
+ # ae = os.path.join(ae, f'{video_id}_causalvideovae444.npy')
+ ae = i
+ if not os.path.exists(ae):
+ continue
+
+ t5 = os.path.split(i)[0].replace('data_split_1024', 'lb_t5_feature')
+ cond_list = []
+ cond_llava = os.path.join(t5, f'{video_id}_t5_llava_fea.npy')
+ mask_llava = os.path.join(t5, f'{video_id}_t5_llava_mask.npy')
+ if os.path.exists(cond_llava) and os.path.exists(mask_llava):
+ llava = dict(cond=cond_llava, mask=mask_llava)
+ cond_list.append(llava)
+ cond_sharegpt4v = os.path.join(t5, f'{video_id}_t5_sharegpt4v_fea.npy')
+ mask_sharegpt4v = os.path.join(t5, f'{video_id}_t5_sharegpt4v_mask.npy')
+ if os.path.exists(cond_sharegpt4v) and os.path.exists(mask_sharegpt4v):
+ sharegpt4v = dict(cond=cond_sharegpt4v, mask=mask_sharegpt4v)
+ cond_list.append(sharegpt4v)
+ if len(cond_list) > 0:
+ sample = dict(ae=ae, t5=cond_list)
+ samples.append(sample)
+ return samples
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, idx):
+ try:
+ sample = self.samples[idx]
+ ae, t5 = sample['ae'], sample['t5']
+ t5 = random.choice(t5)
+
+ video = self.decord_read(ae)
+ video = self.transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ total_frames = video.shape[1]
+ cond = torch.from_numpy(np.load(t5['cond']))[0] # L
+ cond_mask = torch.from_numpy(np.load(t5['mask']))[0] # L D
+
+ if self.use_image_num != 0 and self.use_img_from_vid:
+ select_image_idx = np.random.randint(0, total_frames, self.use_image_num)
+ # print('select_image_idx', total_frames, self.use_image_num, select_image_idx)
+ images = video.numpy()[:, select_image_idx] # c, num_img, h, w
+ images = torch.from_numpy(images)
+ video = torch.cat([video, images], dim=1) # c, num_frame+num_img, h, w
+ cond = torch.stack([cond] * (1+self.use_image_num)) # 1+self.use_image_num, l
+ cond_mask = torch.stack([cond_mask] * (1+self.use_image_num)) # 1+self.use_image_num, l
+ elif self.use_image_num != 0 and not self.use_img_from_vid:
+ images, captions = self.img_cap_list[idx]
+ raise NotImplementedError
+ else:
+ pass
+
+ return video, cond, cond_mask
+ except Exception as e:
+ print(f'Error with {e}, {sample}')
+ return self.__getitem__(random.randint(0, self.__len__() - 1))
+
+ def decord_read(self, path):
+ decord_vr = self.v_decoder(path)
+ total_frames = len(decord_vr)
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_indice).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
+ def get_img_cap_list(self):
+ raise NotImplementedError
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/t2v_datasets.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/t2v_datasets.py
new file mode 100644
index 0000000000000000000000000000000000000000..776f15fff83c446fa7e00777f4432598e6d09795
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/t2v_datasets.py
@@ -0,0 +1,203 @@
+import json
+import os, io, csv, math, random
+import numpy as np
+import torchvision
+from einops import rearrange
+from decord import VideoReader
+from os.path import join as opj
+import gc
+import torch
+import torchvision.transforms as transforms
+from torch.utils.data.dataset import Dataset
+from tqdm import tqdm
+from PIL import Image
+
+from ..utils.dataset_utils import DecordInit
+from ..utils.utils import text_preprocessing
+
+
+def random_video_noise(t, c, h, w):
+ vid = torch.rand(t, c, h, w) * 255.0
+ vid = vid.to(torch.uint8)
+ return vid
+
+class T2V_dataset(Dataset):
+ def __init__(self, args, transform, temporal_sample, tokenizer):
+ self.image_data = args.image_data
+ self.video_data = args.video_data
+ self.num_frames = args.num_frames
+ self.transform = transform
+ self.temporal_sample = temporal_sample
+ self.tokenizer = tokenizer
+ self.model_max_length = args.model_max_length
+ self.v_decoder = DecordInit()
+
+ self.vid_cap_list = self.get_vid_cap_list()
+
+ self.use_image_num = args.use_image_num
+ self.use_img_from_vid = args.use_img_from_vid
+ if self.use_image_num != 0 and not self.use_img_from_vid:
+ self.img_cap_list = self.get_img_cap_list()
+
+
+ def __len__(self):
+ return len(self.vid_cap_list)
+
+ def __getitem__(self, idx):
+ try:
+ # import ipdb;ipdb.set_trace()
+ video_data = self.get_video(idx)
+ image_data = {}
+ if self.use_image_num != 0 and self.use_img_from_vid:
+ image_data = self.get_image_from_video(video_data)
+ elif self.use_image_num != 0 and not self.use_img_from_vid:
+ image_data = self.get_image(idx)
+ else:
+ raise NotImplementedError
+ gc.collect()
+ return dict(video_data=video_data, image_data=image_data)
+ except Exception as e:
+ # print(f'Error with {e}, {self.vid_cap_list[idx]}')
+ if os.path.exists(self.vid_cap_list[idx]['path']) and '_resize_1080p' in self.vid_cap_list[idx]['path']:
+ os.remove(self.vid_cap_list[idx]['path'])
+ print('remove:', self.vid_cap_list[idx]['path'])
+ return self.__getitem__(random.randint(0, self.__len__() - 1))
+
+ def get_video(self, idx):
+ # video = random.choice([random_video_noise(65, 3, 720, 360) * 255, random_video_noise(65, 3, 1024, 1024), random_video_noise(65, 3, 360, 720)])
+ # # print('random shape', video.shape)
+ # input_ids = torch.ones(1, 120).to(torch.long).squeeze(0)
+ # cond_mask = torch.cat([torch.ones(1, 60).to(torch.long), torch.ones(1, 60).to(torch.long)], dim=1).squeeze(0)
+
+ video_path = self.vid_cap_list[idx]['path']
+ frame_idx = self.vid_cap_list[idx]['frame_idx']
+ #print('before decord')
+ video = self.decord_read(video_path, frame_idx)
+ # video = self.tv_read(video_path, frame_idx)
+ #print('after decord')
+ video = self.transform(video) # T C H W -> T C H W
+ # del raw_video
+ # gc.collect()
+ # video = torch.rand(65, 3, 512, 512)
+ #print('after transform')
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ text = self.vid_cap_list[idx]['cap']
+
+ text = text_preprocessing(text)
+ text_tokens_and_mask = self.tokenizer(
+ text,
+ max_length=self.model_max_length,
+ padding='max_length',
+ truncation=True,
+ return_attention_mask=True,
+ add_special_tokens=True,
+ return_tensors='pt'
+ )
+ input_ids = text_tokens_and_mask['input_ids']
+ cond_mask = text_tokens_and_mask['attention_mask']
+ return dict(video=video, input_ids=input_ids, cond_mask=cond_mask)
+
+ def get_image_from_video(self, video_data):
+ select_image_idx = np.linspace(0, self.num_frames-1, self.use_image_num, dtype=int)
+ assert self.num_frames >= self.use_image_num
+ image = [video_data['video'][:, i:i+1] for i in select_image_idx] # num_img [c, 1, h, w]
+ input_ids = video_data['input_ids'].repeat(self.use_image_num, 1) # self.use_image_num, l
+ cond_mask = video_data['cond_mask'].repeat(self.use_image_num, 1) # self.use_image_num, l
+ return dict(image=image, input_ids=input_ids, cond_mask=cond_mask)
+
+ def get_image(self, idx):
+ idx = idx % len(self.img_cap_list) # out of range
+ image_data = self.img_cap_list[idx] # [{'path': path, 'cap': cap}, ...]
+
+ image = [Image.open(i['path']).convert('RGB') for i in image_data] # num_img [h, w, c]
+ image = [torch.from_numpy(np.array(i)) for i in image] # num_img [h, w, c]
+ image = [rearrange(i, 'h w c -> c h w').unsqueeze(0) for i in image] # num_img [1 c h w]
+ image = [self.transform(i) for i in image] # num_img [1 C H W] -> num_img [1 C H W]
+ image = [i.transpose(0, 1) for i in image] # num_img [1 C H W] -> num_img [C 1 H W]
+
+ caps = [i['cap'] for i in image_data]
+ text = [text_preprocessing(cap) for cap in caps]
+ input_ids, cond_mask = [], []
+ for t in text:
+ text_tokens_and_mask = self.tokenizer(
+ t,
+ max_length=self.model_max_length,
+ padding='max_length',
+ truncation=True,
+ return_attention_mask=True,
+ add_special_tokens=True,
+ return_tensors='pt'
+ )
+ input_ids.append(text_tokens_and_mask['input_ids'])
+ cond_mask.append(text_tokens_and_mask['attention_mask'])
+ input_ids = torch.cat(input_ids) # self.use_image_num, l
+ cond_mask = torch.cat(cond_mask) # self.use_image_num, l
+ return dict(image=image, input_ids=input_ids, cond_mask=cond_mask)
+
+ def tv_read(self, path, frame_idx=None):
+ vframes, aframes, info = torchvision.io.read_video(filename=path, pts_unit='sec', output_format='TCHW')
+ total_frames = len(vframes)
+ if frame_idx is None:
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ else:
+ start_frame_ind, end_frame_ind = frame_idx.split(':')
+ start_frame_ind, end_frame_ind = int(start_frame_ind), int(end_frame_ind)
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.num_frames, dtype=int)
+ # frame_indice = np.linspace(0, 63, self.num_frames, dtype=int)
+
+ video = vframes[frame_indice] # (T, C, H, W)
+
+ return video
+
+ def decord_read(self, path, frame_idx=None):
+ decord_vr = self.v_decoder(path)
+ total_frames = len(decord_vr)
+ # Sampling video frames
+ if frame_idx is None:
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ else:
+ start_frame_ind, end_frame_ind = frame_idx.split(':')
+ start_frame_ind, end_frame_ind = int(start_frame_ind), int(end_frame_ind)
+ start_frame_ind, end_frame_ind = int(start_frame_ind), int(start_frame_ind) + self.num_frames
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.num_frames, dtype=int)
+ # frame_indice = np.linspace(0, 63, self.num_frames, dtype=int)
+
+ video_data = decord_vr.get_batch(frame_indice).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
+
+ def get_vid_cap_list(self):
+ vid_cap_lists = []
+ with open(self.video_data, 'r') as f:
+ folder_anno = [i.strip().split(',') for i in f.readlines() if len(i.strip()) > 0]
+ # print(folder_anno)
+ for folder, anno in folder_anno:
+ with open(anno, 'r') as f:
+ vid_cap_list = json.load(f)
+ print(f'Building {anno}...')
+ for i in tqdm(range(len(vid_cap_list))):
+ path = opj(folder, vid_cap_list[i]['path'])
+ if os.path.exists(path.replace('.mp4', '_resize_1080p.mp4')):
+ path = path.replace('.mp4', '_resize_1080p.mp4')
+ vid_cap_list[i]['path'] = path
+
+ vid_cap_lists += vid_cap_list
+ return vid_cap_lists
+
+ def get_img_cap_list(self):
+ img_cap_lists = []
+ with open(self.image_data, 'r') as f:
+ folder_anno = [i.strip().split(',') for i in f.readlines() if len(i.strip()) > 0]
+ for folder, anno in folder_anno:
+ with open(anno, 'r') as f:
+ img_cap_list = json.load(f)
+ print(f'Building {anno}...')
+ for i in tqdm(range(len(img_cap_list))):
+ img_cap_list[i]['path'] = opj(folder, img_cap_list[i]['path'])
+ img_cap_lists += img_cap_list
+ img_cap_lists = [img_cap_lists[i: i+self.use_image_num] for i in range(0, len(img_cap_lists), self.use_image_num)]
+ return img_cap_lists[:-1] # drop last to avoid error length
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/transform.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/transform.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb89c2c85b726d462bde2a30fea03c54278d6063
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/transform.py
@@ -0,0 +1,573 @@
+import torch
+import random
+import numbers
+from torchvision.transforms import RandomCrop, RandomResizedCrop
+
+
+def _is_tensor_video_clip(clip):
+ if not torch.is_tensor(clip):
+ raise TypeError("clip should be Tensor. Got %s" % type(clip))
+
+ if not clip.ndimension() == 4:
+ raise ValueError("clip should be 4D. Got %dD" % clip.dim())
+
+ return True
+
+
+def center_crop_arr(pil_image, image_size):
+ """
+ Center cropping implementation from ADM.
+ https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126
+ """
+ while min(*pil_image.size) >= 2 * image_size:
+ pil_image = pil_image.resize(
+ tuple(x // 2 for x in pil_image.size), resample=Image.BOX
+ )
+
+ scale = image_size / min(*pil_image.size)
+ pil_image = pil_image.resize(
+ tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC
+ )
+
+ arr = np.array(pil_image)
+ crop_y = (arr.shape[0] - image_size) // 2
+ crop_x = (arr.shape[1] - image_size) // 2
+ return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])
+
+
+def crop(clip, i, j, h, w):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ """
+ if len(clip.size()) != 4:
+ raise ValueError("clip should be a 4D tensor")
+ return clip[..., i: i + h, j: j + w]
+
+
+def resize(clip, target_size, interpolation_mode):
+ if len(target_size) != 2:
+ raise ValueError(f"target size should be tuple (height, width), instead got {target_size}")
+ return torch.nn.functional.interpolate(clip, size=target_size, mode=interpolation_mode, align_corners=True, antialias=True)
+
+
+def resize_scale(clip, target_size, interpolation_mode):
+ if len(target_size) != 2:
+ raise ValueError(f"target size should be tuple (height, width), instead got {target_size}")
+ H, W = clip.size(-2), clip.size(-1)
+ scale_ = target_size[0] / min(H, W)
+ return torch.nn.functional.interpolate(clip, scale_factor=scale_, mode=interpolation_mode, align_corners=True, antialias=True)
+
+
+def resized_crop(clip, i, j, h, w, size, interpolation_mode="bilinear"):
+ """
+ Do spatial cropping and resizing to the video clip
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ i (int): i in (i,j) i.e coordinates of the upper left corner.
+ j (int): j in (i,j) i.e coordinates of the upper left corner.
+ h (int): Height of the cropped region.
+ w (int): Width of the cropped region.
+ size (tuple(int, int)): height and width of resized clip
+ Returns:
+ clip (torch.tensor): Resized and cropped clip. Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ clip = crop(clip, i, j, h, w)
+ clip = resize(clip, size, interpolation_mode)
+ return clip
+
+
+def center_crop(clip, crop_size):
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+ th, tw = crop_size
+ if h < th or w < tw:
+ raise ValueError("height and width must be no smaller than crop_size")
+
+ i = int(round((h - th) / 2.0))
+ j = int(round((w - tw) / 2.0))
+ return crop(clip, i, j, th, tw)
+
+
+def center_crop_using_short_edge(clip):
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+ if h < w:
+ th, tw = h, h
+ i = 0
+ j = int(round((w - tw) / 2.0))
+ else:
+ th, tw = w, w
+ i = int(round((h - th) / 2.0))
+ j = 0
+ return crop(clip, i, j, th, tw)
+
+
+def random_shift_crop(clip):
+ '''
+ Slide along the long edge, with the short edge as crop size
+ '''
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ h, w = clip.size(-2), clip.size(-1)
+
+ if h <= w:
+ long_edge = w
+ short_edge = h
+ else:
+ long_edge = h
+ short_edge = w
+
+ th, tw = short_edge, short_edge
+
+ i = torch.randint(0, h - th + 1, size=(1,)).item()
+ j = torch.randint(0, w - tw + 1, size=(1,)).item()
+ return crop(clip, i, j, th, tw)
+
+
+def to_tensor(clip):
+ """
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
+ permute the dimensions of clip tensor
+ Args:
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W)
+ """
+ _is_tensor_video_clip(clip)
+ if not clip.dtype == torch.uint8:
+ raise TypeError("clip tensor should have data type uint8. Got %s" % str(clip.dtype))
+ # return clip.float().permute(3, 0, 1, 2) / 255.0
+ return clip.float() / 255.0
+
+
+def normalize(clip, mean, std, inplace=False):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be normalized. Size is (T, C, H, W)
+ mean (tuple): pixel RGB mean. Size is (3)
+ std (tuple): pixel standard deviation. Size is (3)
+ Returns:
+ normalized clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ if not inplace:
+ clip = clip.clone()
+ mean = torch.as_tensor(mean, dtype=clip.dtype, device=clip.device)
+ # print(mean)
+ std = torch.as_tensor(std, dtype=clip.dtype, device=clip.device)
+ clip.sub_(mean[:, None, None, None]).div_(std[:, None, None, None])
+ return clip
+
+
+def hflip(clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be normalized. Size is (T, C, H, W)
+ Returns:
+ flipped clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if not _is_tensor_video_clip(clip):
+ raise ValueError("clip should be a 4D torch.tensor")
+ return clip.flip(-1)
+
+
+class RandomCropVideo:
+ def __init__(self, size):
+ if isinstance(size, numbers.Number):
+ self.size = (int(size), int(size))
+ else:
+ self.size = size
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: randomly cropped video clip.
+ size is (T, C, OH, OW)
+ """
+ i, j, h, w = self.get_params(clip)
+ return crop(clip, i, j, h, w)
+
+ def get_params(self, clip):
+ h, w = clip.shape[-2:]
+ th, tw = self.size
+
+ if h < th or w < tw:
+ raise ValueError(f"Required crop size {(th, tw)} is larger than input image size {(h, w)}")
+
+ if w == tw and h == th:
+ return 0, 0, h, w
+
+ i = torch.randint(0, h - th + 1, size=(1,)).item()
+ j = torch.randint(0, w - tw + 1, size=(1,)).item()
+
+ return i, j, th, tw
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size})"
+
+
+class SpatialStrideCropVideo:
+ def __init__(self, stride):
+ self.stride = stride
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: cropped video clip by stride.
+ size is (T, C, OH, OW)
+ """
+ i, j, h, w = self.get_params(clip)
+ return crop(clip, i, j, h, w)
+
+ def get_params(self, clip):
+ h, w = clip.shape[-2:]
+
+ th, tw = h // self.stride * self.stride, w // self.stride * self.stride
+
+ return 0, 0, th, tw # from top-left
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size})"
+
+class LongSideResizeVideo:
+ '''
+ First use the long side,
+ then resize to the specified size
+ '''
+
+ def __init__(
+ self,
+ size,
+ skip_low_resolution=False,
+ interpolation_mode="bilinear",
+ ):
+ self.size = size
+ self.skip_low_resolution = skip_low_resolution
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized video clip.
+ size is (T, C, 512, *) or (T, C, *, 512)
+ """
+ _, _, h, w = clip.shape
+ if self.skip_low_resolution and max(h, w) <= self.size:
+ return clip
+ if h > w:
+ w = int(w * self.size / h)
+ h = self.size
+ else:
+ h = int(h * self.size / w)
+ w = self.size
+ resize_clip = resize(clip, target_size=(h, w),
+ interpolation_mode=self.interpolation_mode)
+ return resize_clip
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+class CenterCropResizeVideo:
+ '''
+ First use the short side for cropping length,
+ center crop video, then resize to the specified size
+ '''
+
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized / center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ clip_center_crop = center_crop_using_short_edge(clip)
+ clip_center_crop_resize = resize(clip_center_crop, target_size=self.size,
+ interpolation_mode=self.interpolation_mode)
+ return clip_center_crop_resize
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class UCFCenterCropVideo:
+ '''
+ First scale to the specified size in equal proportion to the short edge,
+ then center cropping
+ '''
+
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: scale resized / center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ clip_resize = resize_scale(clip=clip, target_size=self.size, interpolation_mode=self.interpolation_mode)
+ clip_center_crop = center_crop(clip_resize, self.size)
+ return clip_center_crop
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class KineticsRandomCropResizeVideo:
+ '''
+ Slide along the long edge, with the short edge as crop size. And resie to the desired size.
+ '''
+
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ clip_random_crop = random_shift_crop(clip)
+ clip_resize = resize(clip_random_crop, self.size, self.interpolation_mode)
+ return clip_resize
+
+
+class CenterCropVideo:
+ def __init__(
+ self,
+ size,
+ interpolation_mode="bilinear",
+ ):
+ if isinstance(size, tuple):
+ if len(size) != 2:
+ raise ValueError(f"size should be tuple (height, width), instead got {size}")
+ self.size = size
+ else:
+ self.size = (size, size)
+
+ self.interpolation_mode = interpolation_mode
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Video clip to be cropped. Size is (T, C, H, W)
+ Returns:
+ torch.tensor: center cropped video clip.
+ size is (T, C, crop_size, crop_size)
+ """
+ clip_center_crop = center_crop(clip, self.size)
+ return clip_center_crop
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(size={self.size}, interpolation_mode={self.interpolation_mode}"
+
+
+class NormalizeVideo:
+ """
+ Normalize the video clip by mean subtraction and division by standard deviation
+ Args:
+ mean (3-tuple): pixel RGB mean
+ std (3-tuple): pixel RGB standard deviation
+ inplace (boolean): whether do in-place normalization
+ """
+
+ def __init__(self, mean, std, inplace=False):
+ self.mean = mean
+ self.std = std
+ self.inplace = inplace
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): video clip must be normalized. Size is (C, T, H, W)
+ """
+ return normalize(clip, self.mean, self.std, self.inplace)
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(mean={self.mean}, std={self.std}, inplace={self.inplace})"
+
+
+class ToTensorVideo:
+ """
+ Convert tensor data type from uint8 to float, divide value by 255.0 and
+ permute the dimensions of clip tensor
+ """
+
+ def __init__(self):
+ pass
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor, dtype=torch.uint8): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor, dtype=torch.float): Size is (T, C, H, W)
+ """
+ return to_tensor(clip)
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__
+
+
+class RandomHorizontalFlipVideo:
+ """
+ Flip the video clip along the horizontal direction with a given probability
+ Args:
+ p (float): probability of the clip being flipped. Default value is 0.5
+ """
+
+ def __init__(self, p=0.5):
+ self.p = p
+
+ def __call__(self, clip):
+ """
+ Args:
+ clip (torch.tensor): Size is (T, C, H, W)
+ Return:
+ clip (torch.tensor): Size is (T, C, H, W)
+ """
+ if random.random() < self.p:
+ clip = hflip(clip)
+ return clip
+
+ def __repr__(self) -> str:
+ return f"{self.__class__.__name__}(p={self.p})"
+
+
+# ------------------------------------------------------------
+# --------------------- Sampling ---------------------------
+# ------------------------------------------------------------
+class TemporalRandomCrop(object):
+ """Temporally crop the given frame indices at a random location.
+
+ Args:
+ size (int): Desired length of frames will be seen in the model.
+ """
+
+ def __init__(self, size):
+ self.size = size
+
+ def __call__(self, total_frames):
+ rand_end = max(0, total_frames - self.size - 1)
+ begin_index = random.randint(0, rand_end)
+ end_index = min(begin_index + self.size, total_frames)
+ return begin_index, end_index
+
+class DynamicSampleDuration(object):
+ """Temporally crop the given frame indices at a random location.
+
+ Args:
+ size (int): Desired length of frames will be seen in the model.
+ """
+
+ def __init__(self, t_stride, extra_1):
+ self.t_stride = t_stride
+ self.extra_1 = extra_1
+
+ def __call__(self, t, h, w):
+ if self.extra_1:
+ t = t - 1
+ truncate_t_list = list(range(t+1))[t//2:][::self.t_stride] # need half at least
+ truncate_t = random.choice(truncate_t_list)
+ if self.extra_1:
+ truncate_t = truncate_t + 1
+ return 0, truncate_t
+
+if __name__ == '__main__':
+ from torchvision import transforms
+ import torchvision.io as io
+ import numpy as np
+ from torchvision.utils import save_image
+ import os
+
+ vframes, aframes, info = io.read_video(
+ filename='./v_Archery_g01_c03.avi',
+ pts_unit='sec',
+ output_format='TCHW'
+ )
+
+ trans = transforms.Compose([
+ ToTensorVideo(),
+ RandomHorizontalFlipVideo(),
+ UCFCenterCropVideo(512),
+ # NormalizeVideo(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True),
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
+ ])
+
+ target_video_len = 32
+ frame_interval = 1
+ total_frames = len(vframes)
+ print(total_frames)
+
+ temporal_sample = TemporalRandomCrop(target_video_len * frame_interval)
+
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = temporal_sample(total_frames)
+ # print(start_frame_ind)
+ # print(end_frame_ind)
+ assert end_frame_ind - start_frame_ind >= target_video_len
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, target_video_len, dtype=int)
+ print(frame_indice)
+
+ select_vframes = vframes[frame_indice]
+ print(select_vframes.shape)
+ print(select_vframes.dtype)
+
+ select_vframes_trans = trans(select_vframes)
+ print(select_vframes_trans.shape)
+ print(select_vframes_trans.dtype)
+
+ select_vframes_trans_int = ((select_vframes_trans * 0.5 + 0.5) * 255).to(dtype=torch.uint8)
+ print(select_vframes_trans_int.dtype)
+ print(select_vframes_trans_int.permute(0, 2, 3, 1).shape)
+
+ io.write_video('./test.avi', select_vframes_trans_int.permute(0, 2, 3, 1), fps=8)
+
+ for i in range(target_video_len):
+ save_image(select_vframes_trans[i], os.path.join('./test000', '%04d.png' % i), normalize=True,
+ value_range=(-1, 1))
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/ucf101.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/ucf101.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e982a76c0e367712c24f738e0aba0d9dad66f10
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/dataset/ucf101.py
@@ -0,0 +1,80 @@
+import math
+import os
+
+import decord
+import numpy as np
+import torch
+import torchvision
+from decord import VideoReader, cpu
+from torch.utils.data import Dataset
+from torchvision.transforms import Compose, Lambda, ToTensor
+from torchvision.transforms._transforms_video import NormalizeVideo, RandomCropVideo, RandomHorizontalFlipVideo
+from pytorchvideo.transforms import ApplyTransformToKey, ShortSideScale, UniformTemporalSubsample
+from torch.nn import functional as F
+import random
+
+from ..utils.dataset_utils import DecordInit
+
+
+class UCF101(Dataset):
+ def __init__(self, args, transform, temporal_sample):
+ self.data_path = args.data_path
+ self.num_frames = args.num_frames
+ self.transform = transform
+ self.temporal_sample = temporal_sample
+ self.v_decoder = DecordInit()
+
+ self.classes = sorted(os.listdir(self.data_path))
+ self.class_to_idx = {cls_name: idx for idx, cls_name in enumerate(self.classes)}
+ self.samples = self._make_dataset()
+
+
+ def _make_dataset(self):
+ dataset = []
+ for class_name in self.classes:
+ class_path = os.path.join(self.data_path, class_name)
+ for fname in os.listdir(class_path):
+ if fname.endswith('.avi'):
+ item = (os.path.join(class_path, fname), self.class_to_idx[class_name])
+ dataset.append(item)
+ return dataset
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, idx):
+ video_path, label = self.samples[idx]
+ try:
+ video = self.tv_read(video_path)
+ video = self.transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ return video, label
+ except Exception as e:
+ print(f'Error with {e}, {video_path}')
+ return self.__getitem__(random.randint(0, self.__len__()-1))
+
+ def tv_read(self, path):
+ vframes, aframes, info = torchvision.io.read_video(filename=path, pts_unit='sec', output_format='TCHW')
+ total_frames = len(vframes)
+
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.num_frames, dtype=int)
+ video = vframes[frame_indice] # (T, C, H, W)
+
+ return video
+
+ def decord_read(self, path):
+ decord_vr = self.v_decoder(path)
+ total_frames = len(decord_vr)
+ # Sampling video frames
+ start_frame_ind, end_frame_ind = self.temporal_sample(total_frames)
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.num_frames, dtype=int)
+
+ video_data = decord_vr.get_batch(frame_indice).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
+
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_flolpips.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_flolpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..15cdd771e348fa23f51c2c826ec0cbf855dc43b8
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_flolpips.py
@@ -0,0 +1,83 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+from einops import rearrange
+import sys
+sys.path.append(".")
+from flolpips.pwcnet import Network as PWCNet
+from flolpips.flolpips import FloLPIPS
+
+loss_fn = FloLPIPS(net='alex', version='0.1').eval().requires_grad_(False)
+flownet = PWCNet().eval().requires_grad_(False)
+
+def trans(x):
+ return x
+
+
+def calculate_flolpips(videos1, videos2, device):
+ global loss_fn, flownet
+
+ print("calculate_flowlpips...")
+ loss_fn = loss_fn.to(device)
+ flownet = flownet.to(device)
+
+ if videos1.shape != videos2.shape:
+ print("Warning: the shape of videos are not equal.")
+ min_frames = min(videos1.shape[1], videos2.shape[1])
+ videos1 = videos1[:, :min_frames]
+ videos2 = videos2[:, :min_frames]
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ flolpips_results = []
+ for video_num in tqdm(range(videos1.shape[0])):
+ video1 = videos1[video_num].to(device)
+ video2 = videos2[video_num].to(device)
+ frames_rec = video1[:-1]
+ frames_rec_next = video1[1:]
+ frames_gt = video2[:-1]
+ frames_gt_next = video2[1:]
+ t, c, h, w = frames_gt.shape
+ flow_gt = flownet(frames_gt, frames_gt_next)
+ flow_dis = flownet(frames_rec, frames_rec_next)
+ flow_diff = flow_gt - flow_dis
+ flolpips = loss_fn.forward(frames_gt, frames_rec, flow_diff, normalize=True)
+ flolpips_results.append(flolpips.cpu().numpy().tolist())
+
+ flolpips_results = np.array(flolpips_results) # [batch_size, num_frames]
+ flolpips = {}
+ flolpips_std = {}
+
+ for clip_timestamp in range(flolpips_results.shape[1]):
+ flolpips[clip_timestamp] = np.mean(flolpips_results[:,clip_timestamp], axis=-1)
+ flolpips_std[clip_timestamp] = np.std(flolpips_results[:,clip_timestamp], axis=-1)
+
+ result = {
+ "value": flolpips,
+ "value_std": flolpips_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ "result": flolpips_results,
+ "details": flolpips_results.tolist()
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+
+ import json
+ result = calculate_flolpips(videos1, videos2, "cuda:0")
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_fvd.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..1f1a9806eb55d067a48b222ec718460222205898
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_fvd.py
@@ -0,0 +1,85 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+
+def trans(x):
+ # if greyscale images add channel
+ if x.shape[-3] == 1:
+ x = x.repeat(1, 1, 3, 1, 1)
+
+ # permute BTCHW -> BCTHW
+ x = x.permute(0, 2, 1, 3, 4)
+
+ return x
+
+def calculate_fvd(videos1, videos2, device, method='styleganv'):
+
+ if method == 'styleganv':
+ from fvd.styleganv.fvd import get_fvd_feats, frechet_distance, load_i3d_pretrained
+ elif method == 'videogpt':
+ from fvd.videogpt.fvd import load_i3d_pretrained
+ from fvd.videogpt.fvd import get_fvd_logits as get_fvd_feats
+ from fvd.videogpt.fvd import frechet_distance
+
+ print("calculate_fvd...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ i3d = load_i3d_pretrained(device=device)
+ fvd_results = []
+
+ # support grayscale input, if grayscale -> channel*3
+ # BTCHW -> BCTHW
+ # videos -> [batch_size, channel, timestamps, h, w]
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ fvd_results = {}
+
+ # for calculate FVD, each clip_timestamp must >= 10
+ for clip_timestamp in tqdm(range(10, videos1.shape[-3]+1)):
+
+ # get a video clip
+ # videos_clip [batch_size, channel, timestamps[:clip], h, w]
+ videos_clip1 = videos1[:, :, : clip_timestamp]
+ videos_clip2 = videos2[:, :, : clip_timestamp]
+
+ # get FVD features
+ feats1 = get_fvd_feats(videos_clip1, i3d=i3d, device=device)
+ feats2 = get_fvd_feats(videos_clip2, i3d=i3d, device=device)
+
+ # calculate FVD when timestamps[:clip]
+ fvd_results[clip_timestamp] = frechet_distance(feats1, feats2)
+
+ result = {
+ "value": fvd_results,
+ "video_setting": videos1.shape,
+ "video_setting_name": "batch_size, channel, time, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+ # device = torch.device("cpu")
+
+ import json
+ result = calculate_fvd(videos1, videos2, device, method='videogpt')
+ print(json.dumps(result, indent=4))
+
+ result = calculate_fvd(videos1, videos2, device, method='styleganv')
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_lpips.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_lpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..10edc610b1977b859245d2307f1bebfb0f277216
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_lpips.py
@@ -0,0 +1,97 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+
+import torch
+import lpips
+
+spatial = True # Return a spatial map of perceptual distance.
+
+# Linearly calibrated models (LPIPS)
+loss_fn = lpips.LPIPS(net='alex', spatial=spatial) # Can also set net = 'squeeze' or 'vgg'
+# loss_fn = lpips.LPIPS(net='alex', spatial=spatial, lpips=False) # Can also set net = 'squeeze' or 'vgg'
+
+def trans(x):
+ # if greyscale images add channel
+ if x.shape[-3] == 1:
+ x = x.repeat(1, 1, 3, 1, 1)
+
+ # value range [0, 1] -> [-1, 1]
+ x = x * 2 - 1
+
+ return x
+
+def calculate_lpips(videos1, videos2, device):
+ # image should be RGB, IMPORTANT: normalized to [-1,1]
+ print("calculate_lpips...")
+
+ assert videos1.shape == videos2.shape
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ # support grayscale input, if grayscale -> channel*3
+ # value range [0, 1] -> [-1, 1]
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ lpips_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ lpips_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] tensor
+
+ img1 = video1[clip_timestamp].unsqueeze(0).to(device)
+ img2 = video2[clip_timestamp].unsqueeze(0).to(device)
+
+ loss_fn.to(device)
+
+ # calculate lpips of a video
+ lpips_results_of_a_video.append(loss_fn.forward(img1, img2).mean().detach().cpu().tolist())
+ lpips_results.append(lpips_results_of_a_video)
+
+ lpips_results = np.array(lpips_results)
+
+ lpips = {}
+ lpips_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ lpips[clip_timestamp] = np.mean(lpips_results[:,clip_timestamp])
+ lpips_std[clip_timestamp] = np.std(lpips_results[:,clip_timestamp])
+
+
+ result = {
+ "value": lpips,
+ "value_std": lpips_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.ones(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+ # device = torch.device("cpu")
+
+ import json
+ result = calculate_lpips(videos1, videos2, device)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_psnr.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_psnr.py
new file mode 100644
index 0000000000000000000000000000000000000000..08d6b94db1dd474793cdc00075eb61dfec8bb580
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_psnr.py
@@ -0,0 +1,97 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import math
+
+def img_psnr_cuda(img1, img2):
+ # [0,1]
+ # compute mse
+ # mse = np.mean((img1-img2)**2)
+ mse = torch.mean((img1 / 1.0 - img2 / 1.0) ** 2)
+ # compute psnr
+ if mse < 1e-10:
+ return 100
+ psnr = 20 * torch.log10(1 / torch.sqrt(mse))
+ return psnr
+
+
+def img_psnr(img1, img2):
+ # [0,1]
+ # compute mse
+ # mse = np.mean((img1-img2)**2)
+ mse = np.mean((img1 / 1.0 - img2 / 1.0) ** 2)
+ # compute psnr
+ if mse < 1e-10:
+ return 100
+ psnr = 20 * math.log10(1 / math.sqrt(mse))
+ return psnr
+
+
+def trans(x):
+ return x
+
+def calculate_psnr(videos1, videos2):
+ print("calculate_psnr...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ psnr_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ psnr_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] numpy
+
+ img1 = video1[clip_timestamp].numpy()
+ img2 = video2[clip_timestamp].numpy()
+
+ # calculate psnr of a video
+ psnr_results_of_a_video.append(img_psnr(img1, img2))
+
+ psnr_results.append(psnr_results_of_a_video)
+
+ psnr_results = np.array(psnr_results) # [batch_size, num_frames]
+ psnr = {}
+ psnr_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ psnr[clip_timestamp] = np.mean(psnr_results[:,clip_timestamp])
+ psnr_std[clip_timestamp] = np.std(psnr_results[:,clip_timestamp])
+
+ result = {
+ "value": psnr,
+ "value_std": psnr_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+
+ import json
+ result = calculate_psnr(videos1, videos2)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_ssim.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_ssim.py
new file mode 100644
index 0000000000000000000000000000000000000000..b2de811b6c508667177e0c58a1b8a654063fff6b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/cal_ssim.py
@@ -0,0 +1,113 @@
+import numpy as np
+import torch
+from tqdm import tqdm
+import cv2
+
+def ssim(img1, img2):
+ C1 = 0.01 ** 2
+ C2 = 0.03 ** 2
+ img1 = img1.astype(np.float64)
+ img2 = img2.astype(np.float64)
+ kernel = cv2.getGaussianKernel(11, 1.5)
+ window = np.outer(kernel, kernel.transpose())
+ mu1 = cv2.filter2D(img1, -1, window)[5:-5, 5:-5] # valid
+ mu2 = cv2.filter2D(img2, -1, window)[5:-5, 5:-5]
+ mu1_sq = mu1 ** 2
+ mu2_sq = mu2 ** 2
+ mu1_mu2 = mu1 * mu2
+ sigma1_sq = cv2.filter2D(img1 ** 2, -1, window)[5:-5, 5:-5] - mu1_sq
+ sigma2_sq = cv2.filter2D(img2 ** 2, -1, window)[5:-5, 5:-5] - mu2_sq
+ sigma12 = cv2.filter2D(img1 * img2, -1, window)[5:-5, 5:-5] - mu1_mu2
+ ssim_map = ((2 * mu1_mu2 + C1) * (2 * sigma12 + C2)) / ((mu1_sq + mu2_sq + C1) *
+ (sigma1_sq + sigma2_sq + C2))
+ return ssim_map.mean()
+
+
+def calculate_ssim_function(img1, img2):
+ # [0,1]
+ # ssim is the only metric extremely sensitive to gray being compared to b/w
+ if not img1.shape == img2.shape:
+ raise ValueError('Input images must have the same dimensions.')
+ if img1.ndim == 2:
+ return ssim(img1, img2)
+ elif img1.ndim == 3:
+ if img1.shape[0] == 3:
+ ssims = []
+ for i in range(3):
+ ssims.append(ssim(img1[i], img2[i]))
+ return np.array(ssims).mean()
+ elif img1.shape[0] == 1:
+ return ssim(np.squeeze(img1), np.squeeze(img2))
+ else:
+ raise ValueError('Wrong input image dimensions.')
+
+def trans(x):
+ return x
+
+def calculate_ssim(videos1, videos2):
+ print("calculate_ssim...")
+
+ # videos [batch_size, timestamps, channel, h, w]
+
+ assert videos1.shape == videos2.shape
+
+ videos1 = trans(videos1)
+ videos2 = trans(videos2)
+
+ ssim_results = []
+
+ for video_num in tqdm(range(videos1.shape[0])):
+ # get a video
+ # video [timestamps, channel, h, w]
+ video1 = videos1[video_num]
+ video2 = videos2[video_num]
+
+ ssim_results_of_a_video = []
+ for clip_timestamp in range(len(video1)):
+ # get a img
+ # img [timestamps[x], channel, h, w]
+ # img [channel, h, w] numpy
+
+ img1 = video1[clip_timestamp].numpy()
+ img2 = video2[clip_timestamp].numpy()
+
+ # calculate ssim of a video
+ ssim_results_of_a_video.append(calculate_ssim_function(img1, img2))
+
+ ssim_results.append(ssim_results_of_a_video)
+
+ ssim_results = np.array(ssim_results)
+
+ ssim = {}
+ ssim_std = {}
+
+ for clip_timestamp in range(len(video1)):
+ ssim[clip_timestamp] = np.mean(ssim_results[:,clip_timestamp])
+ ssim_std[clip_timestamp] = np.std(ssim_results[:,clip_timestamp])
+
+ result = {
+ "value": ssim,
+ "value_std": ssim_std,
+ "video_setting": video1.shape,
+ "video_setting_name": "time, channel, heigth, width",
+ }
+
+ return result
+
+# test code / using example
+
+def main():
+ NUMBER_OF_VIDEOS = 8
+ VIDEO_LENGTH = 50
+ CHANNEL = 3
+ SIZE = 64
+ videos1 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ videos2 = torch.zeros(NUMBER_OF_VIDEOS, VIDEO_LENGTH, CHANNEL, SIZE, SIZE, requires_grad=False)
+ device = torch.device("cuda")
+
+ import json
+ result = calculate_ssim(videos1, videos2)
+ print(json.dumps(result, indent=4))
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_clip_score.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_clip_score.py
new file mode 100644
index 0000000000000000000000000000000000000000..ed2f5108233a5bc65d0e945f74edc9599d1d5557
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_clip_score.py
@@ -0,0 +1,225 @@
+"""Calculates the CLIP Scores
+
+The CLIP model is a contrasitively learned language-image model. There is
+an image encoder and a text encoder. It is believed that the CLIP model could
+measure the similarity of cross modalities. Please find more information from
+https://github.com/openai/CLIP.
+
+The CLIP Score measures the Cosine Similarity between two embedded features.
+This repository utilizes the pretrained CLIP Model to calculate
+the mean average of cosine similarities.
+
+See --help to see further details.
+
+Code apapted from https://github.com/mseitzer/pytorch-fid and https://github.com/openai/CLIP.
+
+Copyright 2023 The Hong Kong Polytechnic University
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+import os
+import os.path as osp
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
+
+import clip
+import torch
+from PIL import Image
+from torch.utils.data import Dataset, DataLoader
+
+try:
+ from tqdm import tqdm
+except ImportError:
+ # If tqdm is not available, provide a mock version of it
+ def tqdm(x):
+ return x
+
+
+IMAGE_EXTENSIONS = {'bmp', 'jpg', 'jpeg', 'pgm', 'png', 'ppm',
+ 'tif', 'tiff', 'webp'}
+
+TEXT_EXTENSIONS = {'txt'}
+
+
+class DummyDataset(Dataset):
+
+ FLAGS = ['img', 'txt']
+ def __init__(self, real_path, generated_path,
+ real_flag: str = 'img',
+ generated_flag: str = 'img',
+ transform = None,
+ tokenizer = None) -> None:
+ super().__init__()
+ assert real_flag in self.FLAGS and generated_flag in self.FLAGS, \
+ 'CLIP Score only support modality of {}. However, get {} and {}'.format(
+ self.FLAGS, real_flag, generated_flag
+ )
+ self.real_folder = self._combine_without_prefix(real_path)
+ self.real_flag = real_flag
+ self.fake_foler = self._combine_without_prefix(generated_path)
+ self.generated_flag = generated_flag
+ self.transform = transform
+ self.tokenizer = tokenizer
+ # assert self._check()
+
+ def __len__(self):
+ return len(self.real_folder)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_path = self.real_folder[index]
+ generated_path = self.fake_foler[index]
+ real_data = self._load_modality(real_path, self.real_flag)
+ fake_data = self._load_modality(generated_path, self.generated_flag)
+
+ sample = dict(real=real_data, fake=fake_data)
+ return sample
+
+ def _load_modality(self, path, modality):
+ if modality == 'img':
+ data = self._load_img(path)
+ elif modality == 'txt':
+ data = self._load_txt(path)
+ else:
+ raise TypeError("Got unexpected modality: {}".format(modality))
+ return data
+
+ def _load_img(self, path):
+ img = Image.open(path)
+ if self.transform is not None:
+ img = self.transform(img)
+ return img
+
+ def _load_txt(self, path):
+ with open(path, 'r') as fp:
+ data = fp.read()
+ fp.close()
+ if self.tokenizer is not None:
+ data = self.tokenizer(data).squeeze()
+ return data
+
+ def _check(self):
+ for idx in range(len(self)):
+ real_name = self.real_folder[idx].split('.')
+ fake_name = self.fake_folder[idx].split('.')
+ if fake_name != real_name:
+ return False
+ return True
+
+ def _combine_without_prefix(self, folder_path, prefix='.'):
+ folder = []
+ for name in os.listdir(folder_path):
+ if name[0] == prefix:
+ continue
+ folder.append(osp.join(folder_path, name))
+ folder.sort()
+ return folder
+
+
+@torch.no_grad()
+def calculate_clip_score(dataloader, model, real_flag, generated_flag):
+ score_acc = 0.
+ sample_num = 0.
+ logit_scale = model.logit_scale.exp()
+ for batch_data in tqdm(dataloader):
+ real = batch_data['real']
+ real_features = forward_modality(model, real, real_flag)
+ fake = batch_data['fake']
+ fake_features = forward_modality(model, fake, generated_flag)
+
+ # normalize features
+ real_features = real_features / real_features.norm(dim=1, keepdim=True).to(torch.float32)
+ fake_features = fake_features / fake_features.norm(dim=1, keepdim=True).to(torch.float32)
+
+ # calculate scores
+ # score = logit_scale * real_features @ fake_features.t()
+ # score_acc += torch.diag(score).sum()
+ score = logit_scale * (fake_features * real_features).sum()
+ score_acc += score
+ sample_num += real.shape[0]
+
+ return score_acc / sample_num
+
+
+def forward_modality(model, data, flag):
+ device = next(model.parameters()).device
+ if flag == 'img':
+ features = model.encode_image(data.to(device))
+ elif flag == 'txt':
+ features = model.encode_text(data.to(device))
+ else:
+ raise TypeError
+ return features
+
+
+def main():
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
+ parser.add_argument('--batch-size', type=int, default=50,
+ help='Batch size to use')
+ parser.add_argument('--clip-model', type=str, default='ViT-B/32',
+ help='CLIP model to use')
+ parser.add_argument('--num-workers', type=int, default=8,
+ help=('Number of processes to use for data loading. '
+ 'Defaults to `min(8, num_cpus)`'))
+ parser.add_argument('--device', type=str, default=None,
+ help='Device to use. Like cuda, cuda:0 or cpu')
+ parser.add_argument('--real_flag', type=str, default='img',
+ help=('The modality of real path. '
+ 'Default to img'))
+ parser.add_argument('--generated_flag', type=str, default='txt',
+ help=('The modality of generated path. '
+ 'Default to txt'))
+ parser.add_argument('--real_path', type=str,
+ help=('Paths to the real images or '
+ 'to .npz statistic files'))
+ parser.add_argument('--generated_path', type=str,
+ help=('Paths to the generated images or '
+ 'to .npz statistic files'))
+ args = parser.parse_args()
+
+ if args.device is None:
+ device = torch.device('cuda' if (torch.cuda.is_available()) else 'cpu')
+ else:
+ device = torch.device(args.device)
+
+ if args.num_workers is None:
+ try:
+ num_cpus = len(os.sched_getaffinity(0))
+ except AttributeError:
+ # os.sched_getaffinity is not available under Windows, use
+ # os.cpu_count instead (which may not return the *available* number
+ # of CPUs).
+ num_cpus = os.cpu_count()
+
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
+ else:
+ num_workers = args.num_workers
+
+ print('Loading CLIP model: {}'.format(args.clip_model))
+ model, preprocess = clip.load(args.clip_model, device=device)
+
+ dataset = DummyDataset(args.real_path, args.generated_path,
+ args.real_flag, args.generated_flag,
+ transform=preprocess, tokenizer=clip.tokenize)
+ dataloader = DataLoader(dataset, args.batch_size,
+ num_workers=num_workers, pin_memory=True)
+
+ print('Calculating CLIP Score:')
+ clip_score = calculate_clip_score(dataloader, model,
+ args.real_flag, args.generated_flag)
+ clip_score = clip_score.cpu().item()
+ print('CLIP Score: ', clip_score)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_common_metric.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_common_metric.py
new file mode 100644
index 0000000000000000000000000000000000000000..7e93f8853a91acdf80186decb5e89ad835af7842
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/eval_common_metric.py
@@ -0,0 +1,226 @@
+"""Calculates the CLIP Scores
+
+The CLIP model is a contrasitively learned language-image model. There is
+an image encoder and a text encoder. It is believed that the CLIP model could
+measure the similarity of cross modalities. Please find more information from
+https://github.com/openai/CLIP.
+
+The CLIP Score measures the Cosine Similarity between two embedded features.
+This repository utilizes the pretrained CLIP Model to calculate
+the mean average of cosine similarities.
+
+See --help to see further details.
+
+Code apapted from https://github.com/mseitzer/pytorch-fid and https://github.com/openai/CLIP.
+
+Copyright 2023 The Hong Kong Polytechnic University
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+"""
+
+import os
+import os.path as osp
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
+import numpy as np
+import torch
+from torch.utils.data import Dataset, DataLoader, Subset
+from decord import VideoReader, cpu
+import random
+from pytorchvideo.transforms import ShortSideScale
+from torchvision.io import read_video
+from torchvision.transforms import Lambda, Compose
+from torchvision.transforms._transforms_video import CenterCropVideo
+from cal_lpips import calculate_lpips
+from cal_fvd import calculate_fvd
+from cal_psnr import calculate_psnr
+# from cal_flolpips import calculate_flolpips
+from cal_ssim import calculate_ssim
+try:
+ from tqdm import tqdm
+except ImportError:
+ # If tqdm is not available, provide a mock version of it
+ def tqdm(x):
+ return x
+
+class VideoDataset(Dataset):
+ def __init__(self,
+ real_video_dir,
+ generated_video_dir,
+ num_frames,
+ sample_rate = 1,
+ crop_size=None,
+ resolution=128,
+ ) -> None:
+ super().__init__()
+ self.real_video_files = []
+ self.generated_video_files = self._combine_without_prefix(generated_video_dir)
+ for video_file in self.generated_video_files:
+ filename = os.path.basename(video_file)
+ self.real_video_files.append(os.path.join(real_video_dir, filename))
+ self.num_frames = num_frames
+ self.sample_rate = sample_rate
+ self.crop_size = crop_size
+ self.short_size = resolution
+
+
+ def __len__(self):
+ return len(self.real_video_files)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_video_file = self.real_video_files[index]
+ generated_video_file = self.generated_video_files[index]
+ real_video_tensor = self._load_video(real_video_file, self.sample_rate)
+ generated_video_tensor = self._load_video(generated_video_file, 1)
+ return {'real': real_video_tensor, 'generated':generated_video_tensor }
+
+
+ def _load_video(self, video_path, sample_rate):
+ num_frames = self.num_frames
+ decord_vr = VideoReader(video_path, ctx=cpu(0))
+ total_frames = len(decord_vr)
+ sample_frames_len = sample_rate * num_frames
+
+ if total_frames >= sample_frames_len:
+ s = 0
+ e = s + sample_frames_len
+ num_frames = num_frames
+ else:
+ s = 0
+ e = total_frames
+ num_frames = int(total_frames / sample_frames_len * num_frames)
+ print(f'sample_frames_len {sample_frames_len}, only can sample {num_frames * sample_rate}', video_path,
+ total_frames)
+
+
+ frame_id_list = np.linspace(s, e - 1, num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (C, T, H, W)
+ return _preprocess(video_data, short_size=self.short_size, crop_size = self.crop_size)
+
+
+ def _combine_without_prefix(self, folder_path, prefix='.'):
+ folder = []
+ os.makedirs(folder_path, exist_ok=True)
+ for name in os.listdir(folder_path):
+ if name[0] == prefix:
+ continue
+ if osp.isfile(osp.join(folder_path, name)):
+ folder.append(osp.join(folder_path, name))
+ folder.sort()
+ return folder
+
+def _preprocess(video_data, short_size=128, crop_size=None):
+ transform = Compose(
+ [
+ Lambda(lambda x: x / 255.0),
+ ShortSideScale(size=short_size),
+ CenterCropVideo(crop_size=crop_size),
+ ]
+ )
+ video_outputs = transform(video_data)
+ # video_outputs = torch.unsqueeze(video_outputs, 0) # (bz,c,t,h,w)
+ return video_outputs
+
+
+def calculate_common_metric(args, dataloader, device):
+
+ score_list = []
+ for batch_data in tqdm(dataloader): # {'real': real_video_tensor, 'generated':generated_video_tensor }
+ real_videos = batch_data['real']
+ generated_videos = batch_data['generated']
+
+ assert real_videos.shape[2] == generated_videos.shape[2]
+ if args.metric == 'fvd':
+ tmp_list = list(calculate_fvd(real_videos, generated_videos, args.device, method=args.fvd_method)['value'].values())
+ elif args.metric == 'ssim':
+ tmp_list = list(calculate_ssim(real_videos, generated_videos)['value'].values())
+ elif args.metric == 'psnr':
+ tmp_list = list(calculate_psnr(real_videos, generated_videos)['value'].values())
+ elif args.metric == 'flolpips':
+ result = calculate_flolpips(real_videos, generated_videos, args.device)
+ tmp_list = list(result['value'].values())
+ elif args.metric == 'wraperror':
+ result = calculate_wraperror(real_videos, generated_videos, args.device)
+ tmp_list = list(result['value'].values())
+ else:
+ tmp_list = list(calculate_lpips(real_videos, generated_videos, args.device)['value'].values())
+ score_list += tmp_list
+ return np.mean(score_list)
+
+def main():
+ parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
+ parser.add_argument('--batch_size', type=int, default=2,
+ help='Batch size to use')
+ parser.add_argument('--real_video_dir', type=str,
+ help=('the path of real videos`'))
+ parser.add_argument('--generated_video_dir', type=str,
+ help=('the path of generated videos`'))
+ parser.add_argument('--device', type=str, default=None,
+ help='Device to use. Like cuda, cuda:0 or cpu')
+ parser.add_argument('--num_workers', type=int, default=8,
+ help=('Number of processes to use for data loading. '
+ 'Defaults to `min(8, num_cpus)`'))
+ parser.add_argument('--sample_fps', type=int, default=30)
+ parser.add_argument('--resolution', type=int, default=336)
+ parser.add_argument('--crop_size', type=int, default=None)
+ parser.add_argument('--num_frames', type=int, default=100)
+ parser.add_argument('--sample_rate', type=int, default=1)
+ parser.add_argument('--subset_size', type=int, default=None)
+ parser.add_argument("--metric", type=str, default="fvd",choices=['fvd','psnr','ssim','lpips', 'flolpips'])
+ parser.add_argument("--fvd_method", type=str, default='styleganv',choices=['styleganv','videogpt'])
+
+
+ args = parser.parse_args()
+
+ if args.device is None:
+ device = torch.device('cuda:1' if (torch.cuda.is_available()) else 'cpu')
+ else:
+ device = torch.device(args.device)
+
+ if args.num_workers is None:
+ try:
+ num_cpus = len(os.sched_getaffinity(0))
+ except AttributeError:
+ # os.sched_getaffinity is not available under Windows, use
+ # os.cpu_count instead (which may not return the *available* number
+ # of CPUs).
+ num_cpus = os.cpu_count()
+
+ num_workers = min(num_cpus, 8) if num_cpus is not None else 0
+ else:
+ num_workers = args.num_workers
+
+
+ dataset = VideoDataset(args.real_video_dir,
+ args.generated_video_dir,
+ num_frames = args.num_frames,
+ sample_rate = args.sample_rate,
+ crop_size=args.crop_size,
+ resolution=args.resolution)
+
+ if args.subset_size:
+ indices = range(args.subset_size)
+ dataset = Subset(dataset, indices=indices)
+
+ dataloader = DataLoader(dataset, args.batch_size,
+ num_workers=num_workers, pin_memory=True)
+
+
+ metric_score = calculate_common_metric(args, dataloader,device)
+ print('metric: ', args.metric, " ",metric_score)
+
+if __name__ == '__main__':
+ main()
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/correlation/correlation.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/correlation/correlation.py
new file mode 100644
index 0000000000000000000000000000000000000000..5f88f01076ce9b65249f7fe87b270aef088390e9
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/correlation/correlation.py
@@ -0,0 +1,397 @@
+#!/usr/bin/env python
+
+import torch
+
+import cupy#add
+import re
+
+kernel_Correlation_rearrange = '''
+ extern "C" __global__ void kernel_Correlation_rearrange(
+ const int n,
+ const float* input,
+ float* output
+ ) {
+ int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x;
+
+ if (intIndex >= n) {
+ return;
+ }
+
+ int intSample = blockIdx.z;
+ int intChannel = blockIdx.y;
+
+ float fltValue = input[(((intSample * SIZE_1(input)) + intChannel) * SIZE_2(input) * SIZE_3(input)) + intIndex];
+
+ __syncthreads();
+
+ int intPaddedY = (intIndex / SIZE_3(input)) + 4;
+ int intPaddedX = (intIndex % SIZE_3(input)) + 4;
+ int intRearrange = ((SIZE_3(input) + 8) * intPaddedY) + intPaddedX;
+
+ output[(((intSample * SIZE_1(output) * SIZE_2(output)) + intRearrange) * SIZE_1(input)) + intChannel] = fltValue;
+ }
+'''
+
+kernel_Correlation_updateOutput = '''
+ extern "C" __global__ void kernel_Correlation_updateOutput(
+ const int n,
+ const float* rbot0,
+ const float* rbot1,
+ float* top
+ ) {
+ extern __shared__ char patch_data_char[];
+
+ float *patch_data = (float *)patch_data_char;
+
+ // First (upper left) position of kernel upper-left corner in current center position of neighborhood in image 1
+ int x1 = blockIdx.x + 4;
+ int y1 = blockIdx.y + 4;
+ int item = blockIdx.z;
+ int ch_off = threadIdx.x;
+
+ // Load 3D patch into shared shared memory
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int idx1 = ((item * SIZE_1(rbot0) + y1+j) * SIZE_2(rbot0) + x1+i) * SIZE_3(rbot0) + ch;
+ int idxPatchData = ji_off + ch;
+ patch_data[idxPatchData] = rbot0[idx1];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ __shared__ float sum[32];
+
+ // Compute correlation
+ for (int top_channel = 0; top_channel < SIZE_1(top); top_channel++) {
+ sum[ch_off] = 0;
+
+ int s2o = top_channel % 9 - 4;
+ int s2p = top_channel / 9 - 4;
+
+ for (int j = 0; j < 1; j++) { // HEIGHT
+ for (int i = 0; i < 1; i++) { // WIDTH
+ int ji_off = (j + i) * SIZE_3(rbot0);
+ for (int ch = ch_off; ch < SIZE_3(rbot0); ch += 32) { // CHANNELS
+ int x2 = x1 + s2o;
+ int y2 = y1 + s2p;
+
+ int idxPatchData = ji_off + ch;
+ int idx2 = ((item * SIZE_1(rbot0) + y2+j) * SIZE_2(rbot0) + x2+i) * SIZE_3(rbot0) + ch;
+
+ sum[ch_off] += patch_data[idxPatchData] * rbot1[idx2];
+ }
+ }
+ }
+
+ __syncthreads();
+
+ if (ch_off == 0) {
+ float total_sum = 0;
+ for (int idx = 0; idx < 32; idx++) {
+ total_sum += sum[idx];
+ }
+ const int sumelems = SIZE_3(rbot0);
+ const int index = ((top_channel*SIZE_2(top) + blockIdx.y)*SIZE_3(top))+blockIdx.x;
+ top[index + item*SIZE_1(top)*SIZE_2(top)*SIZE_3(top)] = total_sum / (float)sumelems;
+ }
+ }
+ }
+'''
+
+kernel_Correlation_updateGradFirst = '''
+ #define ROUND_OFF 50000
+
+ extern "C" __global__ void kernel_Correlation_updateGradFirst(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradFirst,
+ float* gradSecond
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradFirst); // channels
+ int l = (intIndex / SIZE_1(gradFirst)) % SIZE_3(gradFirst) + 4; // w-pos
+ int m = (intIndex / SIZE_1(gradFirst) / SIZE_3(gradFirst)) % SIZE_2(gradFirst) + 4; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = round_off;
+
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
+ int ymin = (m - 4 + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4)
+
+ // Same here:
+ int xmax = (l - 4 + round_off_s1) - round_off; // floor (l - 4)
+ int ymax = (m - 4 + round_off_s1) - round_off; // floor (m - 4)
+
+ float sum = 0;
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ for (int p = -4; p <= 4; p++) {
+ for (int o = -4; o <= 4; o++) {
+ // Get rbot1 data:
+ int s2o = o;
+ int s2p = p;
+ int idxbot1 = ((intSample * SIZE_1(rbot0) + (m+s2p)) * SIZE_2(rbot0) + (l+s2o)) * SIZE_3(rbot0) + n;
+ float bot1tmp = rbot1[idxbot1]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+4) * 9 + (o+4); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot1tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradFirst);
+ const int bot0index = ((n * SIZE_2(gradFirst)) + (m-4)) * SIZE_3(gradFirst) + (l-4);
+ gradFirst[bot0index + intSample*SIZE_1(gradFirst)*SIZE_2(gradFirst)*SIZE_3(gradFirst)] = sum / (float)sumelems;
+ } }
+'''
+
+kernel_Correlation_updateGradSecond = '''
+ #define ROUND_OFF 50000
+
+ extern "C" __global__ void kernel_Correlation_updateGradSecond(
+ const int n,
+ const int intSample,
+ const float* rbot0,
+ const float* rbot1,
+ const float* gradOutput,
+ float* gradFirst,
+ float* gradSecond
+ ) { for (int intIndex = (blockIdx.x * blockDim.x) + threadIdx.x; intIndex < n; intIndex += blockDim.x * gridDim.x) {
+ int n = intIndex % SIZE_1(gradSecond); // channels
+ int l = (intIndex / SIZE_1(gradSecond)) % SIZE_3(gradSecond) + 4; // w-pos
+ int m = (intIndex / SIZE_1(gradSecond) / SIZE_3(gradSecond)) % SIZE_2(gradSecond) + 4; // h-pos
+
+ // round_off is a trick to enable integer division with ceil, even for negative numbers
+ // We use a large offset, for the inner part not to become negative.
+ const int round_off = ROUND_OFF;
+ const int round_off_s1 = round_off;
+
+ float sum = 0;
+ for (int p = -4; p <= 4; p++) {
+ for (int o = -4; o <= 4; o++) {
+ int s2o = o;
+ int s2p = p;
+
+ //Get X,Y ranges and clamp
+ // We add round_off before_s1 the int division and subtract round_off after it, to ensure the formula matches ceil behavior:
+ int xmin = (l - 4 - s2o + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
+ int ymin = (m - 4 - s2p + round_off_s1 - 1) + 1 - round_off; // ceil (l - 4 - s2o)
+
+ // Same here:
+ int xmax = (l - 4 - s2o + round_off_s1) - round_off; // floor (l - 4 - s2o)
+ int ymax = (m - 4 - s2p + round_off_s1) - round_off; // floor (m - 4 - s2p)
+
+ if (xmax>=0 && ymax>=0 && (xmin<=SIZE_3(gradOutput)-1) && (ymin<=SIZE_2(gradOutput)-1)) {
+ xmin = max(0,xmin);
+ xmax = min(SIZE_3(gradOutput)-1,xmax);
+
+ ymin = max(0,ymin);
+ ymax = min(SIZE_2(gradOutput)-1,ymax);
+
+ // Get rbot0 data:
+ int idxbot0 = ((intSample * SIZE_1(rbot0) + (m-s2p)) * SIZE_2(rbot0) + (l-s2o)) * SIZE_3(rbot0) + n;
+ float bot0tmp = rbot0[idxbot0]; // rbot1[l+s2o,m+s2p,n]
+
+ // Index offset for gradOutput in following loops:
+ int op = (p+4) * 9 + (o+4); // index[o,p]
+ int idxopoffset = (intSample * SIZE_1(gradOutput) + op);
+
+ for (int y = ymin; y <= ymax; y++) {
+ for (int x = xmin; x <= xmax; x++) {
+ int idxgradOutput = (idxopoffset * SIZE_2(gradOutput) + y) * SIZE_3(gradOutput) + x; // gradOutput[x,y,o,p]
+ sum += gradOutput[idxgradOutput] * bot0tmp;
+ }
+ }
+ }
+ }
+ }
+ const int sumelems = SIZE_1(gradSecond);
+ const int bot1index = ((n * SIZE_2(gradSecond)) + (m-4)) * SIZE_3(gradSecond) + (l-4);
+ gradSecond[bot1index + intSample*SIZE_1(gradSecond)*SIZE_2(gradSecond)*SIZE_3(gradSecond)] = sum / (float)sumelems;
+ } }
+'''
+
+def cupy_kernel(strFunction, objVariables):
+ strKernel = globals()[strFunction]
+
+ while True:
+ objMatch = re.search('(SIZE_)([0-4])(\()([^\)]*)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArg = int(objMatch.group(2))
+
+ strTensor = objMatch.group(4)
+ intSizes = objVariables[strTensor].size()
+
+ strKernel = strKernel.replace(objMatch.group(), str(intSizes[intArg]))
+ # end
+
+ while True:
+ objMatch = re.search('(VALUE_)([0-4])(\()([^\)]+)(\))', strKernel)
+
+ if objMatch is None:
+ break
+ # end
+
+ intArgs = int(objMatch.group(2))
+ strArgs = objMatch.group(4).split(',')
+
+ strTensor = strArgs[0]
+ intStrides = objVariables[strTensor].stride()
+ strIndex = [ '((' + strArgs[intArg + 1].replace('{', '(').replace('}', ')').strip() + ')*' + str(intStrides[intArg]) + ')' for intArg in range(intArgs) ]
+
+ strKernel = strKernel.replace(objMatch.group(0), strTensor + '[' + str.join('+', strIndex) + ']')
+ # end
+
+ return strKernel
+# end
+
+@cupy.memoize(for_each_device=True)
+def cupy_launch(strFunction, strKernel):
+ return cupy.RawKernel(strKernel, strFunction)
+# end
+
+class _FunctionCorrelation(torch.autograd.Function):
+ @staticmethod
+ def forward(self, first, second):
+ rbot0 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
+ rbot1 = first.new_zeros([ first.shape[0], first.shape[2] + 8, first.shape[3] + 8, first.shape[1] ])
+
+ self.save_for_backward(first, second, rbot0, rbot1)
+
+ first = first.contiguous(); assert(first.is_cuda == True)
+ second = second.contiguous(); assert(second.is_cuda == True)
+
+ output = first.new_zeros([ first.shape[0], 81, first.shape[2], first.shape[3] ])
+
+ if first.is_cuda == True:
+ n = first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'input': first,
+ 'output': rbot0
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), first.shape[1], first.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ n, first.data_ptr(), rbot0.data_ptr() ]
+ )
+
+ n = second.shape[2] * second.shape[3]
+ cupy_launch('kernel_Correlation_rearrange', cupy_kernel('kernel_Correlation_rearrange', {
+ 'input': second,
+ 'output': rbot1
+ }))(
+ grid=tuple([ int((n + 16 - 1) / 16), second.shape[1], second.shape[0] ]),
+ block=tuple([ 16, 1, 1 ]),
+ args=[ n, second.data_ptr(), rbot1.data_ptr() ]
+ )
+
+ n = output.shape[1] * output.shape[2] * output.shape[3]
+ cupy_launch('kernel_Correlation_updateOutput', cupy_kernel('kernel_Correlation_updateOutput', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'top': output
+ }))(
+ grid=tuple([ output.shape[3], output.shape[2], output.shape[0] ]),
+ block=tuple([ 32, 1, 1 ]),
+ shared_mem=first.shape[1] * 4,
+ args=[ n, rbot0.data_ptr(), rbot1.data_ptr(), output.data_ptr() ]
+ )
+
+ elif first.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ return output
+ # end
+
+ @staticmethod
+ def backward(self, gradOutput):
+ first, second, rbot0, rbot1 = self.saved_tensors
+
+ gradOutput = gradOutput.contiguous(); assert(gradOutput.is_cuda == True)
+
+ gradFirst = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[0] == True else None
+ gradSecond = first.new_zeros([ first.shape[0], first.shape[1], first.shape[2], first.shape[3] ]) if self.needs_input_grad[1] == True else None
+
+ if first.is_cuda == True:
+ if gradFirst is not None:
+ for intSample in range(first.shape[0]):
+ n = first.shape[1] * first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_updateGradFirst', cupy_kernel('kernel_Correlation_updateGradFirst', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradFirst': gradFirst,
+ 'gradSecond': None
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), gradFirst.data_ptr(), None ]
+ )
+ # end
+ # end
+
+ if gradSecond is not None:
+ for intSample in range(first.shape[0]):
+ n = first.shape[1] * first.shape[2] * first.shape[3]
+ cupy_launch('kernel_Correlation_updateGradSecond', cupy_kernel('kernel_Correlation_updateGradSecond', {
+ 'rbot0': rbot0,
+ 'rbot1': rbot1,
+ 'gradOutput': gradOutput,
+ 'gradFirst': None,
+ 'gradSecond': gradSecond
+ }))(
+ grid=tuple([ int((n + 512 - 1) / 512), 1, 1 ]),
+ block=tuple([ 512, 1, 1 ]),
+ args=[ n, intSample, rbot0.data_ptr(), rbot1.data_ptr(), gradOutput.data_ptr(), None, gradSecond.data_ptr() ]
+ )
+ # end
+ # end
+
+ elif first.is_cuda == False:
+ raise NotImplementedError()
+
+ # end
+
+ return gradFirst, gradSecond
+ # end
+# end
+
+def FunctionCorrelation(tenFirst, tenSecond):
+ return _FunctionCorrelation.apply(tenFirst, tenSecond)
+# end
+
+class ModuleCorrelation(torch.nn.Module):
+ def __init__(self):
+ super(ModuleCorrelation, self).__init__()
+ # end
+
+ def forward(self, tenFirst, tenSecond):
+ return _FunctionCorrelation.apply(tenFirst, tenSecond)
+ # end
+# end
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/flolpips.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/flolpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..66f4731496482d4fe1ccda76680d316cc3d773cd
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/flolpips.py
@@ -0,0 +1,308 @@
+
+from __future__ import absolute_import
+import os
+import numpy as np
+import torch
+import torch.nn as nn
+from torch.autograd import Variable
+from .pretrained_networks import vgg16, alexnet, squeezenet
+import torch.nn
+import torch.nn.functional as F
+import torchvision.transforms.functional as TF
+import cv2
+
+from .pwcnet import Network as PWCNet
+from .utils import *
+
+def spatial_average(in_tens, keepdim=True):
+ return in_tens.mean([2,3],keepdim=keepdim)
+
+def mw_spatial_average(in_tens, flow, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = torch.sqrt(flow[:,0:1]**2 + flow[:,1:2]**2)
+ flow_mag = flow_mag / torch.sum(flow_mag, dim=[1,2,3], keepdim=True)
+ return torch.sum(in_tens*flow_mag, dim=[2,3],keepdim=keepdim)
+
+
+def mtw_spatial_average(in_tens, flow, texture, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ texture = F.interpolate(texture, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = torch.sqrt(flow[:,0:1]**2 + flow[:,1:2]**2)
+ flow_mag = (flow_mag - flow_mag.min()) / (flow_mag.max() - flow_mag.min()) + 1e-6
+ texture = (texture - texture.min()) / (texture.max() - texture.min()) + 1e-6
+ weight = flow_mag / texture
+ weight /= torch.sum(weight)
+ return torch.sum(in_tens*weight, dim=[2,3],keepdim=keepdim)
+
+
+
+def m2w_spatial_average(in_tens, flow, keepdim=True):
+ _,_,h,w = in_tens.shape
+ flow = F.interpolate(flow, (h,w), align_corners=False, mode='bilinear')
+ flow_mag = flow[:,0:1]**2 + flow[:,1:2]**2 # B,1,H,W
+ flow_mag = flow_mag / torch.sum(flow_mag)
+ return torch.sum(in_tens*flow_mag, dim=[2,3],keepdim=keepdim)
+
+def upsample(in_tens, out_HW=(64,64)): # assumes scale factor is same for H and W
+ in_H, in_W = in_tens.shape[2], in_tens.shape[3]
+ return nn.Upsample(size=out_HW, mode='bilinear', align_corners=False)(in_tens)
+
+# Learned perceptual metric
+class LPIPS(nn.Module):
+ def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False,
+ pnet_rand=False, pnet_tune=False, use_dropout=True, model_path=None, eval_mode=True, verbose=False):
+ # lpips - [True] means with linear calibration on top of base network
+ # pretrained - [True] means load linear weights
+
+ super(LPIPS, self).__init__()
+ if(verbose):
+ print('Setting up [%s] perceptual loss: trunk [%s], v[%s], spatial [%s]'%
+ ('LPIPS' if lpips else 'baseline', net, version, 'on' if spatial else 'off'))
+
+ self.pnet_type = net
+ self.pnet_tune = pnet_tune
+ self.pnet_rand = pnet_rand
+ self.spatial = spatial
+ self.lpips = lpips # false means baseline of just averaging all layers
+ self.version = version
+ self.scaling_layer = ScalingLayer()
+
+ if(self.pnet_type in ['vgg','vgg16']):
+ net_type = vgg16
+ self.chns = [64,128,256,512,512]
+ elif(self.pnet_type=='alex'):
+ net_type = alexnet
+ self.chns = [64,192,384,256,256]
+ elif(self.pnet_type=='squeeze'):
+ net_type = squeezenet
+ self.chns = [64,128,256,384,384,512,512]
+ self.L = len(self.chns)
+
+ self.net = net_type(pretrained=not self.pnet_rand, requires_grad=self.pnet_tune)
+
+ if(lpips):
+ self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
+ self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
+ self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
+ self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
+ self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
+ self.lins = [self.lin0,self.lin1,self.lin2,self.lin3,self.lin4]
+ if(self.pnet_type=='squeeze'): # 7 layers for squeezenet
+ self.lin5 = NetLinLayer(self.chns[5], use_dropout=use_dropout)
+ self.lin6 = NetLinLayer(self.chns[6], use_dropout=use_dropout)
+ self.lins+=[self.lin5,self.lin6]
+ self.lins = nn.ModuleList(self.lins)
+
+ if(pretrained):
+ if(model_path is None):
+ import inspect
+ import os
+ model_path = os.path.abspath(os.path.join(inspect.getfile(self.__init__), '..', 'weights/v%s/%s.pth'%(version,net)))
+
+ if(verbose):
+ print('Loading model from: %s'%model_path)
+ self.load_state_dict(torch.load(model_path, map_location='cpu'), strict=False)
+
+ if(eval_mode):
+ self.eval()
+
+ def forward(self, in0, in1, retPerLayer=False, normalize=False):
+ if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
+ in0 = 2 * in0 - 1
+ in1 = 2 * in1 - 1
+
+ # v0.0 - original release had a bug, where input was not scaled
+ in0_input, in1_input = (self.scaling_layer(in0), self.scaling_layer(in1)) if self.version=='0.1' else (in0, in1)
+ outs0, outs1 = self.net.forward(in0_input), self.net.forward(in1_input)
+ feats0, feats1, diffs = {}, {}, {}
+
+ for kk in range(self.L):
+ feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
+ diffs[kk] = (feats0[kk]-feats1[kk])**2
+
+ if(self.lpips):
+ if(self.spatial):
+ res = [upsample(self.lins[kk](diffs[kk]), out_HW=in0.shape[2:]) for kk in range(self.L)]
+ else:
+ res = [spatial_average(self.lins[kk](diffs[kk]), keepdim=True) for kk in range(self.L)]
+ else:
+ if(self.spatial):
+ res = [upsample(diffs[kk].sum(dim=1,keepdim=True), out_HW=in0.shape[2:]) for kk in range(self.L)]
+ else:
+ res = [spatial_average(diffs[kk].sum(dim=1,keepdim=True), keepdim=True) for kk in range(self.L)]
+
+ # val = res[0]
+ # for l in range(1,self.L):
+ # val += res[l]
+ # print(val)
+
+ # a = spatial_average(self.lins[kk](diffs[kk]), keepdim=True)
+ # b = torch.max(self.lins[kk](feats0[kk]**2))
+ # for kk in range(self.L):
+ # a += spatial_average(self.lins[kk](diffs[kk]), keepdim=True)
+ # b = torch.max(b,torch.max(self.lins[kk](feats0[kk]**2)))
+ # a = a/self.L
+ # from IPython import embed
+ # embed()
+ # return 10*torch.log10(b/a)
+
+ # if(retPerLayer):
+ # return (val, res)
+ # else:
+ return torch.sum(torch.cat(res, 1), dim=(1,2,3), keepdims=False)
+
+
+class ScalingLayer(nn.Module):
+ def __init__(self):
+ super(ScalingLayer, self).__init__()
+ self.register_buffer('shift', torch.Tensor([-.030,-.088,-.188])[None,:,None,None])
+ self.register_buffer('scale', torch.Tensor([.458,.448,.450])[None,:,None,None])
+
+ def forward(self, inp):
+ return (inp - self.shift) / self.scale
+
+
+class NetLinLayer(nn.Module):
+ ''' A single linear layer which does a 1x1 conv '''
+ def __init__(self, chn_in, chn_out=1, use_dropout=False):
+ super(NetLinLayer, self).__init__()
+
+ layers = [nn.Dropout(),] if(use_dropout) else []
+ layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),]
+ self.model = nn.Sequential(*layers)
+
+ def forward(self, x):
+ return self.model(x)
+
+class Dist2LogitLayer(nn.Module):
+ ''' takes 2 distances, puts through fc layers, spits out value between [0,1] (if use_sigmoid is True) '''
+ def __init__(self, chn_mid=32, use_sigmoid=True):
+ super(Dist2LogitLayer, self).__init__()
+
+ layers = [nn.Conv2d(5, chn_mid, 1, stride=1, padding=0, bias=True),]
+ layers += [nn.LeakyReLU(0.2,True),]
+ layers += [nn.Conv2d(chn_mid, chn_mid, 1, stride=1, padding=0, bias=True),]
+ layers += [nn.LeakyReLU(0.2,True),]
+ layers += [nn.Conv2d(chn_mid, 1, 1, stride=1, padding=0, bias=True),]
+ if(use_sigmoid):
+ layers += [nn.Sigmoid(),]
+ self.model = nn.Sequential(*layers)
+
+ def forward(self,d0,d1,eps=0.1):
+ return self.model.forward(torch.cat((d0,d1,d0-d1,d0/(d1+eps),d1/(d0+eps)),dim=1))
+
+class BCERankingLoss(nn.Module):
+ def __init__(self, chn_mid=32):
+ super(BCERankingLoss, self).__init__()
+ self.net = Dist2LogitLayer(chn_mid=chn_mid)
+ # self.parameters = list(self.net.parameters())
+ self.loss = torch.nn.BCELoss()
+
+ def forward(self, d0, d1, judge):
+ per = (judge+1.)/2.
+ self.logit = self.net.forward(d0,d1)
+ return self.loss(self.logit, per)
+
+# L2, DSSIM metrics
+class FakeNet(nn.Module):
+ def __init__(self, use_gpu=True, colorspace='Lab'):
+ super(FakeNet, self).__init__()
+ self.use_gpu = use_gpu
+ self.colorspace = colorspace
+
+class L2(FakeNet):
+ def forward(self, in0, in1, retPerLayer=None):
+ assert(in0.size()[0]==1) # currently only supports batchSize 1
+
+ if(self.colorspace=='RGB'):
+ (N,C,X,Y) = in0.size()
+ value = torch.mean(torch.mean(torch.mean((in0-in1)**2,dim=1).view(N,1,X,Y),dim=2).view(N,1,1,Y),dim=3).view(N)
+ return value
+ elif(self.colorspace=='Lab'):
+ value = l2(tensor2np(tensor2tensorlab(in0.data,to_norm=False)),
+ tensor2np(tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
+ ret_var = Variable( torch.Tensor((value,) ) )
+ if(self.use_gpu):
+ ret_var = ret_var.cuda()
+ return ret_var
+
+class DSSIM(FakeNet):
+
+ def forward(self, in0, in1, retPerLayer=None):
+ assert(in0.size()[0]==1) # currently only supports batchSize 1
+
+ if(self.colorspace=='RGB'):
+ value = dssim(1.*tensor2im(in0.data), 1.*tensor2im(in1.data), range=255.).astype('float')
+ elif(self.colorspace=='Lab'):
+ value = dssim(tensor2np(tensor2tensorlab(in0.data,to_norm=False)),
+ tensor2np(tensor2tensorlab(in1.data,to_norm=False)), range=100.).astype('float')
+ ret_var = Variable( torch.Tensor((value,) ) )
+ if(self.use_gpu):
+ ret_var = ret_var.cuda()
+ return ret_var
+
+def print_network(net):
+ num_params = 0
+ for param in net.parameters():
+ num_params += param.numel()
+ print('Network',net)
+ print('Total number of parameters: %d' % num_params)
+
+
+class FloLPIPS(LPIPS):
+ def __init__(self, pretrained=True, net='alex', version='0.1', lpips=True, spatial=False, pnet_rand=False, pnet_tune=False, use_dropout=True, model_path=None, eval_mode=True, verbose=False):
+ super(FloLPIPS, self).__init__(pretrained, net, version, lpips, spatial, pnet_rand, pnet_tune, use_dropout, model_path, eval_mode, verbose)
+
+ def forward(self, in0, in1, flow, retPerLayer=False, normalize=False):
+ if normalize: # turn on this flag if input is [0,1] so it can be adjusted to [-1, +1]
+ in0 = 2 * in0 - 1
+ in1 = 2 * in1 - 1
+
+ in0_input, in1_input = (self.scaling_layer(in0), self.scaling_layer(in1)) if self.version=='0.1' else (in0, in1)
+ outs0, outs1 = self.net.forward(in0_input), self.net.forward(in1_input)
+ feats0, feats1, diffs = {}, {}, {}
+
+ for kk in range(self.L):
+ feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
+ diffs[kk] = (feats0[kk]-feats1[kk])**2
+
+ res = [mw_spatial_average(self.lins[kk](diffs[kk]), flow, keepdim=True) for kk in range(self.L)]
+
+ return torch.sum(torch.cat(res, 1), dim=(1,2,3), keepdims=False)
+
+
+
+
+
+class Flolpips(nn.Module):
+ def __init__(self):
+ super(Flolpips, self).__init__()
+ self.loss_fn = FloLPIPS(net='alex',version='0.1')
+ self.flownet = PWCNet()
+
+ @torch.no_grad()
+ def forward(self, I0, I1, frame_dis, frame_ref):
+ """
+ args:
+ I0: first frame of the triplet, shape: [B, C, H, W]
+ I1: third frame of the triplet, shape: [B, C, H, W]
+ frame_dis: prediction of the intermediate frame, shape: [B, C, H, W]
+ frame_ref: ground-truth of the intermediate frame, shape: [B, C, H, W]
+ """
+ assert I0.size() == I1.size() == frame_dis.size() == frame_ref.size(), \
+ "the 4 input tensors should have same size"
+
+ flow_ref = self.flownet(frame_ref, I0)
+ flow_dis = self.flownet(frame_dis, I0)
+ flow_diff = flow_ref - flow_dis
+ flolpips_wrt_I0 = self.loss_fn.forward(frame_ref, frame_dis, flow_diff, normalize=True)
+
+ flow_ref = self.flownet(frame_ref, I1)
+ flow_dis = self.flownet(frame_dis, I1)
+ flow_diff = flow_ref - flow_dis
+ flolpips_wrt_I1 = self.loss_fn.forward(frame_ref, frame_dis, flow_diff, normalize=True)
+
+ flolpips = (flolpips_wrt_I0 + flolpips_wrt_I1) / 2
+ return flolpips
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pretrained_networks.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pretrained_networks.py
new file mode 100644
index 0000000000000000000000000000000000000000..82f14e206e7b395ac9d989cb2536e17b17e65184
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pretrained_networks.py
@@ -0,0 +1,180 @@
+from collections import namedtuple
+import torch
+from torchvision import models as tv
+
+class squeezenet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(squeezenet, self).__init__()
+ pretrained_features = tv.squeezenet1_1(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.slice6 = torch.nn.Sequential()
+ self.slice7 = torch.nn.Sequential()
+ self.N_slices = 7
+ for x in range(2):
+ self.slice1.add_module(str(x), pretrained_features[x])
+ for x in range(2,5):
+ self.slice2.add_module(str(x), pretrained_features[x])
+ for x in range(5, 8):
+ self.slice3.add_module(str(x), pretrained_features[x])
+ for x in range(8, 10):
+ self.slice4.add_module(str(x), pretrained_features[x])
+ for x in range(10, 11):
+ self.slice5.add_module(str(x), pretrained_features[x])
+ for x in range(11, 12):
+ self.slice6.add_module(str(x), pretrained_features[x])
+ for x in range(12, 13):
+ self.slice7.add_module(str(x), pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1 = h
+ h = self.slice2(h)
+ h_relu2 = h
+ h = self.slice3(h)
+ h_relu3 = h
+ h = self.slice4(h)
+ h_relu4 = h
+ h = self.slice5(h)
+ h_relu5 = h
+ h = self.slice6(h)
+ h_relu6 = h
+ h = self.slice7(h)
+ h_relu7 = h
+ vgg_outputs = namedtuple("SqueezeOutputs", ['relu1','relu2','relu3','relu4','relu5','relu6','relu7'])
+ out = vgg_outputs(h_relu1,h_relu2,h_relu3,h_relu4,h_relu5,h_relu6,h_relu7)
+
+ return out
+
+
+class alexnet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(alexnet, self).__init__()
+ alexnet_pretrained_features = tv.alexnet(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.N_slices = 5
+ for x in range(2):
+ self.slice1.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(2, 5):
+ self.slice2.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(5, 8):
+ self.slice3.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(8, 10):
+ self.slice4.add_module(str(x), alexnet_pretrained_features[x])
+ for x in range(10, 12):
+ self.slice5.add_module(str(x), alexnet_pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1 = h
+ h = self.slice2(h)
+ h_relu2 = h
+ h = self.slice3(h)
+ h_relu3 = h
+ h = self.slice4(h)
+ h_relu4 = h
+ h = self.slice5(h)
+ h_relu5 = h
+ alexnet_outputs = namedtuple("AlexnetOutputs", ['relu1', 'relu2', 'relu3', 'relu4', 'relu5'])
+ out = alexnet_outputs(h_relu1, h_relu2, h_relu3, h_relu4, h_relu5)
+
+ return out
+
+class vgg16(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(vgg16, self).__init__()
+ vgg_pretrained_features = tv.vgg16(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.N_slices = 5
+ for x in range(4):
+ self.slice1.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(4, 9):
+ self.slice2.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(9, 16):
+ self.slice3.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(16, 23):
+ self.slice4.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(23, 30):
+ self.slice5.add_module(str(x), vgg_pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1_2 = h
+ h = self.slice2(h)
+ h_relu2_2 = h
+ h = self.slice3(h)
+ h_relu3_3 = h
+ h = self.slice4(h)
+ h_relu4_3 = h
+ h = self.slice5(h)
+ h_relu5_3 = h
+ vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
+ out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
+
+ return out
+
+
+
+class resnet(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True, num=18):
+ super(resnet, self).__init__()
+ if(num==18):
+ self.net = tv.resnet18(pretrained=pretrained)
+ elif(num==34):
+ self.net = tv.resnet34(pretrained=pretrained)
+ elif(num==50):
+ self.net = tv.resnet50(pretrained=pretrained)
+ elif(num==101):
+ self.net = tv.resnet101(pretrained=pretrained)
+ elif(num==152):
+ self.net = tv.resnet152(pretrained=pretrained)
+ self.N_slices = 5
+
+ self.conv1 = self.net.conv1
+ self.bn1 = self.net.bn1
+ self.relu = self.net.relu
+ self.maxpool = self.net.maxpool
+ self.layer1 = self.net.layer1
+ self.layer2 = self.net.layer2
+ self.layer3 = self.net.layer3
+ self.layer4 = self.net.layer4
+
+ def forward(self, X):
+ h = self.conv1(X)
+ h = self.bn1(h)
+ h = self.relu(h)
+ h_relu1 = h
+ h = self.maxpool(h)
+ h = self.layer1(h)
+ h_conv2 = h
+ h = self.layer2(h)
+ h_conv3 = h
+ h = self.layer3(h)
+ h_conv4 = h
+ h = self.layer4(h)
+ h_conv5 = h
+
+ outputs = namedtuple("Outputs", ['relu1','conv2','conv3','conv4','conv5'])
+ out = outputs(h_relu1, h_conv2, h_conv3, h_conv4, h_conv5)
+
+ return out
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pwcnet.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pwcnet.py
new file mode 100644
index 0000000000000000000000000000000000000000..374f18e20ce27d1fe596559c5a2f17f333e2d50f
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/pwcnet.py
@@ -0,0 +1,344 @@
+#!/usr/bin/env python
+
+import torch
+
+import getopt
+import math
+import numpy
+import os
+import PIL
+import PIL.Image
+import sys
+
+# try:
+from .correlation import correlation # the custom cost volume layer
+# except:
+# sys.path.insert(0, './correlation'); import correlation # you should consider upgrading python
+# end
+
+##########################################################
+
+# assert(int(str('').join(torch.__version__.split('.')[0:2])) >= 13) # requires at least pytorch version 1.3.0
+
+# torch.set_grad_enabled(False) # make sure to not compute gradients for computational performance
+
+# torch.backends.cudnn.enabled = True # make sure to use cudnn for computational performance
+
+# ##########################################################
+
+# arguments_strModel = 'default' # 'default', or 'chairs-things'
+# arguments_strFirst = './images/first.png'
+# arguments_strSecond = './images/second.png'
+# arguments_strOut = './out.flo'
+
+# for strOption, strArgument in getopt.getopt(sys.argv[1:], '', [ strParameter[2:] + '=' for strParameter in sys.argv[1::2] ])[0]:
+# if strOption == '--model' and strArgument != '': arguments_strModel = strArgument # which model to use
+# if strOption == '--first' and strArgument != '': arguments_strFirst = strArgument # path to the first frame
+# if strOption == '--second' and strArgument != '': arguments_strSecond = strArgument # path to the second frame
+# if strOption == '--out' and strArgument != '': arguments_strOut = strArgument # path to where the output should be stored
+# end
+
+##########################################################
+
+
+
+def backwarp(tenInput, tenFlow):
+ backwarp_tenGrid = {}
+ backwarp_tenPartial = {}
+ if str(tenFlow.shape) not in backwarp_tenGrid:
+ tenHor = torch.linspace(-1.0 + (1.0 / tenFlow.shape[3]), 1.0 - (1.0 / tenFlow.shape[3]), tenFlow.shape[3]).view(1, 1, 1, -1).expand(-1, -1, tenFlow.shape[2], -1)
+ tenVer = torch.linspace(-1.0 + (1.0 / tenFlow.shape[2]), 1.0 - (1.0 / tenFlow.shape[2]), tenFlow.shape[2]).view(1, 1, -1, 1).expand(-1, -1, -1, tenFlow.shape[3])
+
+ backwarp_tenGrid[str(tenFlow.shape)] = torch.cat([ tenHor, tenVer ], 1).cuda()
+ # end
+
+ if str(tenFlow.shape) not in backwarp_tenPartial:
+ backwarp_tenPartial[str(tenFlow.shape)] = tenFlow.new_ones([ tenFlow.shape[0], 1, tenFlow.shape[2], tenFlow.shape[3] ])
+ # end
+
+ tenFlow = torch.cat([ tenFlow[:, 0:1, :, :] / ((tenInput.shape[3] - 1.0) / 2.0), tenFlow[:, 1:2, :, :] / ((tenInput.shape[2] - 1.0) / 2.0) ], 1)
+ tenInput = torch.cat([ tenInput, backwarp_tenPartial[str(tenFlow.shape)] ], 1)
+
+ tenOutput = torch.nn.functional.grid_sample(input=tenInput, grid=(backwarp_tenGrid[str(tenFlow.shape)] + tenFlow).permute(0, 2, 3, 1), mode='bilinear', padding_mode='zeros', align_corners=False)
+
+ tenMask = tenOutput[:, -1:, :, :]; tenMask[tenMask > 0.999] = 1.0; tenMask[tenMask < 1.0] = 0.0
+
+ return tenOutput[:, :-1, :, :] * tenMask
+# end
+
+##########################################################
+
+class Network(torch.nn.Module):
+ def __init__(self):
+ super(Network, self).__init__()
+
+ class Extractor(torch.nn.Module):
+ def __init__(self):
+ super(Extractor, self).__init__()
+
+ self.netOne = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netTwo = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netThr = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFou = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=64, out_channels=96, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFiv = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=96, out_channels=128, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netSix = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=128, out_channels=196, kernel_size=3, stride=2, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=196, out_channels=196, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+ # end
+
+ def forward(self, tenInput):
+ tenOne = self.netOne(tenInput)
+ tenTwo = self.netTwo(tenOne)
+ tenThr = self.netThr(tenTwo)
+ tenFou = self.netFou(tenThr)
+ tenFiv = self.netFiv(tenFou)
+ tenSix = self.netSix(tenFiv)
+
+ return [ tenOne, tenTwo, tenThr, tenFou, tenFiv, tenSix ]
+ # end
+ # end
+
+ class Decoder(torch.nn.Module):
+ def __init__(self, intLevel):
+ super(Decoder, self).__init__()
+
+ intPrevious = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 1]
+ intCurrent = [ None, None, 81 + 32 + 2 + 2, 81 + 64 + 2 + 2, 81 + 96 + 2 + 2, 81 + 128 + 2 + 2, 81, None ][intLevel + 0]
+
+ if intLevel < 6: self.netUpflow = torch.nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)
+ if intLevel < 6: self.netUpfeat = torch.nn.ConvTranspose2d(in_channels=intPrevious + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=4, stride=2, padding=1)
+ if intLevel < 6: self.fltBackwarp = [ None, None, None, 5.0, 2.5, 1.25, 0.625, None ][intLevel + 1]
+
+ self.netOne = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netTwo = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128, out_channels=128, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netThr = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128, out_channels=96, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFou = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96, out_channels=64, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netFiv = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64, out_channels=32, kernel_size=3, stride=1, padding=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1)
+ )
+
+ self.netSix = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=intCurrent + 128 + 128 + 96 + 64 + 32, out_channels=2, kernel_size=3, stride=1, padding=1)
+ )
+ # end
+
+ def forward(self, tenFirst, tenSecond, objPrevious):
+ tenFlow = None
+ tenFeat = None
+
+ if objPrevious is None:
+ tenFlow = None
+ tenFeat = None
+
+ tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=tenSecond), negative_slope=0.1, inplace=False)
+
+ tenFeat = torch.cat([ tenVolume ], 1)
+
+ elif objPrevious is not None:
+ tenFlow = self.netUpflow(objPrevious['tenFlow'])
+ tenFeat = self.netUpfeat(objPrevious['tenFeat'])
+
+ tenVolume = torch.nn.functional.leaky_relu(input=correlation.FunctionCorrelation(tenFirst=tenFirst, tenSecond=backwarp(tenInput=tenSecond, tenFlow=tenFlow * self.fltBackwarp)), negative_slope=0.1, inplace=False)
+
+ tenFeat = torch.cat([ tenVolume, tenFirst, tenFlow, tenFeat ], 1)
+
+ # end
+
+ tenFeat = torch.cat([ self.netOne(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netTwo(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netThr(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netFou(tenFeat), tenFeat ], 1)
+ tenFeat = torch.cat([ self.netFiv(tenFeat), tenFeat ], 1)
+
+ tenFlow = self.netSix(tenFeat)
+
+ return {
+ 'tenFlow': tenFlow,
+ 'tenFeat': tenFeat
+ }
+ # end
+ # end
+
+ class Refiner(torch.nn.Module):
+ def __init__(self):
+ super(Refiner, self).__init__()
+
+ self.netMain = torch.nn.Sequential(
+ torch.nn.Conv2d(in_channels=81 + 32 + 2 + 2 + 128 + 128 + 96 + 64 + 32, out_channels=128, kernel_size=3, stride=1, padding=1, dilation=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=2, dilation=2),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=4, dilation=4),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=128, out_channels=96, kernel_size=3, stride=1, padding=8, dilation=8),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=96, out_channels=64, kernel_size=3, stride=1, padding=16, dilation=16),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=64, out_channels=32, kernel_size=3, stride=1, padding=1, dilation=1),
+ torch.nn.LeakyReLU(inplace=False, negative_slope=0.1),
+ torch.nn.Conv2d(in_channels=32, out_channels=2, kernel_size=3, stride=1, padding=1, dilation=1)
+ )
+ # end
+
+ def forward(self, tenInput):
+ return self.netMain(tenInput)
+ # end
+ # end
+
+ self.netExtractor = Extractor()
+
+ self.netTwo = Decoder(2)
+ self.netThr = Decoder(3)
+ self.netFou = Decoder(4)
+ self.netFiv = Decoder(5)
+ self.netSix = Decoder(6)
+
+ self.netRefiner = Refiner()
+
+ self.load_state_dict({ strKey.replace('module', 'net'): tenWeight for strKey, tenWeight in torch.hub.load_state_dict_from_url(url='http://content.sniklaus.com/github/pytorch-pwc/network-' + 'default' + '.pytorch').items() })
+ # end
+
+ def forward(self, tenFirst, tenSecond):
+ intWidth = tenFirst.shape[3]
+ intHeight = tenFirst.shape[2]
+
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
+
+ tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+ tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+
+ tenFirst = self.netExtractor(tenPreprocessedFirst)
+ tenSecond = self.netExtractor(tenPreprocessedSecond)
+
+
+ objEstimate = self.netSix(tenFirst[-1], tenSecond[-1], None)
+ objEstimate = self.netFiv(tenFirst[-2], tenSecond[-2], objEstimate)
+ objEstimate = self.netFou(tenFirst[-3], tenSecond[-3], objEstimate)
+ objEstimate = self.netThr(tenFirst[-4], tenSecond[-4], objEstimate)
+ objEstimate = self.netTwo(tenFirst[-5], tenSecond[-5], objEstimate)
+
+ tenFlow = objEstimate['tenFlow'] + self.netRefiner(objEstimate['tenFeat'])
+ tenFlow = 20.0 * torch.nn.functional.interpolate(input=tenFlow, size=(intHeight, intWidth), mode='bilinear', align_corners=False)
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
+
+ return tenFlow
+ # end
+# end
+
+netNetwork = None
+
+##########################################################
+
+def estimate(tenFirst, tenSecond):
+ global netNetwork
+
+ if netNetwork is None:
+ netNetwork = Network().cuda().eval()
+ # end
+
+ assert(tenFirst.shape[1] == tenSecond.shape[1])
+ assert(tenFirst.shape[2] == tenSecond.shape[2])
+
+ intWidth = tenFirst.shape[2]
+ intHeight = tenFirst.shape[1]
+
+ assert(intWidth == 1024) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+ assert(intHeight == 436) # remember that there is no guarantee for correctness, comment this line out if you acknowledge this and want to continue
+
+ tenPreprocessedFirst = tenFirst.cuda().view(1, 3, intHeight, intWidth)
+ tenPreprocessedSecond = tenSecond.cuda().view(1, 3, intHeight, intWidth)
+
+ intPreprocessedWidth = int(math.floor(math.ceil(intWidth / 64.0) * 64.0))
+ intPreprocessedHeight = int(math.floor(math.ceil(intHeight / 64.0) * 64.0))
+
+ tenPreprocessedFirst = torch.nn.functional.interpolate(input=tenPreprocessedFirst, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+ tenPreprocessedSecond = torch.nn.functional.interpolate(input=tenPreprocessedSecond, size=(intPreprocessedHeight, intPreprocessedWidth), mode='bilinear', align_corners=False)
+
+ tenFlow = 20.0 * torch.nn.functional.interpolate(input=netNetwork(tenPreprocessedFirst, tenPreprocessedSecond), size=(intHeight, intWidth), mode='bilinear', align_corners=False)
+
+ tenFlow[:, 0, :, :] *= float(intWidth) / float(intPreprocessedWidth)
+ tenFlow[:, 1, :, :] *= float(intHeight) / float(intPreprocessedHeight)
+
+ return tenFlow[0, :, :, :].cpu()
+# end
+
+##########################################################
+
+# if __name__ == '__main__':
+# tenFirst = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strFirst))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+# tenSecond = torch.FloatTensor(numpy.ascontiguousarray(numpy.array(PIL.Image.open(arguments_strSecond))[:, :, ::-1].transpose(2, 0, 1).astype(numpy.float32) * (1.0 / 255.0)))
+
+# tenOutput = estimate(tenFirst, tenSecond)
+
+# objOutput = open(arguments_strOut, 'wb')
+
+# numpy.array([ 80, 73, 69, 72 ], numpy.uint8).tofile(objOutput)
+# numpy.array([ tenOutput.shape[2], tenOutput.shape[1] ], numpy.int32).tofile(objOutput)
+# numpy.array(tenOutput.numpy().transpose(1, 2, 0), numpy.float32).tofile(objOutput)
+
+# objOutput.close()
+# end
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..98d4502d5de7b0c44cf11a15de58139325b68a19
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/flolpips/utils.py
@@ -0,0 +1,95 @@
+import numpy as np
+import cv2
+import torch
+
+
+def normalize_tensor(in_feat,eps=1e-10):
+ norm_factor = torch.sqrt(torch.sum(in_feat**2,dim=1,keepdim=True))
+ return in_feat/(norm_factor+eps)
+
+def l2(p0, p1, range=255.):
+ return .5*np.mean((p0 / range - p1 / range)**2)
+
+def dssim(p0, p1, range=255.):
+ from skimage.measure import compare_ssim
+ return (1 - compare_ssim(p0, p1, data_range=range, multichannel=True)) / 2.
+
+def tensor2im(image_tensor, imtype=np.uint8, cent=1., factor=255./2.):
+ image_numpy = image_tensor[0].cpu().float().numpy()
+ image_numpy = (np.transpose(image_numpy, (1, 2, 0)) + cent) * factor
+ return image_numpy.astype(imtype)
+
+def tensor2np(tensor_obj):
+ # change dimension of a tensor object into a numpy array
+ return tensor_obj[0].cpu().float().numpy().transpose((1,2,0))
+
+def np2tensor(np_obj):
+ # change dimenion of np array into tensor array
+ return torch.Tensor(np_obj[:, :, :, np.newaxis].transpose((3, 2, 0, 1)))
+
+def tensor2tensorlab(image_tensor,to_norm=True,mc_only=False):
+ # image tensor to lab tensor
+ from skimage import color
+
+ img = tensor2im(image_tensor)
+ img_lab = color.rgb2lab(img)
+ if(mc_only):
+ img_lab[:,:,0] = img_lab[:,:,0]-50
+ if(to_norm and not mc_only):
+ img_lab[:,:,0] = img_lab[:,:,0]-50
+ img_lab = img_lab/100.
+
+ return np2tensor(img_lab)
+
+def read_frame_yuv2rgb(stream, width, height, iFrame, bit_depth, pix_fmt='420'):
+ if pix_fmt == '420':
+ multiplier = 1
+ uv_factor = 2
+ elif pix_fmt == '444':
+ multiplier = 2
+ uv_factor = 1
+ else:
+ print('Pixel format {} is not supported'.format(pix_fmt))
+ return
+
+ if bit_depth == 8:
+ datatype = np.uint8
+ stream.seek(iFrame*1.5*width*height*multiplier)
+ Y = np.fromfile(stream, dtype=datatype, count=width*height).reshape((height, width))
+
+ # read chroma samples and upsample since original is 4:2:0 sampling
+ U = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+ V = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+
+ else:
+ datatype = np.uint16
+ stream.seek(iFrame*3*width*height*multiplier)
+ Y = np.fromfile(stream, dtype=datatype, count=width*height).reshape((height, width))
+
+ U = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+ V = np.fromfile(stream, dtype=datatype, count=(width//uv_factor)*(height//uv_factor)).\
+ reshape((height//uv_factor, width//uv_factor))
+
+ if pix_fmt == '420':
+ yuv = np.empty((height*3//2, width), dtype=datatype)
+ yuv[0:height,:] = Y
+
+ yuv[height:height+height//4,:] = U.reshape(-1, width)
+ yuv[height+height//4:,:] = V.reshape(-1, width)
+
+ if bit_depth != 8:
+ yuv = (yuv/(2**bit_depth-1)*255).astype(np.uint8)
+
+ #convert to rgb
+ rgb = cv2.cvtColor(yuv, cv2.COLOR_YUV2RGB_I420)
+
+ else:
+ yvu = np.stack([Y,V,U],axis=2)
+ if bit_depth != 8:
+ yvu = (yvu/(2**bit_depth-1)*255).astype(np.uint8)
+ rgb = cv2.cvtColor(yvu, cv2.COLOR_YCrCb2RGB)
+
+ return rgb
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/styleganv/fvd.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/styleganv/fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..3043a2a4a4c4fc48ca97aedba074c2c2379685e4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/styleganv/fvd.py
@@ -0,0 +1,90 @@
+import torch
+import os
+import math
+import torch.nn.functional as F
+
+# https://github.com/universome/fvd-comparison
+
+
+def load_i3d_pretrained(device=torch.device('cpu')):
+ i3D_WEIGHTS_URL = "https://www.dropbox.com/s/ge9e5ujwgetktms/i3d_torchscript.pt"
+ filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'i3d_torchscript.pt')
+ print(filepath)
+ if not os.path.exists(filepath):
+ print(f"preparing for download {i3D_WEIGHTS_URL}, you can download it by yourself.")
+ os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
+ i3d = torch.jit.load(filepath).eval().to(device)
+ i3d = torch.nn.DataParallel(i3d)
+ return i3d
+
+
+def get_feats(videos, detector, device, bs=10):
+ # videos : torch.tensor BCTHW [0, 1]
+ detector_kwargs = dict(rescale=False, resize=False, return_features=True) # Return raw features before the softmax layer.
+ feats = np.empty((0, 400))
+ with torch.no_grad():
+ for i in range((len(videos)-1)//bs + 1):
+ feats = np.vstack([feats, detector(torch.stack([preprocess_single(video) for video in videos[i*bs:(i+1)*bs]]).to(device), **detector_kwargs).detach().cpu().numpy()])
+ return feats
+
+
+def get_fvd_feats(videos, i3d, device, bs=10):
+ # videos in [0, 1] as torch tensor BCTHW
+ # videos = [preprocess_single(video) for video in videos]
+ embeddings = get_feats(videos, i3d, device, bs)
+ return embeddings
+
+
+def preprocess_single(video, resolution=224, sequence_length=None):
+ # video: CTHW, [0, 1]
+ c, t, h, w = video.shape
+
+ # temporal crop
+ if sequence_length is not None:
+ assert sequence_length <= t
+ video = video[:, :sequence_length]
+
+ # scale shorter side to resolution
+ scale = resolution / min(h, w)
+ if h < w:
+ target_size = (resolution, math.ceil(w * scale))
+ else:
+ target_size = (math.ceil(h * scale), resolution)
+ video = F.interpolate(video, size=target_size, mode='bilinear', align_corners=False)
+
+ # center crop
+ c, t, h, w = video.shape
+ w_start = (w - resolution) // 2
+ h_start = (h - resolution) // 2
+ video = video[:, :, h_start:h_start + resolution, w_start:w_start + resolution]
+
+ # [0, 1] -> [-1, 1]
+ video = (video - 0.5) * 2
+
+ return video.contiguous()
+
+
+"""
+Copy-pasted from https://github.com/cvpr2022-stylegan-v/stylegan-v/blob/main/src/metrics/frechet_video_distance.py
+"""
+from typing import Tuple
+from scipy.linalg import sqrtm
+import numpy as np
+
+
+def compute_stats(feats: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
+ mu = feats.mean(axis=0) # [d]
+ sigma = np.cov(feats, rowvar=False) # [d, d]
+ return mu, sigma
+
+
+def frechet_distance(feats_fake: np.ndarray, feats_real: np.ndarray) -> float:
+ mu_gen, sigma_gen = compute_stats(feats_fake)
+ mu_real, sigma_real = compute_stats(feats_real)
+ m = np.square(mu_gen - mu_real).sum()
+ if feats_fake.shape[0]>1:
+ s, _ = sqrtm(np.dot(sigma_gen, sigma_real), disp=False) # pylint: disable=no-member
+ fid = np.real(m + np.trace(sigma_gen + sigma_real - s * 2))
+ else:
+ fid = np.real(m)
+ return float(fid)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/fvd.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/fvd.py
new file mode 100644
index 0000000000000000000000000000000000000000..e81c8290456a5f54de6d31bf0f946f87a12eda9c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/fvd.py
@@ -0,0 +1,137 @@
+import torch
+import os
+import math
+import torch.nn.functional as F
+import numpy as np
+import einops
+
+def load_i3d_pretrained(device=torch.device('cpu')):
+ i3D_WEIGHTS_URL = "https://onedrive.live.com/download?cid=78EEF3EB6AE7DBCB&resid=78EEF3EB6AE7DBCB%21199&authkey=AApKdFHPXzWLNyI"
+ filepath = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'i3d_pretrained_400.pt')
+ print(filepath)
+ if not os.path.exists(filepath):
+ print(f"preparing for download {i3D_WEIGHTS_URL}, you can download it by yourself.")
+ os.system(f"wget {i3D_WEIGHTS_URL} -O {filepath}")
+ from .pytorch_i3d import InceptionI3d
+ i3d = InceptionI3d(400, in_channels=3).eval().to(device)
+ i3d.load_state_dict(torch.load(filepath, map_location=device))
+ i3d = torch.nn.DataParallel(i3d)
+ return i3d
+
+def preprocess_single(video, resolution, sequence_length=None):
+ # video: THWC, {0, ..., 255}
+ video = video.permute(0, 3, 1, 2).float() / 255. # TCHW
+ t, c, h, w = video.shape
+
+ # temporal crop
+ if sequence_length is not None:
+ assert sequence_length <= t
+ video = video[:sequence_length]
+
+ # scale shorter side to resolution
+ scale = resolution / min(h, w)
+ if h < w:
+ target_size = (resolution, math.ceil(w * scale))
+ else:
+ target_size = (math.ceil(h * scale), resolution)
+ video = F.interpolate(video, size=target_size, mode='bilinear',
+ align_corners=False)
+
+ # center crop
+ t, c, h, w = video.shape
+ w_start = (w - resolution) // 2
+ h_start = (h - resolution) // 2
+ video = video[:, :, h_start:h_start + resolution, w_start:w_start + resolution]
+ video = video.permute(1, 0, 2, 3).contiguous() # CTHW
+
+ video -= 0.5
+
+ return video
+
+def preprocess(videos, target_resolution=224):
+ # we should tras videos in [0-1] [b c t h w] as th.float
+ # -> videos in {0, ..., 255} [b t h w c] as np.uint8 array
+ videos = einops.rearrange(videos, 'b c t h w -> b t h w c')
+ videos = (videos*255).numpy().astype(np.uint8)
+
+ b, t, h, w, c = videos.shape
+ videos = torch.from_numpy(videos)
+ videos = torch.stack([preprocess_single(video, target_resolution) for video in videos])
+ return videos * 2 # [-0.5, 0.5] -> [-1, 1]
+
+def get_fvd_logits(videos, i3d, device, bs=10):
+ videos = preprocess(videos)
+ embeddings = get_logits(i3d, videos, device, bs=10)
+ return embeddings
+
+# https://github.com/tensorflow/gan/blob/de4b8da3853058ea380a6152bd3bd454013bf619/tensorflow_gan/python/eval/classifier_metrics.py#L161
+def _symmetric_matrix_square_root(mat, eps=1e-10):
+ u, s, v = torch.svd(mat)
+ si = torch.where(s < eps, s, torch.sqrt(s))
+ return torch.matmul(torch.matmul(u, torch.diag(si)), v.t())
+
+# https://github.com/tensorflow/gan/blob/de4b8da3853058ea380a6152bd3bd454013bf619/tensorflow_gan/python/eval/classifier_metrics.py#L400
+def trace_sqrt_product(sigma, sigma_v):
+ sqrt_sigma = _symmetric_matrix_square_root(sigma)
+ sqrt_a_sigmav_a = torch.matmul(sqrt_sigma, torch.matmul(sigma_v, sqrt_sigma))
+ return torch.trace(_symmetric_matrix_square_root(sqrt_a_sigmav_a))
+
+# https://discuss.pytorch.org/t/covariance-and-gradient-support/16217/2
+def cov(m, rowvar=False):
+ '''Estimate a covariance matrix given data.
+
+ Covariance indicates the level to which two variables vary together.
+ If we examine N-dimensional samples, `X = [x_1, x_2, ... x_N]^T`,
+ then the covariance matrix element `C_{ij}` is the covariance of
+ `x_i` and `x_j`. The element `C_{ii}` is the variance of `x_i`.
+
+ Args:
+ m: A 1-D or 2-D array containing multiple variables and observations.
+ Each row of `m` represents a variable, and each column a single
+ observation of all those variables.
+ rowvar: If `rowvar` is True, then each row represents a
+ variable, with observations in the columns. Otherwise, the
+ relationship is transposed: each column represents a variable,
+ while the rows contain observations.
+
+ Returns:
+ The covariance matrix of the variables.
+ '''
+ if m.dim() > 2:
+ raise ValueError('m has more than 2 dimensions')
+ if m.dim() < 2:
+ m = m.view(1, -1)
+ if not rowvar and m.size(0) != 1:
+ m = m.t()
+
+ fact = 1.0 / (m.size(1) - 1) # unbiased estimate
+ m -= torch.mean(m, dim=1, keepdim=True)
+ mt = m.t() # if complex: mt = m.t().conj()
+ return fact * m.matmul(mt).squeeze()
+
+
+def frechet_distance(x1, x2):
+ x1 = x1.flatten(start_dim=1)
+ x2 = x2.flatten(start_dim=1)
+ m, m_w = x1.mean(dim=0), x2.mean(dim=0)
+ sigma, sigma_w = cov(x1, rowvar=False), cov(x2, rowvar=False)
+ mean = torch.sum((m - m_w) ** 2)
+ if x1.shape[0]>1:
+ sqrt_trace_component = trace_sqrt_product(sigma, sigma_w)
+ trace = torch.trace(sigma + sigma_w) - 2.0 * sqrt_trace_component
+ fd = trace + mean
+ else:
+ fd = np.real(mean)
+ return float(fd)
+
+
+def get_logits(i3d, videos, device, bs=10):
+ # assert videos.shape[0] % 16 == 0
+ with torch.no_grad():
+ logits = []
+ for i in range(0, videos.shape[0], bs):
+ batch = videos[i:i + bs].to(device)
+ # logits.append(i3d.module.extract_features(batch)) # wrong
+ logits.append(i3d(batch)) # right
+ logits = torch.cat(logits, dim=0)
+ return logits
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/pytorch_i3d.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/pytorch_i3d.py
new file mode 100644
index 0000000000000000000000000000000000000000..58a16cdd797e5a0e9d711bb0ba14281486d44d03
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/fvd/videogpt/pytorch_i3d.py
@@ -0,0 +1,322 @@
+# Original code from https://github.com/piergiaj/pytorch-i3d
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+import numpy as np
+
+class MaxPool3dSamePadding(nn.MaxPool3d):
+
+ def compute_pad(self, dim, s):
+ if s % self.stride[dim] == 0:
+ return max(self.kernel_size[dim] - self.stride[dim], 0)
+ else:
+ return max(self.kernel_size[dim] - (s % self.stride[dim]), 0)
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ out_t = np.ceil(float(t) / float(self.stride[0]))
+ out_h = np.ceil(float(h) / float(self.stride[1]))
+ out_w = np.ceil(float(w) / float(self.stride[2]))
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+ return super(MaxPool3dSamePadding, self).forward(x)
+
+
+class Unit3D(nn.Module):
+
+ def __init__(self, in_channels,
+ output_channels,
+ kernel_shape=(1, 1, 1),
+ stride=(1, 1, 1),
+ padding=0,
+ activation_fn=F.relu,
+ use_batch_norm=True,
+ use_bias=False,
+ name='unit_3d'):
+
+ """Initializes Unit3D module."""
+ super(Unit3D, self).__init__()
+
+ self._output_channels = output_channels
+ self._kernel_shape = kernel_shape
+ self._stride = stride
+ self._use_batch_norm = use_batch_norm
+ self._activation_fn = activation_fn
+ self._use_bias = use_bias
+ self.name = name
+ self.padding = padding
+
+ self.conv3d = nn.Conv3d(in_channels=in_channels,
+ out_channels=self._output_channels,
+ kernel_size=self._kernel_shape,
+ stride=self._stride,
+ padding=0, # we always want padding to be 0 here. We will dynamically pad based on input size in forward function
+ bias=self._use_bias)
+
+ if self._use_batch_norm:
+ self.bn = nn.BatchNorm3d(self._output_channels, eps=1e-5, momentum=0.001)
+
+ def compute_pad(self, dim, s):
+ if s % self._stride[dim] == 0:
+ return max(self._kernel_shape[dim] - self._stride[dim], 0)
+ else:
+ return max(self._kernel_shape[dim] - (s % self._stride[dim]), 0)
+
+
+ def forward(self, x):
+ # compute 'same' padding
+ (batch, channel, t, h, w) = x.size()
+ out_t = np.ceil(float(t) / float(self._stride[0]))
+ out_h = np.ceil(float(h) / float(self._stride[1]))
+ out_w = np.ceil(float(w) / float(self._stride[2]))
+ pad_t = self.compute_pad(0, t)
+ pad_h = self.compute_pad(1, h)
+ pad_w = self.compute_pad(2, w)
+
+ pad_t_f = pad_t // 2
+ pad_t_b = pad_t - pad_t_f
+ pad_h_f = pad_h // 2
+ pad_h_b = pad_h - pad_h_f
+ pad_w_f = pad_w // 2
+ pad_w_b = pad_w - pad_w_f
+
+ pad = (pad_w_f, pad_w_b, pad_h_f, pad_h_b, pad_t_f, pad_t_b)
+ x = F.pad(x, pad)
+
+ x = self.conv3d(x)
+ if self._use_batch_norm:
+ x = self.bn(x)
+ if self._activation_fn is not None:
+ x = self._activation_fn(x)
+ return x
+
+
+
+class InceptionModule(nn.Module):
+ def __init__(self, in_channels, out_channels, name):
+ super(InceptionModule, self).__init__()
+
+ self.b0 = Unit3D(in_channels=in_channels, output_channels=out_channels[0], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_0/Conv3d_0a_1x1')
+ self.b1a = Unit3D(in_channels=in_channels, output_channels=out_channels[1], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_1/Conv3d_0a_1x1')
+ self.b1b = Unit3D(in_channels=out_channels[1], output_channels=out_channels[2], kernel_shape=[3, 3, 3],
+ name=name+'/Branch_1/Conv3d_0b_3x3')
+ self.b2a = Unit3D(in_channels=in_channels, output_channels=out_channels[3], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_2/Conv3d_0a_1x1')
+ self.b2b = Unit3D(in_channels=out_channels[3], output_channels=out_channels[4], kernel_shape=[3, 3, 3],
+ name=name+'/Branch_2/Conv3d_0b_3x3')
+ self.b3a = MaxPool3dSamePadding(kernel_size=[3, 3, 3],
+ stride=(1, 1, 1), padding=0)
+ self.b3b = Unit3D(in_channels=in_channels, output_channels=out_channels[5], kernel_shape=[1, 1, 1], padding=0,
+ name=name+'/Branch_3/Conv3d_0b_1x1')
+ self.name = name
+
+ def forward(self, x):
+ b0 = self.b0(x)
+ b1 = self.b1b(self.b1a(x))
+ b2 = self.b2b(self.b2a(x))
+ b3 = self.b3b(self.b3a(x))
+ return torch.cat([b0,b1,b2,b3], dim=1)
+
+
+class InceptionI3d(nn.Module):
+ """Inception-v1 I3D architecture.
+ The model is introduced in:
+ Quo Vadis, Action Recognition? A New Model and the Kinetics Dataset
+ Joao Carreira, Andrew Zisserman
+ https://arxiv.org/pdf/1705.07750v1.pdf.
+ See also the Inception architecture, introduced in:
+ Going deeper with convolutions
+ Christian Szegedy, Wei Liu, Yangqing Jia, Pierre Sermanet, Scott Reed,
+ Dragomir Anguelov, Dumitru Erhan, Vincent Vanhoucke, Andrew Rabinovich.
+ http://arxiv.org/pdf/1409.4842v1.pdf.
+ """
+
+ # Endpoints of the model in order. During construction, all the endpoints up
+ # to a designated `final_endpoint` are returned in a dictionary as the
+ # second return value.
+ VALID_ENDPOINTS = (
+ 'Conv3d_1a_7x7',
+ 'MaxPool3d_2a_3x3',
+ 'Conv3d_2b_1x1',
+ 'Conv3d_2c_3x3',
+ 'MaxPool3d_3a_3x3',
+ 'Mixed_3b',
+ 'Mixed_3c',
+ 'MaxPool3d_4a_3x3',
+ 'Mixed_4b',
+ 'Mixed_4c',
+ 'Mixed_4d',
+ 'Mixed_4e',
+ 'Mixed_4f',
+ 'MaxPool3d_5a_2x2',
+ 'Mixed_5b',
+ 'Mixed_5c',
+ 'Logits',
+ 'Predictions',
+ )
+
+ def __init__(self, num_classes=400, spatial_squeeze=True,
+ final_endpoint='Logits', name='inception_i3d', in_channels=3, dropout_keep_prob=0.5):
+ """Initializes I3D model instance.
+ Args:
+ num_classes: The number of outputs in the logit layer (default 400, which
+ matches the Kinetics dataset).
+ spatial_squeeze: Whether to squeeze the spatial dimensions for the logits
+ before returning (default True).
+ final_endpoint: The model contains many possible endpoints.
+ `final_endpoint` specifies the last endpoint for the model to be built
+ up to. In addition to the output at `final_endpoint`, all the outputs
+ at endpoints up to `final_endpoint` will also be returned, in a
+ dictionary. `final_endpoint` must be one of
+ InceptionI3d.VALID_ENDPOINTS (default 'Logits').
+ name: A string (optional). The name of this module.
+ Raises:
+ ValueError: if `final_endpoint` is not recognized.
+ """
+
+ if final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' % final_endpoint)
+
+ super(InceptionI3d, self).__init__()
+ self._num_classes = num_classes
+ self._spatial_squeeze = spatial_squeeze
+ self._final_endpoint = final_endpoint
+ self.logits = None
+
+ if self._final_endpoint not in self.VALID_ENDPOINTS:
+ raise ValueError('Unknown final endpoint %s' % self._final_endpoint)
+
+ self.end_points = {}
+ end_point = 'Conv3d_1a_7x7'
+ self.end_points[end_point] = Unit3D(in_channels=in_channels, output_channels=64, kernel_shape=[7, 7, 7],
+ stride=(2, 2, 2), padding=(3,3,3), name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_2a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Conv3d_2b_1x1'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=64, kernel_shape=[1, 1, 1], padding=0,
+ name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Conv3d_2c_3x3'
+ self.end_points[end_point] = Unit3D(in_channels=64, output_channels=192, kernel_shape=[3, 3, 3], padding=1,
+ name=name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_3a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[1, 3, 3], stride=(1, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_3b'
+ self.end_points[end_point] = InceptionModule(192, [64,96,128,16,32,32], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_3c'
+ self.end_points[end_point] = InceptionModule(256, [128,128,192,32,96,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_4a_3x3'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[3, 3, 3], stride=(2, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4b'
+ self.end_points[end_point] = InceptionModule(128+192+96+64, [192,96,208,16,48,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4c'
+ self.end_points[end_point] = InceptionModule(192+208+48+64, [160,112,224,24,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4d'
+ self.end_points[end_point] = InceptionModule(160+224+64+64, [128,128,256,24,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4e'
+ self.end_points[end_point] = InceptionModule(128+256+64+64, [112,144,288,32,64,64], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_4f'
+ self.end_points[end_point] = InceptionModule(112+288+64+64, [256,160,320,32,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'MaxPool3d_5a_2x2'
+ self.end_points[end_point] = MaxPool3dSamePadding(kernel_size=[2, 2, 2], stride=(2, 2, 2),
+ padding=0)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_5b'
+ self.end_points[end_point] = InceptionModule(256+320+128+128, [256,160,320,32,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Mixed_5c'
+ self.end_points[end_point] = InceptionModule(256+320+128+128, [384,192,384,48,128,128], name+end_point)
+ if self._final_endpoint == end_point: return
+
+ end_point = 'Logits'
+ self.avg_pool = nn.AvgPool3d(kernel_size=[2, 7, 7],
+ stride=(1, 1, 1))
+ self.dropout = nn.Dropout(dropout_keep_prob)
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+ self.build()
+
+
+ def replace_logits(self, num_classes):
+ self._num_classes = num_classes
+ self.logits = Unit3D(in_channels=384+384+128+128, output_channels=self._num_classes,
+ kernel_shape=[1, 1, 1],
+ padding=0,
+ activation_fn=None,
+ use_batch_norm=False,
+ use_bias=True,
+ name='logits')
+
+
+ def build(self):
+ for k in self.end_points.keys():
+ self.add_module(k, self.end_points[k])
+
+ def forward(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ x = self._modules[end_point](x) # use _modules to work with dataparallel
+
+ x = self.logits(self.dropout(self.avg_pool(x)))
+ if self._spatial_squeeze:
+ logits = x.squeeze(3).squeeze(3)
+ logits = logits.mean(dim=2)
+ # logits is batch X time X classes, which is what we want to work with
+ return logits
+
+
+ def extract_features(self, x):
+ for end_point in self.VALID_ENDPOINTS:
+ if end_point in self.end_points:
+ x = self._modules[end_point](x)
+ return self.avg_pool(x)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_clip_score.sh b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_clip_score.sh
new file mode 100644
index 0000000000000000000000000000000000000000..8bc241c154a72805282b511dcfb2164a5f6a282e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_clip_score.sh
@@ -0,0 +1,23 @@
+# clip_score cross modality
+python eval_clip_score.py \
+ --real_path path/to/image \
+ --generated_path path/to/text \
+ --batch-size 50 \
+ --device "cuda"
+
+# clip_score within the same modality
+python eval_clip_score.py \
+ --real_path path/to/textA \
+ --generated_path path/to/textB \
+ --real_flag txt \
+ --generated_flag txt \
+ --batch-size 50 \
+ --device "cuda"
+
+python eval_clip_score.py \
+ --real_path path/to/imageA \
+ --generated_path path/to/imageB \
+ --real_flag img \
+ --generated_flag img \
+ --batch-size 50 \
+ --device "cuda"
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_fvd.sh b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_fvd.sh
new file mode 100644
index 0000000000000000000000000000000000000000..e344242a0ec2bf4d62f390312d6a396591c049a8
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_fvd.sh
@@ -0,0 +1,9 @@
+python eval_common_metric.py \
+ --real_video_dir path/to/imageA\
+ --generated_video_dir path/to/imageB \
+ --batch_size 10 \
+ --crop_size 64 \
+ --num_frames 20 \
+ --device 'cuda' \
+ --metric 'fvd' \
+ --fvd_method 'styleganv'
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_lpips.sh b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_lpips.sh
new file mode 100644
index 0000000000000000000000000000000000000000..9ebaf26e856166fed4573a8164f7c5b557bfd229
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_lpips.sh
@@ -0,0 +1,8 @@
+python eval_common_metric.py \
+ --real_video_dir path/to/imageA\
+ --generated_video_dir path/to/imageB \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'lpips'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_psnr.sh b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_psnr.sh
new file mode 100644
index 0000000000000000000000000000000000000000..a60a5d1c167f2dcd4a251b31af0d8a534bfee195
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_psnr.sh
@@ -0,0 +1,9 @@
+
+python eval_common_metric.py \
+ --real_video_dir /data/xiaogeng_liu/data/video1 \
+ --generated_video_dir /data/xiaogeng_liu/data/video2 \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'psnr'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_ssim.sh b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_ssim.sh
new file mode 100644
index 0000000000000000000000000000000000000000..404d8da9a12a28a3c173dc87652a380e7a754b25
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/eval/script/cal_ssim.sh
@@ -0,0 +1,8 @@
+python eval_common_metric.py \
+ --real_video_dir /data/xiaogeng_liu/data/video1 \
+ --generated_video_dir /data/xiaogeng_liu/data/video2 \
+ --batch_size 10 \
+ --num_frames 20 \
+ --crop_size 64 \
+ --device 'cuda' \
+ --metric 'ssim'
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ca9d15466146891d6ed259d65c00cb51534d599
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/__init__.py
@@ -0,0 +1,4 @@
+from .causal_vae import (
+ CausalVAEModel, CausalVAEModelWrapper
+)
+from .ema_model import EMA
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1aeb800d75346ac7394829e3983eb8a0921db66
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/__init__.py
@@ -0,0 +1,29 @@
+from .modeling_causalvae import CausalVAEModel
+
+from einops import rearrange
+from torch import nn
+
+class CausalVAEModelWrapper(nn.Module):
+ def __init__(self, model_path, subfolder=None, cache_dir=None, use_ema=False, **kwargs):
+ super(CausalVAEModelWrapper, self).__init__()
+ # if os.path.exists(ckpt):
+ # self.vae = CausalVAEModel.load_from_checkpoint(ckpt)
+ self.vae = CausalVAEModel.from_pretrained(model_path, subfolder=subfolder, cache_dir=cache_dir, **kwargs)
+ if use_ema:
+ self.vae.init_from_ema(model_path)
+ self.vae = self.vae.ema
+ def encode(self, x): # b c t h w
+ # x = self.vae.encode(x).sample()
+ x = self.vae.encode(x).sample().mul_(0.18215)
+ return x
+ def decode(self, x):
+ # x = self.vae.decode(x)
+ x = self.vae.decode(x / 0.18215)
+ x = rearrange(x, 'b c t h w -> b t c h w').contiguous()
+ return x
+
+ def dtype(self):
+ return self.vae.dtype
+ #
+ # def device(self):
+ # return self.vae.device
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/modeling_causalvae.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/modeling_causalvae.py
new file mode 100644
index 0000000000000000000000000000000000000000..59ebe696f50c79bfb0696a000cb097b61f9f7e91
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/causal_vae/modeling_causalvae.py
@@ -0,0 +1,628 @@
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+from ..modeling_videobase import VideoBaseAE
+from ..modules import Normalize
+from ..modules.ops import nonlinearity
+from typing import List, Tuple
+import torch.nn as nn
+
+from ..utils.module_utils import resolve_str_to_obj, Module
+from ..utils.distrib_utils import DiagonalGaussianDistribution
+from ..utils.scheduler_utils import cosine_scheduler
+from ...utils.utils import custom_to_video
+
+import torch
+from diffusers.configuration_utils import register_to_config
+from copy import deepcopy
+import os
+import glob
+
+import numpy as np
+from ...eval.cal_psnr import calculate_psnr
+from decord import VideoReader, cpu
+# from pytorchvideo.transforms import ShortSideScale
+from torchvision.io import read_video
+from torchvision.transforms import Lambda, Compose
+from torchvision.transforms._transforms_video import CenterCropVideo
+
+class Encoder(nn.Module):
+ def __init__(
+ self,
+ z_channels: int,
+ hidden_size: int,
+ hidden_size_mult: Tuple[int] = (1, 2, 4, 4),
+ attn_resolutions: Tuple[int] = (16,),
+ conv_in: Module = "Conv2d",
+ conv_out: Module = "CasualConv3d",
+ attention: Module = "AttnBlock",
+ resnet_blocks: Tuple[Module] = (
+ "ResnetBlock2D",
+ "ResnetBlock2D",
+ "ResnetBlock2D",
+ "ResnetBlock3D",
+ ),
+ spatial_downsample: Tuple[Module] = (
+ "Downsample",
+ "Downsample",
+ "Downsample",
+ "",
+ ),
+ temporal_downsample: Tuple[Module] = ("", "", "TimeDownsampleRes2x", ""),
+ mid_resnet: Module = "ResnetBlock3D",
+ dropout: float = 0.0,
+ resolution: int = 256,
+ num_res_blocks: int = 2,
+ double_z: bool = True,
+ ) -> None:
+ super().__init__()
+ assert len(resnet_blocks) == len(hidden_size_mult), print(
+ hidden_size_mult, resnet_blocks
+ )
+ # ---- Config ----
+ self.num_resolutions = len(hidden_size_mult)
+ self.resolution = resolution
+ self.num_res_blocks = num_res_blocks
+
+ # ---- In ----
+ self.conv_in = resolve_str_to_obj(conv_in)(
+ 3, hidden_size, kernel_size=3, stride=1, padding=1
+ )
+
+ # ---- Downsample ----
+ curr_res = resolution
+ in_ch_mult = (1,) + tuple(hidden_size_mult)
+ self.in_ch_mult = in_ch_mult
+ self.down = nn.ModuleList()
+ for i_level in range(self.num_resolutions):
+ block = nn.ModuleList()
+ attn = nn.ModuleList()
+ block_in = hidden_size * in_ch_mult[i_level]
+ block_out = hidden_size * hidden_size_mult[i_level]
+ for i_block in range(self.num_res_blocks):
+ block.append(
+ resolve_str_to_obj(resnet_blocks[i_level])(
+ in_channels=block_in,
+ out_channels=block_out,
+ dropout=dropout,
+ )
+ )
+ block_in = block_out
+ if curr_res in attn_resolutions:
+ attn.append(resolve_str_to_obj(attention)(block_in))
+ down = nn.Module()
+ down.block = block
+ down.attn = attn
+ if spatial_downsample[i_level]:
+ down.downsample = resolve_str_to_obj(spatial_downsample[i_level])(
+ block_in, block_in
+ )
+ curr_res = curr_res // 2
+ if temporal_downsample[i_level]:
+ down.time_downsample = resolve_str_to_obj(temporal_downsample[i_level])(
+ block_in, block_in
+ )
+ self.down.append(down)
+
+ # ---- Mid ----
+ self.mid = nn.Module()
+ self.mid.block_1 = resolve_str_to_obj(mid_resnet)(
+ in_channels=block_in,
+ out_channels=block_in,
+ dropout=dropout,
+ )
+ self.mid.attn_1 = resolve_str_to_obj(attention)(block_in)
+ self.mid.block_2 = resolve_str_to_obj(mid_resnet)(
+ in_channels=block_in,
+ out_channels=block_in,
+ dropout=dropout,
+ )
+ # ---- Out ----
+ self.norm_out = Normalize(block_in)
+ self.conv_out = resolve_str_to_obj(conv_out)(
+ block_in,
+ 2 * z_channels if double_z else z_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1,
+ )
+
+ def forward(self, x):
+ hs = [self.conv_in(x)]
+ for i_level in range(self.num_resolutions):
+ for i_block in range(self.num_res_blocks):
+ h = self.down[i_level].block[i_block](hs[-1])
+ if len(self.down[i_level].attn) > 0:
+ h = self.down[i_level].attn[i_block](h)
+ hs.append(h)
+ if hasattr(self.down[i_level], "downsample"):
+ hs.append(self.down[i_level].downsample(hs[-1]))
+ if hasattr(self.down[i_level], "time_downsample"):
+ hs_down = self.down[i_level].time_downsample(hs[-1])
+ hs.append(hs_down)
+
+ h = self.mid.block_1(h)
+ h = self.mid.attn_1(h)
+ h = self.mid.block_2(h)
+
+ if npu_config is None:
+ h = self.norm_out(h)
+ else:
+ h = npu_config.run_group_norm(self.norm_out, h)
+ h = nonlinearity(h)
+ h = self.conv_out(h)
+ return h
+
+
+class Decoder(nn.Module):
+ def __init__(
+ self,
+ z_channels: int,
+ hidden_size: int,
+ hidden_size_mult: Tuple[int] = (1, 2, 4, 4),
+ attn_resolutions: Tuple[int] = (16,),
+ conv_in: Module = "Conv2d",
+ conv_out: Module = "CasualConv3d",
+ attention: Module = "AttnBlock",
+ resnet_blocks: Tuple[Module] = (
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ ),
+ spatial_upsample: Tuple[Module] = (
+ "",
+ "SpatialUpsample2x",
+ "SpatialUpsample2x",
+ "SpatialUpsample2x",
+ ),
+ temporal_upsample: Tuple[Module] = ("", "", "", "TimeUpsampleRes2x"),
+ mid_resnet: Module = "ResnetBlock3D",
+ dropout: float = 0.0,
+ resolution: int = 256,
+ num_res_blocks: int = 2,
+ ):
+ super().__init__()
+ # ---- Config ----
+ self.num_resolutions = len(hidden_size_mult)
+ self.resolution = resolution
+ self.num_res_blocks = num_res_blocks
+
+ # ---- In ----
+ block_in = hidden_size * hidden_size_mult[self.num_resolutions - 1]
+ curr_res = resolution // 2 ** (self.num_resolutions - 1)
+ self.conv_in = resolve_str_to_obj(conv_in)(
+ z_channels, block_in, kernel_size=3, padding=1
+ )
+
+ # ---- Mid ----
+ self.mid = nn.Module()
+ self.mid.block_1 = resolve_str_to_obj(mid_resnet)(
+ in_channels=block_in,
+ out_channels=block_in,
+ dropout=dropout,
+ )
+ self.mid.attn_1 = resolve_str_to_obj(attention)(block_in)
+ self.mid.block_2 = resolve_str_to_obj(mid_resnet)(
+ in_channels=block_in,
+ out_channels=block_in,
+ dropout=dropout,
+ )
+
+ # ---- Upsample ----
+ self.up = nn.ModuleList()
+ for i_level in reversed(range(self.num_resolutions)):
+ block = nn.ModuleList()
+ attn = nn.ModuleList()
+ block_out = hidden_size * hidden_size_mult[i_level]
+ for i_block in range(self.num_res_blocks + 1):
+ block.append(
+ resolve_str_to_obj(resnet_blocks[i_level])(
+ in_channels=block_in,
+ out_channels=block_out,
+ dropout=dropout,
+ )
+ )
+ block_in = block_out
+ if curr_res in attn_resolutions:
+ attn.append(resolve_str_to_obj(attention)(block_in))
+ up = nn.Module()
+ up.block = block
+ up.attn = attn
+ if spatial_upsample[i_level]:
+ up.upsample = resolve_str_to_obj(spatial_upsample[i_level])(
+ block_in, block_in
+ )
+ curr_res = curr_res * 2
+ if temporal_upsample[i_level]:
+ up.time_upsample = resolve_str_to_obj(temporal_upsample[i_level])(
+ block_in, block_in
+ )
+ self.up.insert(0, up)
+
+ # ---- Out ----
+ self.norm_out = Normalize(block_in)
+ self.conv_out = resolve_str_to_obj(conv_out)(
+ block_in, 3, kernel_size=3, padding=1
+ )
+
+ def forward(self, z):
+ h = self.conv_in(z)
+ h = self.mid.block_1(h)
+ h = self.mid.attn_1(h)
+ h = self.mid.block_2(h)
+
+ for i_level in reversed(range(self.num_resolutions)):
+ for i_block in range(self.num_res_blocks + 1):
+ h = self.up[i_level].block[i_block](h)
+ if len(self.up[i_level].attn) > 0:
+ h = self.up[i_level].attn[i_block](h)
+ if hasattr(self.up[i_level], "upsample"):
+ h = self.up[i_level].upsample(h)
+ if hasattr(self.up[i_level], "time_upsample"):
+ h = self.up[i_level].time_upsample(h)
+ if npu_config is None:
+ h = self.norm_out(h)
+ else:
+ h = npu_config.run_group_norm(self.norm_out, h)
+ h = nonlinearity(h)
+ if npu_config is None:
+ h = self.conv_out(h)
+ else:
+ h_dtype = h.dtype
+ h = npu_config.run_conv3d(self.conv_out, h, h_dtype)
+ return h
+
+
+class CausalVAEModel(VideoBaseAE):
+
+ @register_to_config
+ def __init__(
+ self,
+ hidden_size: int = 128,
+ z_channels: int = 4,
+ hidden_size_mult: Tuple[int] = (1, 2, 4, 4),
+ attn_resolutions: Tuple[int] = [],
+ dropout: float = 0.0,
+ resolution: int = 256,
+ double_z: bool = True,
+ embed_dim: int = 4,
+ num_res_blocks: int = 2,
+ q_conv: str = "CausalConv3d",
+ encoder_conv_in: Module = "CausalConv3d",
+ encoder_conv_out: Module = "CausalConv3d",
+ encoder_attention: Module = "AttnBlock3D",
+ encoder_resnet_blocks: Tuple[Module] = (
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ ),
+ encoder_spatial_downsample: Tuple[Module] = (
+ "SpatialDownsample2x",
+ "SpatialDownsample2x",
+ "SpatialDownsample2x",
+ "",
+ ),
+ encoder_temporal_downsample: Tuple[Module] = (
+ "",
+ "TimeDownsample2x",
+ "TimeDownsample2x",
+ "",
+ ),
+ encoder_mid_resnet: Module = "ResnetBlock3D",
+ decoder_conv_in: Module = "CausalConv3d",
+ decoder_conv_out: Module = "CausalConv3d",
+ decoder_attention: Module = "AttnBlock3D",
+ decoder_resnet_blocks: Tuple[Module] = (
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ "ResnetBlock3D",
+ ),
+ decoder_spatial_upsample: Tuple[Module] = (
+ "",
+ "SpatialUpsample2x",
+ "SpatialUpsample2x",
+ "SpatialUpsample2x",
+ ),
+ decoder_temporal_upsample: Tuple[Module] = ("", "", "TimeUpsample2x", "TimeUpsample2x"),
+ decoder_mid_resnet: Module = "ResnetBlock3D",
+ use_quant_layer: bool = True
+ ) -> None:
+ super().__init__()
+
+
+ self.tile_sample_min_size = 256
+ self.tile_sample_min_size_t = 33
+ self.tile_latent_min_size = int(self.tile_sample_min_size / (2 ** (len(hidden_size_mult) - 1)))
+
+ # t_down_ratio = [i for i in encoder_temporal_downsample if len(i) > 0]
+ # self.tile_latent_min_size_t = int((self.tile_sample_min_size_t-1) / (2 ** len(t_down_ratio))) + 1
+ self.tile_latent_min_size_t = 16
+ self.tile_overlap_factor = 0.125
+ self.use_tiling = False
+
+ self.use_quant_layer = use_quant_layer
+
+ self.encoder = Encoder(
+ z_channels=z_channels,
+ hidden_size=hidden_size,
+ hidden_size_mult=hidden_size_mult,
+ attn_resolutions=attn_resolutions,
+ conv_in=encoder_conv_in,
+ conv_out=encoder_conv_out,
+ attention=encoder_attention,
+ resnet_blocks=encoder_resnet_blocks,
+ spatial_downsample=encoder_spatial_downsample,
+ temporal_downsample=encoder_temporal_downsample,
+ mid_resnet=encoder_mid_resnet,
+ dropout=dropout,
+ resolution=resolution,
+ num_res_blocks=num_res_blocks,
+ double_z=double_z,
+ )
+
+ self.decoder = Decoder(
+ z_channels=z_channels,
+ hidden_size=hidden_size,
+ hidden_size_mult=hidden_size_mult,
+ attn_resolutions=attn_resolutions,
+ conv_in=decoder_conv_in,
+ conv_out=decoder_conv_out,
+ attention=decoder_attention,
+ resnet_blocks=decoder_resnet_blocks,
+ spatial_upsample=decoder_spatial_upsample,
+ temporal_upsample=decoder_temporal_upsample,
+ mid_resnet=decoder_mid_resnet,
+ dropout=dropout,
+ resolution=resolution,
+ num_res_blocks=num_res_blocks,
+ )
+ if self.use_quant_layer:
+ quant_conv_cls = resolve_str_to_obj(q_conv)
+ self.quant_conv = quant_conv_cls(2 * z_channels, 2 * embed_dim, 1)
+ self.post_quant_conv = quant_conv_cls(embed_dim, z_channels, 1)
+
+ def get_encoder(self):
+ if self.use_quant_layer:
+ return [self.quant_conv, self.encoder]
+ return [self.encoder]
+
+ def get_decoder(self):
+ if self.use_quant_layer:
+ return [self.post_quant_conv, self.decoder]
+ return [self.decoder]
+
+ def encode(self, x):
+ if self.use_tiling and (
+ x.shape[-1] > self.tile_sample_min_size
+ or x.shape[-2] > self.tile_sample_min_size
+ or x.shape[-3] > self.tile_sample_min_size_t
+ ):
+ return self.tiled_encode(x)
+ h = self.encoder(x)
+ if self.use_quant_layer:
+ h = self.quant_conv(h)
+ posterior = DiagonalGaussianDistribution(h)
+ return posterior
+
+ def decode(self, z):
+ if self.use_tiling and (
+ z.shape[-1] > self.tile_latent_min_size
+ or z.shape[-2] > self.tile_latent_min_size
+ or z.shape[-3] > self.tile_latent_min_size_t
+ ):
+ return self.tiled_decode(z)
+ if self.use_quant_layer:
+ z = self.post_quant_conv(z)
+ dec = self.decoder(z)
+ return dec
+
+ def forward(self, input, sample_posterior=True):
+ posterior = self.encode(input)
+ if sample_posterior:
+ z = posterior.sample()
+ else:
+ z = posterior.mode()
+ dec = self.decode(z)
+ return dec, posterior
+
+ def on_train_start(self):
+ self.ema = deepcopy(self) if self.save_ema==True else None
+
+ def get_last_layer(self):
+ if hasattr(self.decoder.conv_out, "conv"):
+ return self.decoder.conv_out.conv.weight
+ else:
+ return self.decoder.conv_out.weight
+
+ def blend_v(
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
+ ) -> torch.Tensor:
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
+ for y in range(blend_extent):
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (
+ 1 - y / blend_extent
+ ) + b[:, :, :, y, :] * (y / blend_extent)
+ return b
+
+ def blend_h(
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
+ ) -> torch.Tensor:
+ blend_extent = min(a.shape[4], b.shape[4], blend_extent)
+ for x in range(blend_extent):
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (
+ 1 - x / blend_extent
+ ) + b[:, :, :, :, x] * (x / blend_extent)
+ return b
+
+ def tiled_encode(self, x):
+ t = x.shape[2]
+ t_chunk_idx = [i for i in range(0, t, self.tile_sample_min_size_t-1)]
+ if len(t_chunk_idx) == 1 and t_chunk_idx[0] == 0:
+ t_chunk_start_end = [[0, t]]
+ else:
+ t_chunk_start_end = [[t_chunk_idx[i], t_chunk_idx[i+1]+1] for i in range(len(t_chunk_idx)-1)]
+ if t_chunk_start_end[-1][-1] > t:
+ t_chunk_start_end[-1][-1] = t
+ elif t_chunk_start_end[-1][-1] < t:
+ last_start_end = [t_chunk_idx[-1], t]
+ t_chunk_start_end.append(last_start_end)
+ moments = []
+ for idx, (start, end) in enumerate(t_chunk_start_end):
+ chunk_x = x[:, :, start: end]
+ if idx != 0:
+ moment = self.tiled_encode2d(chunk_x, return_moments=True)[:, :, 1:]
+ else:
+ moment = self.tiled_encode2d(chunk_x, return_moments=True)
+ moments.append(moment)
+ moments = torch.cat(moments, dim=2)
+ posterior = DiagonalGaussianDistribution(moments)
+ return posterior
+
+ def tiled_decode(self, x):
+ t = x.shape[2]
+ t_chunk_idx = [i for i in range(0, t, self.tile_latent_min_size_t-1)]
+ if len(t_chunk_idx) == 1 and t_chunk_idx[0] == 0:
+ t_chunk_start_end = [[0, t]]
+ else:
+ t_chunk_start_end = [[t_chunk_idx[i], t_chunk_idx[i+1]+1] for i in range(len(t_chunk_idx)-1)]
+ if t_chunk_start_end[-1][-1] > t:
+ t_chunk_start_end[-1][-1] = t
+ elif t_chunk_start_end[-1][-1] < t:
+ last_start_end = [t_chunk_idx[-1], t]
+ t_chunk_start_end.append(last_start_end)
+ dec_ = []
+ for idx, (start, end) in enumerate(t_chunk_start_end):
+ chunk_x = x[:, :, start: end]
+ if idx != 0:
+ dec = self.tiled_decode2d(chunk_x)[:, :, 1:]
+ else:
+ dec = self.tiled_decode2d(chunk_x)
+ dec_.append(dec)
+ dec_ = torch.cat(dec_, dim=2)
+ return dec_
+
+ def tiled_encode2d(self, x, return_moments=False):
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
+ row_limit = self.tile_latent_min_size - blend_extent
+
+ # Split the image into 512x512 tiles and encode them separately.
+ rows = []
+ for i in range(0, x.shape[3], overlap_size):
+ row = []
+ for j in range(0, x.shape[4], overlap_size):
+ tile = x[
+ :,
+ :,
+ :,
+ i : i + self.tile_sample_min_size,
+ j : j + self.tile_sample_min_size,
+ ]
+ tile = self.encoder(tile)
+ if self.use_quant_layer: #看上去就是一个causal 3D卷积
+ tile = self.quant_conv(tile)
+ row.append(tile)
+ rows.append(row)
+ result_rows = []
+ for i, row in enumerate(rows):
+ result_row = []
+ for j, tile in enumerate(row):
+ # blend the above tile and the left tile
+ # to the current tile and add the current tile to the result row
+ if i > 0:
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
+ if j > 0:
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
+ result_rows.append(torch.cat(result_row, dim=4))
+
+ moments = torch.cat(result_rows, dim=3)
+ posterior = DiagonalGaussianDistribution(moments)
+ if return_moments:
+ return moments
+ return posterior
+
+ def tiled_decode2d(self, z):
+
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
+ row_limit = self.tile_sample_min_size - blend_extent
+
+ # Split z into overlapping 64x64 tiles and decode them separately.
+ # The tiles have an overlap to avoid seams between tiles.
+ rows = []
+ for i in range(0, z.shape[3], overlap_size):
+ row = []
+ for j in range(0, z.shape[4], overlap_size):
+ tile = z[
+ :,
+ :,
+ :,
+ i : i + self.tile_latent_min_size,
+ j : j + self.tile_latent_min_size,
+ ]
+ if self.use_quant_layer:
+ tile = self.post_quant_conv(tile)
+ decoded = self.decoder(tile)
+ row.append(decoded)
+ rows.append(row)
+ result_rows = []
+ for i, row in enumerate(rows):
+ result_row = []
+ for j, tile in enumerate(row):
+ # blend the above tile and the left tile
+ # to the current tile and add the current tile to the result row
+ if i > 0:
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
+ if j > 0:
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
+ result_rows.append(torch.cat(result_row, dim=4))
+
+ dec = torch.cat(result_rows, dim=3)
+ return dec
+
+ def enable_tiling(self, use_tiling: bool = True):
+ self.use_tiling = use_tiling
+
+ def disable_tiling(self):
+ self.enable_tiling(False)
+
+ def init_from_ckpt(self, path, ignore_keys=list()):
+ sd = torch.load(path, map_location="cpu")
+ print("init from " + path)
+
+ if "ema_state_dict" in sd and len(sd['ema_state_dict']) > 0 and os.environ.get("NOT_USE_EMA_MODEL", 0) == 0:
+ print("Load from ema model!")
+ sd = sd["ema_state_dict"]
+ sd = {key.replace("module.", ""): value for key, value in sd.items()}
+ elif "state_dict" in sd:
+ print("Load from normal model!")
+ if "gen_model" in sd["state_dict"]:
+ sd = sd["state_dict"]["gen_model"]
+ else:
+ sd = sd["state_dict"]
+
+ keys = list(sd.keys())
+
+ for k in keys:
+ for ik in ignore_keys:
+ if k.startswith(ik):
+ print("Deleting key {} from state_dict.".format(k))
+ del sd[k]
+
+ miss, unexpected = self.load_state_dict(sd, strict=False)
+ assert len(miss) == 0, f"miss key: {miss}"
+ if len(unexpected) > 0:
+ for i in unexpected:
+ assert 'loss' in i, "unexpected key: {i}"
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/configuration_videobase.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/configuration_videobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..f25a25c5b37da8aa8f9e939112ced0b9f861a4b6
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/configuration_videobase.py
@@ -0,0 +1,44 @@
+import json
+import yaml
+from typing import TypeVar, Dict, Any
+from diffusers import ConfigMixin
+
+T = TypeVar('T', bound='VideoBaseConfiguration')
+class VideoBaseConfiguration(ConfigMixin):
+ config_name = "VideoBaseConfiguration"
+ _nested_config_fields: Dict[str, Any] = {}
+
+ def __init__(self, **kwargs):
+ pass
+
+ def to_dict(self) -> Dict[str, Any]:
+ d = {}
+ for key, value in vars(self).items():
+ if isinstance(value, VideoBaseConfiguration):
+ d[key] = value.to_dict() # Serialize nested VideoBaseConfiguration instances
+ elif isinstance(value, tuple):
+ d[key] = list(value)
+ else:
+ d[key] = value
+ return d
+
+ def to_yaml_file(self, yaml_path: str):
+ with open(yaml_path, 'w') as yaml_file:
+ yaml.dump(self.to_dict(), yaml_file, default_flow_style=False)
+
+ @classmethod
+ def load_from_yaml(cls: T, yaml_path: str) -> T:
+ with open(yaml_path, 'r') as yaml_file:
+ config_dict = yaml.safe_load(yaml_file)
+ for field, field_type in cls._nested_config_fields.items():
+ if field in config_dict:
+ config_dict[field] = field_type.load_from_dict(config_dict[field])
+ return cls(**config_dict)
+
+ @classmethod
+ def load_from_dict(cls: T, config_dict: Dict[str, Any]) -> T:
+ # Process nested configuration objects
+ for field, field_type in cls._nested_config_fields.items():
+ if field in config_dict:
+ config_dict[field] = field_type.load_from_dict(config_dict[field])
+ return cls(**config_dict)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/dataset_videobase.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/dataset_videobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..041e94a8859d6b52113ed2f7908bd680a06b3803
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/dataset_videobase.py
@@ -0,0 +1,112 @@
+import os.path as osp
+import random
+from glob import glob
+
+from torchvision import transforms
+import numpy as np
+import torch
+import torch.utils.data as data
+import torch.nn.functional as F
+from torchvision.transforms import Lambda
+import pandas as pd
+
+from ..dataset.transform import ToTensorVideo, CenterCropVideo
+from ..utils.dataset_utils import DecordInit
+
+def TemporalRandomCrop(total_frames, size):
+ """
+ Performs a random temporal crop on a video sequence.
+
+ This function randomly selects a continuous frame sequence of length `size` from a video sequence.
+ `total_frames` indicates the total number of frames in the video sequence, and `size` represents the length of the frame sequence to be cropped.
+
+ Parameters:
+ - total_frames (int): The total number of frames in the video sequence.
+ - size (int): The length of the frame sequence to be cropped.
+
+ Returns:
+ - (int, int): A tuple containing two integers. The first integer is the starting frame index of the cropped sequence,
+ and the second integer is the ending frame index (inclusive) of the cropped sequence.
+ """
+ rand_end = max(0, total_frames - size - 1)
+ begin_index = random.randint(0, rand_end)
+ end_index = min(begin_index + size, total_frames)
+ return begin_index, end_index
+
+def resize(x, resolution):
+ height, width = x.shape[-2:]
+ resolution = min(2 * resolution, height, width)
+ aspect_ratio = width / height
+ if width <= height:
+ new_width = resolution
+ new_height = int(resolution / aspect_ratio)
+ else:
+ new_height = resolution
+ new_width = int(resolution * aspect_ratio)
+ resized_x = F.interpolate(x, size=(new_height, new_width), mode='bilinear', align_corners=True, antialias=True)
+ return resized_x
+
+class VideoDataset(data.Dataset):
+ """ Generic dataset for videos files stored in folders
+ Returns BCTHW videos in the range [-0.5, 0.5] """
+ video_exts = ['avi', 'mp4', 'webm']
+ def __init__(self, video_folder, sequence_length, image_folder=None, train=True, resolution=64, sample_rate=1, dynamic_sample=True):
+
+ self.train = train
+ self.sequence_length = sequence_length
+ self.sample_rate = sample_rate
+ self.resolution = resolution
+ self.v_decoder = DecordInit()
+ self.video_folder = video_folder
+ self.dynamic_sample = dynamic_sample
+
+ self.transform = transforms.Compose([
+ ToTensorVideo(),
+ # Lambda(lambda x: resize(x, self.resolution)),
+ CenterCropVideo(self.resolution),
+ Lambda(lambda x: 2.0 * x - 1.0)
+ ])
+ print('Building datasets...')
+ self.samples = self._make_dataset()
+
+ def _make_dataset(self):
+ samples = []
+ if not self.video_folder.endswith('.csv'):
+ samples += sum([glob(osp.join(self.video_folder, '**', f'*.{ext}'), recursive=True)
+ for ext in self.video_exts], [])
+ else:
+ df = pd.read_csv(self.video_folder)
+ samples = df['path'].tolist()
+ return samples
+
+ def __len__(self):
+ return len(self.samples)
+
+ def __getitem__(self, idx):
+ video_path = self.samples[idx]
+ try:
+ video = self.decord_read(video_path)
+ video = self.transform(video) # T C H W -> T C H W
+ video = video.transpose(0, 1) # T C H W -> C T H W
+ return dict(video=video, label="")
+ except Exception as e:
+ print(f'Error with {e}, {video_path}')
+ return self.__getitem__(random.randint(0, self.__len__()-1))
+
+ def decord_read(self, path):
+ decord_vr = self.v_decoder(path)
+ total_frames = len(decord_vr)
+ # Sampling video frames
+ if self.dynamic_sample:
+ sample_rate = random.randint(1, self.sample_rate)
+ else:
+ sample_rate = self.sample_rate
+ size = self.sequence_length * sample_rate #25帧,采样率是2,也就是至少50帧
+ start_frame_ind, end_frame_ind = TemporalRandomCrop(total_frames, size)
+ # assert end_frame_ind - start_frame_ind >= self.num_frames
+ frame_indice = np.linspace(start_frame_ind, end_frame_ind - 1, self.sequence_length, dtype=int)
+
+ video_data = decord_vr.get_batch(frame_indice).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(0, 3, 1, 2) # (T, H, W, C) -> (T C H W)
+ return video_data
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/ema_model.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/ema_model.py
new file mode 100644
index 0000000000000000000000000000000000000000..c4cf5017285f91c8092d2f1850fb95d70b95d2fe
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/ema_model.py
@@ -0,0 +1,31 @@
+class EMA:
+ def __init__(self, model, decay):
+ self.model = model
+ self.decay = decay
+ self.shadow = {}
+ self.backup = {}
+
+ def register(self):
+ for name, param in self.model.named_parameters():
+ if param.requires_grad:
+ self.shadow[name] = param.data.clone()
+
+ def update(self):
+ for name, param in self.model.named_parameters():
+ if name in self.shadow:
+ new_average = (1.0 - self.decay) * param.data + self.decay * self.shadow[name]
+ self.shadow[name] = new_average.clone()
+
+ def apply_shadow(self):
+ for name, param in self.model.named_parameters():
+ if name in self.shadow:
+ self.backup[name] = param.data
+ param.data = self.shadow[name]
+
+ def restore(self):
+ for name, param in self.model.named_parameters():
+ if name in self.shadow:
+ param.data = self.backup[name]
+ self.backup = {}
+
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..07e6812631f8e9e4ce2e6ede1cdb448563d171dc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/__init__.py
@@ -0,0 +1 @@
+from .perceptual_loss import SimpleLPIPS, LPIPSWithDiscriminator, LPIPSWithDiscriminator3D
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/discriminator.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/discriminator.py
new file mode 100644
index 0000000000000000000000000000000000000000..247a610706f471664eb5e478128d3aa973150877
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/discriminator.py
@@ -0,0 +1,181 @@
+import functools
+import torch.nn as nn
+from ..modules.normalize import ActNorm
+from ..modules.conv import CausalConv3d
+from einops import rearrange
+
+def weights_init(m):
+ classname = m.__class__.__name__
+ if classname.find('Conv') != -1:
+ nn.init.normal_(m.weight.data, 0.0, 0.02)
+ elif classname.find('BatchNorm') != -1:
+ nn.init.normal_(m.weight.data, 1.0, 0.02)
+ nn.init.constant_(m.bias.data, 0)
+
+def weights_init_conv(m):
+ if hasattr(m, 'conv'):
+ m = m.conv
+ classname = m.__class__.__name__
+ if classname.find('Conv') != -1:
+ nn.init.normal_(m.weight.data, 0.0, 0.02)
+ elif classname.find('BatchNorm') != -1:
+ nn.init.normal_(m.weight.data, 1.0, 0.02)
+ nn.init.constant_(m.bias.data, 0)
+
+class NLayerDiscriminator(nn.Module):
+ """Defines a PatchGAN discriminator as in Pix2Pix
+ --> see https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
+ """
+ def __init__(self, input_nc=3, ndf=64, n_layers=3, use_actnorm=False):
+ """Construct a PatchGAN discriminator
+ Parameters:
+ input_nc (int) -- the number of channels in input images
+ ndf (int) -- the number of filters in the last conv layer
+ n_layers (int) -- the number of conv layers in the discriminator
+ norm_layer -- normalization layer
+ """
+ super(NLayerDiscriminator, self).__init__()
+ if not use_actnorm:
+ norm_layer = nn.BatchNorm2d
+ else:
+ norm_layer = ActNorm
+ if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
+ use_bias = norm_layer.func != nn.BatchNorm2d
+ else:
+ use_bias = norm_layer != nn.BatchNorm2d
+
+ kw = 4
+ padw = 1
+ sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
+ nf_mult = 1
+ nf_mult_prev = 1
+ for n in range(1, n_layers): # gradually increase the number of filters
+ nf_mult_prev = nf_mult
+ nf_mult = min(2 ** n, 8)
+ sequence += [
+ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
+ norm_layer(ndf * nf_mult),
+ nn.LeakyReLU(0.2, True)
+ ]
+
+ nf_mult_prev = nf_mult
+ nf_mult = min(2 ** n_layers, 8)
+ sequence += [
+ nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
+ norm_layer(ndf * nf_mult),
+ nn.LeakyReLU(0.2, True)
+ ]
+
+ sequence += [
+ nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
+ self.main = nn.Sequential(*sequence)
+
+ def forward(self, input):
+ """Standard forward."""
+ return self.main(input)
+
+class NLayerDiscriminator3D(nn.Module):
+ """Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs."""
+ def __init__(self, input_nc=1, ndf=64, n_layers=3, use_actnorm=False):
+ """
+ Construct a 3D PatchGAN discriminator
+
+ Parameters:
+ input_nc (int) -- the number of channels in input volumes
+ ndf (int) -- the number of filters in the last conv layer
+ n_layers (int) -- the number of conv layers in the discriminator
+ use_actnorm (bool) -- flag to use actnorm instead of batchnorm
+ """
+ super(NLayerDiscriminator3D, self).__init__()
+ if not use_actnorm:
+ norm_layer = nn.BatchNorm3d
+ else:
+ raise NotImplementedError("Not implemented.")
+ if type(norm_layer) == functools.partial:
+ use_bias = norm_layer.func != nn.BatchNorm3d
+ else:
+ use_bias = norm_layer != nn.BatchNorm3d
+
+ kw = 3
+ padw = 1
+ sequence = [nn.Conv3d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
+ nf_mult = 1
+ nf_mult_prev = 1
+ for n in range(1, n_layers): # gradually increase the number of filters
+ nf_mult_prev = nf_mult
+ nf_mult = min(2 ** n, 8)
+ sequence += [
+ nn.Conv3d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=(2 if n==1 else 1,2,2), padding=padw, bias=use_bias),
+ norm_layer(ndf * nf_mult),
+ nn.LeakyReLU(0.2, True)
+ ]
+
+ nf_mult_prev = nf_mult
+ nf_mult = min(2 ** n_layers, 8)
+ sequence += [
+ nn.Conv3d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=1, padding=padw, bias=use_bias),
+ norm_layer(ndf * nf_mult),
+ nn.LeakyReLU(0.2, True)
+ ]
+
+ sequence += [nn.Conv3d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
+ self.main = nn.Sequential(*sequence)
+
+ def forward(self, input):
+ """Standard forward."""
+ return self.main(input)
+
+
+
+
+
+# class NLayerDiscriminator3D(nn.Module):
+# """Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs."""
+# def __init__(self, input_nc=1, ndf=64, n_layers=3, use_actnorm=False):
+# """
+# Construct a 3D PatchGAN discriminator
+
+# Parameters:
+# input_nc (int) -- the number of channels in input volumes
+# ndf (int) -- the number of filters in the last conv layer
+# n_layers (int) -- the number of conv layers in the discriminator
+# use_actnorm (bool) -- flag to use actnorm instead of batchnorm
+# """
+# super(NLayerDiscriminator3D, self).__init__()
+# if not use_actnorm:
+# norm_layer = nn.BatchNorm3d
+# else:
+# raise NotImplementedError("Not implemented.")
+# if type(norm_layer) == functools.partial:
+# use_bias = norm_layer.func != nn.BatchNorm3d
+# else:
+# use_bias = norm_layer != nn.BatchNorm3d
+
+# kw = 4
+# padw = 1
+# sequence = [CausalConv3d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
+# nf_mult = 1
+# nf_mult_prev = 1
+# for n in range(1, n_layers): # gradually increase the number of filters
+# nf_mult_prev = nf_mult
+# nf_mult = min(2 ** n, 8)
+# sequence += [
+# CausalConv3d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=(2 if n==1 else 1,2,2), padding=padw, bias=use_bias),
+# norm_layer(ndf * nf_mult),
+# nn.LeakyReLU(0.2, True)
+# ]
+
+# nf_mult_prev = nf_mult
+# nf_mult = min(2 ** n_layers, 8)
+# sequence += [
+# CausalConv3d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=1, padding=padw, bias=use_bias),
+# norm_layer(ndf * nf_mult),
+# nn.LeakyReLU(0.2, True)
+# ]
+
+# sequence += [CausalConv3d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
+# self.main = nn.Sequential(*sequence)
+
+# def forward(self, input):
+# """Standard forward."""
+# return self.main(input)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/lpips.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/lpips.py
new file mode 100644
index 0000000000000000000000000000000000000000..5054549c8628879da40a8ef8a119b1576b17e17a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/lpips.py
@@ -0,0 +1,120 @@
+"""Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models"""
+
+import torch
+import torch.nn as nn
+from torchvision import models
+from collections import namedtuple
+from opensora.utils.taming_download import get_ckpt_path
+
+class LPIPS(nn.Module):
+ # Learned perceptual metric
+ def __init__(self, use_dropout=True):
+ super().__init__()
+ self.scaling_layer = ScalingLayer()
+ self.chns = [64, 128, 256, 512, 512] # vg16 features
+ self.net = vgg16(pretrained=True, requires_grad=False)
+ self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)
+ self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)
+ self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)
+ self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)
+ self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)
+ self.load_from_pretrained()
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def load_from_pretrained(self, name="vgg_lpips"):
+ ckpt = get_ckpt_path(name, ".cache/lpips")
+ self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
+ print("loaded pretrained LPIPS loss from {}".format(ckpt))
+
+ @classmethod
+ def from_pretrained(cls, name="vgg_lpips"):
+ if name != "vgg_lpips":
+ raise NotImplementedError
+ model = cls()
+ ckpt = get_ckpt_path(name)
+ model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False)
+ return model
+
+ def forward(self, input, target):
+ in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))
+ outs0, outs1 = self.net(in0_input), self.net(in1_input)
+ feats0, feats1, diffs = {}, {}, {}
+ lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]
+ for kk in range(len(self.chns)):
+ feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])
+ diffs[kk] = (feats0[kk] - feats1[kk]) ** 2
+
+ res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))]
+ val = res[0]
+ for l in range(1, len(self.chns)):
+ val += res[l]
+ return val
+
+
+class ScalingLayer(nn.Module):
+ def __init__(self):
+ super(ScalingLayer, self).__init__()
+ self.register_buffer('shift', torch.Tensor([-.030, -.088, -.188])[None, :, None, None])
+ self.register_buffer('scale', torch.Tensor([.458, .448, .450])[None, :, None, None])
+
+ def forward(self, inp):
+ return (inp - self.shift) / self.scale
+
+
+class NetLinLayer(nn.Module):
+ """ A single linear layer which does a 1x1 conv """
+ def __init__(self, chn_in, chn_out=1, use_dropout=False):
+ super(NetLinLayer, self).__init__()
+ layers = [nn.Dropout(), ] if (use_dropout) else []
+ layers += [nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ]
+ self.model = nn.Sequential(*layers)
+
+
+class vgg16(torch.nn.Module):
+ def __init__(self, requires_grad=False, pretrained=True):
+ super(vgg16, self).__init__()
+ vgg_pretrained_features = models.vgg16(pretrained=pretrained).features
+ self.slice1 = torch.nn.Sequential()
+ self.slice2 = torch.nn.Sequential()
+ self.slice3 = torch.nn.Sequential()
+ self.slice4 = torch.nn.Sequential()
+ self.slice5 = torch.nn.Sequential()
+ self.N_slices = 5
+ for x in range(4):
+ self.slice1.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(4, 9):
+ self.slice2.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(9, 16):
+ self.slice3.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(16, 23):
+ self.slice4.add_module(str(x), vgg_pretrained_features[x])
+ for x in range(23, 30):
+ self.slice5.add_module(str(x), vgg_pretrained_features[x])
+ if not requires_grad:
+ for param in self.parameters():
+ param.requires_grad = False
+
+ def forward(self, X):
+ h = self.slice1(X)
+ h_relu1_2 = h
+ h = self.slice2(h)
+ h_relu2_2 = h
+ h = self.slice3(h)
+ h_relu3_3 = h
+ h = self.slice4(h)
+ h_relu4_3 = h
+ h = self.slice5(h)
+ h_relu5_3 = h
+ vgg_outputs = namedtuple("VggOutputs", ['relu1_2', 'relu2_2', 'relu3_3', 'relu4_3', 'relu5_3'])
+ out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)
+ return out
+
+
+def normalize_tensor(x,eps=1e-10):
+ norm_factor = torch.sqrt(torch.sum(x**2,dim=1,keepdim=True))
+ return x/(norm_factor+eps)
+
+
+def spatial_average(x, keepdim=True):
+ return x.mean([2,3],keepdim=keepdim)
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/perceptual_loss.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/perceptual_loss.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa8dd5ad83c19a9a9816470e84cc114e659da403
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/losses/perceptual_loss.py
@@ -0,0 +1,389 @@
+import torch
+from torch import nn
+import torch.nn.functional as F
+from .lpips import LPIPS
+from einops import rearrange
+from .discriminator import NLayerDiscriminator, weights_init, NLayerDiscriminator3D
+
+
+def hinge_d_loss(logits_real, logits_fake):
+ loss_real = torch.mean(F.relu(1.0 - logits_real))
+ loss_fake = torch.mean(F.relu(1.0 + logits_fake))
+ d_loss = 0.5 * (loss_real + loss_fake)
+ return d_loss
+
+
+def vanilla_d_loss(logits_real, logits_fake):
+ d_loss = 0.5 * (
+ torch.mean(torch.nn.functional.softplus(-logits_real))
+ + torch.mean(torch.nn.functional.softplus(logits_fake))
+ )
+ return d_loss
+
+
+def hinge_d_loss_with_exemplar_weights(logits_real, logits_fake, weights):
+ assert weights.shape[0] == logits_real.shape[0] == logits_fake.shape[0]
+ loss_real = torch.mean(F.relu(1.0 - logits_real), dim=[1, 2, 3])
+ loss_fake = torch.mean(F.relu(1.0 + logits_fake), dim=[1, 2, 3])
+ loss_real = (weights * loss_real).sum() / weights.sum()
+ loss_fake = (weights * loss_fake).sum() / weights.sum()
+ d_loss = 0.5 * (loss_real + loss_fake)
+ return d_loss
+
+
+def adopt_weight(weight, global_step, threshold=0, value=0.0):
+ if global_step < threshold:
+ weight = value
+ return weight
+
+
+def measure_perplexity(predicted_indices, n_embed):
+ # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py
+ # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally
+ encodings = F.one_hot(predicted_indices, n_embed).float().reshape(-1, n_embed)
+ avg_probs = encodings.mean(0)
+ perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp()
+ cluster_use = torch.sum(avg_probs > 0)
+ return perplexity, cluster_use
+
+
+def l1(x, y):
+ return torch.abs(x - y)
+
+
+def l2(x, y):
+ return torch.pow((x - y), 2)
+
+
+class LPIPSWithDiscriminator(nn.Module):
+ def __init__(
+ self,
+ disc_start,
+ logvar_init=0.0,
+ kl_weight=1.0,
+ pixelloss_weight=1.0,
+ perceptual_weight=1.0,
+ # --- Discriminator Loss ---
+ disc_num_layers=3,
+ disc_in_channels=3,
+ disc_factor=1.0,
+ disc_weight=1.0,
+ use_actnorm=False,
+ disc_conditional=False,
+ disc_loss="hinge",
+ loss_type: str = "l1"
+ ):
+
+ super().__init__()
+ assert disc_loss in ["hinge", "vanilla"]
+ self.kl_weight = kl_weight
+ self.pixel_weight = pixelloss_weight
+ self.perceptual_loss = LPIPS().eval()
+ self.perceptual_weight = perceptual_weight
+ self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)
+
+ self.discriminator = NLayerDiscriminator(
+ input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=use_actnorm
+ ).apply(weights_init)
+ self.discriminator_iter_start = disc_start
+ self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss
+ self.disc_factor = disc_factor
+ self.discriminator_weight = disc_weight
+ self.disc_conditional = disc_conditional
+ self.loss_func = l1 if loss_type == "l1" else l2
+
+ def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
+ layer = last_layer if last_layer is not None else self.last_layer[0]
+
+ nll_grads = torch.autograd.grad(nll_loss, layer, retain_graph=True)[0]
+ g_grads = torch.autograd.grad(g_loss, layer, retain_graph=True)[0]
+
+ d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
+ d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
+ d_weight = d_weight * self.discriminator_weight
+ return d_weight
+
+ def forward(
+ self,
+ inputs,
+ reconstructions,
+ posteriors,
+ optimizer_idx,
+ global_step,
+ split="train",
+ weights=None,
+ last_layer=None,
+ cond=None,
+ ):
+ # GAN Part
+ inputs = rearrange(inputs, "b c t h w -> (b t) c h w").contiguous()
+ reconstructions = rearrange(
+ reconstructions, "b c t h w -> (b t) c h w"
+ ).contiguous()
+ if optimizer_idx == 0:
+ rec_loss = self.loss_func(inputs, reconstructions)
+ if self.perceptual_weight > 0:
+ p_loss = self.perceptual_loss(inputs, reconstructions)
+ rec_loss = rec_loss + self.perceptual_weight * p_loss
+ nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
+ weighted_nll_loss = nll_loss
+ if weights is not None:
+ weighted_nll_loss = weights * nll_loss
+ weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
+ nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
+ kl_loss = posteriors.kl()
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
+
+ logits_fake = self.discriminator(reconstructions)
+ g_loss = -torch.mean(logits_fake)
+ if global_step >= self.discriminator_iter_start:
+ if self.disc_factor > 0.0:
+ d_weight = self.calculate_adaptive_weight(
+ nll_loss, g_loss, last_layer=last_layer
+ )
+ else:
+ d_weight = torch.tensor(1.0)
+ else:
+ d_weight = torch.tensor(0.0)
+ g_loss = torch.tensor(0.0, requires_grad=True)
+
+ disc_factor = adopt_weight(
+ self.disc_factor, global_step, threshold=self.discriminator_iter_start
+ )
+ loss = (
+ weighted_nll_loss
+ + self.kl_weight * kl_loss
+ + d_weight * disc_factor * g_loss
+ )
+ log = {
+ "{}/total_loss".format(split): loss.clone().detach().mean(),
+ "{}/logvar".format(split): self.logvar.detach(),
+ "{}/kl_loss".format(split): kl_loss.detach().mean(),
+ "{}/nll_loss".format(split): nll_loss.detach().mean(),
+ "{}/rec_loss".format(split): rec_loss.detach().mean(),
+ "{}/d_weight".format(split): d_weight.detach(),
+ "{}/disc_factor".format(split): torch.tensor(disc_factor),
+ "{}/g_loss".format(split): g_loss.detach().mean(),
+ }
+ return loss, log
+
+ if optimizer_idx == 1:
+ if cond is None:
+ logits_real = self.discriminator(inputs.contiguous().detach())
+ logits_fake = self.discriminator(reconstructions.contiguous().detach())
+ else:
+ logits_real = self.discriminator(
+ torch.cat((inputs.contiguous().detach(), cond), dim=1)
+ )
+ logits_fake = self.discriminator(
+ torch.cat((reconstructions.contiguous().detach(), cond), dim=1)
+ )
+
+ disc_factor = adopt_weight(
+ self.disc_factor, global_step, threshold=self.discriminator_iter_start
+ )
+ d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
+
+ log = {
+ "{}/disc_loss".format(split): d_loss.clone().detach().mean(),
+ "{}/logits_real".format(split): logits_real.detach().mean(),
+ "{}/logits_fake".format(split): logits_fake.detach().mean(),
+ }
+ return d_loss, log
+
+
+class LPIPSWithDiscriminator3D(nn.Module):
+ def __init__(
+ self,
+ disc_start,
+ logvar_init=0.0,
+ kl_weight=1.0,
+ pixelloss_weight=1.0,
+ perceptual_weight=1.0,
+ # --- Discriminator Loss ---
+ disc_num_layers=3,
+ disc_in_channels=3,
+ disc_factor=1.0,
+ disc_weight=1.0,
+ use_actnorm=False,
+ disc_conditional=False,
+ disc_loss="hinge",
+ learn_logvar: bool = False,
+ loss_type: str = "l1"
+ ):
+
+ super().__init__()
+ assert disc_loss in ["hinge", "vanilla"]
+ self.kl_weight = kl_weight
+ self.pixel_weight = pixelloss_weight
+ self.perceptual_loss = LPIPS().eval()
+ self.perceptual_weight = perceptual_weight
+ self.logvar = nn.Parameter(
+ torch.full((), logvar_init), requires_grad=learn_logvar
+ )
+ self.discriminator = NLayerDiscriminator3D(
+ input_nc=disc_in_channels, n_layers=disc_num_layers, use_actnorm=use_actnorm
+ ).apply(weights_init)
+ self.discriminator_iter_start = disc_start
+ self.disc_loss = hinge_d_loss if disc_loss == "hinge" else vanilla_d_loss
+ self.disc_factor = disc_factor
+ self.discriminator_weight = disc_weight
+ self.disc_conditional = disc_conditional
+ self.loss_func = l1 if loss_type == "l1" else l2
+
+ def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer=None):
+ layer = last_layer if last_layer is not None else self.last_layer[0]
+
+ nll_grads = torch.autograd.grad(nll_loss, layer, retain_graph=True)[0]
+ g_grads = torch.autograd.grad(g_loss, layer, retain_graph=True)[0]
+
+ d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)
+ d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()
+ d_weight = d_weight * self.discriminator_weight
+ return d_weight
+
+ def forward(
+ self,
+ inputs,
+ reconstructions,
+ posteriors,
+ optimizer_idx,
+ global_step,
+ split="train",
+ weights=None,
+ last_layer=None,
+ cond=None
+ ):
+
+ t = inputs.shape[2]
+ # GAN Part
+ if optimizer_idx == 0:
+ inputs = rearrange(inputs, "b c t h w -> (b t) c h w").contiguous()
+ reconstructions = rearrange(
+ reconstructions, "b c t h w -> (b t) c h w"
+ ).contiguous()
+ rec_loss = self.loss_func(inputs, reconstructions) #计算重建loss,即l1 loss
+ if self.perceptual_weight > 0:
+ p_loss = self.perceptual_loss(inputs, reconstructions)
+ rec_loss = rec_loss + self.perceptual_weight * p_loss
+ nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
+ weighted_nll_loss = nll_loss
+ if weights is not None:
+ weighted_nll_loss = weights * nll_loss
+ weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
+ nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
+ kl_loss = posteriors.kl()
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
+
+ inputs = rearrange(inputs, "(b t) c h w -> b c t h w", t=t).contiguous()
+ reconstructions = rearrange(
+ reconstructions, "(b t) c h w -> b c t h w", t=t
+ ).contiguous()
+
+ logits_fake = self.discriminator(reconstructions)
+ g_loss = -torch.mean(logits_fake)
+ if global_step >= self.discriminator_iter_start:
+ if self.disc_factor > 0.0:
+ d_weight = self.calculate_adaptive_weight(
+ nll_loss, g_loss, last_layer=last_layer
+ )
+ else:
+ d_weight = torch.tensor(1.0)
+ else:
+ d_weight = torch.tensor(0.0)
+ g_loss = torch.tensor(0.0, requires_grad=True)
+
+ disc_factor = adopt_weight(
+ self.disc_factor, global_step, threshold=self.discriminator_iter_start
+ )
+ loss = (
+ weighted_nll_loss
+ + self.kl_weight * kl_loss
+ + d_weight * disc_factor * g_loss
+ )
+ log = {
+ "{}/total_loss".format(split): loss.clone().detach().mean(),
+ "{}/logvar".format(split): self.logvar.detach(),
+ "{}/kl_loss".format(split): kl_loss.detach().mean(),
+ "{}/nll_loss".format(split): nll_loss.detach().mean(),
+ "{}/rec_loss".format(split): rec_loss.detach().mean(),
+ "{}/d_weight".format(split): d_weight.detach(),
+ "{}/disc_factor".format(split): torch.tensor(disc_factor),
+ "{}/g_loss".format(split): g_loss.detach().mean(),
+ }
+ return loss, log
+ elif optimizer_idx == 1:
+ logits_real = self.discriminator(inputs.contiguous().detach())
+ logits_fake = self.discriminator(reconstructions.contiguous().detach())
+
+ disc_factor = adopt_weight(
+ self.disc_factor, global_step, threshold=self.discriminator_iter_start
+ )
+
+ d_loss = disc_factor * self.disc_loss(logits_real, logits_fake)
+
+ log = {
+ "{}/disc_loss".format(split): d_loss.clone().detach().mean(),
+ "{}/logits_real".format(split): logits_real.detach().mean(),
+ "{}/logits_fake".format(split): logits_fake.detach().mean(),
+ }
+ return d_loss, log
+
+
+class SimpleLPIPS(nn.Module):
+ def __init__(
+ self,
+ logvar_init=0.0,
+ kl_weight=1.0,
+ pixelloss_weight=1.0,
+ perceptual_weight=1.0,
+ disc_loss="hinge",
+ learn_logvar: bool = False,
+ **kwargs
+ ):
+
+ super().__init__()
+ assert disc_loss in ["hinge", "vanilla"]
+ self.kl_weight = kl_weight
+ self.pixel_weight = pixelloss_weight
+ self.perceptual_loss = LPIPS().eval()
+ self.perceptual_weight = perceptual_weight
+ self.logvar = nn.Parameter(
+ torch.full((), logvar_init), requires_grad=learn_logvar
+ )
+
+ def forward(
+ self,
+ inputs,
+ reconstructions,
+ posteriors,
+ split="train",
+ weights=None,
+ ):
+ inputs = rearrange(inputs, "b c t h w -> (b t) c h w").contiguous()
+ reconstructions = rearrange(
+ reconstructions, "b c t h w -> (b t) c h w"
+ ).contiguous()
+ rec_loss = torch.abs(inputs - reconstructions)
+ if self.perceptual_weight > 0:
+ p_loss = self.perceptual_loss(inputs, reconstructions)
+ rec_loss = rec_loss + self.perceptual_weight * p_loss
+ nll_loss = rec_loss / torch.exp(self.logvar) + self.logvar
+ weighted_nll_loss = nll_loss
+ if weights is not None:
+ weighted_nll_loss = weights * nll_loss
+ weighted_nll_loss = torch.sum(weighted_nll_loss) / weighted_nll_loss.shape[0]
+ nll_loss = torch.sum(nll_loss) / nll_loss.shape[0]
+ kl_loss = posteriors.kl()
+ kl_loss = torch.sum(kl_loss) / kl_loss.shape[0]
+ loss = weighted_nll_loss + self.kl_weight * kl_loss
+ log = {
+ "{}/total_loss".format(split): loss.clone().detach().mean(),
+ "{}/logvar".format(split): self.logvar.detach(),
+ "{}/kl_loss".format(split): kl_loss.detach().mean(),
+ "{}/nll_loss".format(split): nll_loss.detach().mean(),
+ "{}/rec_loss".format(split): rec_loss.detach().mean(),
+ }
+ if self.perceptual_weight > 0:
+ log.update({"{}/p_loss".format(split): p_loss.detach().mean()})
+ return loss, log
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modeling_videobase.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modeling_videobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..26057567571bb7fbca26e0284cdb1a504047fd85
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modeling_videobase.py
@@ -0,0 +1,53 @@
+import torch
+from diffusers import ModelMixin, ConfigMixin
+from torch import nn
+import os
+import json
+import pytorch_lightning as pl
+from diffusers.configuration_utils import ConfigMixin
+from diffusers.models.modeling_utils import ModelMixin
+from typing import Optional, Union
+import glob
+
+
+class VideoBaseAE(ModelMixin, ConfigMixin):
+ config_name = "config.json"
+
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+
+ def encode(self, x: torch.Tensor, *args, **kwargs):
+ pass
+
+ def decode(self, encoding: torch.Tensor, *args, **kwargs):
+ pass
+
+ @property
+ def num_training_steps(self) -> int:
+ """Total training steps inferred from datamodule and devices."""
+ if self.trainer.max_steps:
+ return self.trainer.max_steps
+
+ limit_batches = self.trainer.limit_train_batches
+ batches = len(self.train_dataloader())
+ batches = min(batches, limit_batches) if isinstance(limit_batches, int) else int(limit_batches * batches)
+
+ num_devices = max(1, self.trainer.num_gpus, self.trainer.num_processes)
+ if self.trainer.tpu_cores:
+ num_devices = max(num_devices, self.trainer.tpu_cores)
+
+ effective_accum = self.trainer.accumulate_grad_batches * num_devices
+ return (batches // effective_accum) * self.trainer.max_epochs
+
+ @classmethod
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
+ ckpt_files = glob.glob(os.path.join(pretrained_model_name_or_path, '*.ckpt'))
+ if ckpt_files:
+ # Adapt to checkpoint
+ last_ckpt_file = ckpt_files[-1]
+ config_file = os.path.join(pretrained_model_name_or_path, cls.config_name)
+ model = cls.from_config(config_file)
+ model.init_from_ckpt(last_ckpt_file)
+ return model
+ else:
+ return super().from_pretrained(pretrained_model_name_or_path, **kwargs)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ef41edd27bf3c4b9909a991c11d32d5c84f106e
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/__init__.py
@@ -0,0 +1,6 @@
+from .block import Block
+from .attention import *
+from .conv import *
+from .normalize import *
+from .resnet_block import *
+from .updownsample import *
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/attention.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/attention.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c4c37934fbbf71fe1279d9416528c52e8a04ac
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/attention.py
@@ -0,0 +1,239 @@
+import torch.nn as nn
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+from .normalize import Normalize
+from .conv import CausalConv3d
+import torch
+import numpy as np
+from einops import rearrange
+from .block import Block
+from .ops import video_to_image
+
+class LinearAttention(Block):
+ def __init__(self, dim, heads=4, dim_head=32):
+ super().__init__()
+ self.heads = heads
+ hidden_dim = dim_head * heads
+ self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
+ self.to_out = nn.Conv2d(hidden_dim, dim, 1)
+
+ def forward(self, x):
+ b, c, h, w = x.shape
+ qkv = self.to_qkv(x)
+ q, k, v = rearrange(
+ qkv, "b (qkv heads c) h w -> qkv b heads c (h w)", heads=self.heads, qkv=3
+ )
+ k = k.softmax(dim=-1)
+ context = torch.einsum("bhdn,bhen->bhde", k, v)
+ out = torch.einsum("bhde,bhdn->bhen", context, q)
+ out = rearrange(
+ out, "b heads c (h w) -> b (heads c) h w", heads=self.heads, h=h, w=w
+ )
+ return self.to_out(out)
+
+
+class LinAttnBlock(LinearAttention):
+ """to match AttnBlock usage"""
+
+ def __init__(self, in_channels):
+ super().__init__(dim=in_channels, heads=1, dim_head=in_channels)
+
+
+class AttnBlock3D(Block):
+ """Compatible with old versions, there are issues, use with caution."""
+ def __init__(self, in_channels):
+ super().__init__()
+ self.in_channels = in_channels
+
+ self.norm = Normalize(in_channels)
+ self.q = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.k = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.v = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.proj_out = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+
+ def forward(self, x):
+ h_ = x
+ h_ = self.norm(h_)
+ q = self.q(h_)
+ k = self.k(h_)
+ v = self.v(h_)
+
+ # compute attention
+ b, c, t, h, w = q.shape
+ q = q.reshape(b * t, c, h * w)
+ q = q.permute(0, 2, 1) # b,hw,c
+ k = k.reshape(b * t, c, h * w) # b,c,hw
+ w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
+ w_ = w_ * (int(c) ** (-0.5))
+ w_ = torch.nn.functional.softmax(w_, dim=2)
+
+ # attend to values
+ v = v.reshape(b * t, c, h * w)
+ w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
+ h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
+ h_ = h_.reshape(b, c, t, h, w)
+
+ h_ = self.proj_out(h_)
+
+ return x + h_
+
+class AttnBlock3DFix(nn.Module):
+ """
+ Thanks to https://github.com/PKU-YuanGroup/Open-Sora-Plan/pull/172.
+ """
+ def __init__(self, in_channels):
+ super().__init__()
+ self.in_channels = in_channels
+
+ self.norm = Normalize(in_channels)
+ self.q = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.k = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.v = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+ self.proj_out = CausalConv3d(in_channels, in_channels, kernel_size=1, stride=1)
+
+ def forward(self, x):
+ h_ = x
+ if npu_config is None:
+ h_ = self.norm(h_)
+ else:
+ h_ = npu_config.run_group_norm(self.norm, h_)
+ q = self.q(h_)
+ k = self.k(h_)
+ v = self.v(h_)
+
+ # compute attention
+ # q: (b c t h w) -> (b t c h w) -> (b*t c h*w) -> (b*t h*w c)
+ b, c, t, h, w = q.shape
+ q = q.permute(0, 2, 1, 3, 4)
+ q = q.reshape(b * t, c, h * w)
+ q = q.permute(0, 2, 1)
+
+ # k: (b c t h w) -> (b t c h w) -> (b*t c h*w)
+ k = k.permute(0, 2, 1, 3, 4)
+ k = k.reshape(b * t, c, h * w)
+
+ # w: (b*t hw hw)
+ w_ = torch.bmm(q, k)
+ w_ = w_ * (int(c) ** (-0.5))
+ w_ = torch.nn.functional.softmax(w_, dim=2)
+
+ # attend to values
+ # v: (b c t h w) -> (b t c h w) -> (bt c hw)
+ # w_: (bt hw hw) -> (bt hw hw)
+ v = v.permute(0, 2, 1, 3, 4)
+ v = v.reshape(b * t, c, h * w)
+ w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
+ h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
+
+ # h_: (b*t c hw) -> (b t c h w) -> (b c t h w)
+ h_ = h_.reshape(b, t, c, h, w)
+ h_ = h_.permute(0, 2, 1, 3 ,4)
+
+ h_ = self.proj_out(h_)
+
+ return x + h_
+
+
+class AttnBlock(Block):
+ def __init__(self, in_channels):
+ super().__init__()
+ self.in_channels = in_channels
+
+ self.norm = Normalize(in_channels)
+ self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
+ self.k = torch.nn.Conv2d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+ self.v = torch.nn.Conv2d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+ self.proj_out = torch.nn.Conv2d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+
+ @video_to_image
+ def forward(self, x):
+ h_ = x
+ h_ = self.norm(h_)
+ q = self.q(h_)
+ k = self.k(h_)
+ v = self.v(h_)
+
+ # compute attention
+ b, c, h, w = q.shape
+ q = q.reshape(b, c, h * w)
+ q = q.permute(0, 2, 1) # b,hw,c
+ k = k.reshape(b, c, h * w) # b,c,hw
+ w_ = torch.bmm(q, k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
+ w_ = w_ * (int(c) ** (-0.5))
+ w_ = torch.nn.functional.softmax(w_, dim=2)
+
+ # attend to values
+ v = v.reshape(b, c, h * w)
+ w_ = w_.permute(0, 2, 1) # b,hw,hw (first hw of k, second of q)
+ h_ = torch.bmm(v, w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
+ h_ = h_.reshape(b, c, h, w)
+
+ h_ = self.proj_out(h_)
+
+ return x + h_
+
+
+class TemporalAttnBlock(Block):
+ def __init__(self, in_channels):
+ super().__init__()
+ self.in_channels = in_channels
+
+ self.norm = Normalize(in_channels)
+ self.q = torch.nn.Conv3d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
+ self.k = torch.nn.Conv3d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+ self.v = torch.nn.Conv3d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+ self.proj_out = torch.nn.Conv3d(
+ in_channels, in_channels, kernel_size=1, stride=1, padding=0
+ )
+
+ def forward(self, x):
+ h_ = x
+ h_ = self.norm(h_)
+ q = self.q(h_)
+ k = self.k(h_)
+ v = self.v(h_)
+
+ # compute attention
+ b, c, t, h, w = q.shape
+ q = rearrange(q, "b c t h w -> (b h w) t c")
+ k = rearrange(k, "b c t h w -> (b h w) c t")
+ v = rearrange(v, "b c t h w -> (b h w) c t")
+ w_ = torch.bmm(q, k)
+ w_ = w_ * (int(c) ** (-0.5))
+ w_ = torch.nn.functional.softmax(w_, dim=2)
+
+ # attend to values
+ w_ = w_.permute(0, 2, 1)
+ h_ = torch.bmm(v, w_)
+ h_ = rearrange(h_, "(b h w) c t -> b c t h w", h=h, w=w)
+ h_ = self.proj_out(h_)
+
+ return x + h_
+
+
+def make_attn(in_channels, attn_type="vanilla"):
+ assert attn_type in ["vanilla", "linear", "none", "vanilla3D"], f"attn_type {attn_type} unknown"
+ print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
+ print(attn_type)
+ if attn_type == "vanilla":
+ return AttnBlock(in_channels)
+ elif attn_type == "vanilla3D":
+ return AttnBlock3D(in_channels)
+ elif attn_type == "none":
+ return nn.Identity(in_channels)
+ else:
+ return LinAttnBlock(in_channels)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/block.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/block.py
new file mode 100644
index 0000000000000000000000000000000000000000..e93672d20b22cbaaa36b379473149c55f0f44001
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/block.py
@@ -0,0 +1,5 @@
+import torch.nn as nn
+
+class Block(nn.Module):
+ def __init__(self, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/conv.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/conv.py
new file mode 100644
index 0000000000000000000000000000000000000000..71d6a47057203c85774c0801eeffb3336a6e194c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/conv.py
@@ -0,0 +1,127 @@
+import torch.nn as nn
+from typing import Union, Tuple
+import torch.nn.functional as F
+import torch
+from .block import Block
+from .ops import cast_tuple
+from einops import rearrange
+from .ops import video_to_image
+from torch.utils.checkpoint import checkpoint
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+
+class Conv2d(nn.Conv2d):
+ def __init__(
+ self,
+ in_channels: int,
+ out_channels: int,
+ kernel_size: Union[int, Tuple[int]] = 3,
+ stride: Union[int, Tuple[int]] = 1,
+ padding: Union[str, int, Tuple[int]] = 0,
+ dilation: Union[int, Tuple[int]] = 1,
+ groups: int = 1,
+ bias: bool = True,
+ padding_mode: str = "zeros",
+ device=None,
+ dtype=None,
+ ) -> None:
+ super().__init__(
+ in_channels,
+ out_channels,
+ kernel_size,
+ stride,
+ padding,
+ dilation,
+ groups,
+ bias,
+ padding_mode,
+ device,
+ dtype,
+ )
+
+ @video_to_image
+ def forward(self, x):
+ return super().forward(x)
+
+
+
+class CausalConv3d(nn.Module):
+ def __init__(
+ self, chan_in, chan_out, kernel_size: Union[int, Tuple[int, int, int]], init_method="random", **kwargs
+ ):
+ super().__init__()
+ self.kernel_size = cast_tuple(kernel_size, 3)
+ self.time_kernel_size = self.kernel_size[0]
+ self.chan_in = chan_in
+ self.chan_out = chan_out
+ stride = kwargs.pop("stride", 1)
+ padding = kwargs.pop("padding", 0)
+ padding = list(cast_tuple(padding, 3))
+ padding[0] = 0
+ stride = cast_tuple(stride, 3)
+ self.conv = nn.Conv3d(chan_in, chan_out, self.kernel_size, stride=stride, padding=padding)
+ self.pad = nn.ReplicationPad2d((0, 0, self.time_kernel_size - 1, 0))
+ self._init_weights(init_method)
+
+ def _init_weights(self, init_method):
+ ks = torch.tensor(self.kernel_size)
+ if init_method == "avg":
+ assert (
+ self.kernel_size[1] == 1 and self.kernel_size[2] == 1
+ ), "only support temporal up/down sample"
+ assert self.chan_in == self.chan_out, "chan_in must be equal to chan_out"
+ weight = torch.zeros((self.chan_out, self.chan_in, *self.kernel_size))
+
+ eyes = torch.concat(
+ [
+ torch.eye(self.chan_in).unsqueeze(-1) * 1/3,
+ torch.eye(self.chan_in).unsqueeze(-1) * 1/3,
+ torch.eye(self.chan_in).unsqueeze(-1) * 1/3,
+ ],
+ dim=-1,
+ )
+ weight[:, :, :, 0, 0] = eyes
+
+ self.conv.weight = nn.Parameter(
+ weight,
+ requires_grad=True,
+ )
+ elif init_method == "zero":
+ self.conv.weight = nn.Parameter(
+ torch.zeros((self.chan_out, self.chan_in, *self.kernel_size)),
+ requires_grad=True,
+ )
+ if self.conv.bias is not None:
+ nn.init.constant_(self.conv.bias, 0)
+
+ def forward(self, x):
+ if npu_config is not None and npu_config.on_npu:
+ x_dtype = x.dtype
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.time_kernel_size - 1, 1, 1)
+ ) # b c t h w
+ x = torch.concatenate((first_frame_pad, x), dim=2) # 3 + 16
+ return npu_config.run_conv3d(self.conv, x, x_dtype)
+ else:
+ # 1 + 16 16 as video, 1 as image
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.time_kernel_size - 1, 1, 1)
+ ) # b c t h w
+ x = torch.concatenate((first_frame_pad, x), dim=2) # 3 + 16
+ return self.conv(x)
+
+
+class CausalConv3d_GC(CausalConv3d):
+ def __init__(self, chan_in, chan_out, kernel_size: Union[int, Tuple[int]], init_method="random", **kwargs):
+ super().__init__(chan_in, chan_out, kernel_size, init_method, **kwargs)
+ def forward(self, x):
+ # 1 + 16 16 as video, 1 as image
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.time_kernel_size - 1, 1, 1)
+ ) # b c t h w
+ x = torch.concatenate((first_frame_pad, x), dim=2) # 3 + 16
+ return checkpoint(self.conv, x)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/normalize.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/normalize.py
new file mode 100644
index 0000000000000000000000000000000000000000..7c8c05f0fa3459214dd077e09a157c588adb637b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/normalize.py
@@ -0,0 +1,101 @@
+import torch
+import torch.nn as nn
+from .block import Block
+
+class GroupNorm(Block):
+ def __init__(self, num_channels, num_groups=32, eps=1e-6, *args, **kwargs) -> None:
+ super().__init__(*args, **kwargs)
+ self.norm = torch.nn.GroupNorm(
+ num_groups=num_groups, num_channels=num_channels, eps=1e-6, affine=True
+ )
+ def forward(self, x):
+ return self.norm(x)
+
+def Normalize(in_channels, num_groups=32):
+ return torch.nn.GroupNorm(
+ num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True
+ )
+
+class ActNorm(nn.Module):
+ def __init__(self, num_features, logdet=False, affine=True,
+ allow_reverse_init=False):
+ assert affine
+ super().__init__()
+ self.logdet = logdet
+ self.loc = nn.Parameter(torch.zeros(1, num_features, 1, 1))
+ self.scale = nn.Parameter(torch.ones(1, num_features, 1, 1))
+ self.allow_reverse_init = allow_reverse_init
+
+ self.register_buffer('initialized', torch.tensor(0, dtype=torch.uint8))
+
+ def initialize(self, input):
+ with torch.no_grad():
+ flatten = input.permute(1, 0, 2, 3).contiguous().view(input.shape[1], -1)
+ mean = (
+ flatten.mean(1)
+ .unsqueeze(1)
+ .unsqueeze(2)
+ .unsqueeze(3)
+ .permute(1, 0, 2, 3)
+ )
+ std = (
+ flatten.std(1)
+ .unsqueeze(1)
+ .unsqueeze(2)
+ .unsqueeze(3)
+ .permute(1, 0, 2, 3)
+ )
+
+ self.loc.data.copy_(-mean)
+ self.scale.data.copy_(1 / (std + 1e-6))
+
+ def forward(self, input, reverse=False):
+ if reverse:
+ return self.reverse(input)
+ if len(input.shape) == 2:
+ input = input[:,:,None,None]
+ squeeze = True
+ else:
+ squeeze = False
+
+ _, _, height, width = input.shape
+
+ if self.training and self.initialized.item() == 0:
+ self.initialize(input)
+ self.initialized.fill_(1)
+
+ h = self.scale * (input + self.loc)
+
+ if squeeze:
+ h = h.squeeze(-1).squeeze(-1)
+
+ if self.logdet:
+ log_abs = torch.log(torch.abs(self.scale))
+ logdet = height*width*torch.sum(log_abs)
+ logdet = logdet * torch.ones(input.shape[0]).to(input)
+ return h, logdet
+
+ return h
+
+ def reverse(self, output):
+ if self.training and self.initialized.item() == 0:
+ if not self.allow_reverse_init:
+ raise RuntimeError(
+ "Initializing ActNorm in reverse direction is "
+ "disabled by default. Use allow_reverse_init=True to enable."
+ )
+ else:
+ self.initialize(output)
+ self.initialized.fill_(1)
+
+ if len(output.shape) == 2:
+ output = output[:,:,None,None]
+ squeeze = True
+ else:
+ squeeze = False
+
+ h = output / self.scale - self.loc
+
+ if squeeze:
+ h = h.squeeze(-1).squeeze(-1)
+ return h
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/ops.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/ops.py
new file mode 100644
index 0000000000000000000000000000000000000000..e5987e7402ec7dc258d57d525649b2506b849c0a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/ops.py
@@ -0,0 +1,40 @@
+import torch
+from einops import rearrange
+
+def video_to_image(func):
+ def wrapper(self, x, *args, **kwargs):
+ if x.dim() == 5:
+ t = x.shape[2]
+ x = rearrange(x, "b c t h w -> (b t) c h w")
+ x = func(self, x, *args, **kwargs)
+ x = rearrange(x, "(b t) c h w -> b c t h w", t=t)
+ return x
+ return wrapper
+
+def nonlinearity(x):
+ return x * torch.sigmoid(x)
+
+def cast_tuple(t, length=1):
+ return t if isinstance(t, tuple) or isinstance(t, list) else ((t,) * length)
+
+def shift_dim(x, src_dim=-1, dest_dim=-1, make_contiguous=True):
+ n_dims = len(x.shape)
+ if src_dim < 0:
+ src_dim = n_dims + src_dim
+ if dest_dim < 0:
+ dest_dim = n_dims + dest_dim
+ assert 0 <= src_dim < n_dims and 0 <= dest_dim < n_dims
+ dims = list(range(n_dims))
+ del dims[src_dim]
+ permutation = []
+ ctr = 0
+ for i in range(n_dims):
+ if i == dest_dim:
+ permutation.append(src_dim)
+ else:
+ permutation.append(dims[ctr])
+ ctr += 1
+ x = x.permute(permutation)
+ if make_contiguous:
+ x = x.contiguous()
+ return x
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/quant.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/quant.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb702cee5f594e73be3efe9f573f1fbb8032e70c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/quant.py
@@ -0,0 +1,100 @@
+import torch
+import torch.nn as nn
+import torch.distributed as dist
+import numpy as np
+import torch.nn.functional as F
+from .ops import shift_dim
+
+class Codebook(nn.Module):
+ def __init__(self, n_codes, embedding_dim):
+ super().__init__()
+ self.register_buffer("embeddings", torch.randn(n_codes, embedding_dim))
+ self.register_buffer("N", torch.zeros(n_codes))
+ self.register_buffer("z_avg", self.embeddings.data.clone())
+
+ self.n_codes = n_codes
+ self.embedding_dim = embedding_dim
+ self._need_init = True
+
+ def _tile(self, x):
+ d, ew = x.shape
+ if d < self.n_codes:
+ n_repeats = (self.n_codes + d - 1) // d
+ std = 0.01 / np.sqrt(ew)
+ x = x.repeat(n_repeats, 1)
+ x = x + torch.randn_like(x) * std
+ return x
+
+ def _init_embeddings(self, z):
+ # z: [b, c, t, h, w]
+ self._need_init = False
+ flat_inputs = shift_dim(z, 1, -1).flatten(end_dim=-2)
+ y = self._tile(flat_inputs)
+
+ d = y.shape[0]
+ _k_rand = y[torch.randperm(y.shape[0])][: self.n_codes]
+ if dist.is_initialized():
+ dist.broadcast(_k_rand, 0)
+ self.embeddings.data.copy_(_k_rand)
+ self.z_avg.data.copy_(_k_rand)
+ self.N.data.copy_(torch.ones(self.n_codes))
+
+ def forward(self, z):
+ # z: [b, c, t, h, w]
+ if self._need_init and self.training:
+ self._init_embeddings(z)
+ flat_inputs = shift_dim(z, 1, -1).flatten(end_dim=-2)
+ distances = (
+ (flat_inputs**2).sum(dim=1, keepdim=True)
+ - 2 * flat_inputs @ self.embeddings.t()
+ + (self.embeddings.t() ** 2).sum(dim=0, keepdim=True)
+ )
+
+ encoding_indices = torch.argmin(distances, dim=1)
+ encode_onehot = F.one_hot(encoding_indices, self.n_codes).type_as(flat_inputs)
+ encoding_indices = encoding_indices.view(z.shape[0], *z.shape[2:])
+
+ embeddings = F.embedding(encoding_indices, self.embeddings)
+ embeddings = shift_dim(embeddings, -1, 1)
+
+ commitment_loss = 0.25 * F.mse_loss(z, embeddings.detach())
+
+ # EMA codebook update
+ if self.training:
+ n_total = encode_onehot.sum(dim=0)
+ encode_sum = flat_inputs.t() @ encode_onehot
+ if dist.is_initialized():
+ dist.all_reduce(n_total)
+ dist.all_reduce(encode_sum)
+
+ self.N.data.mul_(0.99).add_(n_total, alpha=0.01)
+ self.z_avg.data.mul_(0.99).add_(encode_sum.t(), alpha=0.01)
+
+ n = self.N.sum()
+ weights = (self.N + 1e-7) / (n + self.n_codes * 1e-7) * n
+ encode_normalized = self.z_avg / weights.unsqueeze(1)
+ self.embeddings.data.copy_(encode_normalized)
+
+ y = self._tile(flat_inputs)
+ _k_rand = y[torch.randperm(y.shape[0])][: self.n_codes]
+ if dist.is_initialized():
+ dist.broadcast(_k_rand, 0)
+
+ usage = (self.N.view(self.n_codes, 1) >= 1).float()
+ self.embeddings.data.mul_(usage).add_(_k_rand * (1 - usage))
+
+ embeddings_st = (embeddings - z).detach() + z
+
+ avg_probs = torch.mean(encode_onehot, dim=0)
+ perplexity = torch.exp(-torch.sum(avg_probs * torch.log(avg_probs + 1e-10)))
+
+ return dict(
+ embeddings=embeddings_st,
+ encodings=encoding_indices,
+ commitment_loss=commitment_loss,
+ perplexity=perplexity,
+ )
+
+ def dictionary_lookup(self, encodings):
+ embeddings = F.embedding(encodings, self.embeddings)
+ return embeddings
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/resnet_block.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/resnet_block.py
new file mode 100644
index 0000000000000000000000000000000000000000..ce70334f1602ffcaa6f59a5f552c9d574306cf42
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/resnet_block.py
@@ -0,0 +1,137 @@
+import torch
+import torch.nn as nn
+from einops import rearrange, pack, unpack
+from .normalize import Normalize
+from .ops import nonlinearity, video_to_image
+from .conv import CausalConv3d, CausalConv3d_GC
+from .block import Block
+from torch.utils.checkpoint import checkpoint
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+
+class ResnetBlock2D(Block):
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
+ dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.use_conv_shortcut = conv_shortcut
+
+ self.norm1 = Normalize(in_channels)
+ self.conv1 = torch.nn.Conv2d(
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+ self.norm2 = Normalize(out_channels)
+ self.dropout = torch.nn.Dropout(dropout)
+ self.conv2 = torch.nn.Conv2d(
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ self.conv_shortcut = torch.nn.Conv2d(
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
+ )
+ else:
+ self.nin_shortcut = torch.nn.Conv2d(
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
+ )
+
+ @video_to_image
+ def forward(self, x):
+ h = x
+ h = self.norm1(h)
+ h = nonlinearity(h)
+ h = self.conv1(h)
+ h = self.norm2(h)
+ h = nonlinearity(h)
+ h = self.dropout(h)
+ h = self.conv2(h)
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ x = self.conv_shortcut(x)
+ else:
+ x = self.nin_shortcut(x)
+ x = x + h
+ return x
+
+class ResnetBlock3D(Block):
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.use_conv_shortcut = conv_shortcut
+
+ self.norm1 = Normalize(in_channels)
+ self.conv1 = CausalConv3d(in_channels, out_channels, 3, padding=1)
+ self.norm2 = Normalize(out_channels)
+ self.dropout = torch.nn.Dropout(dropout)
+ self.conv2 = CausalConv3d(out_channels, out_channels, 3, padding=1)
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ self.conv_shortcut = CausalConv3d(in_channels, out_channels, 3, padding=1)
+ else:
+ self.nin_shortcut = CausalConv3d(in_channels, out_channels, 1, padding=0)
+
+ def forward(self, x):
+ h = x
+ if npu_config is None:
+ h = self.norm1(h)
+ else:
+ h = npu_config.run_group_norm(self.norm1, h)
+ h = nonlinearity(h)
+ h = self.conv1(h)
+ if npu_config is None:
+ h = self.norm2(h)
+ else:
+ h = npu_config.run_group_norm(self.norm2, h)
+ h = nonlinearity(h)
+ h = self.dropout(h)
+ h = self.conv2(h)
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ x = self.conv_shortcut(x)
+ else:
+ x = self.nin_shortcut(x)
+ return x + h
+
+
+class ResnetBlock3D_GC(Block):
+ def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, dropout):
+ super().__init__()
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.use_conv_shortcut = conv_shortcut
+
+ self.norm1 = Normalize(in_channels)
+ self.conv1 = CausalConv3d(in_channels, out_channels, 3, padding=1)
+ self.norm2 = Normalize(out_channels)
+ self.dropout = torch.nn.Dropout(dropout)
+ self.conv2 = CausalConv3d(out_channels, out_channels, 3, padding=1)
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ self.conv_shortcut = CausalConv3d(in_channels, out_channels, 3, padding=1)
+ else:
+ self.nin_shortcut = CausalConv3d(in_channels, out_channels, 1, padding=0)
+
+ def forward(self, x):
+ return checkpoint(self._forward, x, use_reentrant=True)
+
+ def _forward(self, x):
+ h = x
+ h = self.norm1(h)
+ h = nonlinearity(h)
+ h = self.conv1(h)
+ h = self.norm2(h)
+ h = nonlinearity(h)
+ h = self.dropout(h)
+ h = self.conv2(h)
+ if self.in_channels != self.out_channels:
+ if self.use_conv_shortcut:
+ x = self.conv_shortcut(x)
+ else:
+ x = self.nin_shortcut(x)
+ return x + h
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/updownsample.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/updownsample.py
new file mode 100644
index 0000000000000000000000000000000000000000..86a48cc38123c84ea625c2917a21e53ccc9c148c
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/modules/updownsample.py
@@ -0,0 +1,385 @@
+from typing import Union, Tuple
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+from .resnet_block import ResnetBlock3D
+from .attention import TemporalAttnBlock
+from .normalize import Normalize
+from .ops import cast_tuple, video_to_image
+from .conv import CausalConv3d, CausalConv3d_GC
+from einops import rearrange
+from .block import Block
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+
+
+class Upsample(Block):
+ def __init__(self, in_channels, out_channels):
+ super().__init__()
+ self.with_conv = True
+ if self.with_conv:
+ self.conv = torch.nn.Conv2d(in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1)
+
+ @video_to_image
+ def forward(self, x):
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
+ if self.with_conv:
+ x = self.conv(x)
+ return x
+
+class Downsample(Block):
+ def __init__(self, in_channels, out_channels, undown=False):
+ super().__init__()
+ self.with_conv = True
+ self.undown = undown
+ if self.with_conv:
+ # no asymmetric padding in torch conv, must do it ourselves
+ if self.undown:
+ self.conv = torch.nn.Conv2d(in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=1,
+ padding=1)
+ else:
+ self.conv = torch.nn.Conv2d(in_channels,
+ out_channels,
+ kernel_size=3,
+ stride=2,
+ padding=0)
+ @video_to_image
+ def forward(self, x):
+ if self.with_conv:
+ if self.undown:
+ if npu_config is not None and npu_config.on_npu:
+ x_dtype = x.dtype
+ x = x.to(npu_config.replaced_type)
+ x = npu_config.run_conv3d(self.conv, x, x_dtype)
+ else:
+ x = self.conv(x)
+ else:
+ pad = (0, 1, 0, 1)
+ if npu_config is not None and npu_config.on_npu:
+ x_dtype = x.dtype
+ x = x.to(npu_config.replaced_type)
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
+ x = npu_config.run_conv3d(self.conv, x, x_dtype)
+ else:
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
+ x = self.conv(x)
+ else:
+ x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
+ return x
+
+class SpatialDownsample2x(Block):
+ def __init__(
+ self,
+ chan_in,
+ chan_out,
+ kernel_size: Union[int, Tuple[int]] = (3, 3),
+ stride: Union[int, Tuple[int]] = (2, 2),
+ **kwargs
+ ):
+ super().__init__()
+ kernel_size = cast_tuple(kernel_size, 2)
+ stride = cast_tuple(stride, 2)
+ self.chan_in = chan_in
+ self.chan_out = chan_out
+ self.kernel_size = kernel_size
+ self.conv = CausalConv3d(
+ self.chan_in,
+ self.chan_out,
+ (1,) + self.kernel_size,
+ stride=(1, ) + stride,
+ padding=0
+ )
+
+ def forward(self, x):
+ pad = (0,1,0,1,0,0)
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
+ x = self.conv(x)
+ return x
+
+class SpatialUpsample2x_GC(Block):
+ def __init__(
+ self,
+ chan_in,
+ chan_out,
+ kernel_size: Union[int, Tuple[int]] = (3, 3),
+ stride: Union[int, Tuple[int]] = (1, 1),
+ unup=False,
+ ):
+ super().__init__()
+ self.chan_in = chan_in
+ self.chan_out = chan_out
+ self.kernel_size = kernel_size
+ self.unup = unup
+ self.conv = CausalConv3d_GC(
+ self.chan_in,
+ self.chan_out,
+ (1,) + self.kernel_size,
+ stride=(1, ) + stride,
+ padding=1
+ )
+
+ def forward(self, x):
+ if not self.unup:
+ t = x.shape[2]
+ x = rearrange(x, "b c t h w -> b (c t) h w")
+ x = F.interpolate(x, scale_factor=(2,2), mode="nearest")
+ x = rearrange(x, "b (c t) h w -> b c t h w", t=t)
+ x = self.conv(x)
+ return x
+
+
+class SpatialUpsample2x(Block):
+ def __init__(
+ self,
+ chan_in,
+ chan_out,
+ kernel_size: Union[int, Tuple[int]] = (3, 3),
+ stride: Union[int, Tuple[int]] = (1, 1),
+ unup=False,
+ ):
+ super().__init__()
+ self.chan_in = chan_in
+ self.chan_out = chan_out
+ self.kernel_size = kernel_size
+ self.unup = unup
+ self.conv = CausalConv3d(
+ self.chan_in,
+ self.chan_out,
+ (1,) + self.kernel_size,
+ stride=(1, ) + stride,
+ padding=1
+ )
+
+ def forward(self, x):
+ if not self.unup:
+ t = x.shape[2]
+ x = rearrange(x, "b c t h w -> b (c t) h w")
+ x = F.interpolate(x, scale_factor=(2,2), mode="nearest")
+ x = rearrange(x, "b (c t) h w -> b c t h w", t=t)
+ x = self.conv(x)
+ return x
+
+class TimeDownsample2x(Block):
+ def __init__(
+ self,
+ chan_in,
+ chan_out,
+ kernel_size: int = 3
+ ):
+ super().__init__()
+ self.kernel_size = kernel_size
+ if npu_config is not None and npu_config.on_npu:
+ self.avg_pool = nn.AvgPool2d((kernel_size, 1), stride=(2, 1))
+ self.pad = nn.ReplicationPad3d((0, 0, 0, 0, self.kernel_size - 1, 0))
+ else:
+ self.conv = nn.AvgPool3d((kernel_size, 1, 1), stride=(2, 1, 1))
+
+ def forward(self, x):
+ if npu_config is not None and npu_config.on_npu:
+ n, c, d, h, w = x.shape
+ x = self.pad(x)
+ x = x.view(n * c, -1, h * w)
+ pooled = self.avg_pool(x)
+ output = pooled.view(n, c, -1, h, w)
+ return output
+ else:
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.kernel_size - 1, 1, 1)
+ )
+ x = torch.concatenate((first_frame_pad, x), dim=2)
+ return self.conv(x)
+
+class TimeUpsample2x(Block):
+ def __init__(
+ self,
+ chan_in,
+ chan_out
+ ):
+ super().__init__()
+ def forward(self, x):
+ if x.size(2) > 1:
+ x,x_= x[:,:,:1],x[:,:,1:]
+ x_= F.interpolate(x_, scale_factor=(2,1,1), mode='trilinear')
+ x = torch.concat([x, x_], dim=2)
+ return x
+
+class TimeDownsampleRes2x(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size: int = 3,
+ mix_factor: float = 2.0,
+ ):
+ super().__init__()
+ self.kernel_size = cast_tuple(kernel_size, 3)
+ if npu_config is not None and npu_config.on_npu:
+ self.avg_pool = nn.AvgPool2d((kernel_size, 1), stride=(2, 1))
+ self.pad = nn.ReplicationPad3d((0, 0, 0, 0, kernel_size - 1, 0))
+ else:
+ self.avg_pool = nn.AvgPool3d((kernel_size, 1, 1), stride=(2, 1, 1))
+ self.conv = nn.Conv3d(
+ in_channels, out_channels, self.kernel_size, stride=(2,1,1), padding=(0,1,1)
+ )
+ self.mix_factor = torch.nn.Parameter(torch.Tensor([mix_factor]))
+
+ def forward(self, x):
+ alpha = torch.sigmoid(self.mix_factor)
+ if npu_config is not None and npu_config.on_npu:
+ n, c, d, h, w = x.shape
+ x_dtype = x.dtype
+ x = x.to(npu_config.replaced_type)
+ x = self.pad(x)
+ pad_x = x.view(n, c, -1, h, w)
+ avg_x = self.avg_pool(x.view(n * c, -1, h * w)).view(n, c, -1, h, w).to(x_dtype)
+ conv_x = npu_config.run_conv3d(self.conv, pad_x, x_dtype)
+ return alpha * avg_x + (1 - alpha) * conv_x
+ else:
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.kernel_size[0] - 1, 1, 1)
+ )
+ x = torch.concatenate((first_frame_pad, x), dim=2)
+ return alpha * self.avg_pool(x) + (1 - alpha) * self.conv(x)
+
+class TimeUpsampleRes2x(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size: int = 3,
+ mix_factor: float = 2.0,
+ ):
+ super().__init__()
+ self.conv = CausalConv3d(
+ in_channels, out_channels, kernel_size, padding=1
+ )
+ self.mix_factor = torch.nn.Parameter(torch.Tensor([mix_factor]))
+
+ def forward(self, x):
+ alpha = torch.sigmoid(self.mix_factor)
+ if x.size(2) > 1:
+ x,x_= x[:,:,:1],x[:,:,1:]
+ if npu_config is not None and npu_config.on_npu:
+ x_dtype = x_.dtype
+ x_ = x_.to(npu_config.replaced_type)
+ x_ = F.interpolate(x_, scale_factor=(2, 1, 1), mode='trilinear')
+ x_ = x_.to(x_dtype)
+ else:
+ x_= F.interpolate(x_, scale_factor=(2,1,1), mode='trilinear')
+ x = torch.concat([x, x_], dim=2)
+ return alpha * x + (1-alpha) * self.conv(x)
+
+class TimeDownsampleResAdv2x(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size: int = 3,
+ mix_factor: float = 1.5,
+ ):
+ super().__init__()
+ self.kernel_size = cast_tuple(kernel_size, 3)
+ self.avg_pool = nn.AvgPool3d((kernel_size,1,1), stride=(2,1,1))
+ self.attn = TemporalAttnBlock(in_channels)
+ self.res = ResnetBlock3D(in_channels=in_channels, out_channels=in_channels, dropout=0.0)
+ self.conv = nn.Conv3d(
+ in_channels, out_channels, self.kernel_size, stride=(2,1,1), padding=(0,1,1)
+ )
+ self.mix_factor = torch.nn.Parameter(torch.Tensor([mix_factor]))
+
+ def forward(self, x):
+ first_frame_pad = x[:, :, :1, :, :].repeat(
+ (1, 1, self.kernel_size[0] - 1, 1, 1)
+ )
+ x = torch.concatenate((first_frame_pad, x), dim=2)
+ alpha = torch.sigmoid(self.mix_factor)
+ return alpha * self.avg_pool(x) + (1 - alpha) * self.conv(self.attn((self.res(x))))
+
+class TimeUpsampleResAdv2x(nn.Module):
+ def __init__(
+ self,
+ in_channels,
+ out_channels,
+ kernel_size: int = 3,
+ mix_factor: float = 1.5,
+ ):
+ super().__init__()
+ self.res = ResnetBlock3D(in_channels=in_channels, out_channels=in_channels, dropout=0.0)
+ self.attn = TemporalAttnBlock(in_channels)
+ self.norm = Normalize(in_channels=in_channels)
+ self.conv = CausalConv3d(
+ in_channels, out_channels, kernel_size, padding=1
+ )
+ self.mix_factor = torch.nn.Parameter(torch.Tensor([mix_factor]))
+
+ def forward(self, x):
+ if x.size(2) > 1:
+ x,x_= x[:,:,:1],x[:,:,1:]
+ if npu_config is not None and npu_config.on_npu:
+ x_dtype = x_.dtype
+ x_ = x_.to(npu_config.replaced_type)
+ x_= F.interpolate(x_, scale_factor=(2,1,1), mode='trilinear')
+ x_ = x_.to(x_dtype)
+ else:
+ x_= F.interpolate(x_, scale_factor=(2,1,1), mode='trilinear')
+ x = torch.concat([x, x_], dim=2)
+ alpha = torch.sigmoid(self.mix_factor)
+ return alpha * x + (1 - alpha) * self.conv(self.attn(self.res(x)))
+
+
+class Spatial2xTime2x3DDownsample(Block):
+ def __init__(self, in_channels, out_channels):
+ super().__init__()
+ self.conv = CausalConv3d(in_channels, out_channels, kernel_size=3, padding=0, stride=2)
+
+ def forward(self, x):
+ pad = (0,1,0,1,0,0)
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
+ x = self.conv(x)
+ return x
+
+class Spatial2x3DDownsample(Block):
+ def __init__(self, in_channels, out_channels):
+ super().__init__()
+ self.conv = CausalConv3d(in_channels, out_channels, kernel_size=3, padding=0, stride=(1,2,2))
+
+ def forward(self, x):
+ pad = (0,1,0,1,0,0)
+ x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
+ x = self.conv(x)
+ return x
+
+
+class Spatial2x3DUpsample(Block):
+ def __init__(self, in_channels, out_channels):
+ super().__init__()
+ self.conv = CausalConv3d(in_channels, out_channels, kernel_size=3, padding=1)
+
+ def forward(self, x):
+ x = F.interpolate(x, scale_factor=(1,2,2), mode='trilinear')
+ return self.conv(x)
+
+class Spatial2xTime2x3DUpsample(Block):
+ def __init__(self, in_channels, out_channels):
+ super().__init__()
+ self.conv = CausalConv3d(in_channels, out_channels, kernel_size=3, padding=1)
+ def forward(self, x):
+ if x.size(2) > 1:
+ x,x_= x[:,:,:1],x[:,:,1:]
+ x_= F.interpolate(x_, scale_factor=(2,2,2), mode='trilinear')
+ x = F.interpolate(x, scale_factor=(1,2,2), mode='trilinear')
+ x = torch.concat([x, x_], dim=2)
+ else:
+ x = F.interpolate(x, scale_factor=(1,2,2), mode='trilinear')
+ return self.conv(x)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/trainer_videobase.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/trainer_videobase.py
new file mode 100644
index 0000000000000000000000000000000000000000..b6c4b0c7d2a2fdec0488cfeedbfa9844416e4053
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/trainer_videobase.py
@@ -0,0 +1,26 @@
+from transformers import Trainer
+import torch.nn.functional as F
+from typing import Optional
+import os
+import torch
+from transformers.utils import WEIGHTS_NAME
+import json
+
+class VideoBaseTrainer(Trainer):
+
+ def _save(self, output_dir: Optional[str] = None, state_dict=None):
+ output_dir = output_dir if output_dir is not None else self.args.output_dir
+ os.makedirs(output_dir, exist_ok=True)
+ if state_dict is None:
+ state_dict = self.model.state_dict()
+
+ # get model config
+ model_config = self.model.config.to_dict()
+
+ # add more information
+ model_config['model'] = self.model.__class__.__name__
+
+ with open(os.path.join(output_dir, "config.json"), "w") as file:
+ json.dump(self.model.config.to_dict(), file)
+ torch.save(state_dict, os.path.join(output_dir, WEIGHTS_NAME))
+ torch.save(self.args, os.path.join(output_dir, "training_args.bin"))
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/distrib_utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/distrib_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..760c0673fe5d8afa663eb1ea5cd7683dbf5dd9f8
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/distrib_utils.py
@@ -0,0 +1,42 @@
+import torch
+import numpy as np
+
+class DiagonalGaussianDistribution(object):
+ def __init__(self, parameters, deterministic=False):
+ self.parameters = parameters
+ self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
+ self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
+ self.deterministic = deterministic
+ self.std = torch.exp(0.5 * self.logvar)
+ self.var = torch.exp(self.logvar)
+ if self.deterministic:
+ self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
+
+ def sample(self):
+ x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
+ return x
+
+ def kl(self, other=None):
+ if self.deterministic:
+ return torch.Tensor([0.])
+ else:
+ if other is None:
+ return 0.5 * torch.sum(torch.pow(self.mean, 2)
+ + self.var - 1.0 - self.logvar,
+ dim=[1, 2, 3])
+ else:
+ return 0.5 * torch.sum(
+ torch.pow(self.mean - other.mean, 2) / other.var
+ + self.var / other.var - 1.0 - self.logvar + other.logvar,
+ dim=[1, 2, 3])
+
+ def nll(self, sample, dims=[1,2,3]):
+ if self.deterministic:
+ return torch.Tensor([0.])
+ logtwopi = np.log(2.0 * np.pi)
+ return 0.5 * torch.sum(
+ logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
+ dim=dims)
+
+ def mode(self):
+ return self.mean
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/module_utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/module_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f843e4f3d141cf1226944456213bc7960aa4fc4
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/module_utils.py
@@ -0,0 +1,17 @@
+import importlib
+
+Module = str
+MODULES_BASE = "opensora.models.causalvideovae.model.modules."
+
+def resolve_str_to_obj(str_val, append=True):
+ if append:
+ str_val = MODULES_BASE + str_val
+ module_name, class_name = str_val.rsplit('.', 1)
+ module = importlib.import_module(module_name)
+ return getattr(module, class_name)
+
+def create_instance(module_class_str: str, **kwargs):
+ module_name, class_name = module_class_str.rsplit('.', 1)
+ module = importlib.import_module(module_name)
+ class_ = getattr(module, class_name)
+ return class_(**kwargs)
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/scheduler_utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/scheduler_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..0650a3f79c3bc4f1bd5bf4a556995dc538b2b23a
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/scheduler_utils.py
@@ -0,0 +1,7 @@
+import torch
+
+def cosine_scheduler(step, max_steps, value_base=1, value_end=0):
+ step = torch.tensor(step)
+ cosine_value = 0.5 * (1 + torch.cos(torch.pi * step / max_steps))
+ value = value_end + (value_base - value_end) * cosine_value
+ return value
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/video_utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/video_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fbd3f04c5e35dd0953e4c1e15bad92c769a9735
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/model/utils/video_utils.py
@@ -0,0 +1,10 @@
+import torch
+import numpy as np
+
+def tensor_to_video(x):
+ x = (x * 2 - 1).detach().cpu()
+ x = torch.clamp(x, -1, 1)
+ x = (x + 1) / 2
+ x = x.permute(1, 0, 2, 3).float().numpy() # c t h w -> t c h w
+ x = (255 * x).astype(np.uint8)
+ return x
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/sample/rec_video_vae.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/sample/rec_video_vae.py
new file mode 100644
index 0000000000000000000000000000000000000000..73341e22d6df6932291fc057d0f1ebdaaf8e1674
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/sample/rec_video_vae.py
@@ -0,0 +1,277 @@
+import random
+import argparse
+import cv2
+from tqdm import tqdm
+import numpy as np
+import numpy.typing as npt
+import torch
+from decord import VideoReader, cpu
+from torch.nn import functional as F
+from pytorchvideo.transforms import ShortSideScale
+from torchvision.transforms import Lambda, Compose
+from torchvision.transforms._transforms_video import CenterCropVideo
+import sys
+from torch.utils.data import Dataset, DataLoader, Subset
+import os
+import glob
+sys.path.append(".")
+from opensora.models.causalvideovae.model import CausalVAEModel
+import torch.nn as nn
+
+
+def array_to_video(
+ image_array: npt.NDArray, fps: float = 30.0, output_file: str = "output_video.mp4"
+) -> None:
+ height, width, channels = image_array[0].shape
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
+ video_writer = cv2.VideoWriter(output_file, fourcc, float(fps), (width, height))
+
+ for image in image_array:
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
+ video_writer.write(image_rgb)
+
+ video_writer.release()
+
+
+def custom_to_video(
+ x: torch.Tensor, fps: float = 2.0, output_file: str = "output_video.mp4"
+) -> None:
+ x = x.detach().cpu()
+ x = torch.clamp(x, -1, 1)
+ x = (x + 1) / 2
+ x = x.permute(1, 2, 3, 0).float().numpy()
+ x = (255 * x).astype(np.uint8)
+ array_to_video(x, fps=fps, output_file=output_file)
+ return
+
+
+def read_video(video_path: str, num_frames: int, sample_rate: int) -> torch.Tensor:
+ decord_vr = VideoReader(video_path, ctx=cpu(0), num_threads=8)
+ total_frames = len(decord_vr)
+ sample_frames_len = sample_rate * num_frames
+
+ if total_frames > sample_frames_len:
+ s = 0
+ e = s + sample_frames_len
+ num_frames = num_frames
+ else:
+ s = 0
+ e = total_frames
+ num_frames = int(total_frames / sample_frames_len * num_frames)
+ print(
+ f"sample_frames_len {sample_frames_len}, only can sample {num_frames * sample_rate}",
+ video_path,
+ total_frames,
+ )
+
+ frame_id_list = np.linspace(s, e - 1, num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(3, 0, 1, 2) # (T, H, W, C) -> (C, T, H, W)
+ return video_data
+
+
+class RealVideoDataset(Dataset):
+ video_exts = ['avi', 'mp4', 'webm']
+
+ def __init__(
+ self,
+ real_video_dir,
+ num_frames,
+ sample_rate=1,
+ crop_size=None,
+ resolution=128,
+ ) -> None:
+ super().__init__()
+ self.real_video_files = self._combine_without_prefix(real_video_dir)
+ self.num_frames = num_frames
+ self.sample_rate = sample_rate
+ self.crop_size = crop_size
+ self.short_size = resolution
+
+ def __len__(self):
+ return len(self.real_video_files)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_video_file = self.real_video_files[index]
+ real_video_tensor = self._load_video(real_video_file)
+ video_name = os.path.basename(real_video_file)
+ return {'video': real_video_tensor, 'file_name': video_name }
+
+ def _load_video(self, video_path):
+ num_frames = self.num_frames
+ sample_rate = self.sample_rate
+ decord_vr = VideoReader(video_path, ctx=cpu(0))
+ total_frames = len(decord_vr)
+ sample_frames_len = sample_rate * num_frames
+
+ if total_frames > sample_frames_len:
+ s = 0
+ e = s + sample_frames_len
+ num_frames = num_frames
+ else:
+ s = 0
+ e = total_frames
+ num_frames = int(total_frames / sample_frames_len * num_frames)
+ print(
+ f"sample_frames_len {sample_frames_len}, only can sample {num_frames * sample_rate}",
+ video_path,
+ total_frames,
+ )
+
+ frame_id_list = np.linspace(s, e - 1, num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(3, 0, 1, 2)
+ return _preprocess(
+ video_data, short_size=self.short_size, crop_size=self.crop_size
+ )
+
+ def _combine_without_prefix(self, folder_path):
+ samples = []
+ samples += sum([glob.glob(os.path.join(folder_path, '**', f'*.{ext}'), recursive=True)
+ for ext in self.video_exts], [])
+ samples.sort()
+ return samples
+
+def resize(x, resolution):
+ height, width = x.shape[-2:]
+ aspect_ratio = width / height
+ if width <= height:
+ new_width = resolution
+ new_height = int(resolution / aspect_ratio)
+ else:
+ new_height = resolution
+ new_width = int(resolution * aspect_ratio)
+ resized_x = F.interpolate(x, size=(new_height, new_width), mode='bilinear', align_corners=True, antialias=True)
+ return resized_x
+
+def _preprocess(video_data, short_size=128, crop_size=None):
+ transform = Compose(
+ [
+ Lambda(lambda x: ((x / 255.0) * 2 - 1)),
+ Lambda(lambda x: resize(x, short_size)),
+ (
+ CenterCropVideo(crop_size=crop_size)
+ if crop_size is not None
+ else Lambda(lambda x: x)
+ ),
+ ]
+ )
+ video_outputs = transform(video_data)
+ video_outputs = _format_video_shape(video_outputs)
+ return video_outputs
+
+
+def _format_video_shape(video, time_compress=4, spatial_compress=8):
+ time = video.shape[1]
+ height = video.shape[2]
+ width = video.shape[3]
+ new_time = (
+ (time - (time - 1) % time_compress)
+ if (time - 1) % time_compress != 0
+ else time
+ )
+ new_height = (
+ (height - (height) % spatial_compress)
+ if height % spatial_compress != 0
+ else height
+ )
+ new_width = (
+ (width - (width) % spatial_compress) if width % spatial_compress != 0 else width
+ )
+ return video[:, :new_time, :new_height, :new_width]
+
+
+@torch.no_grad()
+def main(args: argparse.Namespace):
+ real_video_dir = args.real_video_dir
+ generated_video_dir = args.generated_video_dir
+ ckpt = args.ckpt
+ sample_rate = args.sample_rate
+ resolution = args.resolution
+ crop_size = args.crop_size
+ num_frames = args.num_frames
+ sample_rate = args.sample_rate
+ device = args.device
+ sample_fps = args.sample_fps
+ batch_size = args.batch_size
+ num_workers = args.num_workers
+ subset_size = args.subset_size
+
+ if not os.path.exists(args.generated_video_dir):
+ os.makedirs(args.generated_video_dir, exist_ok=True)
+
+ data_type = torch.bfloat16
+
+ # ---- Load Model ----
+ device = args.device
+ vqvae = CausalVAEModel.from_pretrained(args.ckpt)
+ print(vqvae)
+ vqvae = vqvae.to(device).to(data_type)
+ if args.enable_tiling:
+ vqvae.enable_tiling()
+ vqvae.tile_overlap_factor = args.tile_overlap_factor
+ # ---- Load Model ----
+
+ # ---- Prepare Dataset ----
+ dataset = RealVideoDataset( #先resize到resolution,然后crop一个crop_size的patch
+ real_video_dir=real_video_dir,
+ num_frames=num_frames,
+ sample_rate=sample_rate,
+ crop_size=crop_size,
+ resolution=resolution,
+ )
+
+ if subset_size:
+ indices = range(subset_size)
+ dataset = Subset(dataset, indices=indices)
+
+ dataloader = DataLoader(
+ dataset, batch_size=batch_size, pin_memory=True, num_workers=num_workers
+ )
+ # ---- Prepare Dataset
+
+ # ---- Inference ----
+ for batch in tqdm(dataloader):
+ x, file_names = batch['video'], batch['file_name']
+
+ x = x.to(device=device, dtype=data_type) # b c t h w
+ latents = vqvae.encode(x).sample().to(data_type)
+ video_recon = vqvae.decode(latents)
+ for idx, video in enumerate(video_recon):
+ output_path = os.path.join(generated_video_dir, file_names[idx])
+ if args.output_origin:
+ os.makedirs(os.path.join(generated_video_dir, "origin/"), exist_ok=True)
+ origin_output_path = os.path.join(generated_video_dir, "origin/", file_names[idx])
+ custom_to_video(
+ x[idx], fps=sample_fps / sample_rate, output_file=origin_output_path
+ )
+ custom_to_video(
+ video, fps=sample_fps / sample_rate, output_file=output_path
+ )
+ # ---- Inference ----
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--real_video_dir", type=str, default="")
+ parser.add_argument("--generated_video_dir", type=str, default="")
+ parser.add_argument("--ckpt", type=str, default="")
+ parser.add_argument("--sample_fps", type=int, default=30)
+ parser.add_argument("--resolution", type=int, default=336)
+ parser.add_argument("--crop_size", type=int, default=None)
+ parser.add_argument("--num_frames", type=int, default=17)
+ parser.add_argument("--sample_rate", type=int, default=1)
+ parser.add_argument("--batch_size", type=int, default=1)
+ parser.add_argument("--num_workers", type=int, default=8)
+ parser.add_argument("--subset_size", type=int, default=None)
+ parser.add_argument("--tile_overlap_factor", type=float, default=0.25)
+ parser.add_argument('--enable_tiling', action='store_true')
+ parser.add_argument('--output_origin', action='store_true')
+ parser.add_argument("--device", type=str, default="cuda")
+
+ args = parser.parse_args()
+ main(args)
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/__init__.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/dataset_utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/dataset_utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..1309989b1b05932a2d13b31389fd3c24aa12159b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/dataset_utils.py
@@ -0,0 +1,160 @@
+import math
+from einops import rearrange
+import decord
+from torch.nn import functional as F
+import torch
+
+
+IMG_EXTENSIONS = ['.jpg', '.JPG', '.jpeg', '.JPEG', '.png', '.PNG']
+
+def is_image_file(filename):
+ return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
+
+class DecordInit(object):
+ """Using Decord(https://github.com/dmlc/decord) to initialize the video_reader."""
+
+ def __init__(self, num_threads=1):
+ self.num_threads = num_threads
+ self.ctx = decord.cpu(0)
+
+ def __call__(self, filename):
+ """Perform the Decord initialization.
+ Args:
+ results (dict): The resulting dict to be modified and passed
+ to the next transform in pipeline.
+ """
+ reader = decord.VideoReader(filename,
+ ctx=self.ctx,
+ num_threads=self.num_threads)
+ return reader
+
+ def __repr__(self):
+ repr_str = (f'{self.__class__.__name__}('
+ f'sr={self.sr},'
+ f'num_threads={self.num_threads})')
+ return repr_str
+
+def pad_to_multiple(number, ds_stride):
+ remainder = number % ds_stride
+ if remainder == 0:
+ return number
+ else:
+ padding = ds_stride - remainder
+ return number + padding
+
+class Collate:
+ def __init__(self, args):
+ self.max_image_size = args.max_image_size
+ self.ae_stride = args.ae_stride
+ self.ae_stride_t = args.ae_stride_t
+ self.ae_stride_thw = (self.ae_stride_t, self.ae_stride, self.ae_stride)
+ self.ae_stride_1hw = (1, self.ae_stride, self.ae_stride)
+
+ self.patch_size = args.patch_size
+ self.patch_size_t = args.patch_size_t
+ self.patch_size_thw = (self.patch_size_t, self.patch_size, self.patch_size)
+ self.patch_size_1hw = (1, self.patch_size, self.patch_size)
+
+ self.num_frames = args.num_frames
+ self.use_image_num = args.use_image_num
+ self.max_thw = (self.num_frames, self.max_image_size, self.max_image_size)
+ self.max_1hw = (1, self.max_image_size, self.max_image_size)
+
+ def package(self, batch):
+ # import ipdb;ipdb.set_trace()
+ batch_tubes_vid = [i['video_data']['video'] for i in batch] # b [c t h w]
+ input_ids_vid = torch.stack([i['video_data']['input_ids'] for i in batch]) # b 1 l
+ cond_mask_vid = torch.stack([i['video_data']['cond_mask'] for i in batch]) # b 1 l
+ batch_tubes_img, input_ids_img, cond_mask_img = None, None, None
+ if self.use_image_num != 0:
+ batch_tubes_img = [j for i in batch for j in i['image_data']['image']] # b*num_img [c 1 h w]
+ input_ids_img = torch.stack([i['image_data']['input_ids'] for i in batch]) # b image_num l
+ cond_mask_img = torch.stack([i['image_data']['cond_mask'] for i in batch]) # b image_num l
+ return batch_tubes_vid, input_ids_vid, cond_mask_vid, batch_tubes_img, input_ids_img, cond_mask_img
+
+ def __call__(self, batch):
+ batch_tubes_vid, input_ids_vid, cond_mask_vid, batch_tubes_img, input_ids_img, cond_mask_img = self.package(batch)
+
+ # import ipdb;ipdb.set_trace()
+ ds_stride = self.ae_stride * self.patch_size
+ t_ds_stride = self.ae_stride_t * self.patch_size_t
+ if self.use_image_num == 0:
+ pad_batch_tubes, attention_mask = self.process(batch_tubes_vid, t_ds_stride, ds_stride,
+ self.max_thw, self.ae_stride_thw, self.patch_size_thw, extra_1=True)
+ # attention_mask: b t h w
+ input_ids, cond_mask = input_ids_vid.squeeze(1), cond_mask_vid.squeeze(1) # b 1 l -> b l
+ else:
+ pad_batch_tubes_vid, attention_mask_vid = self.process(batch_tubes_vid, t_ds_stride, ds_stride,
+ self.max_thw, self.ae_stride_thw, self.patch_size_thw, extra_1=True)
+ # attention_mask_vid: b t h w
+ pad_batch_tubes_img, attention_mask_img = self.process(batch_tubes_img, 1, ds_stride,
+ self.max_1hw, self.ae_stride_1hw, self.patch_size_1hw, extra_1=False)
+ pad_batch_tubes_img = rearrange(pad_batch_tubes_img, '(b i) c 1 h w -> b c i h w', i=self.use_image_num)
+ attention_mask_img = rearrange(attention_mask_img, '(b i) 1 h w -> b i h w', i=self.use_image_num)
+ pad_batch_tubes = torch.cat([pad_batch_tubes_vid, pad_batch_tubes_img], dim=2) # concat at temporal, video first
+ # attention_mask_img: b num_img h w
+ attention_mask = torch.cat([attention_mask_vid, attention_mask_img], dim=1) # b t+num_img h w
+ input_ids = torch.cat([input_ids_vid, input_ids_img], dim=1) # b 1+num_img hw
+ cond_mask = torch.cat([cond_mask_vid, cond_mask_img], dim=1) # b 1+num_img hw
+ return pad_batch_tubes, attention_mask, input_ids, cond_mask
+
+ def process(self, batch_tubes, t_ds_stride, ds_stride, max_thw, ae_stride_thw, patch_size_thw, extra_1):
+
+ # pad to max multiple of ds_stride
+ batch_input_size = [i.shape for i in batch_tubes] # [(c t h w), (c t h w)]
+ max_t, max_h, max_w = max_thw
+ pad_max_t, pad_max_h, pad_max_w = pad_to_multiple(max_t-1 if extra_1 else max_t, t_ds_stride), \
+ pad_to_multiple(max_h, ds_stride), \
+ pad_to_multiple(max_w, ds_stride)
+ pad_max_t = pad_max_t + 1 if extra_1 else pad_max_t
+ each_pad_t_h_w = [[pad_max_t - i.shape[1],
+ pad_max_h - i.shape[2],
+ pad_max_w - i.shape[3]] for i in batch_tubes]
+ pad_batch_tubes = [F.pad(im,
+ (0, pad_w,
+ 0, pad_h,
+ 0, pad_t), value=0) for (pad_t, pad_h, pad_w), im in zip(each_pad_t_h_w, batch_tubes)]
+ pad_batch_tubes = torch.stack(pad_batch_tubes, dim=0)
+
+ # make attention_mask
+ # first_channel_first_frame, first_channel_other_frame = pad_batch_tubes[:, :1, :1], pad_batch_tubes[:, :1, 1:] # first channel to make attention_mask
+ # attention_mask_first_frame = F.max_pool3d(first_channel_first_frame, kernel_size=(1, *ae_stride_thw[1:]), stride=(1, *ae_stride_thw[1:]))
+ # if first_channel_other_frame.numel() != 0:
+ # attention_mask_other_frame = F.max_pool3d(first_channel_other_frame, kernel_size=ae_stride_thw, stride=ae_stride_thw)
+ # attention_mask = torch.cat([attention_mask_first_frame, attention_mask_other_frame], dim=2)
+ # else:
+ # attention_mask = attention_mask_first_frame
+ # attention_mask_ = attention_mask[:, 0].bool().float() # b t h w, do not channel
+
+ # import ipdb;ipdb.set_trace()
+ max_tube_size = [pad_max_t, pad_max_h, pad_max_w]
+ max_latent_size = [((max_tube_size[0]-1) // ae_stride_thw[0] + 1) if extra_1 else (max_tube_size[0] // ae_stride_thw[0]),
+ max_tube_size[1] // ae_stride_thw[1],
+ max_tube_size[2] // ae_stride_thw[2]]
+ valid_latent_size = [[int(math.ceil((i[1]-1) / ae_stride_thw[0])) + 1 if extra_1 else int(math.ceil(i[1] / ae_stride_thw[0])),
+ int(math.ceil(i[2] / ae_stride_thw[1])),
+ int(math.ceil(i[3] / ae_stride_thw[2]))] for i in batch_input_size]
+ attention_mask = [F.pad(torch.ones(i),
+ (0, max_latent_size[2] - i[2],
+ 0, max_latent_size[1] - i[1],
+ 0, max_latent_size[0] - i[0]), value=0) for i in valid_latent_size]
+ attention_mask = torch.stack(attention_mask) # b t h w
+
+
+ # max_tube_size = [pad_max_t, pad_max_h, pad_max_w]
+ # max_latent_size = [((max_tube_size[0]-1) // ae_stride_thw[0] + 1) if extra_1 else (max_tube_size[0] // ae_stride_thw[0]),
+ # max_tube_size[1] // ae_stride_thw[1],
+ # max_tube_size[2] // ae_stride_thw[2]]
+ # max_patchify_latent_size = [((max_latent_size[0]-1) // patch_size_thw[0] + 1) if extra_1 else (max_latent_size[0] // patch_size_thw[0]),
+ # max_latent_size[1] // patch_size_thw[1],
+ # max_latent_size[2] // patch_size_thw[2]]
+ # valid_patchify_latent_size = [[int(math.ceil((i[1]-1) / t_ds_stride)) + 1 if extra_1 else int(math.ceil(i[1] / t_ds_stride)),
+ # int(math.ceil(i[2] / ds_stride)),
+ # int(math.ceil(i[3] / ds_stride))] for i in batch_input_size]
+ # attention_mask = [F.pad(torch.ones(i),
+ # (0, max_patchify_latent_size[2] - i[2],
+ # 0, max_patchify_latent_size[1] - i[1],
+ # 0, max_patchify_latent_size[0] - i[0]), value=0) for i in valid_patchify_latent_size]
+ # attention_mask = torch.stack(attention_mask) # b t h w
+
+ return pad_batch_tubes, attention_mask
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/downloader.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/downloader.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2ac4017b10033f67b5affce0906c0defadb38cf
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/downloader.py
@@ -0,0 +1,18 @@
+import gdown
+import os
+
+opensora_cache_home = os.path.expanduser(
+ os.getenv("OPENSORA_HOME", os.path.join("~/.cache", "opensora"))
+)
+
+
+def gdown_download(id, fname, cache_dir=None):
+ cache_dir = opensora_cache_home if not cache_dir else cache_dir
+
+ os.makedirs(cache_dir, exist_ok=True)
+ destination = os.path.join(cache_dir, fname)
+ if os.path.exists(destination):
+ return destination
+
+ gdown.download(id=id, output=destination, quiet=False)
+ return destination
diff --git a/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/utils.py b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/utils.py
new file mode 100644
index 0000000000000000000000000000000000000000..904840a1ef6eea7b715c4dc1f799bfde69cd91dc
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/causalvideovae/utils/utils.py
@@ -0,0 +1,632 @@
+import os
+
+import torch
+
+import os
+import math
+import torch
+import logging
+import random
+import subprocess
+import numpy as np
+import pandas as pd
+import torch.distributed as dist
+
+# from torch._six import inf
+from torch import inf
+from PIL import Image
+from typing import Union, Iterable
+from collections import OrderedDict
+from torch.utils.tensorboard import SummaryWriter
+
+from diffusers.utils import is_bs4_available, is_ftfy_available
+
+import html
+import re
+import urllib.parse as ul
+
+from torch.utils.data import Dataset
+from torchvision.transforms import Lambda, Compose
+from decord import VideoReader, cpu
+
+from torchvision.transforms._transforms_video import CenterCropVideo
+from torch.nn import functional as F
+import cv2
+import numpy.typing as npt
+
+if is_bs4_available():
+ from bs4 import BeautifulSoup
+
+if is_ftfy_available():
+ import ftfy
+
+_tensor_or_tensors = Union[torch.Tensor, Iterable[torch.Tensor]]
+
+def find_model(model_name):
+ """
+ Finds a pre-trained Latte model, downloading it if necessary. Alternatively, loads a model from a local path.
+ """
+ assert os.path.isfile(model_name), f'Could not find Latte checkpoint at {model_name}'
+ checkpoint = torch.load(model_name, map_location=lambda storage, loc: storage)
+
+ # if "ema" in checkpoint: # supports checkpoints from train.py
+ # print('Using Ema!')
+ # checkpoint = checkpoint["ema"]
+ # else:
+ print('Using model!')
+ checkpoint = checkpoint['model']
+ return checkpoint
+
+#################################################################################
+# Training Clip Gradients #
+#################################################################################
+import deepspeed
+def print_grad_norm(model):
+ # 计算并打印梯度范数
+ # model_engine = accelerator.deepspeed_engine_wrapped.engine
+ # gradients = model_engine.get_gradients()
+ # grad_norm = get_grad_norm(gradients)
+ # 计算并打印梯度范数
+ grad_norm = 0
+ n_grad = 0
+ for name, param in model.named_parameters():
+ grad_data = deepspeed.utils.safe_get_full_grad(param)
+ # self.print_tensor_stats(grad_data, name=name)
+
+ if grad_data is not None:
+ param_norm = grad_data.norm(2)
+ grad_norm += param_norm.item() ** 2
+ n_grad += 1
+ grad_norm = (grad_norm / n_grad) ** (1. / 2)
+
+ # self.print_msg('=' * 50)
+ print(f'Gradient Norm is : {grad_norm}')
+
+def get_grad_norm(
+ parameters: _tensor_or_tensors, norm_type: float = 2.0) -> torch.Tensor:
+ r"""
+ Copy from torch.nn.utils.clip_grad_norm_
+
+ Clips gradient norm of an iterable of parameters.
+
+ The norm is computed over all gradients together, as if they were
+ concatenated into a single vector. Gradients are modified in-place.
+
+ Args:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ max_norm (float or int): max norm of the gradients
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+ error_if_nonfinite (bool): if True, an error is thrown if the total
+ norm of the gradients from :attr:`parameters` is ``nan``,
+ ``inf``, or ``-inf``. Default: False (will switch to True in the future)
+
+ Returns:
+ Total norm of the parameter gradients (viewed as a single vector).
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ grads = [p.grad for p in parameters if p.grad is not None]
+ norm_type = float(norm_type)
+ if len(grads) == 0:
+ return torch.tensor(0.)
+ device = grads[0].device
+ if norm_type == inf:
+ norms = [g.detach().abs().max().to(device) for g in grads]
+ total_norm = norms[0] if len(norms) == 1 else torch.max(torch.stack(norms))
+ else:
+ total_norm = torch.norm(torch.stack([torch.norm(g.detach(), norm_type).to(device) for g in grads]), norm_type)
+ return total_norm
+
+
+def clip_grad_norm_(
+ parameters: _tensor_or_tensors, max_norm: float, norm_type: float = 2.0,
+ error_if_nonfinite: bool = False, clip_grad=True) -> torch.Tensor:
+ r"""
+ Copy from torch.nn.utils.clip_grad_norm_
+
+ Clips gradient norm of an iterable of parameters.
+
+ The norm is computed over all gradients together, as if they were
+ concatenated into a single vector. Gradients are modified in-place.
+
+ Args:
+ parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
+ single Tensor that will have gradients normalized
+ max_norm (float or int): max norm of the gradients
+ norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
+ infinity norm.
+ error_if_nonfinite (bool): if True, an error is thrown if the total
+ norm of the gradients from :attr:`parameters` is ``nan``,
+ ``inf``, or ``-inf``. Default: False (will switch to True in the future)
+
+ Returns:
+ Total norm of the parameter gradients (viewed as a single vector).
+ """
+ if isinstance(parameters, torch.Tensor):
+ parameters = [parameters]
+ grads = [p.grad for p in parameters if p.grad is not None]
+ max_norm = float(max_norm)
+ norm_type = float(norm_type)
+ if len(grads) == 0:
+ return torch.tensor(0.)
+ device = grads[0].device
+ if norm_type == inf:
+ norms = [g.detach().abs().max().to(device) for g in grads]
+ total_norm = norms[0] if len(norms) == 1 else torch.max(torch.stack(norms))
+ else:
+ total_norm = torch.norm(torch.stack([torch.norm(g.detach(), norm_type).to(device) for g in grads]), norm_type)
+
+ if clip_grad:
+ if error_if_nonfinite and torch.logical_or(total_norm.isnan(), total_norm.isinf()):
+ raise RuntimeError(
+ f'The total norm of order {norm_type} for gradients from '
+ '`parameters` is non-finite, so it cannot be clipped. To disable '
+ 'this error and scale the gradients by the non-finite norm anyway, '
+ 'set `error_if_nonfinite=False`')
+ clip_coef = max_norm / (total_norm + 1e-6)
+ # Note: multiplying by the clamped coef is redundant when the coef is clamped to 1, but doing so
+ # avoids a `if clip_coef < 1:` conditional which can require a CPU <=> device synchronization
+ # when the gradients do not reside in CPU memory.
+ clip_coef_clamped = torch.clamp(clip_coef, max=1.0)
+ for g in grads:
+ g.detach().mul_(clip_coef_clamped.to(g.device))
+ # gradient_cliped = torch.norm(torch.stack([torch.norm(g.detach(), norm_type).to(device) for g in grads]), norm_type)
+ # print(gradient_cliped)
+ return total_norm
+
+
+def get_experiment_dir(root_dir, args):
+ # if args.pretrained is not None and 'Latte-XL-2-256x256.pt' not in args.pretrained:
+ # root_dir += '-WOPRE'
+ if args.use_compile:
+ root_dir += '-Compile' # speedup by torch compile
+ if args.attention_mode:
+ root_dir += f'-{args.attention_mode.upper()}'
+ # if args.enable_xformers_memory_efficient_attention:
+ # root_dir += '-Xfor'
+ if args.gradient_checkpointing:
+ root_dir += '-Gc'
+ if args.mixed_precision:
+ root_dir += f'-{args.mixed_precision.upper()}'
+ root_dir += f'-{args.max_image_size}'
+ return root_dir
+
+def get_precision(args):
+ if args.mixed_precision == "bf16":
+ dtype = torch.bfloat16
+ elif args.mixed_precision == "fp16":
+ dtype = torch.float16
+ else:
+ dtype = torch.float32
+ return dtype
+
+#################################################################################
+# Training Logger #
+#################################################################################
+
+def create_logger(logging_dir):
+ """
+ Create a logger that writes to a log file and stdout.
+ """
+ if dist.get_rank() == 0: # real logger
+ logging.basicConfig(
+ level=logging.INFO,
+ # format='[\033[34m%(asctime)s\033[0m] %(message)s',
+ format='[%(asctime)s] %(message)s',
+ datefmt='%Y-%m-%d %H:%M:%S',
+ handlers=[logging.StreamHandler(), logging.FileHandler(f"{logging_dir}/log.txt")]
+ )
+ logger = logging.getLogger(__name__)
+
+ else: # dummy logger (does nothing)
+ logger = logging.getLogger(__name__)
+ logger.addHandler(logging.NullHandler())
+ return logger
+
+
+def create_tensorboard(tensorboard_dir):
+ """
+ Create a tensorboard that saves losses.
+ """
+ if dist.get_rank() == 0: # real tensorboard
+ # tensorboard
+ writer = SummaryWriter(tensorboard_dir)
+
+ return writer
+
+
+def write_tensorboard(writer, *args):
+ '''
+ write the loss information to a tensorboard file.
+ Only for pytorch DDP mode.
+ '''
+ if dist.get_rank() == 0: # real tensorboard
+ writer.add_scalar(args[0], args[1], args[2])
+
+
+#################################################################################
+# EMA Update/ DDP Training Utils #
+#################################################################################
+
+@torch.no_grad()
+def update_ema(ema_model, model, decay=0.9999):
+ """
+ Step the EMA model towards the current model.
+ """
+ ema_params = OrderedDict(ema_model.named_parameters())
+ model_params = OrderedDict(model.named_parameters())
+
+ for name, param in model_params.items():
+ # TODO: Consider applying only to params that require_grad to avoid small numerical changes of pos_embed
+ ema_params[name].mul_(decay).add_(param.data, alpha=1 - decay)
+
+
+def requires_grad(model, flag=True):
+ """
+ Set requires_grad flag for all parameters in a model.
+ """
+ for p in model.parameters():
+ p.requires_grad = flag
+
+
+def cleanup():
+ """
+ End DDP training.
+ """
+ dist.destroy_process_group()
+
+
+def setup_distributed(backend="nccl", port=None):
+ """Initialize distributed training environment.
+ support both slurm and torch.distributed.launch
+ see torch.distributed.init_process_group() for more details
+ """
+ num_gpus = torch.cuda.device_count()
+
+ if "SLURM_JOB_ID" in os.environ:
+ rank = int(os.environ["SLURM_PROCID"])
+ world_size = int(os.environ["SLURM_NTASKS"])
+ node_list = os.environ["SLURM_NODELIST"]
+ addr = subprocess.getoutput(f"scontrol show hostname {node_list} | head -n1")
+ # specify master port
+ if port is not None:
+ os.environ["MASTER_PORT"] = str(port)
+ elif "MASTER_PORT" not in os.environ:
+ # os.environ["MASTER_PORT"] = "29566"
+ os.environ["MASTER_PORT"] = str(29567 + num_gpus)
+ if "MASTER_ADDR" not in os.environ:
+ os.environ["MASTER_ADDR"] = addr
+ os.environ["WORLD_SIZE"] = str(world_size)
+ os.environ["LOCAL_RANK"] = str(rank % num_gpus)
+ os.environ["RANK"] = str(rank)
+ else:
+ rank = int(os.environ["RANK"])
+ world_size = int(os.environ["WORLD_SIZE"])
+
+ # torch.cuda.set_device(rank % num_gpus)
+
+ dist.init_process_group(
+ backend=backend,
+ world_size=world_size,
+ rank=rank,
+ )
+
+
+#################################################################################
+# Testing Utils #
+#################################################################################
+
+def save_video_grid(video, nrow=None):
+ b, t, h, w, c = video.shape
+
+ if nrow is None:
+ nrow = math.ceil(math.sqrt(b))
+ ncol = math.ceil(b / nrow)
+ padding = 1
+ video_grid = torch.zeros((t, (padding + h) * nrow + padding,
+ (padding + w) * ncol + padding, c), dtype=torch.uint8)
+
+ print(video_grid.shape)
+ for i in range(b):
+ r = i // ncol
+ c = i % ncol
+ start_r = (padding + h) * r
+ start_c = (padding + w) * c
+ video_grid[:, start_r:start_r + h, start_c:start_c + w] = video[i]
+
+ return video_grid
+
+
+#################################################################################
+# MMCV Utils #
+#################################################################################
+
+
+def collect_env():
+ # Copyright (c) OpenMMLab. All rights reserved.
+ from mmcv.utils import collect_env as collect_base_env
+ from mmcv.utils import get_git_hash
+ """Collect the information of the running environments."""
+
+ env_info = collect_base_env()
+ env_info['MMClassification'] = get_git_hash()[:7]
+
+ for name, val in env_info.items():
+ print(f'{name}: {val}')
+
+ print(torch.cuda.get_arch_list())
+ print(torch.version.cuda)
+
+
+#################################################################################
+# Pixart-alpha Utils #
+#################################################################################
+
+
+bad_punct_regex = re.compile(r'['+'#®•©™&@·º½¾¿¡§~'+'\)'+'\('+'\]'+'\['+'\}'+'\{'+'\|'+'\\'+'\/'+'\*' + r']{1,}') # noqa
+
+def text_preprocessing(text):
+ # The exact text cleaning as was in the training stage:
+ text = clean_caption(text)
+ text = clean_caption(text)
+ return text
+
+def basic_clean(text):
+ text = ftfy.fix_text(text)
+ text = html.unescape(html.unescape(text))
+ return text.strip()
+
+def clean_caption(caption):
+ caption = str(caption)
+ caption = ul.unquote_plus(caption)
+ caption = caption.strip().lower()
+ caption = re.sub('', 'person', caption)
+ # urls:
+ caption = re.sub(
+ r'\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa
+ '', caption) # regex for urls
+ caption = re.sub(
+ r'\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))', # noqa
+ '', caption) # regex for urls
+ # html:
+ caption = BeautifulSoup(caption, features='html.parser').text
+
+ # @
+ caption = re.sub(r'@[\w\d]+\b', '', caption)
+
+ # 31C0—31EF CJK Strokes
+ # 31F0—31FF Katakana Phonetic Extensions
+ # 3200—32FF Enclosed CJK Letters and Months
+ # 3300—33FF CJK Compatibility
+ # 3400—4DBF CJK Unified Ideographs Extension A
+ # 4DC0—4DFF Yijing Hexagram Symbols
+ # 4E00—9FFF CJK Unified Ideographs
+ caption = re.sub(r'[\u31c0-\u31ef]+', '', caption)
+ caption = re.sub(r'[\u31f0-\u31ff]+', '', caption)
+ caption = re.sub(r'[\u3200-\u32ff]+', '', caption)
+ caption = re.sub(r'[\u3300-\u33ff]+', '', caption)
+ caption = re.sub(r'[\u3400-\u4dbf]+', '', caption)
+ caption = re.sub(r'[\u4dc0-\u4dff]+', '', caption)
+ caption = re.sub(r'[\u4e00-\u9fff]+', '', caption)
+ #######################################################
+
+ # все виды тире / all types of dash --> "-"
+ caption = re.sub(
+ r'[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+', # noqa
+ '-', caption)
+
+ # кавычки к одному стандарту
+ caption = re.sub(r'[`´«»“”¨]', '"', caption)
+ caption = re.sub(r'[‘’]', "'", caption)
+
+ # "
+ caption = re.sub(r'"?', '', caption)
+ # &
+ caption = re.sub(r'&', '', caption)
+
+ # ip adresses:
+ caption = re.sub(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ' ', caption)
+
+ # article ids:
+ caption = re.sub(r'\d:\d\d\s+$', '', caption)
+
+ # \n
+ caption = re.sub(r'\\n', ' ', caption)
+
+ # "#123"
+ caption = re.sub(r'#\d{1,3}\b', '', caption)
+ # "#12345.."
+ caption = re.sub(r'#\d{5,}\b', '', caption)
+ # "123456.."
+ caption = re.sub(r'\b\d{6,}\b', '', caption)
+ # filenames:
+ caption = re.sub(r'[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)', '', caption)
+
+ #
+ caption = re.sub(r'[\"\']{2,}', r'"', caption) # """AUSVERKAUFT"""
+ caption = re.sub(r'[\.]{2,}', r' ', caption) # """AUSVERKAUFT"""
+
+ caption = re.sub(bad_punct_regex, r' ', caption) # ***AUSVERKAUFT***, #AUSVERKAUFT
+ caption = re.sub(r'\s+\.\s+', r' ', caption) # " . "
+
+ # this-is-my-cute-cat / this_is_my_cute_cat
+ regex2 = re.compile(r'(?:\-|\_)')
+ if len(re.findall(regex2, caption)) > 3:
+ caption = re.sub(regex2, ' ', caption)
+
+ caption = basic_clean(caption)
+
+ caption = re.sub(r'\b[a-zA-Z]{1,3}\d{3,15}\b', '', caption) # jc6640
+ caption = re.sub(r'\b[a-zA-Z]+\d+[a-zA-Z]+\b', '', caption) # jc6640vc
+ caption = re.sub(r'\b\d+[a-zA-Z]+\d+\b', '', caption) # 6640vc231
+
+ caption = re.sub(r'(worldwide\s+)?(free\s+)?shipping', '', caption)
+ caption = re.sub(r'(free\s)?download(\sfree)?', '', caption)
+ caption = re.sub(r'\bclick\b\s(?:for|on)\s\w+', '', caption)
+ caption = re.sub(r'\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?', '', caption)
+ caption = re.sub(r'\bpage\s+\d+\b', '', caption)
+
+ caption = re.sub(r'\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b', r' ', caption) # j2d1a2a...
+
+ caption = re.sub(r'\b\d+\.?\d*[xх×]\d+\.?\d*\b', '', caption)
+
+ caption = re.sub(r'\b\s+\:\s+', r': ', caption)
+ caption = re.sub(r'(\D[,\./])\b', r'\1 ', caption)
+ caption = re.sub(r'\s+', ' ', caption)
+
+ caption.strip()
+
+ caption = re.sub(r'^[\"\']([\w\W]+)[\"\']$', r'\1', caption)
+ caption = re.sub(r'^[\'\_,\-\:;]', r'', caption)
+ caption = re.sub(r'[\'\_,\-\:\-\+]$', r'', caption)
+ caption = re.sub(r'^\.\S+$', '', caption)
+
+ return caption.strip()
+
+
+#################################################################################
+# eval PSNR when training #
+#################################################################################
+
+def resize(x, resolution):
+ height, width = x.shape[-2:]
+ aspect_ratio = width / height
+ if width <= height:
+ new_width = resolution
+ new_height = int(resolution / aspect_ratio)
+ else:
+ new_height = resolution
+ new_width = int(resolution * aspect_ratio)
+ resized_x = F.interpolate(x, size=(new_height, new_width), mode='bilinear', align_corners=True, antialias=True)
+ return resized_x
+
+def _preprocess(video_data, short_size=128, crop_size=None):
+ transform = Compose(
+ [
+ Lambda(lambda x: (x / 255.0)),
+ Lambda(lambda x: resize(x, short_size)),
+ (
+ CenterCropVideo(crop_size=crop_size)
+ if crop_size is not None
+ else Lambda(lambda x: x)
+ ),
+ ]
+ )
+ video_outputs = transform(video_data)
+ video_outputs = _format_video_shape(video_outputs)
+ return video_outputs
+
+def _format_video_shape(video, time_compress=4, spatial_compress=8):
+ time = video.shape[1]
+ height = video.shape[2]
+ width = video.shape[3]
+ new_time = (
+ (time - (time - 1) % time_compress)
+ if (time - 1) % time_compress != 0
+ else time
+ )
+ new_height = (
+ (height - (height) % spatial_compress)
+ if height % spatial_compress != 0
+ else height
+ )
+ new_width = (
+ (width - (width) % spatial_compress) if width % spatial_compress != 0 else width
+ )
+ return video[:, :new_time, :new_height, :new_width]
+
+def array_to_video(
+ image_array: npt.NDArray, fps: float = 30.0, output_file: str = "output_video.mp4"
+) -> None:
+ height, width, channels = image_array[0].shape
+ fourcc = cv2.VideoWriter_fourcc(*"mp4v")
+ video_writer = cv2.VideoWriter(output_file, fourcc, float(fps), (width, height))
+
+ for image in image_array:
+ image_rgb = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
+ video_writer.write(image_rgb)
+
+ video_writer.release()
+
+
+def custom_to_video(
+ x: torch.Tensor, fps: float = 2.0, output_file: str = "output_video.mp4"
+) -> None:
+ x = x.detach().cpu()
+ x = torch.clamp(x, -1, 1)
+ x = (x + 1) / 2
+ x = x.permute(1, 2, 3, 0).float().numpy()
+ x = (255 * x).astype(np.uint8)
+ array_to_video(x, fps=fps, output_file=output_file)
+ return
+
+class RealVideoDataset(Dataset):
+ def __init__(
+ self,
+ real_video_dir,
+ num_frames,
+ sample_rate=1,
+ crop_size=None,
+ resolution=128,
+ ) -> None:
+ super().__init__()
+ self.real_video_files = self._combine_without_prefix(real_video_dir)
+ self.num_frames = num_frames
+ self.sample_rate = sample_rate
+ self.crop_size = crop_size
+ self.short_size = resolution
+
+ def __len__(self):
+ return len(self.real_video_files)
+
+ def __getitem__(self, index):
+ if index >= len(self):
+ raise IndexError
+ real_video_file = self.real_video_files[index]
+ real_video_tensor = self._load_video(real_video_file)
+ video_name = os.path.basename(real_video_file)
+ return {'video': real_video_tensor, 'file_name': video_name }
+
+ def _load_video(self, video_path):
+ num_frames = self.num_frames
+ sample_rate = self.sample_rate
+ decord_vr = VideoReader(video_path, ctx=cpu(0))
+ total_frames = len(decord_vr)
+ sample_frames_len = sample_rate * num_frames
+
+ if total_frames > sample_frames_len:
+ s = 0
+ e = s + sample_frames_len
+ num_frames = num_frames
+ else:
+ s = 0
+ e = total_frames
+ num_frames = int(total_frames / sample_frames_len * num_frames)
+ print(
+ f"sample_frames_len {sample_frames_len}, only can sample {num_frames * sample_rate}",
+ video_path,
+ total_frames,
+ )
+
+ frame_id_list = np.linspace(s, e - 1, num_frames, dtype=int)
+ video_data = decord_vr.get_batch(frame_id_list).asnumpy()
+ video_data = torch.from_numpy(video_data)
+ video_data = video_data.permute(3, 0, 1, 2)
+ return _preprocess(
+ video_data, short_size=self.short_size, crop_size=self.crop_size
+ )
+
+ def _combine_without_prefix(self, folder_path, prefix="."):
+ folder = []
+ if not folder_path.endswith('.csv'):
+ for name in os.listdir(folder_path):
+ if name[0] == prefix:
+ continue
+ folder.append(os.path.join(folder_path, name))
+ else:
+ df = pd.read_csv(folder_path)
+ folder = df['path'].tolist()
+ folder.sort()
+ return folder
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/__init__.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f1dca9fffdb073a351f38d85862a1d35ddf54d1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/__init__.py
@@ -0,0 +1,17 @@
+
+from .opensora.modeling_opensora import OpenSora_models
+from .udit.modeling_udit import UDiT_models
+
+
+Diffusion_models = {}
+Diffusion_models.update(OpenSora_models)
+Diffusion_models.update(UDiT_models)
+
+from .opensora.modeling_opensora import OpenSora_models_class
+from .udit.modeling_udit import UDiT_models_class
+
+
+Diffusion_models_class = {}
+Diffusion_models_class.update(OpenSora_models_class)
+Diffusion_models_class.update(UDiT_models_class)
+
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/__init__.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd76664b9593bfad8f920e9cbd14d098ab722d17
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora.py
@@ -0,0 +1,754 @@
+import os
+import numpy as np
+from torch import nn
+import torch
+from einops import rearrange, repeat
+from typing import Any, Dict, Optional, Tuple
+from torch.nn import functional as F
+# from diffusers.models.transformer_2d import Transformer2DModelOutput
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version, deprecate
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.normalization import AdaLayerNormSingle
+from diffusers.models.embeddings import PixArtAlphaTextProjection
+from opensora.models.diffusion.opensora.modules import OverlapPatchEmbed3D, OverlapPatchEmbed2D, PatchEmbed2D, BasicTransformerBlock
+from opensora.utils.utils import to_2tuple
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+ from opensora.acceleration.parallel_states import get_sequence_parallel_state, hccl_info
+except:
+ torch_npu = None
+ npu_config = None
+ from opensora.utils.parallel_states import get_sequence_parallel_state, nccl_info
+
+class OpenSoraT2V(ModelMixin, ConfigMixin):
+ """
+ A 2D Transformer model for image-like data.
+
+ Parameters:
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
+ in_channels (`int`, *optional*):
+ The number of channels in the input and output (specify if the input is **continuous**).
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
+ This is fixed during training since it is used to learn a number of position embeddings.
+ num_vector_embeds (`int`, *optional*):
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
+ Includes the class for the masked latent pixel.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
+ num_embeds_ada_norm ( `int`, *optional*):
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
+ added to the hidden states.
+
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
+ attention_bias (`bool`, *optional*):
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 16,
+ attention_head_dim: int = 88,
+ in_channels: Optional[int] = None,
+ out_channels: Optional[int] = None,
+ num_layers: int = 1,
+ dropout: float = 0.0,
+ norm_num_groups: int = 32,
+ cross_attention_dim: Optional[int] = None,
+ attention_bias: bool = False,
+ sample_size: Optional[int] = None,
+ sample_size_t: Optional[int] = None,
+ num_vector_embeds: Optional[int] = None,
+ patch_size: Optional[int] = None,
+ patch_size_t: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ use_linear_projection: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ attention_type: str = "default",
+ caption_channels: int = None,
+ interpolation_scale_h: float = None,
+ interpolation_scale_w: float = None,
+ interpolation_scale_t: float = None,
+ use_additional_conditions: Optional[bool] = None,
+ attention_mode: str = 'xformers',
+ downsampler: str = None,
+ use_rope: bool = False,
+ use_stable_fp32: bool = False,
+ ):
+ super().__init__()
+
+ # Validate inputs.
+ if patch_size is not None:
+ if norm_type not in ["ada_norm", "ada_norm_zero", "ada_norm_single"]:
+ raise NotImplementedError(
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
+ )
+ elif norm_type in ["ada_norm", "ada_norm_zero"] and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
+ )
+
+ # Set some common variables used across the board.
+ self.use_rope = use_rope
+ self.use_linear_projection = use_linear_projection
+ self.interpolation_scale_t = interpolation_scale_t
+ self.interpolation_scale_h = interpolation_scale_h
+ self.interpolation_scale_w = interpolation_scale_w
+ self.downsampler = downsampler
+ self.caption_channels = caption_channels
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_dim = attention_head_dim
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.gradient_checkpointing = False
+ self.config.hidden_size = self.inner_dim
+ use_additional_conditions = False
+ # if use_additional_conditions is None:
+ # if norm_type == "ada_norm_single" and sample_size == 128:
+ # use_additional_conditions = True
+ # else:
+ # use_additional_conditions = False
+ self.use_additional_conditions = use_additional_conditions
+
+ # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
+ # Define whether input is continuous or discrete depending on configuration
+ assert in_channels is not None and patch_size is not None
+
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
+ deprecation_message = (
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
+ " incorrectly set to `'layer_norm'`. Make sure to set `norm_type` to `'ada_norm'` in the config."
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
+ )
+ deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
+ norm_type = "ada_norm"
+
+ # 2. Initialize the right blocks.
+ # Initialize the output blocks and other projection blocks when necessary.
+ self._init_patched_inputs(norm_type=norm_type)
+
+ def _init_patched_inputs(self, norm_type):
+ assert self.config.sample_size_t is not None, "OpenSoraT2V over patched input must provide sample_size_t"
+ assert self.config.sample_size is not None, "OpenSoraT2V over patched input must provide sample_size"
+ #assert not (self.config.sample_size_t == 1 and self.config.patch_size_t == 2), "Image do not need patchfy in t-dim"
+
+ self.num_frames = self.config.sample_size_t
+ self.config.sample_size = to_2tuple(self.config.sample_size)
+ self.height = self.config.sample_size[0]
+ self.width = self.config.sample_size[1]
+ self.patch_size_t = self.config.patch_size_t
+ self.patch_size = self.config.patch_size
+ interpolation_scale_t = ((self.config.sample_size_t - 1) // 16 + 1) if self.config.sample_size_t % 2 == 1 else self.config.sample_size_t / 16
+ interpolation_scale_t = (
+ self.config.interpolation_scale_t if self.config.interpolation_scale_t is not None else interpolation_scale_t
+ )
+ interpolation_scale = (
+ self.config.interpolation_scale_h if self.config.interpolation_scale_h is not None else self.config.sample_size[0] / 30,
+ self.config.interpolation_scale_w if self.config.interpolation_scale_w is not None else self.config.sample_size[1] / 40,
+ )
+ # if self.config.sample_size_t > 1:
+ # self.pos_embed = PatchEmbed3D(
+ # num_frames=self.config.sample_size_t,
+ # height=self.config.sample_size[0],
+ # width=self.config.sample_size[1],
+ # patch_size_t=self.config.patch_size_t,
+ # patch_size=self.config.patch_size,
+ # in_channels=self.in_channels,
+ # embed_dim=self.inner_dim,
+ # interpolation_scale=interpolation_scale,
+ # interpolation_scale_t=interpolation_scale_t,
+ # )
+ # else:
+ if self.config.downsampler is not None and len(self.config.downsampler) == 9:
+ self.pos_embed = OverlapPatchEmbed3D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+ elif self.config.downsampler is not None and len(self.config.downsampler) == 7:
+ self.pos_embed = OverlapPatchEmbed2D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+
+ else: #默认在这
+ self.pos_embed = PatchEmbed2D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+ interpolation_scale_thw = (interpolation_scale_t, *interpolation_scale)
+ self.transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.config.cross_attention_dim,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ downsampler=self.config.downsampler,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.num_layers)
+ ]
+ )
+
+ if self.config.norm_type != "ada_norm_single":
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
+ self.proj_out_2 = nn.Linear(
+ self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+ elif self.config.norm_type == "ada_norm_single":
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
+ self.proj_out = nn.Linear(
+ self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+
+ # PixArt-Alpha blocks.
+ self.adaln_single = None
+ if self.config.norm_type == "ada_norm_single":
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
+ # additional conditions until we find better name
+ self.adaln_single = AdaLayerNormSingle(
+ self.inner_dim, use_additional_conditions=self.use_additional_conditions
+ )
+
+ self.caption_projection = None
+ if self.caption_channels is not None:
+ self.caption_projection = PixArtAlphaTextProjection(
+ in_features=self.caption_channels, hidden_size=self.inner_dim
+ )
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ use_image_num: Optional[int] = 0,
+ return_dict: bool = True,
+ ):
+ """
+ The [`Transformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
+ Input `hidden_states`.
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
+ self-attention.
+ timestep ( `torch.LongTensor`, *optional*):
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
+ `AdaLayerZeroNorm`.
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ attention_mask ( `torch.Tensor`, *optional*):
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
+ negative values to the attention scores corresponding to "discard" tokens.
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
+
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
+
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
+ above. This bias will be added to the cross-attention scores.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ batch_size, c, frame, h, w = hidden_states.shape
+ # print('hidden_states.shape', hidden_states.shape)
+ frame = frame - use_image_num # 21-4=17
+ if cross_attention_kwargs is not None:
+ if cross_attention_kwargs.get("scale", None) is not None:
+ print.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
+ # expects mask of shape:
+ # [batch, key_tokens]
+ # adds singleton query_tokens dimension:
+ # [batch, 1, key_tokens]
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
+ attention_mask_vid, attention_mask_img = None, None
+ if attention_mask is not None and attention_mask.ndim == 4:
+ # assume that mask is expressed as:
+ # (1 = keep, 0 = discard)
+ # convert mask into a bias that can be added to attention scores:
+ # (keep = +0, discard = -10000.0)
+ # b, frame+use_image_num, h, w -> a video with images
+ # b, 1, h, w -> only images
+ attention_mask = attention_mask.to(self.dtype)
+ if get_sequence_parallel_state():
+ if npu_config is not None:
+ attention_mask_vid = attention_mask[:, :frame * hccl_info.world_size] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame * hccl_info.world_size:] # b, use_image_num, h, w
+ else:
+ # print('before attention_mask.shape', attention_mask.shape)
+ attention_mask_vid = attention_mask[:, :frame * nccl_info.world_size] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame * nccl_info.world_size:] # b, use_image_num, h, w
+ # print('after attention_mask.shape', attention_mask_vid.shape)
+ else:
+ attention_mask_vid = attention_mask[:, :frame] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame:] # b, use_image_num, h, w
+
+ if attention_mask_vid.numel() > 0:
+ attention_mask_vid_first_frame = attention_mask_vid[:, :1].repeat(1, self.patch_size_t-1, 1, 1)
+ attention_mask_vid = torch.cat([attention_mask_vid_first_frame, attention_mask_vid], dim=1)
+ attention_mask_vid = attention_mask_vid.unsqueeze(1) # b 1 t h w
+ attention_mask_vid = F.max_pool3d(attention_mask_vid, kernel_size=(self.patch_size_t, self.patch_size, self.patch_size),
+ stride=(self.patch_size_t, self.patch_size, self.patch_size))
+ attention_mask_vid = rearrange(attention_mask_vid, 'b 1 t h w -> (b 1) 1 (t h w)')
+ if attention_mask_img.numel() > 0:
+ attention_mask_img = F.max_pool2d(attention_mask_img, kernel_size=(self.patch_size, self.patch_size), stride=(self.patch_size, self.patch_size))
+ attention_mask_img = rearrange(attention_mask_img, 'b i h w -> (b i) 1 (h w)')
+
+ attention_mask_vid = (1 - attention_mask_vid.bool().to(self.dtype)) * -10000.0 if attention_mask_vid.numel() > 0 else None
+ attention_mask_img = (1 - attention_mask_img.bool().to(self.dtype)) * -10000.0 if attention_mask_img.numel() > 0 else None
+
+ if frame == 1 and use_image_num == 0 and not get_sequence_parallel_state():
+ attention_mask_img = attention_mask_vid
+ attention_mask_vid = None
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
+ # import ipdb;ipdb.set_trace()
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 3:
+ # b, 1+use_image_num, l -> a video with images
+ # b, 1, l -> only images
+ encoder_attention_mask = (1 - encoder_attention_mask.to(self.dtype)) * -10000.0
+ in_t = encoder_attention_mask.shape[1]
+ encoder_attention_mask_vid = encoder_attention_mask[:, :in_t-use_image_num] # b, 1, l
+ encoder_attention_mask_vid = rearrange(encoder_attention_mask_vid, 'b 1 l -> (b 1) 1 l') if encoder_attention_mask_vid.numel() > 0 else None
+
+ encoder_attention_mask_img = encoder_attention_mask[:, in_t-use_image_num:] # b, use_image_num, l
+ encoder_attention_mask_img = rearrange(encoder_attention_mask_img, 'b i l -> (b i) 1 l') if encoder_attention_mask_img.numel() > 0 else None
+
+ if frame == 1 and use_image_num == 0 and not get_sequence_parallel_state():
+ encoder_attention_mask_img = encoder_attention_mask_vid
+ encoder_attention_mask_vid = None
+
+ if npu_config is not None and attention_mask_vid is not None:
+ attention_mask_vid = npu_config.get_attention_mask(attention_mask_vid, attention_mask_vid.shape[-1])
+ encoder_attention_mask_vid = npu_config.get_attention_mask(encoder_attention_mask_vid,
+ attention_mask_vid.shape[-2])
+ if npu_config is not None and attention_mask_img is not None:
+ attention_mask_img = npu_config.get_attention_mask(attention_mask_img, attention_mask_img.shape[-1])
+ encoder_attention_mask_img = npu_config.get_attention_mask(encoder_attention_mask_img,
+ attention_mask_img.shape[-2])
+
+
+ # 1. Input
+ frame = ((frame - 1) // self.patch_size_t + 1) if frame % 2 == 1 else frame // self.patch_size_t # patchfy
+ # print('frame', frame)
+ height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
+
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
+ hidden_states_vid, hidden_states_img, encoder_hidden_states_vid, encoder_hidden_states_img, \
+ timestep_vid, timestep_img, embedded_timestep_vid, embedded_timestep_img = self._operate_on_patched_inputs(
+ hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num
+ )
+ # 2. Blocks
+ # import ipdb;ipdb.set_trace()
+ if get_sequence_parallel_state():
+ if hidden_states_vid is not None:
+ # print(333333333333333)
+ hidden_states_vid = rearrange(hidden_states_vid, 'b s h -> s b h', b=batch_size).contiguous()
+ encoder_hidden_states_vid = rearrange(encoder_hidden_states_vid, 'b s h -> s b h',
+ b=batch_size).contiguous()
+ timestep_vid = timestep_vid.view(batch_size, 6, -1).transpose(0, 1).contiguous()
+ # print('timestep_vid', timestep_vid.shape)
+
+
+ for block in self.transformer_blocks:
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ # import ipdb;ipdb.set_trace()
+ if hidden_states_vid is not None:
+ hidden_states_vid = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states_vid,
+ attention_mask_vid,
+ encoder_hidden_states_vid,
+ encoder_attention_mask_vid,
+ timestep_vid,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ # import ipdb;ipdb.set_trace()
+ if hidden_states_img is not None:
+ hidden_states_img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states_img,
+ attention_mask_img,
+ encoder_hidden_states_img,
+ encoder_attention_mask_img,
+ timestep_img,
+ cross_attention_kwargs,
+ class_labels,
+ 1,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ if hidden_states_vid is not None:
+ hidden_states_vid = block(
+ hidden_states_vid,
+ attention_mask=attention_mask_vid,
+ encoder_hidden_states=encoder_hidden_states_vid,
+ encoder_attention_mask=encoder_attention_mask_vid,
+ timestep=timestep_vid,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+ if hidden_states_img is not None:
+ hidden_states_img = block(
+ hidden_states_img,
+ attention_mask=attention_mask_img,
+ encoder_hidden_states=encoder_hidden_states_img,
+ encoder_attention_mask=encoder_attention_mask_img,
+ timestep=timestep_img,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=1,
+ height=height,
+ width=width,
+ )
+
+ if get_sequence_parallel_state():
+ if hidden_states_vid is not None:
+ hidden_states_vid = rearrange(hidden_states_vid, 's b h -> b s h', b=batch_size).contiguous()
+
+ # 3. Output
+ output_vid, output_img = None, None
+ if hidden_states_vid is not None:
+ output_vid = self._get_output_for_patched_inputs(
+ hidden_states=hidden_states_vid,
+ timestep=timestep_vid,
+ class_labels=class_labels,
+ embedded_timestep=embedded_timestep_vid,
+ num_frames=frame,
+ height=height,
+ width=width,
+ ) # b c t h w
+ if hidden_states_img is not None:
+ output_img = self._get_output_for_patched_inputs(
+ hidden_states=hidden_states_img,
+ timestep=timestep_img,
+ class_labels=class_labels,
+ embedded_timestep=embedded_timestep_img,
+ num_frames=1,
+ height=height,
+ width=width,
+ ) # b c 1 h w
+ if use_image_num != 0:
+ output_img = rearrange(output_img, '(b i) c 1 h w -> b c i h w', i=use_image_num)
+
+ if output_vid is not None and output_img is not None:
+ output = torch.cat([output_vid, output_img], dim=2)
+ elif output_vid is not None:
+ output = output_vid
+ elif output_img is not None:
+ output = output_img
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
+
+
+ def _operate_on_patched_inputs(self, hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num):
+ # batch_size = hidden_states.shape[0]
+ hidden_states_vid, hidden_states_img = self.pos_embed(hidden_states.to(self.dtype), frame) #实际上就是单纯地conv2d proj
+ timestep_vid, timestep_img = None, None
+ embedded_timestep_vid, embedded_timestep_img = None, None
+ encoder_hidden_states_vid, encoder_hidden_states_img = None, None
+
+ if self.adaln_single is not None: #pixart中的Ada single层
+ if self.use_additional_conditions and added_cond_kwargs is None:
+ raise ValueError(
+ "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
+ )
+ timestep, embedded_timestep = self.adaln_single(
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=self.dtype
+ ) # b 6d, b d
+ if hidden_states_vid is None:
+ timestep_img = timestep
+ embedded_timestep_img = embedded_timestep
+ else:
+ timestep_vid = timestep
+ embedded_timestep_vid = embedded_timestep
+ if hidden_states_img is not None:
+ timestep_img = repeat(timestep, 'b d -> (b i) d', i=use_image_num).contiguous()
+ embedded_timestep_img = repeat(embedded_timestep, 'b d -> (b i) d', i=use_image_num).contiguous()
+
+ if self.caption_projection is not None:
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states) # b, 1+use_image_num, l, d or b, 1, l, d
+ if hidden_states_vid is None:
+ encoder_hidden_states_img = rearrange(encoder_hidden_states, 'b 1 l d -> (b 1) l d')
+ else:
+ encoder_hidden_states_vid = rearrange(encoder_hidden_states[:, :1], 'b 1 l d -> (b 1) l d')
+ if hidden_states_img is not None:
+ encoder_hidden_states_img = rearrange(encoder_hidden_states[:, 1:], 'b i l d -> (b i) l d')
+
+
+ return hidden_states_vid, hidden_states_img, encoder_hidden_states_vid, encoder_hidden_states_img, timestep_vid, timestep_img, embedded_timestep_vid, embedded_timestep_img
+
+
+
+ def _get_output_for_patched_inputs(
+ self, hidden_states, timestep, class_labels, embedded_timestep, num_frames, height=None, width=None
+ ):
+ # import ipdb;ipdb.set_trace()
+ if self.config.norm_type != "ada_norm_single":
+ conditioning = self.transformer_blocks[0].norm1.emb(
+ timestep, class_labels, hidden_dtype=self.dtype
+ )
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
+ hidden_states = self.proj_out_2(hidden_states)
+ elif self.config.norm_type == "ada_norm_single":
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states)
+ # Modulation
+ hidden_states = hidden_states * (1 + scale) + shift
+ hidden_states = self.proj_out(hidden_states)
+ hidden_states = hidden_states.squeeze(1)
+
+ # unpatchify
+ if self.adaln_single is None:
+ height = width = int(hidden_states.shape[1] ** 0.5)
+ hidden_states = hidden_states.reshape(
+ shape=(-1, num_frames, height, width, self.patch_size_t, self.patch_size, self.patch_size, self.out_channels)
+ )
+ hidden_states = torch.einsum("nthwopqc->nctohpwq", hidden_states)
+ output = hidden_states.reshape(
+ shape=(-1, self.out_channels, num_frames * self.patch_size_t, height * self.patch_size, width * self.patch_size)
+ )
+ # import ipdb;ipdb.set_trace()
+ # if output.shape[2] % 2 == 0:
+ # output = output[:, :, 1:]
+ return output
+
+def OpenSoraT2V_S_122(**kwargs):
+ return OpenSoraT2V(num_layers=28, attention_head_dim=96, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=1536, **kwargs)
+
+def OpenSoraT2V_B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=96, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=1920, **kwargs)
+
+def OpenSoraT2V_L_122(**kwargs):
+ return OpenSoraT2V(num_layers=40, attention_head_dim=128, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2048, **kwargs)
+
+def OpenSoraT2V_ROPE_L_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=96, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2304, **kwargs)
+
+def OpenSoraT2V_ROPE_L_4B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=120, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2880, **kwargs)
+
+def OpenSoraT2V_ROPE_L_5B_122(**kwargs):
+ return OpenSoraT2V(num_layers=40, attention_head_dim=120, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2880, **kwargs)
+
+def OpenSoraT2V_ROPE_L_6B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=144, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=3456, **kwargs)
+
+
+OpenSora_models = {
+ "OpenSoraT2V-S/122": OpenSoraT2V_S_122, # 1.1B
+ "OpenSoraT2V-B/122": OpenSoraT2V_B_122,
+ "OpenSoraT2V-L/122": OpenSoraT2V_L_122,
+ "OpenSoraT2V-ROPE-L/122": OpenSoraT2V_ROPE_L_122,
+ "OpenSoraT2V-ROPE-L-4B/122": OpenSoraT2V_ROPE_L_4B_122, # 4.32B
+ "OpenSoraT2V-ROPE-L-5B/122": OpenSoraT2V_ROPE_L_5B_122, # 5.38B
+ "OpenSoraT2V-ROPE-L-6B/122": OpenSoraT2V_ROPE_L_6B_122, # 6.22B
+}
+
+OpenSora_models_class = {
+ "OpenSoraT2V-S/122": OpenSoraT2V,
+ "OpenSoraT2V-B/122": OpenSoraT2V,
+ "OpenSoraT2V-L/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-4B/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-5B/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-6B/122": OpenSoraT2V,
+}
+
+if __name__ == '__main__':
+ from opensora.models.causalvideovae import ae_channel_config, ae_stride_config
+ from opensora.models.causalvideovae import getae, getae_wrapper
+ from opensora.models.causalvideovae import CausalVAEModelWrapper
+
+ args = type('args', (),
+ {
+ 'ae': 'CausalVAEModel_4x8x8',
+ 'attention_mode': 'xformers',
+ 'use_rope': True,
+ 'model_max_length': 300,
+ 'max_height': 320,
+ 'max_width': 240,
+ 'num_frames': 1,
+ 'use_image_num': 0,
+ 'compress_kv_factor': 1,
+ 'interpolation_scale_t': 1,
+ 'interpolation_scale_h': 1,
+ 'interpolation_scale_w': 1,
+ }
+ )
+ b = 16
+ c = 8
+ cond_c = 4096
+ num_timesteps = 1000
+ ae_stride_t, ae_stride_h, ae_stride_w = ae_stride_config[args.ae]
+ latent_size = (args.max_height // ae_stride_h, args.max_width // ae_stride_w)
+ num_frames = (args.num_frames - 1) // ae_stride_t + 1
+
+ device = torch.device('cuda:0')
+ model = OpenSoraT2V_ROPE_L_122(in_channels=c,
+ out_channels=c,
+ sample_size=latent_size,
+ sample_size_t=num_frames,
+ activation_fn="gelu-approximate",
+ attention_bias=True,
+ attention_type="default",
+ double_self_attention=False,
+ norm_elementwise_affine=False,
+ norm_eps=1e-06,
+ norm_num_groups=32,
+ num_vector_embeds=None,
+ only_cross_attention=False,
+ upcast_attention=False,
+ use_linear_projection=False,
+ use_additional_conditions=False,
+ downsampler=None,
+ interpolation_scale_t=args.interpolation_scale_t,
+ interpolation_scale_h=args.interpolation_scale_h,
+ interpolation_scale_w=args.interpolation_scale_w,
+ use_rope=args.use_rope,
+ ).to(device)
+
+ try:
+ path = "PixArt-Alpha-XL-2-512.safetensors"
+ from safetensors.torch import load_file as safe_load
+ ckpt = safe_load(path, device="cpu")
+ # import ipdb;ipdb.set_trace()
+ if ckpt['pos_embed.proj.weight'].shape != model.pos_embed.proj.weight.shape and ckpt['pos_embed.proj.weight'].ndim == 4:
+ repeat = model.pos_embed.proj.weight.shape[2]
+ ckpt['pos_embed.proj.weight'] = ckpt['pos_embed.proj.weight'].unsqueeze(2).repeat(1, 1, repeat, 1, 1) / float(repeat)
+ del ckpt['proj_out.weight'], ckpt['proj_out.bias']
+ msg = model.load_state_dict(ckpt, strict=False)
+ print(msg)
+ except Exception as e:
+ print(e)
+ print(model)
+ print(f'{sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e9} B')
+ # import sys;sys.exit()
+ x = torch.randn(b, c, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w).to(device)
+ cond = torch.randn(b, 1+args.use_image_num, args.model_max_length, cond_c).to(device)
+ attn_mask = torch.randint(0, 2, (b, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w)).to(device) # B L or B 1+num_images L
+ cond_mask = torch.randint(0, 2, (b, 1+args.use_image_num, args.model_max_length)).to(device) # B L or B 1+num_images L
+ timestep = torch.randint(0, 1000, (b,), device=device)
+ model_kwargs = dict(hidden_states=x, encoder_hidden_states=cond, attention_mask=attn_mask,
+ encoder_attention_mask=cond_mask, use_image_num=args.use_image_num, timestep=timestep)
+ with torch.no_grad():
+ output = model(**model_kwargs)
+ print(output[0].shape)
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora_2.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora_2.py
new file mode 100644
index 0000000000000000000000000000000000000000..f316567fd8f3dfb3ce42ab01d01700f607613408
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modeling_opensora_2.py
@@ -0,0 +1,754 @@
+import os
+import numpy as np
+from torch import nn
+import torch
+from einops import rearrange, repeat
+from typing import Any, Dict, Optional, Tuple
+from torch.nn import functional as F
+#from diffusers.models.transformer_2d import Transformer2DModelOutput
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+from diffusers.utils import is_torch_version, deprecate
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.normalization import AdaLayerNormSingle
+from diffusers.models.embeddings import PixArtAlphaTextProjection
+from opensora.models.diffusion.opensora.modules import OverlapPatchEmbed3D, OverlapPatchEmbed2D, PatchEmbed2D, BasicTransformerBlock
+from opensora.utils.utils import to_2tuple
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+ from opensora.acceleration.parallel_states import get_sequence_parallel_state, hccl_info
+except:
+ torch_npu = None
+ npu_config = None
+ from opensora.utils.parallel_states import get_sequence_parallel_state, nccl_info
+
+class OpenSoraT2V(ModelMixin, ConfigMixin):
+ """
+ A 2D Transformer model for image-like data.
+
+ Parameters:
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
+ in_channels (`int`, *optional*):
+ The number of channels in the input and output (specify if the input is **continuous**).
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
+ This is fixed during training since it is used to learn a number of position embeddings.
+ num_vector_embeds (`int`, *optional*):
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
+ Includes the class for the masked latent pixel.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
+ num_embeds_ada_norm ( `int`, *optional*):
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
+ added to the hidden states.
+
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
+ attention_bias (`bool`, *optional*):
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 16,
+ attention_head_dim: int = 88,
+ in_channels: Optional[int] = None,
+ out_channels: Optional[int] = None,
+ num_layers: int = 1,
+ dropout: float = 0.0,
+ norm_num_groups: int = 32,
+ cross_attention_dim: Optional[int] = None,
+ attention_bias: bool = False,
+ sample_size: Optional[int] = None,
+ sample_size_t: Optional[int] = None,
+ num_vector_embeds: Optional[int] = None,
+ patch_size: Optional[int] = None,
+ patch_size_t: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ use_linear_projection: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ attention_type: str = "default",
+ caption_channels: int = None,
+ interpolation_scale_h: float = None,
+ interpolation_scale_w: float = None,
+ interpolation_scale_t: float = None,
+ use_additional_conditions: Optional[bool] = None,
+ attention_mode: str = 'xformers',
+ downsampler: str = None,
+ use_rope: bool = False,
+ use_stable_fp32: bool = False,
+ ):
+ super().__init__()
+
+ # Validate inputs.
+ if patch_size is not None:
+ if norm_type not in ["ada_norm", "ada_norm_zero", "ada_norm_single"]:
+ raise NotImplementedError(
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
+ )
+ elif norm_type in ["ada_norm", "ada_norm_zero"] and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
+ )
+
+ # Set some common variables used across the board.
+ self.use_rope = use_rope
+ self.use_linear_projection = use_linear_projection
+ self.interpolation_scale_t = interpolation_scale_t
+ self.interpolation_scale_h = interpolation_scale_h
+ self.interpolation_scale_w = interpolation_scale_w
+ self.downsampler = downsampler
+ self.caption_channels = caption_channels
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_dim = attention_head_dim
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.gradient_checkpointing = False
+ self.config.hidden_size = self.inner_dim
+ use_additional_conditions = False
+ # if use_additional_conditions is None:
+ # if norm_type == "ada_norm_single" and sample_size == 128:
+ # use_additional_conditions = True
+ # else:
+ # use_additional_conditions = False
+ self.use_additional_conditions = use_additional_conditions
+
+ # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
+ # Define whether input is continuous or discrete depending on configuration
+ assert in_channels is not None and patch_size is not None
+
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
+ deprecation_message = (
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
+ " incorrectly set to `'layer_norm'`. Make sure to set `norm_type` to `'ada_norm'` in the config."
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
+ )
+ deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
+ norm_type = "ada_norm"
+
+ # 2. Initialize the right blocks.
+ # Initialize the output blocks and other projection blocks when necessary.
+ self._init_patched_inputs(norm_type=norm_type)
+
+ def _init_patched_inputs(self, norm_type):
+ assert self.config.sample_size_t is not None, "OpenSoraT2V over patched input must provide sample_size_t"
+ assert self.config.sample_size is not None, "OpenSoraT2V over patched input must provide sample_size"
+ #assert not (self.config.sample_size_t == 1 and self.config.patch_size_t == 2), "Image do not need patchfy in t-dim"
+
+ self.num_frames = self.config.sample_size_t
+ self.config.sample_size = to_2tuple(self.config.sample_size)
+ self.height = self.config.sample_size[0]
+ self.width = self.config.sample_size[1]
+ self.patch_size_t = self.config.patch_size_t
+ self.patch_size = self.config.patch_size
+ interpolation_scale_t = ((self.config.sample_size_t - 1) // 16 + 1) if self.config.sample_size_t % 2 == 1 else self.config.sample_size_t / 16
+ interpolation_scale_t = (
+ self.config.interpolation_scale_t if self.config.interpolation_scale_t is not None else interpolation_scale_t
+ )
+ interpolation_scale = (
+ self.config.interpolation_scale_h if self.config.interpolation_scale_h is not None else self.config.sample_size[0] / 30,
+ self.config.interpolation_scale_w if self.config.interpolation_scale_w is not None else self.config.sample_size[1] / 40,
+ )
+ # if self.config.sample_size_t > 1:
+ # self.pos_embed = PatchEmbed3D(
+ # num_frames=self.config.sample_size_t,
+ # height=self.config.sample_size[0],
+ # width=self.config.sample_size[1],
+ # patch_size_t=self.config.patch_size_t,
+ # patch_size=self.config.patch_size,
+ # in_channels=self.in_channels,
+ # embed_dim=self.inner_dim,
+ # interpolation_scale=interpolation_scale,
+ # interpolation_scale_t=interpolation_scale_t,
+ # )
+ # else:
+ if self.config.downsampler is not None and len(self.config.downsampler) == 9:
+ self.pos_embed = OverlapPatchEmbed3D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+ elif self.config.downsampler is not None and len(self.config.downsampler) == 7:
+ self.pos_embed = OverlapPatchEmbed2D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+
+ else:
+ self.pos_embed = PatchEmbed2D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+ interpolation_scale_thw = (interpolation_scale_t, *interpolation_scale)
+ self.transformer_blocks = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.config.cross_attention_dim,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ downsampler=self.config.downsampler,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.num_layers)
+ ]
+ )
+
+ if self.config.norm_type != "ada_norm_single":
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
+ self.proj_out_2 = nn.Linear(
+ self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+ elif self.config.norm_type == "ada_norm_single":
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
+ self.proj_out = nn.Linear(
+ self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+
+ # PixArt-Alpha blocks.
+ self.adaln_single = None
+ if self.config.norm_type == "ada_norm_single":
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
+ # additional conditions until we find better name
+ self.adaln_single = AdaLayerNormSingle(
+ self.inner_dim, use_additional_conditions=self.use_additional_conditions
+ )
+
+ self.caption_projection = None
+ if self.caption_channels is not None:
+ self.caption_projection = PixArtAlphaTextProjection(
+ in_features=self.caption_channels, hidden_size=self.inner_dim
+ )
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ use_image_num: Optional[int] = 0,
+ return_dict: bool = True,
+ ):
+ """
+ The [`Transformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
+ Input `hidden_states`.
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
+ self-attention.
+ timestep ( `torch.LongTensor`, *optional*):
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
+ `AdaLayerZeroNorm`.
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ attention_mask ( `torch.Tensor`, *optional*):
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
+ negative values to the attention scores corresponding to "discard" tokens.
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
+
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
+
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
+ above. This bias will be added to the cross-attention scores.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ batch_size, c, frame, h, w = hidden_states.shape # [16, 4, 8, 60, 80]
+ # print('hidden_states.shape', hidden_states.shape)
+ frame = frame - use_image_num # 21-4=17
+ if cross_attention_kwargs is not None:
+ if cross_attention_kwargs.get("scale", None) is not None:
+ print.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
+ # expects mask of shape:
+ # [batch, key_tokens]
+ # adds singleton query_tokens dimension:
+ # [batch, 1, key_tokens]
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
+ attention_mask_vid, attention_mask_img = None, None
+ if attention_mask is not None and attention_mask.ndim == 4:
+ # assume that mask is expressed as:
+ # (1 = keep, 0 = discard)
+ # convert mask into a bias that can be added to attention scores:
+ # (keep = +0, discard = -10000.0)
+ # b, frame+use_image_num, h, w -> a video with images
+ # b, 1, h, w -> only images
+ attention_mask = attention_mask.to(self.dtype) # [16, 8, 60, 80]nnu
+ if get_sequence_parallel_state():
+ if npu_config is not None:
+ attention_mask_vid = attention_mask[:, :frame * hccl_info.world_size] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame * hccl_info.world_size:] # b, use_image_num, h, w
+ else:
+ # print('before attention_mask.shape', attention_mask.shape)
+ attention_mask_vid = attention_mask[:, :frame * nccl_info.world_size] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame * nccl_info.world_size:] # b, use_image_num, h, w
+ # print('after attention_mask.shape', attention_mask_vid.shape)
+ else:
+ attention_mask_vid = attention_mask[:, :frame] # b, frame, h, w
+ attention_mask_img = attention_mask[:, frame:] # b, use_image_num, h, w
+
+ if attention_mask_vid.numel() > 0:
+ attention_mask_vid_first_frame = attention_mask_vid[:, :1].repeat(1, self.patch_size_t-1, 1, 1)
+ attention_mask_vid = torch.cat([attention_mask_vid_first_frame, attention_mask_vid], dim=1)
+ attention_mask_vid = attention_mask_vid.unsqueeze(1) # b 1 t h w
+ attention_mask_vid = F.max_pool3d(attention_mask_vid, kernel_size=(self.patch_size_t, self.patch_size, self.patch_size),
+ stride=(self.patch_size_t, self.patch_size, self.patch_size))
+ attention_mask_vid = rearrange(attention_mask_vid, 'b 1 t h w -> (b 1) 1 (t h w)')
+ if attention_mask_img.numel() > 0:
+ attention_mask_img = F.max_pool2d(attention_mask_img, kernel_size=(self.patch_size, self.patch_size), stride=(self.patch_size, self.patch_size))
+ attention_mask_img = rearrange(attention_mask_img, 'b i h w -> (b i) 1 (h w)')
+
+ attention_mask_vid = (1 - attention_mask_vid.bool().to(self.dtype)) * -10000.0 if attention_mask_vid.numel() > 0 else None
+ attention_mask_img = (1 - attention_mask_img.bool().to(self.dtype)) * -10000.0 if attention_mask_img.numel() > 0 else None
+
+ if frame == 1 and use_image_num == 0 and not get_sequence_parallel_state():
+ attention_mask_img = attention_mask_vid
+ attention_mask_vid = None
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
+ # import ipdb;ipdb.set_trace()
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 3:
+ # b, 1+use_image_num, l -> a video with images
+ # b, 1, l -> only images
+ encoder_attention_mask = (1 - encoder_attention_mask.to(self.dtype)) * -10000.0
+ in_t = encoder_attention_mask.shape[1]
+ encoder_attention_mask_vid = encoder_attention_mask[:, :in_t-use_image_num] # b, 1, l
+ encoder_attention_mask_vid = rearrange(encoder_attention_mask_vid, 'b 1 l -> (b 1) 1 l') if encoder_attention_mask_vid.numel() > 0 else None
+
+ encoder_attention_mask_img = encoder_attention_mask[:, in_t-use_image_num:] # b, use_image_num, l
+ encoder_attention_mask_img = rearrange(encoder_attention_mask_img, 'b i l -> (b i) 1 l') if encoder_attention_mask_img.numel() > 0 else None
+
+ if frame == 1 and use_image_num == 0 and not get_sequence_parallel_state():
+ encoder_attention_mask_img = encoder_attention_mask_vid
+ encoder_attention_mask_vid = None
+
+ if npu_config is not None and attention_mask_vid is not None:
+ attention_mask_vid = npu_config.get_attention_mask(attention_mask_vid, attention_mask_vid.shape[-1])
+ encoder_attention_mask_vid = npu_config.get_attention_mask(encoder_attention_mask_vid,
+ attention_mask_vid.shape[-2])
+ if npu_config is not None and attention_mask_img is not None:
+ attention_mask_img = npu_config.get_attention_mask(attention_mask_img, attention_mask_img.shape[-1])
+ encoder_attention_mask_img = npu_config.get_attention_mask(encoder_attention_mask_img,
+ attention_mask_img.shape[-2])
+
+
+ # 1. Input
+ frame = ((frame - 1) // self.patch_size_t + 1) if frame % 2 == 1 else frame // self.patch_size_t # patchfy
+ # print('frame', frame)
+ height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
+
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
+ hidden_states_vid, hidden_states_img, encoder_hidden_states_vid, encoder_hidden_states_img, \
+ timestep_vid, timestep_img, embedded_timestep_vid, embedded_timestep_img = self._operate_on_patched_inputs(
+ hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num
+ ) # hidden_states_vid[16, 9600, 2880]其中2880是dim,9600=8x30x40是序列长度
+ # 2. Blocks
+ # import ipdb;ipdb.set_trace()
+ if get_sequence_parallel_state():
+ if hidden_states_vid is not None:
+ # print(333333333333333)
+ hidden_states_vid = rearrange(hidden_states_vid, 'b s h -> s b h', b=batch_size).contiguous()
+ encoder_hidden_states_vid = rearrange(encoder_hidden_states_vid, 'b s h -> s b h',
+ b=batch_size).contiguous()
+ timestep_vid = timestep_vid.view(batch_size, 6, -1).transpose(0, 1).contiguous()
+ # print('timestep_vid', timestep_vid.shape)
+
+
+ for block in self.transformer_blocks:
+ if self.training and self.gradient_checkpointing:
+
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ # import ipdb;ipdb.set_trace()
+ if hidden_states_vid is not None:
+ hidden_states_vid = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states_vid,
+ attention_mask_vid,
+ encoder_hidden_states_vid,
+ encoder_attention_mask_vid,
+ timestep_vid,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ # import ipdb;ipdb.set_trace()
+ if hidden_states_img is not None:
+ hidden_states_img = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ hidden_states_img,
+ attention_mask_img,
+ encoder_hidden_states_img,
+ encoder_attention_mask_img,
+ timestep_img,
+ cross_attention_kwargs,
+ class_labels,
+ 1,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ if hidden_states_vid is not None:
+ hidden_states_vid = block( # hidden_states_vid[16,9600,2880]输入和输出一致
+ hidden_states_vid,
+ attention_mask=attention_mask_vid,
+ encoder_hidden_states=encoder_hidden_states_vid,
+ encoder_attention_mask=encoder_attention_mask_vid,
+ timestep=timestep_vid,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+ if hidden_states_img is not None:
+ hidden_states_img = block(
+ hidden_states_img,
+ attention_mask=attention_mask_img,
+ encoder_hidden_states=encoder_hidden_states_img,
+ encoder_attention_mask=encoder_attention_mask_img,
+ timestep=timestep_img,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=1,
+ height=height,
+ width=width,
+ )
+
+ if get_sequence_parallel_state():
+ if hidden_states_vid is not None:
+ hidden_states_vid = rearrange(hidden_states_vid, 's b h -> b s h', b=batch_size).contiguous()
+
+ # 3. Output
+ output_vid, output_img = None, None
+ if hidden_states_vid is not None:
+ output_vid = self._get_output_for_patched_inputs( # output_vid[16, 4, 8, 60, 80]
+ hidden_states=hidden_states_vid,
+ timestep=timestep_vid,
+ class_labels=class_labels,
+ embedded_timestep=embedded_timestep_vid,
+ num_frames=frame,
+ height=height,
+ width=width,
+ ) # b c t h w
+ if hidden_states_img is not None:
+ output_img = self._get_output_for_patched_inputs(
+ hidden_states=hidden_states_img,
+ timestep=timestep_img,
+ class_labels=class_labels,
+ embedded_timestep=embedded_timestep_img,
+ num_frames=1,
+ height=height,
+ width=width,
+ ) # b c 1 h w
+ if use_image_num != 0:
+ output_img = rearrange(output_img, '(b i) c 1 h w -> b c i h w', i=use_image_num)
+
+ if output_vid is not None and output_img is not None:
+ output = torch.cat([output_vid, output_img], dim=2)
+ elif output_vid is not None:
+ output = output_vid
+ elif output_img is not None:
+ output = output_img
+
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
+
+
+ def _operate_on_patched_inputs(self, hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num):
+ # batch_size = hidden_states.shape[0]
+ hidden_states_vid, hidden_states_img = self.pos_embed(hidden_states.to(self.dtype), frame)
+ timestep_vid, timestep_img = None, None
+ embedded_timestep_vid, embedded_timestep_img = None, None
+ encoder_hidden_states_vid, encoder_hidden_states_img = None, None
+
+ if self.adaln_single is not None:
+ if self.use_additional_conditions and added_cond_kwargs is None:
+ raise ValueError(
+ "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
+ )
+ timestep, embedded_timestep = self.adaln_single(
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=self.dtype
+ ) # b 6d, b d
+ if hidden_states_vid is None:
+ timestep_img = timestep
+ embedded_timestep_img = embedded_timestep
+ else:
+ timestep_vid = timestep
+ embedded_timestep_vid = embedded_timestep
+ if hidden_states_img is not None:
+ timestep_img = repeat(timestep, 'b d -> (b i) d', i=use_image_num).contiguous()
+ embedded_timestep_img = repeat(embedded_timestep, 'b d -> (b i) d', i=use_image_num).contiguous()
+
+ if self.caption_projection is not None:
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states) # b, 1+use_image_num, l, d or b, 1, l, d
+ if hidden_states_vid is None:
+ encoder_hidden_states_img = rearrange(encoder_hidden_states, 'b 1 l d -> (b 1) l d')
+ else:
+ encoder_hidden_states_vid = rearrange(encoder_hidden_states[:, :1], 'b 1 l d -> (b 1) l d')
+ if hidden_states_img is not None:
+ encoder_hidden_states_img = rearrange(encoder_hidden_states[:, 1:], 'b i l d -> (b i) l d')
+
+
+ return hidden_states_vid, hidden_states_img, encoder_hidden_states_vid, encoder_hidden_states_img, timestep_vid, timestep_img, embedded_timestep_vid, embedded_timestep_img
+
+
+
+ def _get_output_for_patched_inputs(
+ self, hidden_states, timestep, class_labels, embedded_timestep, num_frames, height=None, width=None
+ ):
+ # import ipdb;ipdb.set_trace()
+ if self.config.norm_type != "ada_norm_single":
+ conditioning = self.transformer_blocks[0].norm1.emb(
+ timestep, class_labels, hidden_dtype=self.dtype
+ )
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
+ hidden_states = self.proj_out_2(hidden_states)
+ elif self.config.norm_type == "ada_norm_single":
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states)
+ # Modulation
+ hidden_states = hidden_states * (1 + scale) + shift
+ hidden_states = self.proj_out(hidden_states)
+ hidden_states = hidden_states.squeeze(1)
+
+ # unpatchify
+ if self.adaln_single is None:
+ height = width = int(hidden_states.shape[1] ** 0.5)
+ hidden_states = hidden_states.reshape(
+ shape=(-1, num_frames, height, width, self.patch_size_t, self.patch_size, self.patch_size, self.out_channels)
+ )
+ hidden_states = torch.einsum("nthwopqc->nctohpwq", hidden_states)
+ output = hidden_states.reshape(
+ shape=(-1, self.out_channels, num_frames * self.patch_size_t, height * self.patch_size, width * self.patch_size)
+ )
+ # import ipdb;ipdb.set_trace()
+ # if output.shape[2] % 2 == 0:
+ # output = output[:, :, 1:]
+ return output
+
+def OpenSoraT2V_S_122(**kwargs):
+ return OpenSoraT2V(num_layers=28, attention_head_dim=96, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=1536, **kwargs)
+
+def OpenSoraT2V_B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=96, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=1920, **kwargs)
+
+def OpenSoraT2V_L_122(**kwargs):
+ return OpenSoraT2V(num_layers=40, attention_head_dim=128, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2048, **kwargs)
+
+def OpenSoraT2V_ROPE_L_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=96, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2304, **kwargs)
+
+def OpenSoraT2V_ROPE_L_4B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=120, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2880, **kwargs)
+
+def OpenSoraT2V_ROPE_L_5B_122(**kwargs):
+ return OpenSoraT2V(num_layers=40, attention_head_dim=120, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=2880, **kwargs)
+
+def OpenSoraT2V_ROPE_L_6B_122(**kwargs):
+ return OpenSoraT2V(num_layers=32, attention_head_dim=144, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ norm_type="ada_norm_single", caption_channels=4096, cross_attention_dim=3456, **kwargs)
+
+OpenSora_models = {
+ "OpenSoraT2V-S/122": OpenSoraT2V_S_122, # 1.1B
+ "OpenSoraT2V-B/122": OpenSoraT2V_B_122, # 1.27B
+ "OpenSoraT2V-L/122": OpenSoraT2V_L_122, # 2.7B
+ "OpenSoraT2V-ROPE-L/122": OpenSoraT2V_ROPE_L_122, # 2.7B
+ "OpenSoraT2V-ROPE-L-4B/122": OpenSoraT2V_ROPE_L_4B_122, # 4.32B
+ "OpenSoraT2V-ROPE-L-5B/122": OpenSoraT2V_ROPE_L_5B_122, # 5.38B
+ "OpenSoraT2V-ROPE-L-6B/122": OpenSoraT2V_ROPE_L_6B_122, # 6.22B
+}
+
+OpenSora_models_class = {
+ "OpenSoraT2V-S/122": OpenSoraT2V,
+ "OpenSoraT2V-B/122": OpenSoraT2V,
+ "OpenSoraT2V-L/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-4B/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-5B/122": OpenSoraT2V,
+ "OpenSoraT2V-ROPE-L-6B/122": OpenSoraT2V,
+}
+
+if __name__ == '__main__':
+ from opensora.models.causalvideovae import ae_channel_config, ae_stride_config
+ # from opensora.models.causalvideovae import getae, getae_wrapper
+ # from opensora.models.causalvideovae import CausalVAEModelWrapper
+
+ args = type('args', (),
+ {
+ 'ae': 'CausalVAEModel_D4_4x8x8',
+ 'attention_mode': 'xformers',
+ 'use_rope': True,
+ 'model_max_length': 512,
+ 'max_height': 480,
+ 'max_width': 640,
+ 'num_frames': 29,
+ 'use_image_num': 0,
+ 'compress_kv_factor': 1,
+ 'interpolation_scale_t': 1,
+ 'interpolation_scale_h': 1,
+ 'interpolation_scale_w': 1,
+ }
+ )
+ b = 16
+ c = 4
+ cond_c = 4096
+ num_timesteps = 1000
+ ae_stride_t, ae_stride_h, ae_stride_w = ae_stride_config[args.ae] # 4, 8, 8
+ latent_size = (args.max_height // ae_stride_h, args.max_width // ae_stride_w)
+ num_frames = (args.num_frames - 1) // ae_stride_t + 1 # 8
+
+ device = torch.device('cuda:0')
+ # model = OpenSoraT2V_ROPE_L_122(in_channels=c,
+ model = OpenSoraT2V_ROPE_L_5B_122(in_channels=c,
+ out_channels=c,
+ sample_size=latent_size,
+ sample_size_t=num_frames,
+ activation_fn="gelu-approximate",
+ attention_bias=True,
+ attention_type="default",
+ double_self_attention=False,
+ norm_elementwise_affine=False,
+ norm_eps=1e-06,
+ norm_num_groups=32,
+ num_vector_embeds=None,
+ only_cross_attention=False,
+ upcast_attention=False,
+ use_linear_projection=False,
+ use_additional_conditions=False,
+ downsampler=None,
+ interpolation_scale_t=args.interpolation_scale_t,
+ interpolation_scale_h=args.interpolation_scale_h,
+ interpolation_scale_w=args.interpolation_scale_w,
+ use_rope=args.use_rope,
+ ).to(device)
+
+ try:
+ path = "PixArt-Alpha-XL-2-512.safetensors"
+ from safetensors.torch import load_file as safe_load
+ ckpt = safe_load(path, device="cpu")
+ # import ipdb;ipdb.set_trace()
+ if ckpt['pos_embed.proj.weight'].shape != model.pos_embed.proj.weight.shape and ckpt['pos_embed.proj.weight'].ndim == 4:
+ repeat = model.pos_embed.proj.weight.shape[2]
+ ckpt['pos_embed.proj.weight'] = ckpt['pos_embed.proj.weight'].unsqueeze(2).repeat(1, 1, repeat, 1, 1) / float(repeat)
+ del ckpt['proj_out.weight'], ckpt['proj_out.bias']
+ msg = model.load_state_dict(ckpt, strict=False)
+ print(msg)
+ except Exception as e:
+ print(e)
+ print(model)
+ print(f'{sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e9} B')
+ # import sys;sys.exit()
+ x = torch.randn(b, c, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w).to(device)
+ cond = torch.randn(b, 1+args.use_image_num, args.model_max_length, cond_c).to(device)
+ attn_mask = torch.randint(0, 2, (b, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w)).to(device) # B L or B 1+num_images L
+ cond_mask = torch.randint(0, 2, (b, 1+args.use_image_num, args.model_max_length)).to(device) # B L or B 1+num_images L
+ timestep = torch.randint(0, 1000, (b,), device=device)
+ model_kwargs = dict(hidden_states=x, encoder_hidden_states=cond, attention_mask=attn_mask,
+ encoder_attention_mask=cond_mask, use_image_num=args.use_image_num, timestep=timestep)
+ with torch.no_grad():
+ output = model(**model_kwargs)
+ print(output[0].shape)
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modules.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc7a17d658b0a40a09427fb7a1b966efb1f9ca36
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/modules.py
@@ -0,0 +1,1379 @@
+from einops import rearrange
+from torch import nn
+import torch
+import numpy as np
+
+from einops import rearrange, repeat
+from typing import Any, Dict, Optional, Tuple
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from typing import Any, Dict, Optional
+import re
+import torch
+import torch.nn.functional as F
+from torch import nn
+import diffusers
+from diffusers.utils import deprecate, logging
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.attention import FeedForward, GatedSelfAttentionDense
+from diffusers.models.attention_processor import Attention as Attention_
+from diffusers.models.embeddings import SinusoidalPositionalEmbedding
+from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
+from .rope import PositionGetter3D, RoPE3D
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config, set_run_dtype
+ from opensora.acceleration.parallel_states import get_sequence_parallel_state, hccl_info
+ from opensora.acceleration.communications import all_to_all_SBH
+except:
+ torch_npu = None
+ npu_config = None
+ set_run_dtype = None
+ from opensora.utils.parallel_states import get_sequence_parallel_state, nccl_info
+ from opensora.utils.communications import all_to_all_SBH
+logger = logging.get_logger(__name__)
+
+def get_3d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+ grid_t = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size[0]) / interpolation_scale[0]
+ grid_h = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size[1]) / interpolation_scale[1]
+ grid_w = np.arange(grid_size[2], dtype=np.float32) / (grid_size[2] / base_size[2]) / interpolation_scale[2]
+ grid = np.meshgrid(grid_w, grid_h, grid_t) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([3, 1, grid_size[2], grid_size[1], grid_size[0]])
+ pos_embed = get_3d_sincos_pos_embed_from_grid(embed_dim, grid)
+ # import ipdb;ipdb.set_trace()
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_3d_sincos_pos_embed_from_grid(embed_dim, grid):
+ if embed_dim % 3 != 0:
+ raise ValueError("embed_dim must be divisible by 3")
+
+ # import ipdb;ipdb.set_trace()
+ # use 1/3 of dimensions to encode grid_t/h/w
+ emb_t = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # (T*H*W, D/3)
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (T*H*W, D/3)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2]) # (T*H*W, D/3)
+
+ emb = np.concatenate([emb_t, emb_h, emb_w], axis=1) # (T*H*W, D)
+ return emb
+
+
+def get_2d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size[0]) / interpolation_scale[0]
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size[1]) / interpolation_scale[1]
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ # use 1/3 of dimensions to encode grid_t/h/w
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
+ return emb
+
+def get_1d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid return: pos_embed: [grid_size, embed_dim] or
+ [1+grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+
+ grid = np.arange(grid_size, dtype=np.float32) / (grid_size / base_size) / interpolation_scale
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid) # (H*W, D/2)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
+ """
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
+ """
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
+
+ emb_sin = np.sin(out) # (M, D/2)
+ emb_cos = np.cos(out) # (M, D/2)
+
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
+ return emb
+
+
+class PatchEmbed2D(nn.Module):
+ """2D Image to Patch Embedding but with 3D position embedding"""
+
+ def __init__(
+ self,
+ num_frames=1,
+ height=224,
+ width=224,
+ patch_size_t=1,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=(1, 1),
+ interpolation_scale_t=1,
+ use_abs_pos=True, #这个是False
+ ):
+ super().__init__()
+ # assert num_frames == 1
+ self.use_abs_pos = use_abs_pos
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size_t = patch_size_t
+ self.patch_size = patch_size
+ # See:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
+
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = (height // patch_size, width // patch_size)
+ self.interpolation_scale = (interpolation_scale[0], interpolation_scale[1])
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, (self.height, self.width), base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False) #persistent=False,不会在ckpt中被保留,因此每次都是全新的
+
+ self.num_frames = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.base_size_t = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.interpolation_scale_t = interpolation_scale_t
+ temp_pos_embed = get_1d_sincos_pos_embed(embed_dim, self.num_frames, base_size=self.base_size_t, interpolation_scale=self.interpolation_scale_t)
+ self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
+ # self.temp_embed_gate = nn.Parameter(torch.tensor([0.0]))
+
+ def forward(self, latent, num_frames):
+ b, _, _, _, _ = latent.shape
+ video_latent, image_latent = None, None
+ # b c 1 h w
+ # assert latent.shape[-3] == 1 and num_frames == 1
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ latent = rearrange(latent, 'b c t h w -> (b t) c h w')
+ latent = self.proj(latent)
+
+ if self.flatten:
+ latent = latent.flatten(2).transpose(1, 2) # BT C H W -> BT N C
+ if self.layer_norm:
+ latent = self.norm(latent)
+
+ if self.use_abs_pos: #不会走这里,应该是使用了ROPE
+ # Interpolate positional embeddings if needed.
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
+ if self.height != height or self.width != width:
+ # raise NotImplementedError
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed)
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+
+ if self.num_frames != num_frames:
+ # import ipdb;ipdb.set_trace()
+ # raise NotImplementedError
+ if get_sequence_parallel_state():
+ if npu_config is not None:
+ sp_size = hccl_info.world_size
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames * sp_size,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ rank = hccl_info.rank % sp_size
+ st_frame = rank * num_frames
+ ed_frame = st_frame + num_frames
+ temp_pos_embed = temp_pos_embed[st_frame: ed_frame]
+ else:
+ sp_size = nccl_info.world_size
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames * sp_size,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ rank = nccl_info.rank % sp_size
+ st_frame = rank * num_frames
+ ed_frame = st_frame + num_frames
+ temp_pos_embed = temp_pos_embed[st_frame: ed_frame]
+
+ else:
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ temp_pos_embed = torch.from_numpy(temp_pos_embed)
+ temp_pos_embed = temp_pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ temp_pos_embed = self.temp_pos_embed
+
+ latent = (latent + pos_embed).to(latent.dtype)
+
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=b)
+ video_latent, image_latent = latent[:, :num_frames], latent[:, num_frames:]
+
+ if self.use_abs_pos:
+ # temp_pos_embed = temp_pos_embed.unsqueeze(2) * self.temp_embed_gate.tanh()
+ temp_pos_embed = temp_pos_embed.unsqueeze(2)
+ video_latent = (video_latent + temp_pos_embed).to(video_latent.dtype) if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = (image_latent + temp_pos_embed[:, :1]).to(image_latent.dtype) if image_latent is not None and image_latent.numel() > 0 else None
+
+ video_latent = rearrange(video_latent, 'b t n c -> b (t n) c') if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = rearrange(image_latent, 'b t n c -> (b t) n c') if image_latent is not None and image_latent.numel() > 0 else None
+
+ if num_frames == 1 and image_latent is None and not get_sequence_parallel_state():
+ image_latent = video_latent
+ video_latent = None
+ # print('video_latent is None, image_latent is None', video_latent is None, image_latent is None)
+ return video_latent, image_latent
+
+
+
+class OverlapPatchEmbed3D(nn.Module):
+ """2D Image to Patch Embedding but with 3D position embedding"""
+
+ def __init__(
+ self,
+ num_frames=1,
+ height=224,
+ width=224,
+ patch_size_t=1,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=(1, 1),
+ interpolation_scale_t=1,
+ use_abs_pos=True,
+ ):
+ super().__init__()
+ # assert patch_size_t == 1 and patch_size == 1
+ self.use_abs_pos = use_abs_pos
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+
+ self.proj = nn.Conv3d(
+ in_channels, embed_dim, kernel_size=(patch_size_t, patch_size, patch_size), stride=(patch_size_t, patch_size, patch_size), bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size_t = patch_size_t
+ self.patch_size = patch_size
+ # See:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
+
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = (height // patch_size, width // patch_size)
+ self.interpolation_scale = (interpolation_scale[0], interpolation_scale[1])
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, (self.height, self.width), base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
+
+ self.num_frames = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.base_size_t = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.interpolation_scale_t = interpolation_scale_t
+ temp_pos_embed = get_1d_sincos_pos_embed(embed_dim, self.num_frames, base_size=self.base_size_t, interpolation_scale=self.interpolation_scale_t)
+ self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
+ # self.temp_embed_gate = nn.Parameter(torch.tensor([0.0]))
+
+ def forward(self, latent, num_frames):
+ b, _, _, _, _ = latent.shape
+ video_latent, image_latent = None, None
+ # b c 1 h w
+ # assert latent.shape[-3] == 1 and num_frames == 1
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ # latent = rearrange(latent, 'b c t h w -> (b t) c h w')
+ latent = self.proj(latent)
+
+ if self.flatten:
+ # latent = latent.flatten(2).transpose(1, 2) # BT C H W -> BT N C
+ latent = rearrange(latent, 'b c t h w -> (b t) (h w) c ')
+ if self.layer_norm:
+ latent = self.norm(latent)
+
+ if self.use_abs_pos:
+ # Interpolate positional embeddings if needed.
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
+ if self.height != height or self.width != width:
+ # raise NotImplementedError
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed)
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+
+ if self.num_frames != num_frames:
+ # import ipdb;ipdb.set_trace()
+ # raise NotImplementedError
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ temp_pos_embed = torch.from_numpy(temp_pos_embed)
+ temp_pos_embed = temp_pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ temp_pos_embed = self.temp_pos_embed
+
+ latent = (latent + pos_embed).to(latent.dtype)
+
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=b)
+ video_latent, image_latent = latent[:, :num_frames], latent[:, num_frames:]
+
+ if self.use_abs_pos:
+ # temp_pos_embed = temp_pos_embed.unsqueeze(2) * self.temp_embed_gate.tanh()
+ temp_pos_embed = temp_pos_embed.unsqueeze(2)
+ video_latent = (video_latent + temp_pos_embed).to(video_latent.dtype) if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = (image_latent + temp_pos_embed[:, :1]).to(image_latent.dtype) if image_latent is not None and image_latent.numel() > 0 else None
+
+
+ video_latent = rearrange(video_latent, 'b t n c -> b (t n) c') if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = rearrange(image_latent, 'b t n c -> (b t) n c') if image_latent is not None and image_latent.numel() > 0 else None
+
+ if num_frames == 1 and image_latent is None:
+ image_latent = video_latent
+ video_latent = None
+ return video_latent, image_latent
+
+
+
+class OverlapPatchEmbed2D(nn.Module):
+ """2D Image to Patch Embedding but with 3D position embedding"""
+
+ def __init__(
+ self,
+ num_frames=1,
+ height=224,
+ width=224,
+ patch_size_t=1,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=(1, 1),
+ interpolation_scale_t=1,
+ use_abs_pos=True,
+ ):
+ super().__init__()
+ assert patch_size_t == 1
+ self.use_abs_pos = use_abs_pos
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size_t = patch_size_t
+ self.patch_size = patch_size
+ # See:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
+
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = (height // patch_size, width // patch_size)
+ self.interpolation_scale = (interpolation_scale[0], interpolation_scale[1])
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, (self.height, self.width), base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
+
+ self.num_frames = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.base_size_t = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.interpolation_scale_t = interpolation_scale_t
+ temp_pos_embed = get_1d_sincos_pos_embed(embed_dim, self.num_frames, base_size=self.base_size_t, interpolation_scale=self.interpolation_scale_t)
+ self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
+ # self.temp_embed_gate = nn.Parameter(torch.tensor([0.0]))
+
+ def forward(self, latent, num_frames):
+ b, _, _, _, _ = latent.shape
+ video_latent, image_latent = None, None
+ # b c 1 h w
+ # assert latent.shape[-3] == 1 and num_frames == 1
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ latent = rearrange(latent, 'b c t h w -> (b t) c h w')
+ latent = self.proj(latent)
+
+ if self.flatten:
+ latent = latent.flatten(2).transpose(1, 2) # BT C H W -> BT N C
+ if self.layer_norm:
+ latent = self.norm(latent)
+
+ if self.use_abs_pos:
+ # Interpolate positional embeddings if needed.
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
+ if self.height != height or self.width != width:
+ # raise NotImplementedError
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed)
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+
+ if self.num_frames != num_frames:
+ # import ipdb;ipdb.set_trace()
+ # raise NotImplementedError
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ temp_pos_embed = torch.from_numpy(temp_pos_embed)
+ temp_pos_embed = temp_pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ temp_pos_embed = self.temp_pos_embed
+
+ latent = (latent + pos_embed).to(latent.dtype)
+
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=b)
+ video_latent, image_latent = latent[:, :num_frames], latent[:, num_frames:]
+
+ if self.use_abs_pos:
+ # temp_pos_embed = temp_pos_embed.unsqueeze(2) * self.temp_embed_gate.tanh()
+ temp_pos_embed = temp_pos_embed.unsqueeze(2)
+ video_latent = (video_latent + temp_pos_embed).to(video_latent.dtype) if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = (image_latent + temp_pos_embed[:, :1]).to(image_latent.dtype) if image_latent is not None and image_latent.numel() > 0 else None
+
+
+ video_latent = rearrange(video_latent, 'b t n c -> b (t n) c') if video_latent is not None and video_latent.numel() > 0 else None
+ image_latent = rearrange(image_latent, 'b t n c -> (b t) n c') if image_latent is not None and image_latent.numel() > 0 else None
+
+ if num_frames == 1 and image_latent is None:
+ image_latent = video_latent
+ video_latent = None
+ return video_latent, image_latent
+
+class Attention(Attention_):
+ def __init__(self, downsampler, attention_mode, use_rope, interpolation_scale_thw, **kwags):
+ processor = AttnProcessor2_0(attention_mode=attention_mode, use_rope=use_rope, interpolation_scale_thw=interpolation_scale_thw)
+ super().__init__(processor=processor, **kwags)
+ self.downsampler = None
+ if downsampler: # downsampler k155_s122
+ downsampler_ker_size = list(re.search(r'k(\d{2,3})', downsampler).group(1)) # 122
+ down_factor = list(re.search(r's(\d{2,3})', downsampler).group(1))
+ downsampler_ker_size = [int(i) for i in downsampler_ker_size]
+ downsampler_padding = [(i - 1) // 2 for i in downsampler_ker_size]
+ down_factor = [int(i) for i in down_factor]
+
+ if len(downsampler_ker_size) == 2:
+ self.downsampler = DownSampler2d(kwags['query_dim'], kwags['query_dim'], kernel_size=downsampler_ker_size, stride=1,
+ padding=downsampler_padding, groups=kwags['query_dim'], down_factor=down_factor,
+ down_shortcut=True)
+ elif len(downsampler_ker_size) == 3:
+ self.downsampler = DownSampler3d(kwags['query_dim'], kwags['query_dim'], kernel_size=downsampler_ker_size, stride=1,
+ padding=downsampler_padding, groups=kwags['query_dim'], down_factor=down_factor,
+ down_shortcut=True)
+
+ # self.q_norm = nn.LayerNorm(kwags['dim_head'], elementwise_affine=True, eps=1e-6)
+ # self.k_norm = nn.LayerNorm(kwags['dim_head'], elementwise_affine=True, eps=1e-6)
+
+ def prepare_attention_mask(
+ self, attention_mask: torch.Tensor, target_length: int, batch_size: int, out_dim: int = 3
+ ) -> torch.Tensor:
+ r"""
+ Prepare the attention mask for the attention computation.
+
+ Args:
+ attention_mask (`torch.Tensor`):
+ The attention mask to prepare.
+ target_length (`int`):
+ The target length of the attention mask. This is the length of the attention mask after padding.
+ batch_size (`int`):
+ The batch size, which is used to repeat the attention mask.
+ out_dim (`int`, *optional*, defaults to `3`):
+ The output dimension of the attention mask. Can be either `3` or `4`.
+
+ Returns:
+ `torch.Tensor`: The prepared attention mask.
+ """
+ head_size = self.heads
+ if get_sequence_parallel_state():
+ head_size = head_size // nccl_info.world_size
+ if attention_mask is None:
+ return attention_mask
+
+ current_length: int = attention_mask.shape[-1]
+ if current_length != target_length:
+ if attention_mask.device.type == "mps":
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
+ # Instead, we can manually construct the padding tensor.
+ padding_shape = (attention_mask.shape[0], attention_mask.shape[1], target_length)
+ padding = torch.zeros(padding_shape, dtype=attention_mask.dtype, device=attention_mask.device)
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
+ else:
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
+ # remaining_length: int = target_length - current_length
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
+
+ if out_dim == 3:
+ if attention_mask.shape[0] < batch_size * head_size:
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
+ elif out_dim == 4:
+ attention_mask = attention_mask.unsqueeze(1)
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
+
+ return attention_mask
+
+class DownSampler3d(nn.Module):
+ def __init__(self, *args, **kwargs):
+ ''' Required kwargs: down_factor, downsampler'''
+ super().__init__()
+ self.down_factor = kwargs.pop('down_factor')
+ self.down_shortcut = kwargs.pop('down_shortcut')
+ self.layer = nn.Conv3d(*args, **kwargs)
+
+ def forward(self, x, attention_mask, t, h, w):
+ b = x.shape[0]
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=t, h=h, w=w)
+ if npu_config is None:
+ x = self.layer(x) + (x if self.down_shortcut else 0)
+ else:
+ x_dtype = x.dtype
+ x = npu_config.run_conv3d(self.layer, x, x_dtype) + (x if self.down_shortcut else 0)
+
+ self.t = t//self.down_factor[0]
+ self.h = h//self.down_factor[1]
+ self.w = w//self.down_factor[2]
+ x = rearrange(x, 'b d (t dt) (h dh) (w dw) -> (b dt dh dw) (t h w) d',
+ t=t//self.down_factor[0], h=h//self.down_factor[1], w=w//self.down_factor[2],
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> b 1 t h w', t=t, h=h, w=w)
+ attention_mask = rearrange(attention_mask, 'b 1 (t dt) (h dh) (w dw) -> (b dt dh dw) 1 (t h w)',
+ t=t//self.down_factor[0], h=h//self.down_factor[1], w=w//self.down_factor[2],
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+ return x, attention_mask
+
+ def reverse(self, x, t, h, w):
+ x = rearrange(x, '(b dt dh dw) (t h w) d -> b (t dt h dh w dw) d',
+ t=t, h=h, w=w,
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+ return x
+
+
+class DownSampler2d(nn.Module):
+ def __init__(self, *args, **kwargs):
+ ''' Required kwargs: down_factor, downsampler'''
+ super().__init__()
+ self.down_factor = kwargs.pop('down_factor')
+ self.down_shortcut = kwargs.pop('down_shortcut')
+ self.layer = nn.Conv2d(*args, **kwargs)
+
+ def forward(self, x, attention_mask, t, h, w):
+ b = x.shape[0]
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=t, h=h, w=w)
+ x = self.layer(x) + (x if self.down_shortcut else 0)
+
+ self.t = 1
+ self.h = h//self.down_factor[0]
+ self.w = w//self.down_factor[1]
+
+ x = rearrange(x, 'b d (h dh) (w dw) -> (b dh dw) (h w) d',
+ h=h//self.down_factor[0], w=w//self.down_factor[1],
+ dh=self.down_factor[0], dw=self.down_factor[1])
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> (b t) 1 h w', h=h, w=w)
+ attention_mask = rearrange(attention_mask, 'b 1 (h dh) (w dw) -> (b dh dw) 1 (h w)',
+ h=h//self.down_factor[0], w=w//self.down_factor[1],
+ dh=self.down_factor[0], dw=self.down_factor[1])
+ return x, attention_mask
+
+ def reverse(self, x, t, h, w):
+ x = rearrange(x, '(b t dh dw) (h w) d -> b (t h dh w dw) d',
+ t=t, h=h, w=w,
+ dh=self.down_factor[0], dw=self.down_factor[1])
+ return x
+
+class AttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ """
+
+ def __init__(self, attention_mode='xformers', use_rope=False, interpolation_scale_thw=(1, 1, 1)):
+ self.use_rope = use_rope
+ self.interpolation_scale_thw = interpolation_scale_thw
+ if self.use_rope:
+ self._init_rope(interpolation_scale_thw)
+ self.attention_mode = attention_mode
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+
+ def _init_rope(self, interpolation_scale_thw):
+ self.rope = RoPE3D(interpolation_scale_thw=interpolation_scale_thw)
+ self.position_getter = PositionGetter3D()
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ temb: Optional[torch.FloatTensor] = None,
+ frame: int = 8,
+ height: int = 16,
+ width: int = 16,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+
+ try:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+
+ if attn.downsampler is not None:
+ hidden_states, attention_mask = attn.downsampler(hidden_states, attention_mask, t=frame, h=height, w=width)
+ frame, height, width = attn.downsampler.t, attn.downsampler.h, attn.downsampler.w
+
+ residual = hidden_states
+
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ if input_ndim == 4:
+ batch_size, channel, height, width = hidden_states.shape
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ if get_sequence_parallel_state():
+ if npu_config is not None:
+ sequence_length, batch_size, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+ else:
+ sequence_length, batch_size, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+ else:
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ if npu_config is None:
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ if get_sequence_parallel_state():
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length * nccl_info.world_size, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads // nccl_info.world_size, -1, attention_mask.shape[-1])
+ else:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length * 0, batch_size)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+ else:
+ attention_mask = attention_mask.view(batch_size, 1, -1, attention_mask.shape[-1])
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ if npu_config is not None and npu_config.on_npu:
+ if get_sequence_parallel_state():
+ query = query.view(-1, attn.heads, head_dim) # [s // sp, b, h * d] -> [s // sp * b, h, d]
+ key = key.view(-1, attn.heads, head_dim)
+ value = value.view(-1, attn.heads, head_dim)
+ # query = attn.q_norm(query)
+ # key = attn.k_norm(key)
+ h_size = attn.heads * head_dim
+ sp_size = hccl_info.world_size
+ h_size_sp = h_size // sp_size
+ # apply all_to_all to gather sequence and split attention heads [s // sp * b, h, d] -> [s * b, h // sp, d]
+ query = all_to_all_SBH(query, scatter_dim=1, gather_dim=0).view(-1, batch_size, h_size_sp)
+ key = all_to_all_SBH(key, scatter_dim=1, gather_dim=0).view(-1, batch_size, h_size_sp)
+ value = all_to_all_SBH(value, scatter_dim=1, gather_dim=0).view(-1, batch_size, h_size_sp)
+ if self.use_rope:
+ query = query.view(-1, batch_size, attn.heads // sp_size, head_dim)
+ key = key.view(-1, batch_size, attn.heads // sp_size, head_dim)
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame * sp_size, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+ query = query.view(-1, batch_size, h_size_sp)
+ key = key.view(-1, batch_size, h_size_sp)
+ value = value.view(-1, batch_size, h_size_sp)
+ hidden_states = npu_config.run_attention(query, key, value, attention_mask, "SBH",
+ head_dim, attn.heads // sp_size)
+
+ hidden_states = hidden_states.view(-1, attn.heads // sp_size, head_dim)
+
+ # [s * b, h // sp, d] -> [s // sp * b, h, d] -> [s // sp, b, h * d]
+ hidden_states = all_to_all_SBH(hidden_states, scatter_dim=0, gather_dim=1).view(-1, batch_size, h_size)
+ else:
+ if npu_config.enable_FA and query.dtype == torch.float32:
+ dtype = torch.bfloat16
+ else:
+ dtype = None
+
+ query = query.view(batch_size, -1, attn.heads, head_dim)
+ key = key.view(batch_size, -1, attn.heads, head_dim)
+ # query = attn.q_norm(query)
+ # key = attn.k_norm(key)
+ if self.use_rope:
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+ query = query.view(batch_size, -1, attn.heads * head_dim)
+ key = key.view(batch_size, -1, attn.heads * head_dim)
+
+ with set_run_dtype(query, dtype):
+ query, key, value = npu_config.set_current_run_dtype([query, key, value])
+ hidden_states = npu_config.run_attention(query, key, value, attention_mask, "BSH",
+ head_dim, attn.heads)
+
+ hidden_states = npu_config.restore_dtype(hidden_states)
+ else:
+ if get_sequence_parallel_state():
+ query = query.reshape(-1, attn.heads, head_dim) # [s // sp, b, h * d] -> [s // sp * b, h, d]
+ key = key.reshape(-1, attn.heads, head_dim)
+ value = value.reshape(-1, attn.heads, head_dim)
+ # query = attn.q_norm(query)
+ # key = attn.k_norm(key)
+ h_size = attn.heads * head_dim
+ sp_size = nccl_info.world_size
+ h_size_sp = h_size // sp_size
+ # apply all_to_all to gather sequence and split attention heads [s // sp * b, h, d] -> [s * b, h // sp, d]
+ query = all_to_all_SBH(query, scatter_dim=1, gather_dim=0).reshape(-1, batch_size, h_size_sp)
+ key = all_to_all_SBH(key, scatter_dim=1, gather_dim=0).reshape(-1, batch_size, h_size_sp)
+ value = all_to_all_SBH(value, scatter_dim=1, gather_dim=0).reshape(-1, batch_size, h_size_sp)
+ query = query.reshape(-1, batch_size, attn.heads // sp_size, head_dim)
+ key = key.reshape(-1, batch_size, attn.heads // sp_size, head_dim)
+ value = value.reshape(-1, batch_size, attn.heads // sp_size, head_dim)
+ # print('query', query.shape, 'key', key.shape, 'value', value.shape)
+ if self.use_rope:
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame * sp_size, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+
+ # print('after rope query', query.shape, 'key', key.shape, 'value', value.shape)
+ query = rearrange(query, 's b h d -> b h s d')
+ key = rearrange(key, 's b h d -> b h s d')
+ value = rearrange(value, 's b h d -> b h s d')
+ # print('rearrange query', query.shape, 'key', key.shape, 'value', value.shape)
+
+ # 0, -10000 ->(bool) False, True ->(any) True ->(not) False
+ # 0, 0 ->(bool) False, False ->(any) False ->(not) True
+ if attention_mask is None or not torch.any(attention_mask.bool()): # 0 mean visible
+ attention_mask = None
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ # import ipdb;ipdb.set_trace()
+ # print(attention_mask)
+ if self.attention_mode == 'flash' and attention_mask is None:
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=True, enable_mem_efficient=False):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False
+ )
+ elif (self.attention_mode == 'xformers') or (self.attention_mode == 'flash' and attention_mask is not None):
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ else:
+ raise NotImplementedError(f'Found attention_mode: {self.attention_mode}')
+
+ hidden_states = rearrange(hidden_states, 'b h s d -> s b h d')
+
+ hidden_states = hidden_states.reshape(-1, attn.heads // sp_size, head_dim)
+
+ # [s * b, h // sp, d] -> [s // sp * b, h, d] -> [s // sp, b, h * d]
+ hidden_states = all_to_all_SBH(hidden_states, scatter_dim=0, gather_dim=1).reshape(-1, batch_size, h_size)
+ else:
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) #这里transpse了一下,没问题
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # qk norm
+ # query = attn.q_norm(query)
+ # key = attn.k_norm(key)
+
+ if self.use_rope:
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # 0, -10000 ->(bool) False, True ->(any) True ->(not) False
+ # 0, 0 ->(bool) False, False ->(any) False ->(not) True
+ if attention_mask is None or not torch.any(attention_mask.bool()): # 0 mean visible
+ attention_mask = None
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+ # import ipdb;ipdb.set_trace()
+ # print(attention_mask)
+ if self.attention_mode == 'flash' and attention_mask is None:
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=True, enable_mem_efficient=False):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False
+ )
+ elif self.attention_mode == 'xformers' or (self.attention_mode == 'flash' and attention_mask is not None):
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ else:
+ raise NotImplementedError(f'Found attention_mode: {self.attention_mode}')
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ if attn.downsampler is not None:
+ hidden_states = attn.downsampler.reverse(hidden_states, t=frame, h=height, w=width)
+ return hidden_states
+ except Exception as e:
+ print([hidden_states.shape, encoder_hidden_states.shape, query.shape, key.shape, value.shape, attention_mask.shape])
+ raise Exception(e)
+
+
+
+class FeedForward_Conv3d(nn.Module):
+ def __init__(self, downsampler, dim, hidden_features, bias=True):
+ super(FeedForward_Conv3d, self).__init__()
+
+ self.bias = bias
+
+ self.project_in = nn.Linear(dim, hidden_features, bias=bias)
+
+ self.dwconv = nn.ModuleList([
+ nn.Conv3d(hidden_features, hidden_features, kernel_size=(5, 5, 5), stride=1, padding=(2, 2, 2), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv3d(hidden_features, hidden_features, kernel_size=(3, 3, 3), stride=1, padding=(1, 1, 1), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv3d(hidden_features, hidden_features, kernel_size=(1, 1, 1), stride=1, padding=(0, 0, 0), dilation=1,
+ groups=hidden_features, bias=bias)
+ ])
+
+ self.project_out = nn.Linear(hidden_features, dim, bias=bias)
+
+
+ def forward(self, x, t, h, w):
+ # import ipdb;ipdb.set_trace()
+ if npu_config is None:
+ x = self.project_in(x)
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=t, h=h, w=w)
+ x = F.gelu(x)
+ out = x
+ for module in self.dwconv:
+ out = out + module(x)
+ out = rearrange(out, 'b d t h w -> b (t h w) d', t=t, h=h, w=w)
+ x = self.project_out(out)
+ else:
+ x_dtype = x.dtype
+ x = npu_config.run_conv3d(self.project_in, x, npu_config.replaced_type)
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=t, h=h, w=w)
+ x = F.gelu(x)
+ out = x
+ for module in self.dwconv:
+ out = out + npu_config.run_conv3d(module, x, npu_config.replaced_type)
+ out = rearrange(out, 'b d t h w -> b (t h w) d', t=t, h=h, w=w)
+ x = npu_config.run_conv3d(self.project_out, out, x_dtype)
+ return x
+
+
+class FeedForward_Conv2d(nn.Module):
+ def __init__(self, downsampler, dim, hidden_features, bias=True):
+ super(FeedForward_Conv2d, self).__init__()
+
+ self.bias = bias
+
+ self.project_in = nn.Linear(dim, hidden_features, bias=bias)
+
+ self.dwconv = nn.ModuleList([
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(5, 5), stride=1, padding=(2, 2), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(3, 3), stride=1, padding=(1, 1), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(1, 1), stride=1, padding=(0, 0), dilation=1,
+ groups=hidden_features, bias=bias)
+ ])
+
+ self.project_out = nn.Linear(hidden_features, dim, bias=bias)
+
+
+ def forward(self, x, t, h, w):
+ # import ipdb;ipdb.set_trace()
+ x = self.project_in(x)
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=t, h=h, w=w)
+ x = F.gelu(x)
+ out = x
+ for module in self.dwconv:
+ out = out + module(x)
+ out = rearrange(out, '(b t) d h w -> b (t h w) d', t=t, h=h, w=w)
+ x = self.project_out(out)
+ return x
+
+@maybe_allow_in_graph
+class BasicTransformerBlock(nn.Module):
+ r"""
+ A basic Transformer block.
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm (:
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
+ attention_bias (:
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
+ only_cross_attention (`bool`, *optional*):
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
+ double_self_attention (`bool`, *optional*):
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
+ upcast_attention (`bool`, *optional*):
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
+ Whether to use learnable elementwise affine parameters for normalization.
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
+ The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
+ final_dropout (`bool` *optional*, defaults to False):
+ Whether to apply a final dropout after the last feed-forward layer.
+ attention_type (`str`, *optional*, defaults to `"default"`):
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
+ positional_embeddings (`str`, *optional*, defaults to `None`):
+ The type of positional embeddings to apply to.
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
+ The maximum number of positional embeddings to apply.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
+ norm_eps: float = 1e-5,
+ final_dropout: bool = False,
+ attention_type: str = "default",
+ positional_embeddings: Optional[str] = None,
+ num_positional_embeddings: Optional[int] = None,
+ ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
+ ada_norm_bias: Optional[int] = None,
+ ff_inner_dim: Optional[int] = None,
+ ff_bias: bool = True,
+ attention_out_bias: bool = True,
+ attention_mode: str = "xformers",
+ downsampler: str = None,
+ use_rope: bool = False,
+ interpolation_scale_thw: Tuple[int] = (1, 1, 1),
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+ self.downsampler = downsampler
+
+ # We keep these boolean flags for backward-compatibility.
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
+ self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
+ self.use_layer_norm = norm_type == "layer_norm"
+ self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
+ )
+
+ self.norm_type = norm_type
+ self.num_embeds_ada_norm = num_embeds_ada_norm
+
+ if positional_embeddings and (num_positional_embeddings is None):
+ raise ValueError(
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
+ )
+
+ if positional_embeddings == "sinusoidal":
+ self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
+ else:
+ self.pos_embed = None
+
+ # Define 3 blocks. Each block has its own normalization layer.
+ # 1. Self-Attn
+ if norm_type == "ada_norm":
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_zero":
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_continuous":
+ self.norm1 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "rms_norm",
+ )
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
+
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ out_bias=attention_out_bias,
+ attention_mode=attention_mode,
+ downsampler=downsampler,
+ use_rope=use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+
+ # 2. Cross-Attn
+ if cross_attention_dim is not None or double_self_attention:
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
+ # the second cross attention block.
+ if norm_type == "ada_norm":
+ self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_continuous":
+ self.norm2 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "rms_norm",
+ )
+ else:
+ self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
+
+ self.attn2 = Attention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ out_bias=attention_out_bias,
+ attention_mode=attention_mode,
+ downsampler=False,
+ use_rope=False,
+ interpolation_scale_thw=interpolation_scale_thw,
+ ) # is self-attn if encoder_hidden_states is none
+ else:
+ self.norm2 = None
+ self.attn2 = None
+
+ # 3. Feed-forward
+ if norm_type == "ada_norm_continuous":
+ self.norm3 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "layer_norm",
+ )
+
+ elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
+ self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
+ elif norm_type == "layer_norm_i2vgen":
+ self.norm3 = None
+
+ if downsampler:
+ downsampler_ker_size = list(re.search(r'k(\d{2,3})', downsampler).group(1)) # 122
+ # if len(downsampler_ker_size) == 3:
+ # self.ff = FeedForward_Conv3d(
+ # downsampler,
+ # dim,
+ # 2 * dim,
+ # bias=ff_bias,
+ # )
+ # elif len(downsampler_ker_size) == 2:
+ self.ff = FeedForward_Conv2d(
+ downsampler,
+ dim,
+ 2 * dim,
+ bias=ff_bias,
+ )
+ else:
+ self.ff = FeedForward(
+ dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ final_dropout=final_dropout,
+ inner_dim=ff_inner_dim,
+ bias=ff_bias,
+ )
+
+ # 4. Fuser
+ if attention_type == "gated" or attention_type == "gated-text-image":
+ self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
+
+ # 5. Scale-shift for PixArt-Alpha.
+ if norm_type == "ada_norm_single":
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
+ # Sets chunk feed-forward
+ self._chunk_size = chunk_size
+ self._chunk_dim = dim
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ timestep: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ frame: int = None,
+ height: int = None,
+ width: int = None,
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> torch.FloatTensor:
+ if cross_attention_kwargs is not None:
+ if cross_attention_kwargs.get("scale", None) is not None:
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
+
+ # Notice that normalization is always applied before the real computation in the following blocks.
+ # 0. Self-Attention
+ batch_size = hidden_states.shape[0]
+
+ # import ipdb;ipdb.set_trace()
+ if self.norm_type == "ada_norm":
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.norm_type == "ada_norm_zero":
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
+ norm_hidden_states = self.norm1(hidden_states)
+ elif self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ elif self.norm_type == "ada_norm_single":
+ # import ipdb;ipdb.set_trace()
+ if get_sequence_parallel_state():
+ batch_size = hidden_states.shape[1]
+ # print('hidden_states', hidden_states.shape)
+ # print('timestep', timestep.shape)
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
+ self.scale_shift_table[:, None] + timestep.reshape(6, batch_size, -1)
+ ).chunk(6, dim=0)
+ else:
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
+ ).chunk(6, dim=1)
+ norm_hidden_states = self.norm1(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
+ # norm_hidden_states = norm_hidden_states.squeeze(1)
+ else:
+ raise ValueError("Incorrect norm used")
+
+ if self.pos_embed is not None:
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
+
+ # 1. Prepare GLIGEN inputs
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
+
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
+ attention_mask=attention_mask, frame=frame, height=height, width=width,
+ **cross_attention_kwargs,
+ )
+ if self.norm_type == "ada_norm_zero":
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ elif self.norm_type == "ada_norm_single":
+ attn_output = gate_msa * attn_output
+
+ hidden_states = attn_output + hidden_states
+ if hidden_states.ndim == 4:
+ hidden_states = hidden_states.squeeze(1)
+
+ # 1.2 GLIGEN Control
+ if gligen_kwargs is not None:
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
+
+ # 3. Cross-Attention
+ if self.attn2 is not None:
+ if self.norm_type == "ada_norm":
+ norm_hidden_states = self.norm2(hidden_states, timestep)
+ elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
+ norm_hidden_states = self.norm2(hidden_states)
+ elif self.norm_type == "ada_norm_single":
+ # For PixArt norm2 isn't applied here:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
+ norm_hidden_states = hidden_states
+ elif self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ else:
+ raise ValueError("Incorrect norm")
+
+ if self.pos_embed is not None and self.norm_type != "ada_norm_single":
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
+
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+
+ # 4. Feed-forward
+ # i2vgen doesn't have this norm 🤷♂️
+ if self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ elif not self.norm_type == "ada_norm_single":
+ norm_hidden_states = self.norm3(hidden_states)
+
+ if self.norm_type == "ada_norm_zero":
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ if self.norm_type == "ada_norm_single":
+ norm_hidden_states = self.norm2(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
+
+ # if self._chunk_size is not None:
+ # # "feed_forward_chunk_size" can be used to save memory
+ # ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
+ # else:
+
+ if self.downsampler:
+ ff_output = self.ff(norm_hidden_states, t=frame, h=height, w=width)
+ else:
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.norm_type == "ada_norm_zero":
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+ elif self.norm_type == "ada_norm_single":
+ ff_output = gate_mlp * ff_output
+
+ hidden_states = ff_output + hidden_states
+ if hidden_states.ndim == 4:
+ hidden_states = hidden_states.squeeze(1)
+
+ return hidden_states
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/rope.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/rope.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0baeaf9a6574b54bc77c18900e5c1ff8393e725
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/opensora/rope.py
@@ -0,0 +1,98 @@
+import torch
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config, set_run_dtype
+ from opensora.acceleration.parallel_states import get_sequence_parallel_state
+except:
+ torch_npu = None
+ npu_config = None
+ from opensora.utils.parallel_states import get_sequence_parallel_state
+
+class PositionGetter3D(object):
+ """ return positions of patches """
+
+ def __init__(self, ):
+ self.cache_positions = {}
+
+ def __call__(self, b, t, h, w, device):
+ if not (b, t,h,w) in self.cache_positions:
+ x = torch.arange(w, device=device)
+ y = torch.arange(h, device=device)
+ z = torch.arange(t, device=device)
+ pos = torch.cartesian_prod(z, y, x) #差不多等同于构建一个grid坐标
+ if get_sequence_parallel_state():
+ # print('PositionGetter3D', PositionGetter3D)
+ pos = pos.reshape(t * h * w, 3).transpose(0, 1).reshape(3, -1, 1).contiguous().expand(3, -1, b).clone()
+ else:
+ pos = pos.reshape(t * h * w, 3).transpose(0, 1).reshape(3, 1, -1).contiguous().expand(3, b, -1).clone()
+ poses = (pos[0].contiguous(), pos[1].contiguous(), pos[2].contiguous())
+ max_poses = (int(poses[0].max()), int(poses[1].max()), int(poses[2].max()))
+
+ self.cache_positions[b, t, h, w] = (poses, max_poses)
+ pos = self.cache_positions[b, t, h, w]
+
+ return pos
+
+
+class RoPE3D(torch.nn.Module):
+
+ def __init__(self, freq=10000.0, F0=1.0, interpolation_scale_thw=(1, 1, 1)):
+ super().__init__()
+ self.base = freq
+ self.F0 = F0
+ self.interpolation_scale_t = interpolation_scale_thw[0]
+ self.interpolation_scale_h = interpolation_scale_thw[1]
+ self.interpolation_scale_w = interpolation_scale_thw[2]
+ self.cache = {}
+
+ def get_cos_sin(self, D, seq_len, device, dtype, interpolation_scale=1):
+ if (D, seq_len, device, dtype) not in self.cache:
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D))
+ t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) / interpolation_scale
+ freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype)
+ freqs = torch.cat((freqs, freqs), dim=-1)
+ cos = freqs.cos() # (Seq, Dim)
+ sin = freqs.sin()
+ self.cache[D, seq_len, device, dtype] = (cos, sin)
+ return self.cache[D, seq_len, device, dtype]
+
+ @staticmethod
+ def rotate_half(x):
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
+ return torch.cat((-x2, x1), dim=-1)
+
+ def apply_rope1d(self, tokens, pos1d, cos, sin):
+ assert pos1d.ndim == 2
+ if npu_config is None and not get_sequence_parallel_state():
+ # for (batch_size x nheads x ntokens x dim)
+ cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :]
+ sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :]
+ else:
+ # for (batch_size x ntokens x nheads x dim)
+ cos = torch.nn.functional.embedding(pos1d, cos)[:, :, None, :]
+ sin = torch.nn.functional.embedding(pos1d, sin)[:, :, None, :]
+
+ return (tokens * cos) + (self.rotate_half(tokens) * sin)
+
+ def forward(self, tokens, positions):
+ """
+ input:
+ * tokens: batch_size x nheads x ntokens x dim
+ * positions: batch_size x ntokens x 3 (t, y and x position of each token)
+ output:
+ * tokens after appplying RoPE3D (batch_size x nheads x ntokens x x dim)
+ """
+ assert tokens.size(3) % 3 == 0, "number of dimensions should be a multiple of three"
+ D = tokens.size(3) // 3
+ poses, max_poses = positions
+ assert len(poses) == 3 and poses[0].ndim == 2# Batch, Seq, 3
+ cos_t, sin_t = self.get_cos_sin(D, max_poses[0] + 1, tokens.device, tokens.dtype, self.interpolation_scale_t)
+ cos_y, sin_y = self.get_cos_sin(D, max_poses[1] + 1, tokens.device, tokens.dtype, self.interpolation_scale_h)
+ cos_x, sin_x = self.get_cos_sin(D, max_poses[2] + 1, tokens.device, tokens.dtype, self.interpolation_scale_w)
+ # split features into three along the feature dimension, and apply rope1d on each half
+ t, y, x = tokens.chunk(3, dim=-1)
+ t = self.apply_rope1d(t, poses[0], cos_t, sin_t)
+ y = self.apply_rope1d(y, poses[1], cos_y, sin_y)
+ x = self.apply_rope1d(x, poses[2], cos_x, sin_x)
+ tokens = torch.cat((t, y, x), dim=-1)
+ return tokens
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modeling_udit.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modeling_udit.py
new file mode 100644
index 0000000000000000000000000000000000000000..2735d8361f3f4ffbe66b0c3a2e03e42f1c8027db
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modeling_udit.py
@@ -0,0 +1,1075 @@
+import os
+import numpy as np
+from torch import nn
+import torch
+from einops import rearrange, repeat
+from typing import Any, Dict, Optional, Tuple
+from torch.nn import functional as F
+from diffusers.loaders import PeftAdapterMixin
+# from diffusers.models.transformer_2d import Transformer2DModelOutput
+from diffusers.models.modeling_outputs import Transformer2DModelOutput
+
+from diffusers.utils import is_torch_version, deprecate
+from diffusers.configuration_utils import ConfigMixin, register_to_config
+from diffusers.models.modeling_utils import ModelMixin
+from diffusers.models.normalization import AdaLayerNormSingle
+from diffusers.models.embeddings import PixArtAlphaTextProjection
+from opensora.models.diffusion.udit.modules import Upsample2d, Downsample2d, PatchEmbed2D, BasicTransformerBlock, \
+ FP32_GELU, FP32_SiLU, FP32_Layernorm
+from opensora.utils.utils import to_2tuple
+import math
+import re
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config
+except:
+ torch_npu = None
+ npu_config = None
+
+class UDiTT2V(ModelMixin, ConfigMixin, PeftAdapterMixin):
+ """
+ A 2D Transformer model for image-like data.
+
+ Parameters:
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
+ in_channels (`int`, *optional*):
+ The number of channels in the input and output (specify if the input is **continuous**).
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
+ This is fixed during training since it is used to learn a number of position embeddings.
+ num_vector_embeds (`int`, *optional*):
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
+ Includes the class for the masked latent pixel.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
+ num_embeds_ada_norm ( `int`, *optional*):
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
+ added to the hidden states.
+
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
+ attention_bias (`bool`, *optional*):
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
+ """
+
+ _supports_gradient_checkpointing = True
+
+ @register_to_config
+ def __init__(
+ self,
+ num_attention_heads: int = 16,
+ attention_head_dim: int = 88,
+ in_channels: Optional[int] = None,
+ out_channels: Optional[int] = None,
+ num_layers: int = 1,
+ dropout: float = 0.0,
+ norm_num_groups: int = 32,
+ cross_attention_dim: Optional[int] = None,
+ attention_bias: bool = False,
+ sample_size: Optional[int] = None,
+ sample_size_t: Optional[int] = None,
+ patch_size: Optional[int] = None,
+ patch_size_t: Optional[int] = None,
+ num_vector_embeds: Optional[int] = None,
+ mlp_ratio: int = 4,
+ depth: Optional[list] = [2, 5, 8, 5, 2],
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ use_linear_projection: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
+ norm_elementwise_affine: bool = True,
+ norm_eps: float = 1e-5,
+ attention_type: str = "default",
+ caption_channels: int = None,
+ interpolation_scale_h: float = None,
+ interpolation_scale_w: float = None,
+ interpolation_scale_t: float = None,
+ use_additional_conditions: Optional[bool] = None,
+ attention_mode: str = 'xformers',
+ downsampler: str = 'k333_s222',
+ use_rope: bool = False,
+ use_stable_fp32: bool = False,
+ ):
+ super().__init__()
+
+ # Set some common variables used across the board.
+ self.use_stable_fp32 = use_stable_fp32
+ self.use_rope = use_rope
+ self.downsampler = downsampler
+ self.use_linear_projection = use_linear_projection
+ self.interpolation_scale_t = interpolation_scale_t
+ self.interpolation_scale_h = interpolation_scale_h
+ self.interpolation_scale_w = interpolation_scale_w
+ self.caption_channels = caption_channels
+ self.num_attention_heads = num_attention_heads
+ self.attention_head_dim = attention_head_dim
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
+ self.in_channels = in_channels
+ self.out_channels = in_channels if out_channels is None else out_channels
+ self.gradient_checkpointing = False
+ use_additional_conditions = False
+ # if use_additional_conditions is None:
+ # if norm_type == "ada_norm_single" and sample_size == 128:
+ # use_additional_conditions = True
+ # else:
+ # use_additional_conditions = False
+ self.use_additional_conditions = use_additional_conditions
+
+ # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
+ # Define whether input is continuous or discrete depending on configuration
+ assert in_channels is not None
+
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
+ deprecation_message = (
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
+ " incorrectly set to `'layer_norm'`. Make sure to set `norm_type` to `'ada_norm'` in the config."
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
+ )
+ deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
+ norm_type = "ada_norm"
+
+ # 2. Initialize the right blocks.
+ # Initialize the output blocks and other projection blocks when necessary.
+ self._init_patched_inputs(norm_type=norm_type)
+ if self.use_stable_fp32:
+ self._replace_fp32_layers()
+
+ def _init_patched_inputs(self, norm_type):
+ assert self.config.sample_size_t is not None, "OpenSoraT2V over patched input must provide sample_size_t"
+ assert self.config.sample_size is not None, "OpenSoraT2V over patched input must provide sample_size"
+
+ self.config.sample_size = to_2tuple(self.config.sample_size)
+ # self.num_frames = self.config.sample_size_t
+ # self.height = self.config.sample_size[0]
+ # self.width = self.config.sample_size[1]
+ interpolation_scale_t = ((self.config.sample_size_t - 1) // 16 + 1) if self.config.sample_size_t % 2 == 1 else self.config.sample_size_t / 16
+ interpolation_scale_t = (
+ self.config.interpolation_scale_t if self.config.interpolation_scale_t is not None else interpolation_scale_t
+ )
+ interpolation_scale = (
+ self.config.interpolation_scale_h if self.config.interpolation_scale_h is not None else self.config.sample_size[0] / 30,
+ self.config.interpolation_scale_w if self.config.interpolation_scale_w is not None else self.config.sample_size[1] / 40,
+ )
+
+ # down_factor = list(re.search(r's(\d{2,3})', self.downsampler).group(1))
+ # down_factor = [int(i) for i in down_factor]
+ # down_factor = down_factor if isinstance(self.config.down_factor, list) else [self.config.down_factor] * 5
+ # down_factor = [2] * len(self.config.depth)
+ is_video_model = False
+ # if self.config.downsampler is not None and len(self.config.downsampler) == 9:
+ # is_video_model = True # to init weight from image
+ # self.pos_embed = OverlapPatchEmbed3D(
+ # num_frames=self.config.sample_size_t,
+ # height=self.config.sample_size[0],
+ # width=self.config.sample_size[1],
+ # patch_size_t=self.config.patch_size_t,
+ # patch_size=self.config.patch_size,
+ # in_channels=self.in_channels,
+ # embed_dim=self.inner_dim,
+ # interpolation_scale=interpolation_scale,
+ # interpolation_scale_t=interpolation_scale_t,
+ # use_abs_pos=not self.config.use_rope,
+ # )
+ # elif self.config.downsampler is not None and len(self.config.downsampler) == 7:
+ # is_video_model = False
+ self.pos_embed = PatchEmbed2D(
+ num_frames=self.config.sample_size_t,
+ height=self.config.sample_size[0],
+ width=self.config.sample_size[1],
+ patch_size_t=self.config.patch_size_t,
+ patch_size=self.config.patch_size,
+ in_channels=self.in_channels,
+ embed_dim=self.inner_dim,
+ interpolation_scale=interpolation_scale,
+ interpolation_scale_t=interpolation_scale_t,
+ use_abs_pos=not self.config.use_rope,
+ )
+ # layer_thw = [[self.config.sample_size_t//self.config.patch_size_t,
+ # (self.config.sample_size[0] + self.config.sample_size[0] % (self.config.patch_size*2))//self.config.patch_size,
+ # (self.config.sample_size[1] + self.config.sample_size[1] % (self.config.patch_size*2))//self.config.patch_size]]
+ interpolation_scale_thw = (interpolation_scale_t, *interpolation_scale)
+ # for i in range((len(self.config.depth)-1)//2):
+ # t = layer_thw[i][0] // 2 if layer_thw[i][0] != 1 else 1
+ # h = (layer_thw[i][1] + layer_thw[i][1] % 4) // 2 # why mod 4, because downsample and downsampler in attention
+ # w = (layer_thw[i][2] + layer_thw[i][2] % 4) // 2
+ # layer_thw.append([t, h, w])
+ # self.layer_thw = layer_thw
+ self.encoder_level_1 = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim,
+ downsampler=self.config.downsampler,
+ mlp_ratio=self.config.mlp_ratio,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.inner_dim,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.depth[0])
+ ]
+ )
+ # self.down1_2 = Downsample3d(self.inner_dim) if is_video_model else Downsample2d(self.inner_dim)
+ self.down1_2 = Downsample2d(self.inner_dim)
+
+ self.encoder_level_2 = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim * 2,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim * 2,
+ downsampler=self.config.downsampler,
+ mlp_ratio=self.config.mlp_ratio,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.inner_dim * 2,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.depth[1])
+ ]
+ )
+ # self.down2_3 = Downsample3d(self.inner_dim * 2) if is_video_model else Downsample2d(self.inner_dim * 2)
+ self.down2_3 = Downsample2d(self.inner_dim * 2)
+
+ self.latent = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim * 4,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim * 4,
+ downsampler=self.config.downsampler,
+ mlp_ratio=self.config.mlp_ratio,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.inner_dim * 4,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.depth[2])
+ ]
+ )
+
+ # self.up3_2 = Upsample3d(int(self.inner_dim * 4)) if is_video_model else Upsample2d(self.inner_dim * 4) ## From Level 4 to Level 3
+ self.up3_2 = Upsample2d(self.inner_dim * 4) ## From Level 4 to Level 3
+
+ self.reduce_chan_level2_norm = nn.LayerNorm(int(self.inner_dim * 4), elementwise_affine=True, eps=1e-6)
+ self.reduce_chan_level2 = nn.Linear(int(self.inner_dim * 4), int(self.inner_dim * 2), bias=True)
+ self.decoder_level_2 = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim * 2,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim * 2,
+ downsampler=self.config.downsampler,
+ mlp_ratio=self.config.mlp_ratio,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.inner_dim * 2,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.depth[3])
+ ]
+ )
+
+ # self.up2_1 = Upsample3d(int(self.inner_dim * 2)) if is_video_model else Upsample2d(self.inner_dim * 2) ## From Level 4 to Level 3
+ self.up2_1 = Upsample2d(self.inner_dim * 2) ## From Level 4 to Level 3
+
+ self.reduce_chan_level1_norm = nn.LayerNorm(int(self.inner_dim * 2), elementwise_affine=True, eps=1e-6)
+ self.reduce_chan_level1 = nn.Linear(int(self.inner_dim * 2), int(self.inner_dim * 1), bias=True)
+ self.decoder_level_1 = nn.ModuleList(
+ [
+ BasicTransformerBlock(
+ self.inner_dim,
+ self.config.num_attention_heads,
+ self.config.attention_head_dim,
+ downsampler=self.config.downsampler,
+ mlp_ratio=self.config.mlp_ratio,
+ dropout=self.config.dropout,
+ cross_attention_dim=self.inner_dim,
+ activation_fn=self.config.activation_fn,
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
+ attention_bias=self.config.attention_bias,
+ only_cross_attention=self.config.only_cross_attention,
+ double_self_attention=self.config.double_self_attention,
+ upcast_attention=self.config.upcast_attention,
+ norm_type=norm_type,
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
+ norm_eps=self.config.norm_eps,
+ attention_type=self.config.attention_type,
+ attention_mode=self.config.attention_mode,
+ use_rope=self.config.use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+ for _ in range(self.config.depth[4])
+ ]
+ )
+
+ if self.config.norm_type != "ada_norm_single":
+ self.norm_out = nn.LayerNorm(2 * self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.proj_out_1 = nn.Linear(2 * self.inner_dim, 2 * self.inner_dim)
+ self.proj_out_2 = nn.Linear(
+ 2 * self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+ elif self.config.norm_type == "ada_norm_single":
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / (self.inner_dim)**0.5)
+ self.proj_out = nn.Linear(
+ self.inner_dim, self.config.patch_size_t * self.config.patch_size * self.config.patch_size * self.out_channels
+ )
+
+ # PixArt-Alpha blocks.
+ # self.adaln_single = None
+ # if self.config.norm_type == "ada_norm_single":
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
+ # additional conditions until we find better name
+ self.adaln_single_1 = AdaLayerNormSingle(
+ self.inner_dim, use_additional_conditions=self.use_additional_conditions
+ )
+ self.adaln_single_2 = AdaLayerNormSingle(
+ self.inner_dim * 2, use_additional_conditions=self.use_additional_conditions
+ )
+ self.adaln_single_3 = AdaLayerNormSingle(
+ self.inner_dim * 4, use_additional_conditions=self.use_additional_conditions
+ )
+
+ # self.caption_projection = None
+ # if self.caption_channels is not None:
+ self.caption_projection_1 = PixArtAlphaTextProjection(
+ in_features=self.caption_channels, hidden_size=self.inner_dim
+ )
+ self.caption_projection_2 = PixArtAlphaTextProjection(
+ in_features=self.caption_channels, hidden_size=self.inner_dim * 2
+ )
+ self.caption_projection_3 = PixArtAlphaTextProjection(
+ in_features=self.caption_channels, hidden_size=self.inner_dim * 4
+ )
+
+ def _replace_fp32_layers(self, module=None):
+ if module is None:
+ module = self
+ for name, submodule in module.named_children():
+ if isinstance(submodule, nn.LayerNorm):
+ # print(f"Replacing LayerNorm in {name}")
+ new_layer = FP32_Layernorm(submodule.normalized_shape, submodule.eps, submodule.elementwise_affine)
+ if submodule.elementwise_affine:
+ new_layer.weight.data.copy_(submodule.weight.data.float())
+ if submodule.bias is not None:
+ new_layer.bias.data.copy_(submodule.bias.data.float())
+ setattr(module, name, new_layer)
+ elif isinstance(submodule, nn.SiLU):
+ # print(f"Replacing SiLU in {name}")
+ setattr(module, name, FP32_SiLU(submodule.inplace))
+ elif isinstance(submodule, nn.GELU):
+ # print(f"Replacing GELU in {name}")
+ setattr(module, name, FP32_GELU(submodule.approximate))
+ else:
+ self._replace_fp32_layers(submodule)
+
+ def _set_gradient_checkpointing(self, module, value=False):
+ if hasattr(module, "gradient_checkpointing"):
+ module.gradient_checkpointing = value
+
+ def forward(
+ self,
+ hidden_states: torch.Tensor,
+ timestep: Optional[torch.LongTensor] = None,
+ encoder_hidden_states: Optional[torch.Tensor] = None,
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ attention_mask: Optional[torch.Tensor] = None,
+ encoder_attention_mask: Optional[torch.Tensor] = None,
+ use_image_num: Optional[int] = 0,
+ return_dict: bool = True,
+ ):
+ """
+ The [`Transformer2DModel`] forward method.
+
+ Args:
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
+ Input `hidden_states`.
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
+ self-attention.
+ timestep ( `torch.LongTensor`, *optional*):
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
+ `AdaLayerZeroNorm`.
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
+ `self.processor` in
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
+ attention_mask ( `torch.Tensor`, *optional*):
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
+ negative values to the attention scores corresponding to "discard" tokens.
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
+
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
+
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
+ above. This bias will be added to the cross-attention scores.
+ return_dict (`bool`, *optional*, defaults to `True`):
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
+ tuple.
+
+ Returns:
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
+ `tuple` where the first element is the sample tensor.
+ """
+ batch_size, c, frame, height, width = hidden_states.shape
+ frame = frame - use_image_num # 21-4=17
+ if cross_attention_kwargs is not None:
+ if cross_attention_kwargs.get("scale", None) is not None:
+ print.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
+ # expects mask of shape:
+ # [batch, key_tokens]
+ # adds singleton query_tokens dimension:
+ # [batch, 1, key_tokens]
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
+
+ if attention_mask is not None and attention_mask.ndim == 4:
+ # assume that mask is expressed as:
+ # (1 = keep, 0 = discard)
+ # convert mask into a bias that can be added to attention scores:
+ # (keep = +0, discard = -10000.0)
+ # b, frame+use_image_num, h, w -> a video with images
+ # b, 1, h, w -> only images
+ pad_h_0, pad_w_0 = height % (self.config.patch_size * 2), width % (self.config.patch_size * 2)
+
+ hidden_states = F.pad(hidden_states, (0, pad_w_0, 0, pad_h_0, 0, 0), mode='reflect')
+ attention_mask = attention_mask.to(self.dtype)
+ attention_mask = attention_mask.unsqueeze(1) # b 1 t h w
+ attention_mask = F.pad(attention_mask, (0, pad_w_0, 0, pad_h_0, 0, 0))
+ attention_mask = F.max_pool3d(attention_mask, kernel_size=(self.config.patch_size_t, self.config.patch_size, self.config.patch_size),
+ stride=(self.config.patch_size_t, self.config.patch_size, self.config.patch_size))
+ attention_mask = rearrange(attention_mask, 'b 1 t h w -> b 1 (t h w)')
+
+ attention_bias = (1 - attention_mask.bool().to(self.dtype)) * -10000.0
+
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 3:
+ # b, 1, l -> only video
+ encoder_attention_mask = (1 - encoder_attention_mask.to(self.dtype)) * -10000.0
+
+
+ # 1. Input
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
+ hidden_states, encoder_hidden_states_1, encoder_hidden_states_2, encoder_hidden_states_3, \
+ timestep_1, timestep_2, timestep_3, \
+ embedded_timestep_1, embedded_timestep_2, embedded_timestep_3 = self._operate_on_patched_inputs(
+ hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num
+ )
+ frame, height, width = frame // self.config.patch_size_t, \
+ (height + pad_h_0) // (self.config.patch_size), (width + pad_w_0) // (self.config.patch_size)
+
+
+ assert not torch.any(torch.isnan(hidden_states)), 'after _operate_on_patched_inputs'
+ def create_custom_forward(module, return_dict=None):
+ def custom_forward(*inputs):
+ if return_dict is not None:
+ return module(*inputs, return_dict=return_dict)
+ else:
+ return module(*inputs)
+
+ return custom_forward
+
+ # encoder_1
+ out_enc_level1 = hidden_states
+ # import ipdb;ipdb.set_trace()
+ if self.training and self.gradient_checkpointing:
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+ for block in self.encoder_level_1:
+ out_enc_level1 = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ out_enc_level1,
+ attention_bias,
+ encoder_hidden_states_1,
+ encoder_attention_mask,
+ timestep_1,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ for block in self.encoder_level_1:
+ out_enc_level1 = block(
+ out_enc_level1,
+ attention_mask=attention_bias,
+ encoder_hidden_states=encoder_hidden_states_1,
+ encoder_attention_mask=encoder_attention_mask,
+ timestep=timestep_1,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+ pad_h_1, pad_w_1 = height % 4, width % 4
+
+ inp_enc_level2, attention_bias, attention_mask = self.down1_2(out_enc_level1, attention_mask, frame, height, width, pad_h=pad_h_1, pad_w=pad_w_1)
+ # frame, height, width = frame // 2 if frame != 1 else frame, (height + pad_h_1) // 2, (width + pad_w_1) // 2
+ height, width = (height + pad_h_1) // 2, (width + pad_w_1) // 2
+
+ # encoder_2
+ out_enc_level2 = inp_enc_level2
+
+ if self.training and self.gradient_checkpointing:
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+ for block in self.encoder_level_2:
+ out_enc_level2 = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ out_enc_level2,
+ attention_bias,
+ encoder_hidden_states_2,
+ encoder_attention_mask,
+ timestep_2,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ for block in self.encoder_level_2:
+ out_enc_level2 = block(
+ out_enc_level2,
+ attention_mask=attention_bias,
+ encoder_hidden_states=encoder_hidden_states_2,
+ encoder_attention_mask=encoder_attention_mask,
+ timestep=timestep_2,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+ pad_h_2, pad_w_2 = height % 4, width % 4
+
+ # import ipdb;ipdb.set_trace()
+ inp_enc_level3, attention_bias, attention_mask = self.down2_3(out_enc_level2, attention_mask, frame, height, width, pad_h=pad_h_2, pad_w=pad_w_2)
+ # frame, height, width = frame // 2 if frame != 1 else frame, (height + pad_h_2) // 2, (width + pad_w_2) // 2
+ height, width = (height + pad_h_2) // 2, (width + pad_w_2) // 2
+
+ # latent
+ latent = inp_enc_level3
+ if self.training and self.gradient_checkpointing:
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+ for block in self.latent:
+ latent = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ latent,
+ attention_bias,
+ encoder_hidden_states_3,
+ encoder_attention_mask,
+ timestep_3,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ for block in self.latent:
+ latent = block(
+ latent,
+ attention_mask=attention_bias,
+ encoder_hidden_states=encoder_hidden_states_3,
+ encoder_attention_mask=encoder_attention_mask,
+ timestep=timestep_3,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+
+ # decoder_2
+
+ # import ipdb;ipdb.set_trace()
+ inp_dec_level2, attention_bias, attention_mask = self.up3_2(latent, attention_mask, frame, height, width, pad_h=pad_h_2, pad_w=pad_w_2)
+ # frame, height, width = frame * 2 if frame != 1 else frame, height * 2 - pad_h_2, width * 2 - pad_w_2
+ height, width = height * 2 - pad_h_2, width * 2 - pad_w_2
+ inp_dec_level2 = torch.cat([inp_dec_level2, out_enc_level2], 2)
+ inp_dec_level2 = self.reduce_chan_level2_norm(inp_dec_level2)
+ inp_dec_level2 = self.reduce_chan_level2(inp_dec_level2)
+ out_dec_level2 = inp_dec_level2
+
+ if self.training and self.gradient_checkpointing:
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+ for block in self.decoder_level_2:
+ out_dec_level2 = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ out_dec_level2,
+ attention_bias,
+ encoder_hidden_states_2,
+ encoder_attention_mask,
+ timestep_2,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ for block in self.decoder_level_2:
+ out_dec_level2 = block(
+ out_dec_level2,
+ attention_mask=attention_bias,
+ encoder_hidden_states=encoder_hidden_states_2,
+ encoder_attention_mask=encoder_attention_mask,
+ timestep=timestep_2,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+
+ # decoder_1
+
+ # import ipdb;ipdb.set_trace()
+ inp_dec_level1, attention_bias, attention_mask = self.up2_1(out_dec_level2, attention_mask, frame, height, width, pad_h=pad_h_1, pad_w=pad_w_1)
+ # frame, height, width = frame * 2 if frame != 1 else frame, height * 2 - pad_h_1, width * 2 - pad_w_1
+ height, width = height * 2 - pad_h_1, width * 2 - pad_w_1
+ inp_dec_level1 = torch.cat([inp_dec_level1, out_enc_level1], 2)
+ inp_dec_level1 = self.reduce_chan_level1_norm(inp_dec_level1)
+ inp_dec_level1 = self.reduce_chan_level1(inp_dec_level1)
+ out_dec_level1 = inp_dec_level1
+
+ if self.training and self.gradient_checkpointing:
+
+ ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
+
+ for block in self.decoder_level_1:
+ out_dec_level1 = torch.utils.checkpoint.checkpoint(
+ create_custom_forward(block),
+ out_dec_level1,
+ attention_bias,
+ encoder_hidden_states_1,
+ encoder_attention_mask,
+ timestep_1,
+ cross_attention_kwargs,
+ class_labels,
+ frame,
+ height,
+ width,
+ **ckpt_kwargs,
+ )
+ else:
+ for block in self.decoder_level_1:
+ out_dec_level1 = block(
+ out_dec_level1,
+ attention_mask=attention_bias,
+ encoder_hidden_states=encoder_hidden_states_1,
+ encoder_attention_mask=encoder_attention_mask,
+ timestep=timestep_1,
+ cross_attention_kwargs=cross_attention_kwargs,
+ class_labels=class_labels,
+ frame=frame,
+ height=height,
+ width=width,
+ )
+
+ assert not torch.any(torch.isnan(out_dec_level1)), 'after out_dec_level1'
+ # 3. Output
+ output = self._get_output_for_patched_inputs(
+ hidden_states=out_dec_level1,
+ timestep=timestep_1,
+ class_labels=class_labels,
+ embedded_timestep=embedded_timestep_1,
+ num_frames=frame,
+ height=height,
+ width=width,
+ ) # b c t h w
+
+ assert not torch.any(torch.isnan(output)), 'after output'
+ frame, height, width = frame * self.config.patch_size_t, height * self.config.patch_size - pad_h_0, width * self.config.patch_size - pad_w_0
+ output = output[:, :, :frame, :height, :width]
+ if not return_dict:
+ return (output,)
+
+ return Transformer2DModelOutput(sample=output)
+
+
+ def _operate_on_patched_inputs(self, hidden_states, encoder_hidden_states, timestep, added_cond_kwargs, batch_size, frame, use_image_num):
+ # batch_size = hidden_states.shape[0]
+ hidden_states = self.pos_embed(hidden_states.to(self.dtype), frame)
+
+ if self.use_additional_conditions and added_cond_kwargs is None:
+ raise ValueError(
+ "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
+ )
+ timestep_1, embedded_timestep_1 = self.adaln_single_1(
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=self.dtype
+ ) # b 6d, b d
+ timestep_2, embedded_timestep_2 = self.adaln_single_2(
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=self.dtype
+ ) # b 6d, b d
+ timestep_3, embedded_timestep_3 = self.adaln_single_3(
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=self.dtype
+ ) # b 6d, b d
+
+ encoder_hidden_states_1 = self.caption_projection_1(encoder_hidden_states) # b, 1+use_image_num, l, d or b, 1, l, d
+ encoder_hidden_states_1 = rearrange(encoder_hidden_states_1[:, :1], 'b 1 l d -> (b 1) l d')
+ encoder_hidden_states_2 = self.caption_projection_2(encoder_hidden_states) # b, 1+use_image_num, l, d or b, 1, l, d
+ encoder_hidden_states_2 = rearrange(encoder_hidden_states_2[:, :1], 'b 1 l d -> (b 1) l d')
+ encoder_hidden_states_3 = self.caption_projection_3(encoder_hidden_states) # b, 1+use_image_num, l, d or b, 1, l, d
+ encoder_hidden_states_3 = rearrange(encoder_hidden_states_3[:, :1], 'b 1 l d -> (b 1) l d')
+
+
+ return hidden_states, encoder_hidden_states_1, encoder_hidden_states_2, encoder_hidden_states_3, \
+ timestep_1, timestep_2, timestep_3, embedded_timestep_1, embedded_timestep_2, embedded_timestep_3
+
+
+
+ def _get_output_for_patched_inputs(
+ self, hidden_states, timestep, class_labels, embedded_timestep, num_frames, height=None, width=None
+ ):
+ if self.config.norm_type != "ada_norm_single":
+ conditioning = self.transformer_blocks[0].norm1.emb(
+ timestep, class_labels, hidden_dtype=self.dtype
+ )
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
+ hidden_states = self.proj_out_2(hidden_states)
+ elif self.config.norm_type == "ada_norm_single":
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
+ hidden_states = self.norm_out(hidden_states)
+ # Modulation
+ hidden_states = hidden_states * (1 + scale) + shift
+ hidden_states = self.proj_out(hidden_states)
+ hidden_states = hidden_states.squeeze(1)
+
+ # # unpatchify
+ # hidden_states = hidden_states.reshape(
+ # shape=(-1, num_frames, height, width, self.out_channels)
+ # )
+ # output = torch.einsum("nthwc->ncthw", hidden_states)
+ # return output
+ # unpatchify
+ hidden_states = hidden_states.reshape(
+ shape=(-1, num_frames, height, width, self.config.patch_size_t, self.config.patch_size, self.config.patch_size, self.config.out_channels)
+ )
+ hidden_states = torch.einsum("nthwopqc->nctohpwq", hidden_states)
+ output = hidden_states.reshape(
+ shape=(-1, self.config.out_channels, num_frames * self.config.patch_size_t, height * self.config.patch_size, width * self.config.patch_size)
+ )
+ # import ipdb;ipdb.set_trace()
+ # if output.shape[2] % 2 == 0:
+ # output = output[:, :, 1:]
+ return output
+
+
+def UDiTT2V_S_111(**kwargs):
+ return UDiTT2V(depth=[2, 5, 8, 5, 2], attention_head_dim=24, num_attention_heads=16, patch_size_t=1, patch_size=1,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_S_122(**kwargs):
+ return UDiTT2V(depth=[2, 5, 8, 5, 2], attention_head_dim=24, num_attention_heads=16, patch_size_t=1, patch_size=2,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_B_111(**kwargs):
+ return UDiTT2V(depth=[2, 5, 10, 5, 2], attention_head_dim=24, num_attention_heads=24, patch_size_t=1, patch_size=1,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_B_122(**kwargs):
+ return UDiTT2V(depth=[2, 5, 10, 5, 2], attention_head_dim=24, num_attention_heads=24, patch_size_t=1, patch_size=2,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_L_111(**kwargs):
+ return UDiTT2V(depth=[4, 8, 12, 8, 4], attention_head_dim=24, num_attention_heads=32, patch_size_t=1, patch_size=1,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_L_211(**kwargs):
+ return UDiTT2V(depth=[4, 8, 12, 8, 4], attention_head_dim=24, num_attention_heads=32, patch_size_t=2, patch_size=1,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_L_122(**kwargs):
+ return UDiTT2V(depth=[4, 8, 12, 8, 4], attention_head_dim=24, num_attention_heads=32, patch_size_t=1, patch_size=2,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_L_222(**kwargs):
+ return UDiTT2V(depth=[4, 8, 12, 8, 4], attention_head_dim=24, num_attention_heads=32, patch_size_t=2, patch_size=2,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+def UDiTT2V_XL_111(**kwargs):
+ return UDiTT2V(depth=[4, 8, 12, 8, 4], attention_head_dim=24, num_attention_heads=48, patch_size_t=1, patch_size=1,
+ mlp_ratio=2, norm_type="ada_norm_single", caption_channels=4096, **kwargs)
+
+
+UDiT_models = {
+ "UDiTT2V-S/111": UDiTT2V_S_111, # 0.4B 0.7B if video
+ "UDiTT2V-S/122": UDiTT2V_S_122, # 0.4B 0.7B if video
+ "UDiTT2V-B/111": UDiTT2V_B_111, # 1.0B 1.6B if video
+ "UDiTT2V-B/122": UDiTT2V_B_122, # 1.0B 1.6B if video
+ "UDiTT2V-L/111": UDiTT2V_L_111, # 2.2B 3.3B if video
+ "UDiTT2V-L/211": UDiTT2V_L_211, # 2.2B 3.3B if video
+ "UDiTT2V-L/122": UDiTT2V_L_122, # 2.2B 3.3B if video
+ "UDiTT2V-L/222": UDiTT2V_L_222, # 2.2B 3.3B if video
+ "UDiTT2V-XL/111": UDiTT2V_XL_111, # 5.0B 7.4B if video
+}
+
+UDiT_models_class = {
+ "UDiTT2V-S/111": UDiTT2V,
+ "UDiTT2V-S/122": UDiTT2V,
+ "UDiTT2V-B/111": UDiTT2V,
+ "UDiTT2V-B/122": UDiTT2V,
+ "UDiTT2V-L/111": UDiTT2V,
+ "UDiTT2V-L/211": UDiTT2V,
+ "UDiTT2V-L/122": UDiTT2V,
+ "UDiTT2V-L/222": UDiTT2V,
+ "UDiTT2V-XL/111": UDiTT2V,
+}
+
+
+if __name__ == '__main__':
+ import sys
+ from copy import deepcopy
+ from opensora.models.causalvideovae import ae_channel_config, ae_stride_config
+ from opensora.models.causalvideovae import getae, getae_wrapper
+ from opensora.models.causalvideovae import CausalVAEModelWrapper
+
+ args = type('args', (),
+ {
+ 'ae': 'CausalVAEModel_4x8x8',
+ 'attention_mode': 'xformers',
+ 'use_rope': True,
+ 'model_max_length': 300,
+ 'max_height': 240,
+ 'max_width': 320,
+ 'num_frames': 1,
+ 'use_image_num': 0,
+ 'compress_kv_factor': 1,
+ 'interpolation_scale_t': 1,
+ 'interpolation_scale_h': 1,
+ 'interpolation_scale_w': 1,
+ }
+ )
+ b = 16
+ c = 4
+ cond_c = 4096
+ num_timesteps = 1000
+ ae_stride_t, ae_stride_h, ae_stride_w = ae_stride_config[args.ae]
+ latent_size = (args.max_height // ae_stride_h, args.max_width // ae_stride_w)
+ num_frames = (args.num_frames - 1) // ae_stride_t + 1
+
+ device = torch.device('cuda:0')
+
+
+
+ model = UDiTT2V_L_122(in_channels=c,
+ out_channels=c,
+ sample_size=latent_size,
+ sample_size_t=num_frames,
+ activation_fn="gelu-approximate",
+ attention_bias=True,
+ attention_type="default",
+ double_self_attention=False,
+ norm_elementwise_affine=False,
+ norm_eps=1e-06,
+ norm_num_groups=32,
+ num_vector_embeds=None,
+ only_cross_attention=False,
+ upcast_attention=False,
+ use_linear_projection=False,
+ use_additional_conditions=False,
+ downsampler=None,
+ interpolation_scale_t=args.interpolation_scale_t,
+ interpolation_scale_h=args.interpolation_scale_h,
+ interpolation_scale_w=args.interpolation_scale_w,
+ use_rope=args.use_rope).to(device)
+
+ print(model)
+ print(f'{sum(p.numel() for p in model.parameters() if p.requires_grad)/1e9} B')
+
+
+ model_state_dict = model.state_dict()
+ pretrained = "/storage/ongoing/new/Open-Sora-Plan/bs2_20node_73000k_480p_61x480p_lr5e-5_snr5_noioff0.02_ema_rope_uditultra122_qknorm_ds222_mt5xxl_sucai288w/checkpoint-11500/model_ema/diffusion_pytorch_model.safetensors"
+ try:
+ if 'safetensors' in pretrained: # pixart series
+ from safetensors.torch import load_file as safe_load
+ # import ipdb;ipdb.set_trace()
+ pretrained_checkpoint = safe_load(pretrained, device="cpu")
+ pretrained_keys = set(list(pretrained_checkpoint.keys()))
+ model_keys = set(list(model_state_dict.keys()))
+ common_keys = list(pretrained_keys & model_keys)
+ checkpoint = {k: pretrained_checkpoint[k] for k in common_keys if model_state_dict[k].numel() == pretrained_checkpoint[k].numel()}
+ # if checkpoint['pos_embed.proj.weight'].shape != model.pos_embed.proj.weight.shape and checkpoint['pos_embed.proj.weight'].ndim == 4:
+ # logger.info(f"Resize pos_embed, {checkpoint['pos_embed.proj.weight'].shape} -> {model.pos_embed.proj.weight.shape}")
+ # repeat = model.pos_embed.proj.weight.shape[2]
+ # checkpoint['pos_embed.proj.weight'] = checkpoint['pos_embed.proj.weight'].unsqueeze(2).repeat(1, 1, repeat, 1, 1) / float(repeat)
+ # del checkpoint['proj_out.weight'], checkpoint['proj_out.bias']
+ else: # latest stage training weight
+ checkpoint = torch.load(pretrained, map_location='cpu')
+ if 'model' in checkpoint:
+ checkpoint = checkpoint['model']
+ # import ipdb;ipdb.set_trace()
+ missing_keys, unexpected_keys = model.load_state_dict(checkpoint, strict=False)
+ print(f'missing_keys {len(missing_keys)} {missing_keys}, unexpected_keys {len(unexpected_keys)}')
+ print(f'Successfully load {len(model_state_dict) - len(missing_keys)}/{len(model_state_dict)} keys from {args.pretrained}!')
+ except Exception as e:
+ print(e)
+
+ # import sys;sys.exit()
+ # try:
+ # path = "bs32_1node_480p_lr1e-4_snr5_noioff0.02_ema_uditultra22_ds22_mt5xxl/checkpoint-500/model/diffusion_pytorch_model.safetensors"
+ # from safetensors.torch import load_file as safe_load
+ # ckpt = safe_load(path, device="cpu")
+ # new_ckpt = {}
+ # k_size = 3
+ # t_stride = 1
+ # for k, v in ckpt.items():
+ # if 'pos_embed.proj.weight' in k:
+ # new_v = v.unsqueeze(-3).repeat(1, 1, k_size, 1, 1) # 768, 4, 3, 3 -> 768, 4, 3, 3, 3
+ # elif 'attn1.downsampler.layer.weight' in k:
+ # new_v = v.unsqueeze(-3).repeat(1, 1, k_size, 1, 1) # 768, 4, 3, 3 -> 768, 4, 3, 3, 3
+ # elif 'body.0.weight' in k and 'down' in k:
+ # in_c = v.shape[0]
+ # new_v = v[:in_c//2].unsqueeze(-3).repeat(1, 1, k_size, 1, 1) # 384, 768, 3, 3 -> 192, 768, 3, 3, 3
+ # elif 'body.0.weight' in k and 'up' in k:
+ # new_v = v.unsqueeze(-3).repeat(2, 1, k_size, 1, 1) # 6144, 3072, 3, 3 -> 12288, 3072, 3, 3, 3
+ # elif 'proj_out' in k:
+ # if 'weight' in k:
+ # new_v = v.repeat(t_stride, 1) # 16, 768 -> 32, 768
+ # elif 'bias' in k:
+ # new_v = v.repeat(t_stride) # 16 -> 32
+ # else:
+ # new_v = v
+ # new_ckpt[k] = new_v
+ # msg = model.load_state_dict(new_ckpt, strict=False)
+ # # print(msg)
+ # except Exception as e:
+ # print(e)
+ x = torch.randn(b, c, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w).to(device)
+ cond = torch.randn(b, 1+args.use_image_num, args.model_max_length, cond_c).to(device)
+ attn_mask = torch.randint(0, 2, (b, 1+(args.num_frames-1)//ae_stride_t+args.use_image_num, args.max_height//ae_stride_h, args.max_width//ae_stride_w)).to(device) # B L or B 1+num_images L
+ cond_mask = torch.randint(0, 2, (b, 1+args.use_image_num, args.model_max_length)).to(device) # B L or B 1+num_images L
+ timestep = torch.randint(0, 1000, (b,), device=device)
+ model_kwargs = dict(hidden_states=x, encoder_hidden_states=cond, attention_mask=attn_mask,
+ encoder_attention_mask=cond_mask, use_image_num=args.use_image_num, timestep=timestep)
+ with torch.no_grad():
+ output = model(**model_kwargs)[0]
+ import ipdb;ipdb.set_trace()
+ print(output.shape)
+
+
+
+
+ # from peft import LoraConfig, PeftModel, get_peft_model
+ # from opensora.utils.lora_utils import EMAModel_LoRA, maybe_zero_3, get_peft_state_maybe_zero_3
+ # lora_save_path = '/storage/ongoing/new/Open-Sora-Plan/debug_lora/model_lora'
+ # ema_lora_save_path = '/storage/ongoing/new/Open-Sora-Plan/debug_lora/ema_model_lora'
+ # origin_model_path = '/storage/ongoing/new/Open-Sora-Plan/bs16_4node_240p_lr1e-4_snr5_noioff0.02_ema_rope_uditultra22_ds22_mt5xxl/checkpoint-500/model_ema'
+ # model = UDiTUltraT2V.from_pretrained(origin_model_path)
+ # lora_config = LoraConfig(
+ # r=64,
+ # lora_alpha=64,
+ # init_lora_weights="gaussian",
+ # target_modules=["to_k", "to_q", "to_v", "to_out.0"],
+ # )
+ # model_lora = get_peft_model(model, lora_config)
+ # # --------------------ema lora_model----------------------------------
+ # # create ema lora_model
+ # ema_model = deepcopy(model_lora)
+ # ema_model_lora = EMAModel_LoRA(lora_config, parameters=ema_model.parameters(), update_after_step=0,
+ # model_cls=UDiTUltraT2V, model_config=ema_model.config)
+ # ema_model_lora.save_pretrained(ema_lora_save_path)
+ # ema_model_load_lora = EMAModel_LoRA.from_pretrained(ema_lora_save_path, UDiTUltraT2V, lora_config, origin_model_path)
+ # ema_model_lora.load_state_dict(ema_model_load_lora.state_dict())
+ # ema_model_lora.to(device)
+
+ # # -----------------lora model---------------------------------
+ # # get lora weight
+ # model_lora.save_pretrained(lora_save_path)
+ # # ----------------load lora model------------------------------
+ # # load lora weight
+ # model = UDiTUltraT2V.from_pretrained(origin_model_path)
+ # import ipdb;ipdb.set_trace()
+ # model_load_lora = PeftModel.from_pretrained(model, lora_save_path)
+ # for k, v in model_load_lora.state_dict().items():
+ # assert torch.allclose(v, model_lora.state_dict()[k])
+ # # for k, v in zip(ema_model_lora.shadow_params, model_lora.parameters()):
+ # # assert torch.allclose(v, k)
+ # print('Merging LoRA weights...')
+ # import ipdb;ipdb.set_trace()
+ # model_load_lora_merge = model_load_lora.merge_and_unload()
+ # with torch.no_grad():
+ # output = model_load_lora_merge(**model_kwargs)
+ # print(output[0].shape)
+
+
+
+
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modules.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modules.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc1ce394ce5801049f70f8a59c65d144adc53b4d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/modules.py
@@ -0,0 +1,1173 @@
+from einops import rearrange
+from torch import nn
+import torch
+import numpy as np
+
+from einops import rearrange, repeat
+from typing import Any, Dict, Optional, Tuple
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from typing import Any, Dict, Optional
+
+import torch
+import torch.nn.functional as F
+from torch import nn
+import diffusers
+from diffusers.utils import deprecate, logging
+from diffusers.utils.torch_utils import maybe_allow_in_graph
+from diffusers.models.attention import FeedForward, GatedSelfAttentionDense
+from diffusers.models.attention_processor import Attention as Attention_
+from diffusers.models.embeddings import SinusoidalPositionalEmbedding
+from diffusers.models.normalization import AdaLayerNorm, AdaLayerNormContinuous, AdaLayerNormZero, RMSNorm
+from .rope import PositionGetter3D, RoPE3D
+import re
+try:
+ import torch_npu
+ from opensora.npu_config import npu_config, set_run_dtype
+except:
+ torch_npu = None
+ npu_config = None
+ set_run_dtype = None
+logger = logging.get_logger(__name__)
+
+def get_3d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+ grid_t = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size[0]) / interpolation_scale[0]
+ grid_h = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size[1]) / interpolation_scale[1]
+ grid_w = np.arange(grid_size[2], dtype=np.float32) / (grid_size[2] / base_size[2]) / interpolation_scale[2]
+ grid = np.meshgrid(grid_w, grid_h, grid_t) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([3, 1, grid_size[2], grid_size[1], grid_size[0]])
+ pos_embed = get_3d_sincos_pos_embed_from_grid(embed_dim, grid)
+
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_3d_sincos_pos_embed_from_grid(embed_dim, grid):
+ if embed_dim % 3 != 0:
+ raise ValueError("embed_dim must be divisible by 3")
+
+ # use 1/3 of dimensions to encode grid_t/h/w
+ emb_t = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # (T*H*W, D/3)
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (T*H*W, D/3)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2]) # (T*H*W, D/3)
+
+ emb = np.concatenate([emb_t, emb_h, emb_w], axis=1) # (T*H*W, D)
+ return emb
+
+
+def get_2d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+
+ grid_h = np.arange(grid_size[0], dtype=np.float32) / (grid_size[0] / base_size[0]) / interpolation_scale[0]
+ grid_w = np.arange(grid_size[1], dtype=np.float32) / (grid_size[1] / base_size[1]) / interpolation_scale[1]
+ grid = np.meshgrid(grid_w, grid_h) # here w goes first
+ grid = np.stack(grid, axis=0)
+
+ grid = grid.reshape([2, 1, grid_size[1], grid_size[0]])
+ pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+
+def get_2d_sincos_pos_embed_from_grid(embed_dim, grid):
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ # use 1/3 of dimensions to encode grid_t/h/w
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0]) # (H*W, D/2)
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1]) # (H*W, D/2)
+
+ emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)
+ return emb
+
+def get_1d_sincos_pos_embed(
+ embed_dim, grid_size, cls_token=False, extra_tokens=0, interpolation_scale=1.0, base_size=16,
+):
+ """
+ grid_size: int of the grid return: pos_embed: [grid_size, embed_dim] or
+ [1+grid_size, embed_dim] (w/ or w/o cls_token)
+ """
+ # if isinstance(grid_size, int):
+ # grid_size = (grid_size, grid_size)
+
+ grid = np.arange(grid_size, dtype=np.float32) / (grid_size / base_size) / interpolation_scale
+ pos_embed = get_1d_sincos_pos_embed_from_grid(embed_dim, grid) # (H*W, D/2)
+ if cls_token and extra_tokens > 0:
+ pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)
+ return pos_embed
+
+def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
+ """
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
+ """
+ if embed_dim % 2 != 0:
+ raise ValueError("embed_dim must be divisible by 2")
+
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
+ omega /= embed_dim / 2.0
+ omega = 1.0 / 10000**omega # (D/2,)
+
+ pos = pos.reshape(-1) # (M,)
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
+
+ emb_sin = np.sin(out) # (M, D/2)
+ emb_cos = np.cos(out) # (M, D/2)
+
+ emb = np.concatenate([emb_sin, emb_cos], axis=1) # (M, D)
+ return emb
+
+class FP32_Layernorm(nn.LayerNorm):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ origin_dtype = inputs.dtype
+ return F.layer_norm(inputs.float(), self.normalized_shape, self.weight.float() if self.weight is not None else None,
+ self.bias.float() if self.bias is not None else None, self.eps).to(origin_dtype)
+
+
+class FP32_SiLU(nn.SiLU):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.silu(inputs.float(), inplace=self.inplace).to(inputs.dtype)
+
+
+class FP32_GELU(nn.GELU):
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
+ return torch.nn.functional.gelu(inputs.float(), approximate=self.approximate).to(inputs.dtype)
+
+
+
+class OverlapPatchEmbed3D(nn.Module):
+ """2D Image to Patch Embedding but with 3D position embedding"""
+
+ def __init__(
+ self,
+ num_frames=1,
+ height=224,
+ width=224,
+ patch_size_t=1,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=(1, 1),
+ interpolation_scale_t=1,
+ use_abs_pos=False,
+ ):
+ super().__init__()
+ # assert patch_size_t == 1 and patch_size == 1
+ self.use_abs_pos = use_abs_pos
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+ self.proj = nn.Conv3d(
+ in_channels, embed_dim, kernel_size=3, padding=1, stride=(patch_size_t, patch_size, patch_size), bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size_t = patch_size_t
+ self.patch_size = patch_size
+ # See:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = (height // patch_size, width // patch_size)
+ self.interpolation_scale = (interpolation_scale[0], interpolation_scale[1])
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, (self.height, self.width), base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
+
+ self.num_frames = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.base_size_t = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.interpolation_scale_t = interpolation_scale_t
+ temp_pos_embed = get_1d_sincos_pos_embed(embed_dim, self.num_frames, base_size=self.base_size_t, interpolation_scale=self.interpolation_scale_t)
+ self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
+ # self.temp_embed_gate = nn.Parameter(torch.tensor([0.0]))
+
+ def forward(self, latent, num_frames):
+ b, _, _, _, _ = latent.shape
+ video_latent, image_latent = None, None
+ # b c 1 h w
+ # assert latent.shape[-3] == 1 and num_frames == 1
+
+ num_frames = latent.shape[-3] // self.patch_size_t
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ # latent = rearrange(latent, 'b c t h w -> (b t) c h w')
+ latent = self.proj(latent)
+
+ if self.flatten:
+ # latent = latent.flatten(2).transpose(1, 2) # BT C H W -> BT N C
+ latent = rearrange(latent, 'b c t h w -> (b t) (h w) c ')
+ if self.layer_norm:
+ latent = self.norm(latent)
+
+ if self.use_abs_pos:
+ # Interpolate positional embeddings if needed.
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
+ if self.height != height or self.width != width:
+ # raise NotImplementedError
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed)
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+
+ if self.num_frames != num_frames:
+ # import ipdb;ipdb.set_trace()
+ # raise NotImplementedError
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ temp_pos_embed = torch.from_numpy(temp_pos_embed)
+ temp_pos_embed = temp_pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ temp_pos_embed = self.temp_pos_embed
+
+ latent = (latent + pos_embed).to(latent.dtype)
+
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=b)
+ video_latent = latent
+
+ if self.use_abs_pos:
+ # temp_pos_embed = temp_pos_embed.unsqueeze(2) * self.temp_embed_gate.tanh()
+ temp_pos_embed = temp_pos_embed.unsqueeze(2)
+ video_latent = (video_latent + temp_pos_embed).to(video_latent.dtype)
+
+ video_latent = rearrange(video_latent, 'b t n c -> b (t n) c')
+ return video_latent
+
+
+
+class PatchEmbed2D(nn.Module):
+ """2D Image to Patch Embedding but with 3D position embedding"""
+
+ def __init__(
+ self,
+ num_frames=1,
+ height=224,
+ width=224,
+ patch_size_t=1,
+ patch_size=16,
+ in_channels=3,
+ embed_dim=768,
+ layer_norm=False,
+ flatten=True,
+ bias=True,
+ interpolation_scale=(1, 1),
+ interpolation_scale_t=1,
+ use_abs_pos=True,
+ ):
+ super().__init__()
+ # assert num_frames == 1
+ self.use_abs_pos = use_abs_pos
+ self.flatten = flatten
+ self.layer_norm = layer_norm
+
+ self.proj = nn.Conv2d(
+ in_channels, embed_dim, kernel_size=(patch_size, patch_size), stride=(patch_size, patch_size), bias=bias
+ )
+ if layer_norm:
+ self.norm = nn.LayerNorm(embed_dim, elementwise_affine=False, eps=1e-6)
+ else:
+ self.norm = None
+
+ self.patch_size_t = patch_size_t
+ self.patch_size = patch_size
+ # See:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L161
+
+ self.height, self.width = height // patch_size, width // patch_size
+ self.base_size = (height // patch_size, width // patch_size)
+ self.interpolation_scale = (interpolation_scale[0], interpolation_scale[1])
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim, (self.height, self.width), base_size=self.base_size, interpolation_scale=self.interpolation_scale
+ )
+ self.register_buffer("pos_embed", torch.from_numpy(pos_embed).float().unsqueeze(0), persistent=False)
+
+ self.num_frames = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.base_size_t = (num_frames - 1) // patch_size_t + 1 if num_frames % 2 == 1 else num_frames // patch_size_t
+ self.interpolation_scale_t = interpolation_scale_t
+ temp_pos_embed = get_1d_sincos_pos_embed(embed_dim, self.num_frames, base_size=self.base_size_t, interpolation_scale=self.interpolation_scale_t)
+ self.register_buffer("temp_pos_embed", torch.from_numpy(temp_pos_embed).float().unsqueeze(0), persistent=False)
+ # self.temp_embed_gate = nn.Parameter(torch.tensor([0.0]))
+
+ def forward(self, latent, num_frames):
+ b, _, _, _, _ = latent.shape
+ video_latent, image_latent = None, None
+ # b c 1 h w
+ # assert latent.shape[-3] == 1 and num_frames == 1
+ height, width = latent.shape[-2] // self.patch_size, latent.shape[-1] // self.patch_size
+ latent = rearrange(latent, 'b c t h w -> (b t) c h w')
+ latent = self.proj(latent)
+
+ if self.flatten:
+ latent = latent.flatten(2).transpose(1, 2) # BT C H W -> BT N C
+ if self.layer_norm:
+ latent = self.norm(latent)
+
+ if self.use_abs_pos:
+ # Interpolate positional embeddings if needed.
+ # (For PixArt-Alpha: https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L162C151-L162C160)
+ if self.height != height or self.width != width:
+ # raise NotImplementedError
+ pos_embed = get_2d_sincos_pos_embed(
+ embed_dim=self.pos_embed.shape[-1],
+ grid_size=(height, width),
+ base_size=self.base_size,
+ interpolation_scale=self.interpolation_scale,
+ )
+ pos_embed = torch.from_numpy(pos_embed)
+ pos_embed = pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ pos_embed = self.pos_embed
+
+
+ if self.num_frames != num_frames:
+ # import ipdb;ipdb.set_trace()
+ # raise NotImplementedError
+ if get_sequence_parallel_state():
+ if npu_config is not None:
+ sp_size = hccl_info.world_size
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames * sp_size,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ rank = hccl_info.rank % sp_size
+ st_frame = rank * num_frames
+ ed_frame = st_frame + num_frames
+ temp_pos_embed = temp_pos_embed[st_frame: ed_frame]
+ else:
+ sp_size = nccl_info.world_size
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames * sp_size,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ rank = nccl_info.rank % sp_size
+ st_frame = rank * num_frames
+ ed_frame = st_frame + num_frames
+ temp_pos_embed = temp_pos_embed[st_frame: ed_frame]
+
+ else:
+ temp_pos_embed = get_1d_sincos_pos_embed(
+ embed_dim=self.temp_pos_embed.shape[-1],
+ grid_size=num_frames,
+ base_size=self.base_size_t,
+ interpolation_scale=self.interpolation_scale_t,
+ )
+ temp_pos_embed = torch.from_numpy(temp_pos_embed)
+ temp_pos_embed = temp_pos_embed.float().unsqueeze(0).to(latent.device)
+ else:
+ temp_pos_embed = self.temp_pos_embed
+
+ latent = (latent + pos_embed).to(latent.dtype)
+
+ latent = rearrange(latent, '(b t) n c -> b t n c', b=b)
+ video_latent = latent
+
+ if self.use_abs_pos:
+ # temp_pos_embed = temp_pos_embed.unsqueeze(2) * self.temp_embed_gate.tanh()
+ temp_pos_embed = temp_pos_embed.unsqueeze(2)
+ video_latent = (video_latent + temp_pos_embed).to(video_latent.dtype)
+ video_latent = rearrange(video_latent, 'b t n c -> b (t n) c')
+
+ return video_latent
+
+
+
+class Attention(Attention_):
+ def __init__(self, downsampler, attention_mode, use_rope, interpolation_scale_thw, **kwags):
+ processor = AttnProcessor2_0(attention_mode=attention_mode, use_rope=use_rope, interpolation_scale_thw=interpolation_scale_thw)
+ super().__init__(processor=processor, **kwags)
+ self.downsampler = None
+ # if downsampler: # downsampler k155_s122
+ # downsampler_ker_size = list(re.search(r'k(\d{2,3})', downsampler).group(1)) # 122
+ # down_factor = list(re.search(r's(\d{2,3})', downsampler).group(1))
+ # downsampler_ker_size = [int(i) for i in downsampler_ker_size]
+ # downsampler_padding = [(i - 1) // 2 for i in downsampler_ker_size]
+ # down_factor = [int(i) for i in down_factor]
+
+ # if len(downsampler_ker_size) == 2:
+ # self.downsampler = DownSampler2d(kwags['query_dim'], kwags['query_dim'], kernel_size=downsampler_ker_size, stride=1,
+ # padding=downsampler_padding, groups=kwags['query_dim'], down_factor=down_factor,
+ # down_shortcut=True)
+ # elif len(downsampler_ker_size) == 3:
+ # self.downsampler = DownSampler3d(kwags['query_dim'], kwags['query_dim'], kernel_size=downsampler_ker_size, stride=1,
+ # padding=downsampler_padding, groups=kwags['query_dim'], down_factor=down_factor,
+ # down_shortcut=True)
+
+ # self.q_norm = nn.LayerNorm(kwags['dim_head'], elementwise_affine=True, eps=1e-6)
+ # self.k_norm = nn.LayerNorm(kwags['dim_head'], elementwise_affine=True, eps=1e-6)
+
+
+class DownSampler3d(nn.Module):
+ def __init__(self, *args, **kwargs):
+ ''' Required kwargs: down_factor, downsampler'''
+ super().__init__()
+ self.down_factor = kwargs.pop('down_factor')
+ self.down_shortcut = kwargs.pop('down_shortcut')
+ self.layer = nn.Conv3d(*args, **kwargs)
+
+ def forward(self, x, attention_mask, t, h, w):
+ b = x.shape[0]
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=t, h=h, w=w)
+ if npu_config is None:
+ x = self.layer(x) + (x if self.down_shortcut else 0)
+ else:
+ x_dtype = x.dtype
+ x = npu_config.run_conv3d(self.layer, x, x_dtype) + (x if self.down_shortcut else 0)
+
+ self.t = t//self.down_factor[0]
+ self.h = h//self.down_factor[1]
+ self.w = w//self.down_factor[2]
+ # import ipdb;ipdb.set_trace()
+ x = rearrange(x, 'b d (t dt) (h dh) (w dw) -> (b dt dh dw) (t h w) d',
+ t=t//self.down_factor[0], h=h//self.down_factor[1], w=w//self.down_factor[2],
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> b 1 t h w', t=t, h=h, w=w)
+ attention_mask = rearrange(attention_mask, 'b 1 (t dt) (h dh) (w dw) -> (b dt dh dw) 1 (t h w)',
+ t=t//self.down_factor[0], h=h//self.down_factor[1], w=w//self.down_factor[2],
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+ return x, attention_mask
+
+ def reverse(self, x, t, h, w):
+ # import ipdb;ipdb.set_trace()
+ x = rearrange(x, '(b dt dh dw) (t h w) d -> b (t dt h dh w dw) d',
+ t=t, h=h, w=w,
+ dt=self.down_factor[0], dh=self.down_factor[1], dw=self.down_factor[2])
+ return x
+
+
+
+class DownSampler2d(nn.Module):
+ def __init__(self, *args, **kwargs):
+ ''' Required kwargs: down_factor, downsampler'''
+ super().__init__()
+ self.down_factor = kwargs.pop('down_factor')
+ self.down_shortcut = kwargs.pop('down_shortcut')
+ self.layer = nn.Conv2d(*args, **kwargs)
+
+ def forward(self, x, attention_mask, t, h, w):
+ # import ipdb;ipdb.set_trace()
+ b = x.shape[0]
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=t, h=h, w=w)
+ x = self.layer(x) + (x if self.down_shortcut else 0)
+
+ self.t = 1
+ self.h = h//self.down_factor[0]
+ self.w = w//self.down_factor[1]
+
+ x = rearrange(x, 'b d (h dh) (w dw) -> (b dh dw) (h w) d',
+ h=h//self.down_factor[0], w=w//self.down_factor[1],
+ dh=self.down_factor[0], dw=self.down_factor[1])
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> (b t) 1 h w', h=h, w=w)
+ attention_mask = rearrange(attention_mask, 'b 1 (h dh) (w dw) -> (b dh dw) 1 (h w)',
+ h=h//self.down_factor[0], w=w//self.down_factor[1],
+ dh=self.down_factor[0], dw=self.down_factor[1])
+ return x, attention_mask
+
+ def reverse(self, x, t, h, w):
+ x = rearrange(x, '(b t dh dw) (h w) d -> b (t h dh w dw) d',
+ t=t, h=h, w=w,
+ dh=self.down_factor[0], dw=self.down_factor[1])
+ return x
+
+
+class AttnProcessor2_0:
+ r"""
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
+ """
+
+ def __init__(self, attention_mode='xformers', use_rope=False, interpolation_scale_thw=(1, 1, 1)):
+ self.use_rope = use_rope
+ self.interpolation_scale_thw = interpolation_scale_thw
+ if self.use_rope:
+ self._init_rope(interpolation_scale_thw)
+ self.attention_mode = attention_mode
+ if not hasattr(F, "scaled_dot_product_attention"):
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
+
+ def _init_rope(self, interpolation_scale_thw):
+ self.rope = RoPE3D(interpolation_scale_thw=interpolation_scale_thw)
+ self.position_getter = PositionGetter3D()
+
+ def __call__(
+ self,
+ attn: Attention,
+ hidden_states: torch.FloatTensor,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ temb: Optional[torch.FloatTensor] = None,
+ frame: int = 8,
+ height: int = 16,
+ width: int = 16,
+ *args,
+ **kwargs,
+ ) -> torch.FloatTensor:
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
+ deprecate("scale", "1.0.0", deprecation_message)
+
+ if attn.downsampler is not None:
+ hidden_states, attention_mask = attn.downsampler(hidden_states, attention_mask, t=frame, h=height, w=width)
+ frame, height, width = attn.downsampler.t, attn.downsampler.h, attn.downsampler.w
+
+ residual = hidden_states
+ if attn.spatial_norm is not None:
+ hidden_states = attn.spatial_norm(hidden_states, temb)
+
+ input_ndim = hidden_states.ndim
+
+ # if input_ndim == 4:
+ # batch_size, channel, height, width = hidden_states.shape
+ # hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
+
+ batch_size, sequence_length, _ = (
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
+ )
+
+ if attention_mask is not None:
+ if npu_config is None:
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
+ # scaled_dot_product_attention expects attention_mask shape to be
+ # (batch, heads, source_length, target_length)
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
+ else:
+ if npu_config.enable_FA:
+ attention_mask = attention_mask.to(torch.bool)
+ attention_mask = attention_mask.view(batch_size, 1, -1, attention_mask.shape[-1])
+ attention_mask = attention_mask.repeat(1, 1, hidden_states.shape[1], 1)
+
+ if attn.group_norm is not None:
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
+
+ query = attn.to_q(hidden_states)
+
+ if encoder_hidden_states is None:
+ encoder_hidden_states = hidden_states
+ elif attn.norm_cross:
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
+
+ key = attn.to_k(encoder_hidden_states)
+ value = attn.to_v(encoder_hidden_states)
+
+ inner_dim = key.shape[-1]
+ head_dim = inner_dim // attn.heads
+
+ if npu_config is not None and npu_config.on_npu:
+ if npu_config.enable_FA and query.dtype == torch.float32:
+ dtype = torch.bfloat16
+ else:
+ dtype = None
+
+ if self.use_rope:
+ query = query.view(batch_size, -1, attn.heads, head_dim)
+ key = key.view(batch_size, -1, attn.heads, head_dim)
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+ query = query.view(batch_size, -1, attn.heads * head_dim)
+ key = key.view(batch_size, -1, attn.heads * head_dim)
+
+ with set_run_dtype(query, dtype):
+ query, key, value = npu_config.set_current_run_dtype([query, key, value])
+ hidden_states = npu_config.run_attention(query, key, value, attention_mask, "BSH",
+ head_dim, attn.heads)
+
+ hidden_states = npu_config.restore_dtype(hidden_states)
+ else:
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+
+ # qk norm
+ # query = attn.q_norm(query)
+ # key = attn.k_norm(key)
+
+ if self.use_rope:
+ # require the shape of (batch_size x nheads x ntokens x dim)
+ pos_thw = self.position_getter(batch_size, t=frame, h=height, w=width, device=query.device)
+ query = self.rope(query, pos_thw)
+ key = self.rope(key, pos_thw)
+
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
+ # 0, -10000 ->(bool) False, True ->(any) True ->(not) False
+ # 0, 0 ->(bool) False, False ->(any) False ->(not) True
+ if attention_mask is None or not torch.any(attention_mask.bool()): # 0 mean visible
+ attention_mask = None
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
+ # TODO: add support for attn.scale when we move to Torch 2.1
+
+ if self.attention_mode == 'flash' and attention_mask is None:
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=True, enable_mem_efficient=False):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, dropout_p=0.0, is_causal=False
+ )
+ elif self.attention_mode == 'xformers' or (self.attention_mode == 'flash' and attention_mask is not None):
+ with torch.backends.cuda.sdp_kernel(enable_math=False, enable_flash=False, enable_mem_efficient=True):
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ elif self.attention_mode == 'math':
+ raise RuntimeError
+ hidden_states = F.scaled_dot_product_attention(
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
+ )
+ else:
+ raise NotImplementedError(f'Found attention_mode: {self.attention_mode}')
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
+ hidden_states = hidden_states.to(query.dtype)
+
+ # linear proj
+ hidden_states = attn.to_out[0](hidden_states)
+ # dropout
+ hidden_states = attn.to_out[1](hidden_states)
+
+ if input_ndim == 4:
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
+
+ if attn.residual_connection:
+ hidden_states = hidden_states + residual
+
+ hidden_states = hidden_states / attn.rescale_output_factor
+
+ if attn.downsampler is not None:
+ hidden_states = attn.downsampler.reverse(hidden_states, t=frame, h=height, w=width)
+
+ return hidden_states
+
+
+class PixelUnshuffle(nn.Module):
+ def __init__(self, ratio, ratio_t=None):
+ super().__init__()
+ self.r = ratio
+ self.r_t = ratio_t if ratio_t else 1
+
+ def forward(self, x):
+ # if self.r_t is not None and self.r_t != 1:
+ if x.ndim == 5:
+ b, c, t, h, w = x.shape
+ # import ipdb;ipdb.set_trace()
+ assert t % self.r_t == 0 and h % self.r == 0 and w % self.r == 0
+ x = rearrange(x, 'b c (t r1) (h r2) (w r3) -> b (c r1 r2 r3) t h w', r1=self.r_t, r2=self.r, r3=self.r)
+ else:
+ b, c, h, w = x.shape
+ assert h % self.r == 0 and w % self.r == 0
+ x = rearrange(x, 'b c (h r2) (w r3) -> b (c r2 r3) h w', r2=self.r, r3=self.r)
+ return x
+
+class PixelShuffle(nn.Module):
+ def __init__(self, ratio, ratio_t=None):
+ super().__init__()
+ self.r = ratio
+ self.r_t = ratio_t if ratio_t else 1
+
+ def forward(self, x):
+ if x.ndim == 5:
+ b, c, t, h, w = x.shape
+ # import ipdb;ipdb.set_trace()
+ assert c % (self.r_t*self.r*self.r) == 0
+ x = rearrange(x, 'b (c r1 r2 r3) t h w -> b c (t r1) (h r2) (w r3)', r1=self.r_t, r2=self.r, r3=self.r)
+ else:
+ b, c, h, w = x.shape
+ assert c % (self.r*self.r) == 0
+ x = rearrange(x, 'b (c r2 r3) h w -> b c (h r2) (w r3)', r2=self.r, r3=self.r)
+ return x
+
+class Downsample3d(nn.Module):
+ def __init__(self, n_feat):
+ super(Downsample3d, self).__init__()
+
+ self.body = nn.Sequential(nn.Conv3d(n_feat, n_feat // 4, kernel_size=3, stride=1, padding=1, bias=False),
+ PixelUnshuffle(2, 2))
+
+ def forward(self, x, attention_mask, frames, height, width, pad_h=0, pad_w=0):
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=frames, h=height, w=width)
+ # x = F.pad(x, (0, pad_w, 0, pad_h, 0, 0), mode='reflect')
+ x = F.pad(x, (0, pad_w, 0, pad_h, 0, 0))
+ if npu_config is None:
+ x = self.body(x)
+ else:
+ x_dtype = x.dtype
+ x = npu_config.run_conv3d(self.body, x, x_dtype)
+ x = rearrange(x, 'b d t h w -> b (t h w) d')
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> b 1 t h w', t=frames, h=height, w=width)
+ attention_mask = F.pad(attention_mask, (0, pad_w, 0, pad_h, 0, 0))
+ attention_mask = F.max_pool3d(attention_mask, kernel_size=2, stride=2)
+ attention_mask = rearrange(attention_mask, 'b 1 t h w -> b 1 (t h w)')
+ attention_bias = (1 - attention_mask.bool().to(x.dtype)) * -10000.0
+
+ return x, attention_bias, attention_mask
+
+class Upsample3d(nn.Module):
+ def __init__(self, n_feat):
+ super(Upsample3d, self).__init__()
+
+ self.body = nn.Sequential(nn.Conv3d(n_feat, n_feat * 4, kernel_size=3, stride=1, padding=1, bias=False),
+ PixelShuffle(2, 2))
+
+ def forward(self, x, attention_mask, frames, height, width, pad_h=0, pad_w=0):
+ x = rearrange(x, 'b (t h w) d -> b d t h w', t=frames, h=height, w=width)
+ if npu_config is None:
+ x = self.body(x)
+ else:
+ x_dtype = x.dtype
+ x = npu_config.run_conv3d(self.body, x, x_dtype)
+ x = x[:, :, :, :height*2-pad_h, :width*2-pad_w]
+ x = rearrange(x, 'b d t h w -> b (t h w) d')
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> b 1 t h w', t=frames, h=height, w=width)
+ attention_mask = attention_mask.repeat_interleave(2, -1).repeat_interleave(2, -2).repeat_interleave(2, -3)
+ attention_mask = attention_mask[:, :, :, :height*2-pad_h, :width*2-pad_w]
+ attention_mask = rearrange(attention_mask, 'b 1 t h w -> b 1 (t h w)')
+ attention_bias = (1 - attention_mask.bool().to(x.dtype)) * -10000.0
+
+ return x, attention_bias, attention_mask
+
+
+class Downsample2d(nn.Module):
+ def __init__(self, n_feat, is_video_model=False):
+ super(Downsample2d, self).__init__()
+ self.body = nn.Conv2d(n_feat, 2*n_feat, kernel_size=3, stride=2, padding=1, bias=False)
+
+ def forward(self, x, attention_mask, frames, height, width, pad_h=0, pad_w=0):
+ # import ipdb;ipdb.set_trace()
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=frames, h=height, w=width)
+ if npu_config is None:
+ x = F.pad(x, (0, pad_w, 0, pad_h))
+ else:
+ x = npu_config.run_pad_2d(F.pad, x, pad=(0, pad_w, 0, pad_h))
+ x = self.body(x)
+ x = rearrange(x, '(b t) d h w -> b (t h w) d', t=frames)
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> (b t) 1 h w', t=frames, h=height, w=width)
+ attention_mask = F.pad(attention_mask, (0, pad_w, 0, pad_h))
+ attention_mask = F.max_pool2d(attention_mask.float(), kernel_size=2, stride=2)
+ attention_mask = rearrange(attention_mask, '(b t) 1 h w -> b 1 (t h w)', t=frames)
+ attention_bias = (1 - attention_mask.bool().to(x.dtype)) * -10000.0
+
+ return x, attention_bias, attention_mask
+
+class Upsample2d(nn.Module):
+ def __init__(self, n_feat, is_video_model=False):
+ super(Upsample2d, self).__init__()
+ self.body = nn.Conv2d(n_feat, n_feat // 2, kernel_size=3, stride=1, padding=1, bias=False)
+
+ def forward(self, x, attention_mask, frames, height, width, pad_h=0, pad_w=0):
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=frames, h=height, w=width)
+ x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
+ x = self.body(x)
+ x = x[:, :, :height*2-pad_h, :width*2-pad_w]
+ x = rearrange(x, '(b t) d h w -> b (t h w) d', t=frames)
+
+ attention_mask = rearrange(attention_mask, 'b 1 (t h w) -> (b t) 1 h w', t=frames, h=height, w=width)
+ attention_mask = attention_mask.repeat_interleave(2, -1).repeat_interleave(2, -2)
+ attention_mask = attention_mask[:, :, :height*2-pad_h, :width*2-pad_w]
+ attention_mask = rearrange(attention_mask, '(b t) 1 h w -> b 1 (t h w)', t=frames)
+ attention_bias = (1 - attention_mask.bool().to(x.dtype)) * -10000.0
+
+ return x, attention_bias, attention_mask
+
+
+class FeedForward_Conv2d(nn.Module):
+ def __init__(self, downsampler, dim, hidden_features, bias=True):
+ super(FeedForward_Conv2d, self).__init__()
+
+ self.bias = bias
+
+ self.project_in = nn.Linear(dim, hidden_features, bias=bias)
+ self.act = nn.GELU()
+ self.dwconv = nn.ModuleList([
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(5, 5), stride=1, padding=(2, 2), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(3, 3), stride=1, padding=(1, 1), dilation=1,
+ groups=hidden_features, bias=bias),
+ nn.Conv2d(hidden_features, hidden_features, kernel_size=(1, 1), stride=1, padding=(0, 0), dilation=1,
+ groups=hidden_features, bias=bias)
+ ])
+
+ self.project_out = nn.Linear(hidden_features, dim, bias=bias)
+
+
+ def forward(self, x, t, h, w):
+ # import ipdb;ipdb.set_trace()
+ x = self.project_in(x)
+ x = rearrange(x, 'b (t h w) d -> (b t) d h w', t=t, h=h, w=w)
+
+ x = self.act(x)
+ out = x
+ for module in self.dwconv:
+ out = out + module(x)
+ out = rearrange(out, '(b t) d h w -> b (t h w) d', t=t, h=h, w=w)
+ x = self.project_out(out)
+ return x
+
+@maybe_allow_in_graph
+class BasicTransformerBlock(nn.Module):
+ r"""
+ A basic Transformer block.
+
+ Parameters:
+ dim (`int`): The number of channels in the input and output.
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
+ attention_head_dim (`int`): The number of channels in each head.
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
+ num_embeds_ada_norm (:
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
+ attention_bias (:
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
+ only_cross_attention (`bool`, *optional*):
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
+ double_self_attention (`bool`, *optional*):
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
+ upcast_attention (`bool`, *optional*):
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
+ Whether to use learnable elementwise affine parameters for normalization.
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
+ The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
+ final_dropout (`bool` *optional*, defaults to False):
+ Whether to apply a final dropout after the last feed-forward layer.
+ attention_type (`str`, *optional*, defaults to `"default"`):
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
+ positional_embeddings (`str`, *optional*, defaults to `None`):
+ The type of positional embeddings to apply to.
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
+ The maximum number of positional embeddings to apply.
+ """
+
+ def __init__(
+ self,
+ dim: int,
+ num_attention_heads: int,
+ attention_head_dim: int,
+ dropout=0.0,
+ cross_attention_dim: Optional[int] = None,
+ activation_fn: str = "geglu",
+ num_embeds_ada_norm: Optional[int] = None,
+ attention_bias: bool = False,
+ only_cross_attention: bool = False,
+ double_self_attention: bool = False,
+ upcast_attention: bool = False,
+ norm_elementwise_affine: bool = True,
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
+ norm_eps: float = 1e-5,
+ final_dropout: bool = False,
+ attention_type: str = "default",
+ positional_embeddings: Optional[str] = None,
+ num_positional_embeddings: Optional[int] = None,
+ ada_norm_continous_conditioning_embedding_dim: Optional[int] = None,
+ ada_norm_bias: Optional[int] = None,
+ ff_inner_dim: Optional[int] = None,
+ ff_bias: bool = True,
+ attention_out_bias: bool = True,
+ attention_mode: str = "xformers",
+ downsampler: str = None,
+ mlp_ratio: int = 4,
+ use_rope: bool = False,
+ interpolation_scale_thw: Tuple[int] = (1, 1, 1),
+ ):
+ super().__init__()
+ self.only_cross_attention = only_cross_attention
+
+ # We keep these boolean flags for backward-compatibility.
+ self.use_ada_layer_norm_zero = (num_embeds_ada_norm is not None) and norm_type == "ada_norm_zero"
+ self.use_ada_layer_norm = (num_embeds_ada_norm is not None) and norm_type == "ada_norm"
+ self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
+ self.use_layer_norm = norm_type == "layer_norm"
+ self.use_ada_layer_norm_continuous = norm_type == "ada_norm_continuous"
+
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
+ raise ValueError(
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
+ )
+
+ self.norm_type = norm_type
+ self.num_embeds_ada_norm = num_embeds_ada_norm
+
+ if positional_embeddings and (num_positional_embeddings is None):
+ raise ValueError(
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
+ )
+
+ if positional_embeddings == "sinusoidal":
+ self.pos_embed = SinusoidalPositionalEmbedding(dim, max_seq_length=num_positional_embeddings)
+ else:
+ self.pos_embed = None
+
+ # Define 3 blocks. Each block has its own normalization layer.
+ # 1. Self-Attn
+ if norm_type == "ada_norm":
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_zero":
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_continuous":
+ self.norm1 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "rms_norm",
+ )
+ else:
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
+
+ self.attn1 = Attention(
+ query_dim=dim,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
+ upcast_attention=upcast_attention,
+ out_bias=attention_out_bias,
+ downsampler=downsampler,
+ attention_mode=attention_mode,
+ use_rope=use_rope,
+ interpolation_scale_thw=interpolation_scale_thw,
+ )
+
+ # 2. Cross-Attn
+ if cross_attention_dim is not None or double_self_attention:
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
+ # the second cross attention block.
+ if norm_type == "ada_norm":
+ self.norm2 = AdaLayerNorm(dim, num_embeds_ada_norm)
+ elif norm_type == "ada_norm_continuous":
+ self.norm2 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "rms_norm",
+ )
+ else:
+ self.norm2 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
+
+ self.attn2 = Attention(
+ query_dim=dim,
+ cross_attention_dim=cross_attention_dim if not double_self_attention else None,
+ heads=num_attention_heads,
+ dim_head=attention_head_dim,
+ dropout=dropout,
+ bias=attention_bias,
+ upcast_attention=upcast_attention,
+ out_bias=attention_out_bias,
+ downsampler=None,
+ attention_mode=attention_mode,
+ use_rope=False,
+ interpolation_scale_thw=interpolation_scale_thw,
+ ) # is self-attn if encoder_hidden_states is none
+ else:
+ self.norm2 = None
+ self.attn2 = None
+
+ # 3. Feed-forward
+ if norm_type == "ada_norm_continuous":
+ self.norm3 = AdaLayerNormContinuous(
+ dim,
+ ada_norm_continous_conditioning_embedding_dim,
+ norm_elementwise_affine,
+ norm_eps,
+ ada_norm_bias,
+ "layer_norm",
+ )
+
+ elif norm_type in ["ada_norm_zero", "ada_norm", "layer_norm", "ada_norm_continuous"]:
+ self.norm3 = nn.LayerNorm(dim, norm_eps, norm_elementwise_affine)
+ elif norm_type == "layer_norm_i2vgen":
+ self.norm3 = None
+
+ self.ff = FeedForward(
+ dim,
+ dropout=dropout,
+ activation_fn=activation_fn,
+ final_dropout=final_dropout,
+ inner_dim=ff_inner_dim,
+ bias=ff_bias,
+ )
+
+ # 4. Fuser
+ if attention_type == "gated" or attention_type == "gated-text-image":
+ self.fuser = GatedSelfAttentionDense(dim, cross_attention_dim, num_attention_heads, attention_head_dim)
+
+ # 5. Scale-shift for PixArt-Alpha.
+ if norm_type == "ada_norm_single":
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
+
+ # let chunk size default to None
+ self._chunk_size = None
+ self._chunk_dim = 0
+
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
+ # Sets chunk feed-forward
+ self._chunk_size = chunk_size
+ self._chunk_dim = dim
+
+ def forward(
+ self,
+ hidden_states: torch.FloatTensor,
+ attention_mask: Optional[torch.FloatTensor] = None,
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
+ timestep: Optional[torch.LongTensor] = None,
+ cross_attention_kwargs: Dict[str, Any] = None,
+ class_labels: Optional[torch.LongTensor] = None,
+ frame: int = None,
+ height: int = None,
+ width: int = None,
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
+ ) -> torch.FloatTensor:
+ if cross_attention_kwargs is not None:
+ if cross_attention_kwargs.get("scale", None) is not None:
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
+
+ # Notice that normalization is always applied before the real computation in the following blocks.
+ # 0. Self-Attention
+ batch_size = hidden_states.shape[0]
+
+ if self.norm_type == "ada_norm":
+ norm_hidden_states = self.norm1(hidden_states, timestep)
+ elif self.norm_type == "ada_norm_zero":
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
+ )
+ elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
+ norm_hidden_states = self.norm1(hidden_states)
+ elif self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ elif self.norm_type == "ada_norm_single":
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
+ ).chunk(6, dim=1)
+ norm_hidden_states = self.norm1(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
+ norm_hidden_states = norm_hidden_states.squeeze(1)
+ else:
+ raise ValueError("Incorrect norm used")
+
+ if self.pos_embed is not None:
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
+
+ # 1. Prepare GLIGEN inputs
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
+
+ # 0, -10000 ->(bool) False, True ->(any) True ->(not) False
+ # 0, 0 ->(bool) False, False ->(any) False ->(not) True
+ # assert attention_mask.bool().float().sum() / attention_mask.bool().float().numel() <= 1/16, 'must ~all visible'
+ attn_output = self.attn1(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
+ attention_mask=attention_mask, frame=frame, height=height, width=width,
+ **cross_attention_kwargs,
+ )
+ if self.norm_type == "ada_norm_zero":
+ attn_output = gate_msa.unsqueeze(1) * attn_output
+ elif self.norm_type == "ada_norm_single":
+ attn_output = gate_msa * attn_output
+
+ hidden_states = attn_output + hidden_states
+ if hidden_states.ndim == 4:
+ hidden_states = hidden_states.squeeze(1)
+
+ # 1.2 GLIGEN Control
+ if gligen_kwargs is not None:
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
+
+ # 3. Cross-Attention
+ if self.attn2 is not None:
+ if self.norm_type == "ada_norm":
+ norm_hidden_states = self.norm2(hidden_states, timestep)
+ elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
+ norm_hidden_states = self.norm2(hidden_states)
+ elif self.norm_type == "ada_norm_single":
+ # For PixArt norm2 isn't applied here:
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
+ norm_hidden_states = hidden_states
+ elif self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ else:
+ raise ValueError("Incorrect norm")
+
+ if self.pos_embed is not None and self.norm_type != "ada_norm_single":
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
+
+ attn_output = self.attn2(
+ norm_hidden_states,
+ encoder_hidden_states=encoder_hidden_states,
+ attention_mask=encoder_attention_mask,
+ **cross_attention_kwargs,
+ )
+ hidden_states = attn_output + hidden_states
+ # 4. Feed-forward
+ # i2vgen doesn't have this norm 🤷♂️
+ if self.norm_type == "ada_norm_continuous":
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
+ elif not self.norm_type == "ada_norm_single":
+ norm_hidden_states = self.norm3(hidden_states)
+
+ if self.norm_type == "ada_norm_zero":
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
+
+ if self.norm_type == "ada_norm_single":
+ norm_hidden_states = self.norm2(hidden_states)
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
+
+ # if self.downsampler:
+ # ff_output = self.ff(norm_hidden_states, t=frame, h=height, w=width)
+ # else:
+ ff_output = self.ff(norm_hidden_states)
+
+ if self.norm_type == "ada_norm_zero":
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
+ elif self.norm_type == "ada_norm_single":
+ ff_output = gate_mlp * ff_output
+
+ hidden_states = ff_output + hidden_states
+ if hidden_states.ndim == 4:
+ hidden_states = hidden_states.squeeze(1)
+
+ return hidden_states
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/rope.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/rope.py
new file mode 100644
index 0000000000000000000000000000000000000000..b42096b9d4f23a40382f87255b47b34fb3c1e2c1
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/udit/rope.py
@@ -0,0 +1,154 @@
+import torch
+
+class PositionGetter3D(object):
+ """ return positions of patches """
+
+ def __init__(self, ):
+ self.cache_positions = {}
+
+ def __call__(self, b, t, h, w, device):
+ if not (t,h,w) in self.cache_positions:
+ x = torch.arange(w, device=device)
+ y = torch.arange(h, device=device)
+ z = torch.arange(t, device=device)
+ self.cache_positions[t,h,w] = torch.cartesian_prod(z, y, x) # (t, h, w, 3)
+ pos = self.cache_positions[t,h,w].view(1, t*h*w, 3).expand(b, -1, 3).clone()
+ return pos
+
+
+class RoPE3D(torch.nn.Module):
+
+ def __init__(self, freq=10000.0, F0=1.0, interpolation_scale_thw=(1, 1, 1)):
+ super().__init__()
+ self.base = freq
+ self.F0 = F0
+ self.interpolation_scale_t = interpolation_scale_thw[0]
+ self.interpolation_scale_h = interpolation_scale_thw[1]
+ self.interpolation_scale_w = interpolation_scale_thw[2]
+ self.cache = {}
+
+ def get_cos_sin(self, D, seq_len, device, dtype, interpolation_scale=1):
+ if (D, seq_len, device, dtype) not in self.cache:
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D))
+ t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) / interpolation_scale
+ freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype)
+ freqs = torch.cat((freqs, freqs), dim=-1)
+ cos = freqs.cos() # (Seq, Dim)
+ sin = freqs.sin()
+ self.cache[D, seq_len, device, dtype] = (cos, sin)
+ return self.cache[D, seq_len, device, dtype]
+
+ @staticmethod
+ def rotate_half(x):
+ x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
+ return torch.cat((-x2, x1), dim=-1)
+
+ def apply_rope1d(self, tokens, pos1d, cos, sin):
+ assert pos1d.ndim == 2
+ cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :]
+ sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :]
+ return (tokens * cos) + (self.rotate_half(tokens) * sin)
+
+ def forward(self, tokens, positions):
+ """
+ input:
+ * tokens: batch_size x nheads x ntokens x dim
+ * positions: batch_size x ntokens x 3 (t, y and x position of each token)
+ output:
+ * tokens after appplying RoPE3D (batch_size x nheads x ntokens x dim)
+ """
+ assert tokens.size(3) % 3 == 0, "number of dimensions should be a multiple of three"
+ D = tokens.size(3) // 3
+ assert positions.ndim == 3 and positions.shape[-1] == 3 # Batch, Seq, 3
+ cos_t, sin_t = self.get_cos_sin(D, int(positions[:, :, 0].max()) + 1, tokens.device, tokens.dtype, self.interpolation_scale_t)
+ cos_y, sin_y = self.get_cos_sin(D, int(positions[:, :, 1].max()) + 1, tokens.device, tokens.dtype, self.interpolation_scale_h)
+ cos_x, sin_x = self.get_cos_sin(D, int(positions[:, :, 2].max()) + 1, tokens.device, tokens.dtype, self.interpolation_scale_w)
+ # split features into three along the feature dimension, and apply rope1d on each half
+ t, y, x = tokens.chunk(3, dim=-1)
+ t = self.apply_rope1d(t, positions[:, :, 0], cos_t, sin_t)
+ y = self.apply_rope1d(y, positions[:, :, 1], cos_y, sin_y)
+ x = self.apply_rope1d(x, positions[:, :, 2], cos_x, sin_x)
+ tokens = torch.cat((t, y, x), dim=-1)
+ return tokens
+
+
+
+# import torch
+# from einops import rearrange, repeat
+
+# class PositionGetter3D(object):
+# """ return positions of patches """
+
+# def __init__(self, ):
+# self.cache_positions = {}
+
+# def __call__(self, b, t, h, w, device):
+# if not (t,h,w) in self.cache_positions:
+# x = torch.arange(w, device=device)
+# y = torch.arange(h, device=device)
+# z = torch.arange(t, device=device)
+# positions = torch.cartesian_prod(z, y, x) # (t, h, w, 3)
+# positions = rearrange(positions, 'n d -> d 1 n')
+# positions = repeat(positions, 'd 1 n -> d b n', b=b).clone()
+# poses = (positions[0], positions[1], positions[2])
+# max_pos = (int(poses[0].max()), int(poses[1].max()), int(poses[2].max()))
+# self.cache_positions[t,h,w] = (poses, max_pos)
+# pos = self.cache_positions[t,h,w]
+# return pos
+
+
+# class RoPE3D(torch.nn.Module):
+
+# def __init__(self, freq=10000.0, F0=1.0, interpolation_scale_thw=(1, 1, 1)):
+# super().__init__()
+# self.base = freq
+# self.F0 = F0
+# self.interpolation_scale_t = interpolation_scale_thw[0]
+# self.interpolation_scale_h = interpolation_scale_thw[1]
+# self.interpolation_scale_w = interpolation_scale_thw[2]
+# self.cache = {}
+
+# def get_cos_sin(self, D, seq_len, device, dtype, interpolation_scale=1):
+# if (D, seq_len, device, dtype) not in self.cache:
+# inv_freq = 1.0 / (self.base ** (torch.arange(0, D, 2).float().to(device) / D))
+# t = torch.arange(seq_len, device=device, dtype=inv_freq.dtype) / interpolation_scale
+# freqs = torch.einsum("i,j->ij", t, inv_freq).to(dtype)
+# freqs = torch.cat((freqs, freqs), dim=-1)
+# cos = freqs.cos() # (Seq, Dim)
+# sin = freqs.sin()
+# self.cache[D, seq_len, device, dtype] = (cos, sin)
+# return self.cache[D, seq_len, device, dtype]
+
+# @staticmethod
+# def rotate_half(x):
+# x1, x2 = x[..., : x.shape[-1] // 2], x[..., x.shape[-1] // 2:]
+# return torch.cat((-x2, x1), dim=-1)
+
+# def apply_rope1d(self, tokens, pos1d, cos, sin):
+# assert pos1d.ndim == 2
+# cos = torch.nn.functional.embedding(pos1d, cos)[:, None, :, :]
+# sin = torch.nn.functional.embedding(pos1d, sin)[:, None, :, :]
+# return (tokens * cos) + (self.rotate_half(tokens) * sin)
+
+# def forward(self, tokens, positions):
+# """
+# input:
+# * tokens: batch_size x nheads x ntokens x dim
+# * positions: batch_size x ntokens x 3 (t, y and x position of each token)
+# output:
+# * tokens after appplying RoPE3D (batch_size x nheads x ntokens x dim)
+# """
+# assert tokens.size(3) % 3 == 0, "number of dimensions should be a multiple of three"
+# D = tokens.size(3) // 3
+# poses, max_pos = positions
+# assert len(poses) == 3 and poses[0].ndim == 2 # Batch, Seq, 3
+# cos_t, sin_t = self.get_cos_sin(D, max_pos[0] + 1, tokens.device, tokens.dtype, self.interpolation_scale_t)
+# cos_y, sin_y = self.get_cos_sin(D, max_pos[1] + 1, tokens.device, tokens.dtype, self.interpolation_scale_h)
+# cos_x, sin_x = self.get_cos_sin(D, max_pos[2] + 1, tokens.device, tokens.dtype, self.interpolation_scale_w)
+# # split features into three along the feature dimension, and apply rope1d on each half
+# t, y, x = tokens.chunk(3, dim=-1)
+# t = self.apply_rope1d(t, poses[0], cos_t, sin_t)
+# y = self.apply_rope1d(y, poses[1], cos_y, sin_y)
+# x = self.apply_rope1d(x, poses[2], cos_x, sin_x)
+# tokens = torch.cat((t, y, x), dim=-1)
+# return tokens
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/__init__.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..25e3d48a162760260826080f6366838e83e26878
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/__init__.py
@@ -0,0 +1,4 @@
+# Copyright (C) 2022-present Naver Corporation. All rights reserved.
+# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
+
+from .curope2d import cuRoPE2D
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope.cpp b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope.cpp
new file mode 100644
index 0000000000000000000000000000000000000000..8fe9058e05aa1bf3f37b0d970edc7312bc68455b
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope.cpp
@@ -0,0 +1,69 @@
+/*
+ Copyright (C) 2022-present Naver Corporation. All rights reserved.
+ Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
+*/
+
+#include
+
+// forward declaration
+void rope_2d_cuda( torch::Tensor tokens, const torch::Tensor pos, const float base, const float fwd );
+
+void rope_2d_cpu( torch::Tensor tokens, const torch::Tensor positions, const float base, const float fwd )
+{
+ const int B = tokens.size(0);
+ const int N = tokens.size(1);
+ const int H = tokens.size(2);
+ const int D = tokens.size(3) / 4;
+
+ auto tok = tokens.accessor();
+ auto pos = positions.accessor();
+
+ for (int b = 0; b < B; b++) {
+ for (int x = 0; x < 2; x++) { // y and then x (2d)
+ for (int n = 0; n < N; n++) {
+
+ // grab the token position
+ const int p = pos[b][n][x];
+
+ for (int h = 0; h < H; h++) {
+ for (int d = 0; d < D; d++) {
+ // grab the two values
+ float u = tok[b][n][h][d+0+x*2*D];
+ float v = tok[b][n][h][d+D+x*2*D];
+
+ // grab the cos,sin
+ const float inv_freq = fwd * p / powf(base, d/float(D));
+ float c = cosf(inv_freq);
+ float s = sinf(inv_freq);
+
+ // write the result
+ tok[b][n][h][d+0+x*2*D] = u*c - v*s;
+ tok[b][n][h][d+D+x*2*D] = v*c + u*s;
+ }
+ }
+ }
+ }
+ }
+}
+
+void rope_2d( torch::Tensor tokens, // B,N,H,D
+ const torch::Tensor positions, // B,N,2
+ const float base,
+ const float fwd )
+{
+ TORCH_CHECK(tokens.dim() == 4, "tokens must have 4 dimensions");
+ TORCH_CHECK(positions.dim() == 3, "positions must have 3 dimensions");
+ TORCH_CHECK(tokens.size(0) == positions.size(0), "batch size differs between tokens & positions");
+ TORCH_CHECK(tokens.size(1) == positions.size(1), "seq_length differs between tokens & positions");
+ TORCH_CHECK(positions.size(2) == 2, "positions.shape[2] must be equal to 2");
+ TORCH_CHECK(tokens.is_cuda() == positions.is_cuda(), "tokens and positions are not on the same device" );
+
+ if (tokens.is_cuda())
+ rope_2d_cuda( tokens, positions, base, fwd );
+ else
+ rope_2d_cpu( tokens, positions, base, fwd );
+}
+
+PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
+ m.def("rope_2d", &rope_2d, "RoPE 2d forward/backward");
+}
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope2d.py b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope2d.py
new file mode 100644
index 0000000000000000000000000000000000000000..a49c12f8c529e9a889b5ac20c5767158f238e17d
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/curope2d.py
@@ -0,0 +1,40 @@
+# Copyright (C) 2022-present Naver Corporation. All rights reserved.
+# Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
+
+import torch
+
+try:
+ import curope as _kernels # run `python setup.py install`
+except ModuleNotFoundError:
+ from . import curope as _kernels # run `python setup.py build_ext --inplace`
+
+
+class cuRoPE2D_func (torch.autograd.Function):
+
+ @staticmethod
+ def forward(ctx, tokens, positions, base, F0=1):
+ ctx.save_for_backward(positions)
+ ctx.saved_base = base
+ ctx.saved_F0 = F0
+ # tokens = tokens.clone() # uncomment this if inplace doesn't work
+ _kernels.rope_2d( tokens, positions, base, F0 )
+ ctx.mark_dirty(tokens)
+ return tokens
+
+ @staticmethod
+ def backward(ctx, grad_res):
+ positions, base, F0 = ctx.saved_tensors[0], ctx.saved_base, ctx.saved_F0
+ _kernels.rope_2d( grad_res, positions, base, -F0 )
+ ctx.mark_dirty(grad_res)
+ return grad_res, None, None, None
+
+
+class cuRoPE2D(torch.nn.Module):
+ def __init__(self, freq=100.0, F0=1.0):
+ super().__init__()
+ self.base = freq
+ self.F0 = F0
+
+ def forward(self, tokens, positions):
+ cuRoPE2D_func.apply( tokens.transpose(1,2), positions, self.base, self.F0 )
+ return tokens
\ No newline at end of file
diff --git a/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/kernels.cu b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/kernels.cu
new file mode 100644
index 0000000000000000000000000000000000000000..7156cd1bb935cb1f0be45e58add53f9c21505c20
--- /dev/null
+++ b/One-to-All-Animation/video-generation/opensora/models/diffusion/utils/curope/kernels.cu
@@ -0,0 +1,108 @@
+/*
+ Copyright (C) 2022-present Naver Corporation. All rights reserved.
+ Licensed under CC BY-NC-SA 4.0 (non-commercial use only).
+*/
+
+#include